Sameer360/Document_based_chatbot
0
1### retriever.py ###2from langchain.memory import ConversationBufferMemory3 4 5def retrieve_context(query, db, memory):6 # print("Debug: retrieve_context function started")7 retriever = db.as_retriever(8 search_type="similarity", search_kwargs={"k": 7}9 )10 relevant_docs = retriever.invoke(query)11 # print(f"Debug: Number of relevant documents found: {len(relevant_docs)}") # number of docs12 13 # for i, doc in enumerate(relevant_docs):14 # print(f"Debug: Relevant document {i + 1}:")15 # print(f"Debug: Source: {doc.metadata.get('source', 'Unknown')}") # source of the doc16 # print(f"Debug: Content (first 100 chars): {doc.page_content[:100]}...") # content of the doc17 conversation_history = memory.load_memory_variables({})["history"]18 19 combined_input = (20 f"Conversation History: {conversation_history}\n"21 f"User Query: {query}\n"22 "Relevant Documents:\n"23 + "\n".join(doc.page_content for doc in relevant_docs if doc.page_content)24 + "\nPlease provide a concise answer based only on the provided documents. "25 "If the answer is not found in the documents, respond with 'I'm not sure'."26 )27 28 memory.save_context({"input": query}, {"output": "Retrieving relevant context..."})29 30 # Get the sources31 sources = []32 for doc in relevant_docs:33 source = doc.metadata.get("source", "Unknown Source")34 if source not in sources:35 sources.append(source)36 # print(f"Debug: sources found : {sources}") # source found37 # print("Debug: retrieve_context function ended")38 return combined_input, ", ".join(sources)39 