mobius.dev commited on
Commit
dee08f7
·
1 Parent(s): 8d2434f

Simplify ConversationalRetrievalChain

Browse files

delete prompt, because the built in prompt of ConversationalRetrievalChain is suffisant, economize prompt cost

Files changed (1) hide show
  1. talk_sheet.py +20 -38
talk_sheet.py CHANGED
@@ -13,7 +13,9 @@ from langchain.chains import ConversationalRetrievalChain
13
  from langchain.document_loaders.csv_loader import CSVLoader
14
  from langchain.prompts import PromptTemplate
15
  from langchain.vectorstores import FAISS
16
- from langchain.text_splitter import CharacterTextSplitter
 
 
17
 
18
  # Set the Streamlit page configuration, including the layout and page title/icon
19
  st.set_page_config(layout="wide", page_icon="contents\logo_site.png", page_title="Talk-Sheet")
@@ -44,7 +46,7 @@ async def main():
44
  os.environ["OPENAI_API_KEY"] = user_api_key
45
 
46
  # Allow the user to upload a CSV file
47
- uploaded_file = st.sidebar.file_uploader("", type="csv", label_visibility="hidden")
48
 
49
  # If the user has uploaded a file, display it in an expander
50
  if uploaded_file is not None:
@@ -74,23 +76,23 @@ async def main():
74
  tmp_file_path = tmp_file.name
75
 
76
  # Load the data from the CSV file using Langchain
77
- loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8")
78
  data = loader.load()
79
-
80
- # Split the text into smaller chunks for easier processing
81
- splitter = CharacterTextSplitter(separator="\n",chunk_size=1500, chunk_overlap=0)
82
- chunks = splitter.split_documents(data)
83
-
84
  # Create an embeddings object using Langchain
85
  embeddings = OpenAIEmbeddings()
86
 
87
  # Store the embeddings vectors using FAISS
88
- vectors = FAISS.from_documents(chunks, embeddings)
89
  os.remove(tmp_file_path)
90
 
91
  # Save the vectors to a pickle file
92
  with open(filename + ".pkl", "wb") as f:
93
  pickle.dump(vectors, f)
 
 
 
 
94
 
95
  # Define an asynchronous function for retrieving document embeddings
96
  async def getDocEmbeds(file, filename):
@@ -111,7 +113,7 @@ async def main():
111
  async def conversational_chat(query):
112
 
113
  # Use the Langchain ConversationalRetrievalChain to generate a response to the user's query
114
- result = qa({"question": query, "chat_history": st.session_state['history']})
115
 
116
  # Add the user's query and the chatbot's response to the chat history
117
  st.session_state['history'].append((query, result["answer"]))
@@ -122,28 +124,6 @@ async def main():
122
 
123
  return result["answer"]
124
 
125
- # Define a template for prompts to be used by the Langchain ConversationalRetrievalChain
126
- prompt_template = (
127
- "You are Talk-Sheet, a user-friendly chatbot designed to assist users by engaging in conversations based on data from CSV or Excel files. "
128
- "Your knowledge comes from:"
129
-
130
- "{context}"
131
-
132
- "Help users by providing relevant information from the data in their files. Answer their questions accurately and concisely. "
133
- "If the user's specific issue or need cannot be addressed with the available data, "
134
- "empathize with their situation and suggest that they may need to seek assistance elsewhere. "
135
- "Always maintain a friendly and helpful tone. "
136
- "If you don't know the answer to a question, truthfully say you don't know."
137
- "answers the user's question in the same language as the user"
138
-
139
- "Human: {question} "
140
-
141
- "Talk-Sheet: "
142
- )
143
-
144
- # Create a PromptTemplate object using the prompt_template defined above
145
- PROMPT = PromptTemplate(template=prompt_template, input_variables=["context","question"])
146
-
147
  # Set up sidebar with various options
148
  with st.sidebar.expander("🛠️ Settings", expanded=False):
149
 
@@ -178,11 +158,10 @@ async def main():
178
 
179
  # Generate embeddings vectors for the file
180
  vectors = await getDocEmbeds(file, uploaded_file.name)
181
-
182
  # Use the Langchain ConversationalRetrievalChain to set up the chatbot
183
- qa = ConversationalRetrievalChain.from_llm(ChatOpenAI(model_name=MODEL),
184
- retriever=vectors.as_retriever(),
185
- qa_prompt=PROMPT,return_source_documents=False)
186
 
