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"""[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.", []