raghuv-aditya commited on
Commit
599840c
·
verified ·
1 Parent(s): 999f447

Create chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +48 -0
chatbot.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ chatbot.py
3
+
4
+ Module to create a chatbot using RetrievalQA and the ChromaDB embeddings.
5
+ """
6
+
7
+ from langchain_openai import OpenAI
8
+ from langchain.chains import RetrievalQA
9
+
10
+ def create_chatbot(vector_store):
11
+ """Creates a chatbot that retrieves and answers questions.
12
+
13
+ Args:
14
+ vector_store (Chroma): Vector store with document embeddings.
15
+
16
+ Returns:
17
+ RetrievalQA: A retrieval-based QA system.
18
+ """
19
+ llm = OpenAI(temperature=0.5)
20
+ retriever = vector_store.as_retriever(search_type="mmr", k=3)
21
+
22
+ qa = RetrievalQA.from_chain_type(
23
+ llm=llm,
24
+ chain_type="stuff",
25
+ retriever=retriever,
26
+ return_source_documents=True
27
+ )
28
+ return qa
29
+
30
+ def ask_question(qa, query):
31
+ """Queries the chatbot and returns the answer.
32
+
33
+ Args:
34
+ qa (RetrievalQA): The QA system.
35
+ query (str): The user query.
36
+
37
+ Returns:
38
+ str: The answer with source information if available.
39
+ """
40
+ try:
41
+ response = qa.invoke({"query": query})
42
+ answer = response.get('result', 'No answer found.')
43
+ sources = response.get('source_documents', [])
44
+
45
+ return f"Answer: {answer}\n"
46
+ except Exception as e:
47
+ print(f"Error processing query '{query}': {e}")
48
+ return f"Error: {e}"