187
  # Set the "ready" flag to True now that the chatbot is ready to chat
188
  st.session_state['ready'] = True
@@ -215,8 +194,8 @@ async def main():
215
  if st.session_state['reset_chat']:
216
 
217
  st.session_state['history'] = []
218
- st.session_state['past'] = ["Hey!"]
219
- st.session_state['generated'] = ["Welcome! You can now ask any questions regarding " + uploaded_file.name]
220
  response_container.empty()
221
  st.session_state['reset_chat'] = False
222
 
@@ -239,8 +218,11 @@ async def main():
239
  for i in range(len(st.session_state['generated'])):
240
  message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
241
  message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
 
 
242
  except Exception as e:
243
  st.error(f"Error: {str(e)}")
 
244
  # Create an expander for the "About" section
245
  about = st.sidebar.expander("About Talk-Sheet 🤖")
246
 
 
13
  from langchain.document_loaders.csv_loader import CSVLoader
14
  from langchain.prompts import PromptTemplate
15
  from langchain.vectorstores import FAISS
16
+ from langchain.chains import LLMChain
17
+ from langchain.chains.question_answering import load_qa_chain
18
+ from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
19
 
20
  # Set the Streamlit page configuration, including the layout and page title/icon
21
  st.set_page_config(layout="wide", page_icon="contents\logo_site.png", page_title="Talk-Sheet")
 
46
  os.environ["OPENAI_API_KEY"] = user_api_key
47
 
48
  # Allow the user to upload a CSV file
49
+ uploaded_file = st.sidebar.file_uploader("upload", type="csv", label_visibility="hidden")
50
 
51
  # If the user has uploaded a file, display it in an expander
52
  if uploaded_file is not None:
 
76
  tmp_file_path = tmp_file.name
77
 
78
  # Load the data from the CSV file using Langchain
79
+ loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8", csv_args={'delimiter': ','})
80
  data = loader.load()
81
+
 
 
 
 
82
  # Create an embeddings object using Langchain
83
  embeddings = OpenAIEmbeddings()
84
 
85
  # Store the embeddings vectors using FAISS
86
+ vectors = FAISS.from_documents(data, embeddings)
87
  os.remove(tmp_file_path)
88
 
89
  # Save the vectors to a pickle file
90
  with open(filename + ".pkl", "wb") as f:
91
  pickle.dump(vectors, f)
92
+
93
+
94
+
95
+
96
 
97
  # Define an asynchronous function for retrieving document embeddings
98
  async def getDocEmbeds(file, filename):
 
113
  async def conversational_chat(query):
114
 
115
  # Use the Langchain ConversationalRetrievalChain to generate a response to the user's query
116
+ result = chain({"question": query, "chat_history": st.session_state['history']})
117
 
118
  # Add the user's query and the chatbot's response to the chat history
119
  st.session_state['history'].append((query, result["answer"]))
 
124
 
125
  return result["answer"]
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  # Set up sidebar with various options
128
  with st.sidebar.expander("🛠️ Settings", expanded=False):
129
 
 
158
 
159
  # Generate embeddings vectors for the file
160
  vectors = await getDocEmbeds(file, uploaded_file.name)
161
+
162
  # Use the Langchain ConversationalRetrievalChain to set up the chatbot
163
+ chain = ConversationalRetrievalChain.from_llm(llm = ChatOpenAI(temperature=0.0,model_name=MODEL),retriever=vectors.as_retriever(),
164
+ )
 
165
 
166
  # Set the "ready" flag to True now that the chatbot is ready to chat
167
  st.session_state['ready'] = True
 
194
  if st.session_state['reset_chat']:
195
 
196
  st.session_state['history'] = []
197
+ st.session_state['past'] = ["Hey Talk-Sheet ! 👋"]
198
+ st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " 🤗"]
199
  response_container.empty()
200
  st.session_state['reset_chat'] = False
201
 
 
218
  for i in range(len(st.session_state['generated'])):
219
  message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
220
  message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
221
+ #st.write(chain)
222
+
223
  except Exception as e:
224
  st.error(f"Error: {str(e)}")
225
+
226
  # Create an expander for the "About" section
227
  about = st.sidebar.expander("About Talk-Sheet 🤖")
228