poemsforaphrodite commited on
Commit
ac0ce5d
1 Parent(s): 77468eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -32
app.py CHANGED
@@ -36,12 +36,13 @@ if 'assistant_id' not in st.session_state:
36
  st.session_state.assistant_id = None
37
  if 'thread_id' not in st.session_state:
38
  st.session_state.thread_id = None
 
 
39
 
40
  # ---------------------- Helper Functions ----------------------
41
 
42
  def get_vector_stores():
43
  try:
44
- client = OpenAI()
45
  vector_stores = client.beta.vector_stores.list()
46
  return vector_stores
47
  except Exception as e:
@@ -103,14 +104,16 @@ def create_assistant():
103
  return assistant.id
104
 
105
  def chat_with_assistant(file_ids, user_message):
106
- for file_id in file_ids:
107
- print("File ID:", file_id)
108
- # Create a thread and attach the file to the message
109
- print("final file id:", file_id)
 
110
  attachments = [{"file_id": file_id, "tools": [{"type": "file_search"}]} for file_id in file_ids]
111
- print("attachments:", attachments)
112
-
113
  if st.session_state.thread_id is None:
 
114
  thread = client.beta.threads.create(
115
  messages=[
116
  {
@@ -121,36 +124,83 @@ def chat_with_assistant(file_ids, user_message):
121
  ]
122
  )
123
  st.session_state.thread_id = thread.id
 
124
  else:
125
- thread = client.beta.threads.messages.create(
 
 
126
  thread_id=st.session_state.thread_id,
127
  role="user",
128
  content=user_message,
129
  attachments=attachments
130
  )
131
-
132
- # The thread now has a vector store with that file in its tool resources.
133
- print(thread.tool_resources.file_search)
134
- print("assistant_id:", st.session_state.assistant_id)
135
- print("thread_id:", thread.id)
136
- run = client.beta.threads.runs.create_and_poll(
137
- thread_id=thread.id, assistant_id=st.session_state.assistant_id
138
- )
139
- print("run:", run)
140
- messages = list(client.beta.threads.messages.list(thread_id=thread.id, run_id=run.id))
141
-
142
- message_content = messages[0].content[0].text
143
- annotations = message_content.annotations
144
- citations = []
145
- for index, annotation in enumerate(annotations):
146
- message_content.value = message_content.value.replace(annotation.text, f"[{index}]")
147
- if file_citation := getattr(annotation, "file_citation", None):
148
- cited_file = client.files.retrieve(file_citation.file_id)
149
- citations.append(f"[{index}] {cited_file.filename}")
150
-
151
- print(message_content.value)
152
- print("\n".join(citations))
153
- return message_content.value, citations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
 
156
 
@@ -201,7 +251,7 @@ if page == "Home":
201
  if submit and user_input.strip() != "":
202
  # Add user message to chat history
203
  st.session_state.chat_history.append({"role": "user", "content": user_input})
204
-
205
  if not st.session_state.file_ids:
206
  st.error("Please process PDFs first.")
207
  else:
@@ -209,7 +259,10 @@ if page == "Home":
209
  try:
210
  response, citations = chat_with_assistant(st.session_state.file_ids, user_input)
211
  # Add assistant response to chat history
 
 
212
  st.session_state.chat_history.append({"role": "assistant", "content": response+"\n\n"+"\n".join(citations)})
 
213
  except Exception as e:
214
  st.error(f"Error generating response: {str(e)}")
215
 
 
36
  st.session_state.assistant_id = None
37
  if 'thread_id' not in st.session_state:
38
  st.session_state.thread_id = None
39
+ if 'file_ids' not in st.session_state:
40
+ st.session_state.file_ids = []
41
 
42
  # ---------------------- Helper Functions ----------------------
43
 
44
  def get_vector_stores():
45
  try:
 
46
  vector_stores = client.beta.vector_stores.list()
47
  return vector_stores
48
  except Exception as e:
 
104
  return assistant.id
105
 
106
  def chat_with_assistant(file_ids, user_message):
107
+ print("----- Starting chat_with_assistant -----")
108
+ print("Received file_ids:", file_ids)
109
+ print("Received user_message:", user_message)
110
+
111
+ # Create attachments for each file_id
112
  attachments = [{"file_id": file_id, "tools": [{"type": "file_search"}]} for file_id in file_ids]
113
+ print("Attachments created:", attachments)
114
+
115
  if st.session_state.thread_id is None:
116
+ print("No existing thread_id found. Creating a new thread.")
117
  thread = client.beta.threads.create(
118
  messages=[
119
  {
 
124
  ]
125
  )
126
  st.session_state.thread_id = thread.id
127
+ print("New thread created with id:", st.session_state.thread_id)
128
  else:
129
+ print(f"Existing thread_id found: {st.session_state.thread_id}. Adding message to the thread.")
130
+ # Add a message to the existing thread without updating thread_id
131
+ message = client.beta.threads.messages.create(
132
  thread_id=st.session_state.thread_id,
133
  role="user",
134
  content=user_message,
135
  attachments=attachments
136
  )
137
+ print("Message added to thread with id:", message.id)
138
+ # Do NOT update st.session_state.thread_id here
139
+
140
+ # Retrieve the thread object using the thread_id
141
+ try:
142
+ thread = client.beta.threads.retrieve(thread_id=st.session_state.thread_id)
143
+ print("Retrieved thread:", thread)
144
+ except Exception as e:
145
+ print(f"Error retrieving thread with id {st.session_state.thread_id}: {e}")
146
+ return "An error occurred while processing your request.", []
147
+
148
+ # Debugging tool resources
149
+ try:
150
+ tool_resources = thread.tool_resources.file_search
151
+ print("Thread tool resources (file_search):", tool_resources)
152
+ except AttributeError:
153
+ print("No tool_resources.file_search found in thread.")
154
+
155
+ print("Assistant ID:", st.session_state.assistant_id)
156
+ print("Thread ID:", thread.id)
157
+
158
+ # Create and poll the run
159
+ try:
160
+ run = client.beta.threads.runs.create_and_poll(
161
+ thread_id=thread.id, assistant_id=st.session_state.assistant_id
162
+ )
163
+ print("Run created and polled:", run)
164
+ except Exception as e:
165
+ print("Error during run creation and polling:", e)
166
+ return "An error occurred while processing your request.", []
167
+
168
+ # Retrieve messages
169
+ try:
170
+ messages = list(client.beta.threads.messages.list(thread_id=thread.id, run_id=run.id))
171
+ print("Retrieved messages:", messages)
172
+ except Exception as e:
173
+ print("Error retrieving messages:", e)
174
+ return "An error occurred while retrieving messages.", []
175
+
176
+ # Process the first message content
177
+ if messages and messages[0].content:
178
+ message_content = messages[0].content[0].text
179
+ print("Raw message content:", message_content)
180
+
181
+ annotations = message_content.annotations
182
+ print("Annotations found:", annotations)
183
+
184
+ citations = []
185
+ for index, annotation in enumerate(annotations):
186
+ print(f"Processing annotation {index}: {annotation.text}")
187
+ message_content.value = message_content.value.replace(annotation.text, f"[{index}]")
188
+ if file_citation := getattr(annotation, "file_citation", None):
189
+ try:
190
+ cited_file = client.files.retrieve(file_citation.file_id)
191
+ citation_entry = f"[{index}] {cited_file.filename}"
192
+ citations.append(citation_entry)
193
+ print(f"Citation added: {citation_entry}")
194
+ except Exception as e:
195
+ print(f"Error retrieving cited file for annotation {index}: {e}")
196
+
197
+ print("Final message content after replacements:", message_content.value)
198
+ print("All citations:", citations)
199
+ print("----- Ending chat_with_assistant -----")
200
+ return message_content.value, citations
201
+ else:
202
+ print("No messages or content found in the retrieved messages.")
203
+ return "No response received from the assistant.", []
204
 
205
 
206
 
 
251
  if submit and user_input.strip() != "":
252
  # Add user message to chat history
253
  st.session_state.chat_history.append({"role": "user", "content": user_input})
254
+ print("chat history:", st.session_state.chat_history)
255
  if not st.session_state.file_ids:
256
  st.error("Please process PDFs first.")
257
  else:
 
259
  try:
260
  response, citations = chat_with_assistant(st.session_state.file_ids, user_input)
261
  # Add assistant response to chat history
262
+ print("response:", response)
263
+ print("citations:", citations)
264
  st.session_state.chat_history.append({"role": "assistant", "content": response+"\n\n"+"\n".join(citations)})
265
+ print("chat history:", st.session_state.chat_history)
266
  except Exception as e:
267
  st.error(f"Error generating response: {str(e)}")
268