File size: 3,127 Bytes
46f282d
 
 
e55933e
46f282d
 
 
 
 
 
 
 
 
 
e55933e
 
 
46f282d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb69fd
46f282d
 
 
6cb69fd
46f282d
6cb69fd
46f282d
6cb69fd
46f282d
6cb69fd
46f282d
 
 
 
e55933e
 
46f282d
 
 
 
 
 
6cb69fd
46f282d
 
 
 
 
 
6cb69fd
46f282d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb69fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from huggingface_hub import InferenceClient
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings
import os

class LLMHandler:
    def __init__(self):
        self.hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
        self.client = InferenceClient(
            model="mistralai/Mistral-7B-Instruct-v0.2",
            token=self.hf_token
        )
        
        self.embeddings = HuggingFaceInferenceAPIEmbeddings(
            api_key=self.hf_token,
            model_name="BAAI/bge-small-en-v1.5"
        )
        
    def create_qa_chain(self, vector_store):
        memory = ConversationBufferMemory(
            memory_key="chat_history",
            return_messages=True,
            output_key="answer"
        )
        
        retriever = vector_store.as_retriever(search_kwargs={"k": 3})
        
        def get_relevant_context(question):
            docs = retriever.get_relevant_documents(question)
            return "\n".join([doc.page_content for doc in docs])
        
        def generate_answer(question, context):
            # Limit context length to avoid exceeding token limit
            if len(context) > 3000:
                context = context[:3000]
                
            prompt = f"""<s>[INST] You are a helpful AI assistant. Use the following text to answer the question. If you cannot find the answer, say "I couldn't find information about this in the document." Provide a complete and detailed answer.

Text: {context}

Question: {question}

Answer in Vietnamese: [/INST]"""
            
            try:
                response = self.client.text_generation(
                    prompt,
                    max_new_tokens=2500,
                    temperature=0.5,
                    top_p=0.95,
                    repetition_penalty=1.15,
                    do_sample=True,
                    return_full_text=False
                )
                
                # Ensure complete answer
                if response and not response.endswith(('.', '!', '?', '"', ')', ']', '}')):
                    response += "..."
                    
                return response
            except Exception as e:
                print(f"Error generating response: {e}")
                return "Sorry, I encountered an error processing your question. Please try again."
            
        return {
            "get_context": get_relevant_context,
            "generate_answer": generate_answer,
            "memory": memory
        }
    
    def get_answer(self, qa_chain, question):
        try:
            context = qa_chain["get_context"](question)
            answer = qa_chain["generate_answer"](question, context)
            
            qa_chain["memory"].save_context(
                {"question": question},
                {"answer": answer}
            )
            
            return answer, []
        except Exception as e:
            print(f"Error in get_answer: {e}")
            return "Sorry, an error occurred.", []