NEXAS commited on
Commit
cb560d6
·
verified ·
1 Parent(s): d68fe02

Update utils/llm.py

Browse files
Files changed (1) hide show
  1. utils/llm.py +65 -49
utils/llm.py CHANGED
@@ -1,49 +1,65 @@
1
- from langchain_community.embeddings.fastembed import FastEmbedEmbeddings
2
- from langchain_groq import ChatGroq
3
- import os
4
- import json
5
- from typing import List, Dict
6
-
7
- class LLMProcessor:
8
- def __init__(self):
9
- """Initialize embedding model and Groq LLM"""
10
- self.api_key = os.getenv("GROQ_API_KEY")
11
-
12
- # Use FastEmbed instead of SentenceTransformer
13
- self.embed_model = FastEmbedEmbeddings()
14
-
15
- self.llm = ChatGroq(
16
- model_name="mixtral-8x7b-32768",
17
- api_key=self.api_key
18
- )
19
-
20
- def format_context(self, chunks: List[Dict]) -> str:
21
- """Format retrieved chunks into a structured context for the LLM"""
22
- context_parts = []
23
- for chunk in chunks:
24
- try:
25
- headings = json.loads(chunk['headings'])
26
- if headings:
27
- context_parts.append(f"Section: {' > '.join(headings)}")
28
- except:
29
- pass
30
-
31
- if chunk['page']:
32
- context_parts.append(f"Page {chunk['page']}:")
33
-
34
- context_parts.append(chunk['text'])
35
- context_parts.append("-" * 40)
36
-
37
- return "\n".join(context_parts)
38
-
39
- def generate_answer(self, context: str, question: str) -> str:
40
- """Generate answer using structured context"""
41
- prompt = f"""Based on the following excerpts from a document:
42
-
43
- {context}
44
-
45
- Please answer this question: {question}
46
-
47
- Make use of the section information and page numbers in your answer when relevant.
48
- """
49
- return self.llm.invoke(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.embeddings.fastembed import FastEmbedEmbeddings
2
+ from langchain_groq import ChatGroq
3
+ import os
4
+ import json
5
+ from typing import List, Dict
6
+
7
+ class LLMProcessor:
8
+ def __init__(self):
9
+ """Initialize embedding model and Groq LLM"""
10
+ self.api_key = os.getenv("GROQ_API_KEY")
11
+
12
+ # Use FastEmbed instead of SentenceTransformer
13
+ self.embed_model = FastEmbedEmbeddings()
14
+
15
+ self.llm = ChatGroq(
16
+ model_name="mixtral-8x7b-32768",
17
+ api_key=self.api_key
18
+ )
19
+
20
+ def format_context(self, chunks: List[Dict]) -> str:
21
+ """Format retrieved chunks into a structured context for the LLM"""
22
+ context_parts = []
23
+ for chunk in chunks:
24
+ try:
25
+ headings = json.loads(chunk['headings'])
26
+ if headings:
27
+ context_parts.append(f"Section: {' > '.join(headings)}")
28
+ except:
29
+ pass
30
+
31
+ if chunk['page']:
32
+ context_parts.append(f"Page {chunk['page']}:")
33
+
34
+ context_parts.append(chunk['text'])
35
+ context_parts.append("-" * 40)
36
+
37
+ return "\n".join(context_parts)
38
+
39
+ def generate_answer(self, context: str, question: str) -> str:
40
+ """Generate answer using structured context"""
41
+ prompt = f"""
42
+ You are an AI assistant tasked with answering user questions based on the given document excerpts. Your goal is to provide a clear, accurate, and helpful answer using only the provided context.
43
+
44
+ If the answer is not found in the context, explicitly state that you do not know instead of making up an answer. If the question is out of context, say that it is out of context, but still try to provide the best possible response from the available information.
45
+
46
+ ---
47
+ ### Context:
48
+ {context}
49
+
50
+ ### User Question:
51
+ {question}
52
+
53
+ ---
54
+ #### Instructions:
55
+ - Use only the given context to construct your answer.
56
+ - Reference relevant sections and page numbers where applicable.
57
+ - Be concise yet informative, focusing on clarity and usefulness.
58
+ - If uncertain, respond honestly (e.g., "The answer is not found in the provided context.").
59
+ - If out of context, state so clearly (e.g., "The question is out of context, but here’s what I found in the document...").
60
+
61
+ ---
62
+ ### Helpful Answer:
63
+ """
64
+
65
+ return self.llm.invoke(prompt)