Update app.py
Browse files
app.py
CHANGED
@@ -43,29 +43,26 @@ def rag_from_pdf(question, pdf_file, api_key):
|
|
43 |
vectorstore = initialize_vectorstore(documents, api_key)
|
44 |
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 3})
|
45 |
|
46 |
-
# Initialize the LLM
|
47 |
-
llm = ChatOpenAI(model="gpt-3.5-turbo")
|
48 |
-
|
49 |
-
# Create a prompt template for combining context and question
|
50 |
-
prompt_template = """
|
51 |
-
You are a helpful assistant answering questions based on the provided PDF document.
|
52 |
-
Only use the given context to answer the question.
|
53 |
-
Question: {question}
|
54 |
-
Context: {context}
|
55 |
-
"""
|
56 |
-
prompt = ChatPromptTemplate.from_template(prompt_template)
|
57 |
-
|
58 |
# Retrieve relevant documents
|
59 |
retrieved_docs = retriever.get_relevant_documents(question)
|
60 |
context = "\n".join([doc.page_content for doc in retrieved_docs])
|
61 |
|
62 |
-
#
|
63 |
if not context.strip():
|
64 |
return "No relevant information found in the document to answer the question."
|
65 |
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
except Exception as e:
|
70 |
return f"An error occurred: {str(e)}"
|
71 |
|
|
|
43 |
vectorstore = initialize_vectorstore(documents, api_key)
|
44 |
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 3})
|
45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
# Retrieve relevant documents
|
47 |
retrieved_docs = retriever.get_relevant_documents(question)
|
48 |
context = "\n".join([doc.page_content for doc in retrieved_docs])
|
49 |
|
50 |
+
# Check if there's relevant context
|
51 |
if not context.strip():
|
52 |
return "No relevant information found in the document to answer the question."
|
53 |
|
54 |
+
# Initialize the LLM
|
55 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo")
|
56 |
+
|
57 |
+
# Create the chat prompt
|
58 |
+
messages = [
|
59 |
+
{"role": "system", "content": "You are a helpful assistant answering questions based on the provided PDF document."},
|
60 |
+
{"role": "user", "content": f"Question: {question}\n\nContext: {context}"}
|
61 |
+
]
|
62 |
+
|
63 |
+
# Generate response
|
64 |
+
response = llm(messages=messages)
|
65 |
+
return response["choices"][0]["message"]["content"].strip()
|
66 |
except Exception as e:
|
67 |
return f"An error occurred: {str(e)}"
|
68 |
|