Create chat_with_doc.py
Browse files- chat_with_doc.py +50 -0
chat_with_doc.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import openai
|
3 |
+
import streamlit as st
|
4 |
+
import chunk # Import the chunking function from chunk.py
|
5 |
+
|
6 |
+
# Load environment variables
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
load_dotenv()
|
9 |
+
|
10 |
+
# Set the OpenAI API key
|
11 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
12 |
+
|
13 |
+
# Function to interact with OpenAI GPT model
|
14 |
+
def get_openai_response(prompt, model="gpt-4", max_tokens=150):
|
15 |
+
response = openai.Completion.create(
|
16 |
+
engine=model,
|
17 |
+
prompt=prompt,
|
18 |
+
max_tokens=max_tokens,
|
19 |
+
n=1,
|
20 |
+
stop=None,
|
21 |
+
temperature=0.7,
|
22 |
+
)
|
23 |
+
return response.choices[0].text.strip()
|
24 |
+
|
25 |
+
# Streamlit UI
|
26 |
+
st.title("Chat with Your Document")
|
27 |
+
|
28 |
+
# Get the chunked data directly from chunk.py (assuming `chunk_text()` is already executed)
|
29 |
+
# For example, you can load the chunked data from a file or directly invoke the chunking logic
|
30 |
+
document_text = """Your long document text goes here..."""
|
31 |
+
chunked_data = chunk.chunk_text(document_text)
|
32 |
+
|
33 |
+
# Display chunked data
|
34 |
+
st.write("Document has been chunked into the following parts:")
|
35 |
+
for i, chunk_part in enumerate(chunked_data, 1):
|
36 |
+
st.write(f"**Chunk {i}:**\n{chunk_part}\n")
|
37 |
+
|
38 |
+
# Input field for user to ask questions about the chunked document
|
39 |
+
st.subheader("Ask a question about the document:")
|
40 |
+
user_question = st.text_input("Your question")
|
41 |
+
|
42 |
+
# Button to submit the question
|
43 |
+
if st.button("Get Answer"):
|
44 |
+
if user_question:
|
45 |
+
# Create the prompt with the document chunks and user's question
|
46 |
+
prompt = f"Document Chunks: {chunked_data}\n\nQuestion: {user_question}\nAnswer:"
|
47 |
+
response = get_openai_response(prompt)
|
48 |
+
st.write(f"**Answer**: {response}")
|
49 |
+
else:
|
50 |
+
st.error("Please provide a question.")
|