themanas021 commited on
Commit
2ed9eb6
·
verified ·
1 Parent(s): 1549600

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain.embeddings import OpenAIEmbeddings
3
+ from langchain.vectorstores import Chroma
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.chat_models import ChatOpenAI
6
+ from langchain.chains import RetrievalQA
7
+ from langchain_community.document_loaders import TextLoader
8
+
9
+ import os
10
+ os.environ["OPENAI_API_KEY"]=os.getenv('OPENAI_API_KEY')
11
+ # Initialize the embeddings and model
12
+ embd = OpenAIEmbeddings()
13
+ llm = ChatOpenAI(model_name="gpt-4", temperature=0)
14
+
15
+ # Initialize conversation history
16
+ if "conversation_history" not in st.session_state:
17
+ st.session_state.conversation_history = []
18
+
19
+ # Define the Streamlit app
20
+ st.title("Text File Question-Answering with History")
21
+ st.subheader("Upload a text file and ask questions. The app will maintain a conversation history.")
22
+
23
+ # File upload section
24
+ uploaded_file = st.file_uploader("Upload a text file", type=["txt"])
25
+
26
+ if uploaded_file:
27
+ # Load and split the text file
28
+ text_loader = TextLoader(uploaded_file)
29
+ document = text_loader.load()
30
+
31
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
32
+ doc_splits = text_splitter.split_documents(document)
33
+
34
+ # Create a vector store
35
+ vectorstore = Chroma.from_documents(
36
+ documents=doc_splits,
37
+ collection_name="conversation_history",
38
+ embedding=embd,
39
+ )
40
+ retriever = vectorstore.as_retriever()
41
+
42
+ # Initialize the QA chain
43
+ qa_chain = RetrievalQA.from_chain_type(
44
+ llm=llm,
45
+ chain_type="stuff",
46
+ retriever=retriever,
47
+ return_source_documents=True,
48
+ )
49
+
50
+ # Question-answering section
51
+ query = st.text_input("Ask a question:")
52
+
53
+ if query:
54
+ result = qa_chain({"query": query})
55
+ answer = result["result"]
56
+ st.session_state.conversation_history.append((query, answer))
57
+
58
+ # Display the current answer
59
+ st.write("**Answer:**", answer)
60
+
61
+ # Display conversation history
62
+ st.subheader("Conversation History")
63
+ for idx, (q, a) in enumerate(st.session_state.conversation_history, 1):
64
+ st.write(f"**Q{idx}:** {q}")
65
+ st.write(f"**A{idx}:** {a}")
66
+