broductmanager commited on
Commit
e0a13cb
Β·
1 Parent(s): b2233d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -23
app.py CHANGED
@@ -1,35 +1,87 @@
1
- from langchain.agents import create_csv_agent
2
- from langchain.llms import OpenAI
 
 
 
 
 
 
 
3
  from dotenv import load_dotenv
4
  import os
5
- import streamlit as st
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- def main():
9
- load_dotenv()
 
10
 
11
- # Load the OpenAI API key from the environment variable
12
- if os.getenv("OPENAI_API_KEY") is None or os.getenv("OPENAI_API_KEY") == "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":
13
- print("OPENAI_API_KEY is not set")
14
- exit(1)
15
- else:
16
- print("OPENAI_API_KEY is set")
17
 
18
- st.set_page_config(page_title="Ask your CSV")
19
- st.header("Ask your CSV πŸ“ˆ")
 
 
 
 
20
 
21
- csv_file = st.file_uploader("Upload a CSV file", type="csv")
22
- if csv_file is not None:
 
23
 
24
- agent = create_csv_agent(
25
- OpenAI(temperature=0), csv_file, verbose=True)
26
 
27
- user_question = st.text_input("Ask a question about your CSV: ")
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- if user_question is not None and user_question != "":
30
- with st.spinner(text="In progress..."):
31
- st.write(agent.run(user_question))
 
32
 
 
 
 
33
 
34
- if __name__ == "__main__":
35
- main()
 
 
1
+
2
+
3
+ import streamlit as st
4
+ from langchain.document_loaders import DirectoryLoader, TextLoader
5
+ from langchain.text_splitter import CharacterTextSplitter
6
+ from langchain.embeddings.openai import OpenAIEmbeddings
7
+ from langchain.vectorstores import FAISS
8
+ from langchain.chains import RetrievalQA
9
+ from langchain.llms import OpenAI as LangchainOpenAI
10
  from dotenv import load_dotenv
11
  import os
 
12
 
13
+ # Load environment variables
14
+ load_dotenv()
15
+
16
+ # Initialize Streamlit
17
+ st.set_page_config(page_title="Ask the Docs")
18
+ st.header("Ask the Docs πŸ“š")
19
+ st.write('Unleash your credit card superpowers')
20
+ st.write('Revolutionize the way you track and manage your credit cards.')
21
+ st.write('Experience hassle-free financial control with Anek.')
22
+
23
+ # Initialize chat session state with a welcome message
24
+ if "messages" not in st.session_state.keys():
25
+ st.session_state.messages = [{"role": "assistant", "content": "Welcome to CreditCardChat! Your personal credit card advisor πŸ˜‰. Drop in your queries."}]
26
+
27
+ # Display previous chat messages
28
+ for message in st.session_state.messages:
29
+ with st.chat_message(message["role"]):
30
+ st.write(message["content"])
31
+
32
+
33
+ # Load Documents from Directory
34
+ text_loader_kwargs = {'encoding': 'utf-8'}
35
+ loader = DirectoryLoader(r'C:\Users\iamma\Documents\JupyterHub\MODELS\V1\credit_card_texts17AUG', glob="**/*.txt", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
36
+ docs = loader.load()
37
 
38
+ # Embedding Configuration
39
+ openai_api_key = os.getenv('OPENAI_API_KEY')
40
+ embedding = OpenAIEmbeddings(openai_api_key=openai_api_key)
41
 
42
+ try:
43
+ embeddings = embedding.embed_documents([doc.page_content for doc in docs])
44
+ except Exception as e:
45
+ st.write(f"An error occurred: {e}")
46
+ st.stop()
 
47
 
48
+ # FAISS Database Configuration
49
+ try:
50
+ db = FAISS.from_documents(docs, embedding)
51
+ except Exception as e:
52
+ st.write(f"An error occurred while creating FAISS database: {e}")
53
+ st.stop()
54
 
55
+ # Initialize Langchain components
56
+ llm = LangchainOpenAI(openai_api_key=openai_api_key)
57
+ qa_chain = RetrievalQA.from_chain_type(llm, retriever=db.as_retriever())
58
 
59
+ # User-provided question
60
+ # ... (previous imports and initialization)
61
 
62
+ # User-provided question
63
+ if user_question := st.chat_input("Ask a question about the documents: "):
64
+ # Manually append user's question to session state and display immediately
65
+ st.session_state.messages.append({"role": "user", "content": user_question})
66
+
67
+ # Display chat messages including the new question
68
+ for message in st.session_state.messages:
69
+ with st.chat_message(message["role"]):
70
+ st.write(message["content"])
71
+
72
+ # Placeholder for assistant's response
73
+ with st.chat_message("assistant"):
74
+ assistant_placeholder = st.empty()
75
 
76
+ try:
77
+ # Get the model's response
78
+ result_dict = qa_chain({"query": user_question})
79
+ result = result_dict.get("result", "I don't know.")
80
 
81
+ # Update assistant's message
82
+ assistant_placeholder.write(result)
83
+ st.session_state.messages.append({"role": "assistant", "content": result})
84
 
85
+ except Exception as e:
86
+ assistant_placeholder.write(f"An error occurred: {e}")
87
+ st.session_state.messages.append({"role": "assistant", "content": f"An error occurred: {e}"})