qa.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from langchain_community.llms import Ollama
  2. from langchain.chains import LLMChain
  3. from langchain.prompts import PromptTemplate
  4. from langchain_community.vectorstores import Chroma
  5. from langchain_community.embeddings import OllamaEmbeddings
  6. from langchain_community.document_loaders import TextLoader
  7. from langchain_text_splitters import CharacterTextSplitter
  8. from langchain.memory import ConversationBufferWindowMemory
  9. import os
  10. from dotenv import load_dotenv
  11. from tempfile import NamedTemporaryFile
  12. # Load environment variables
  13. load_dotenv()
  14. # Initialize Ollama LLM and Embeddings
  15. llm = Ollama(model="tinyllama", temperature=0.7)
  16. embeddings = OllamaEmbeddings(model="tinyllama")
  17. # Initialize global Chroma vector store (in-memory)
  18. vector_store = Chroma.from_texts([""], embeddings) # Initialize empty store
  19. # Function to index uploaded file
  20. def index_file(file_content: bytes, file_name: str):
  21. with NamedTemporaryFile(delete=False, suffix=os.path.splitext(file_name)[1]) as temp_file:
  22. temp_file.write(file_content)
  23. temp_file_path = temp_file.name
  24. loader = TextLoader(temp_file_path)
  25. documents = loader.load()
  26. # Split documents into chunks
  27. text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
  28. chunks = text_splitter.split_documents(documents)
  29. # Add to vector store
  30. vector_store.add_documents(chunks)
  31. # Clean up temp file
  32. os.unlink(temp_file_path)
  33. # Define prompt templates
  34. def get_prompt_with_history(memory):
  35. return PromptTemplate(
  36. input_variables=["history", "question"],
  37. template=f"Previous conversation:\n{{history}}\n\nResponda à seguinte pergunta: {{question}}"
  38. )
  39. def get_prompt_with_history_and_docs(memory, docs):
  40. docs_text = "\n".join([f"Source: {doc.page_content}" for doc in docs]) if docs else "No relevant documents found."
  41. return PromptTemplate(
  42. input_variables=["history", "question"],
  43. template=f"Previous conversation:\n{{history}}\n\nRelevant documents:\n{docs_text}\n\nResponda à seguinte pergunta usando as fontes relevantes e citando trechos como fontes: {{question}}"
  44. )
  45. def get_answer(session_id: str, question: str) -> str:
  46. # Get or initialize memory for this session
  47. memory = ConversationBufferWindowMemory(memory_key="history", input_key="question", k=3, session_id=session_id)
  48. # Create chain with dynamic prompt including history
  49. prompt = get_prompt_with_history(memory)
  50. chain = LLMChain(llm=llm, prompt=prompt, memory=memory)
  51. # Get response
  52. response = chain.run(question=question)
  53. response = response[:100] if len(response) > 100 else response # Truncate if needed
  54. return response
  55. # RAG function for /ask endpoint
  56. def ask_rag(session_id: str, question: str, file_content: bytes = None, file_name: str = None) -> dict:
  57. # Get or initialize memory for this session
  58. memory = ConversationBufferWindowMemory(memory_key="history", input_key="question", k=3, session_id=session_id)
  59. if file_content and file_name:
  60. index_file(file_content, file_name)
  61. # Retrieve relevant documents
  62. docs = vector_store.similarity_search(question, k=3)
  63. # Create chain with dynamic prompt including history and docs
  64. prompt = get_prompt_with_history_and_docs(memory, docs)
  65. chain = LLMChain(llm=llm, prompt=prompt, memory=memory)
  66. # Get response
  67. response = chain.run(question=question)
  68. response = response[:100] if len(response) > 100 else response
  69. # Prepare sources
  70. sources = [doc.page_content for doc in docs]
  71. return {"answer": response, "sources": sources}
  72. if __name__ == "__main__":
  73. session_id = "test_session"
  74. print(get_answer(session_id, "Qual a capital da França?"))
  75. print(get_answer(session_id, "E a capital da Espanha?"))