pvanand commited on
Commit
e08d293
·
verified ·
1 Parent(s): 564f142

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +50 -16
main.py CHANGED
@@ -178,10 +178,19 @@ prompt = ChatPromptTemplate.from_messages([
178
  ("placeholder", "{messages}"),
179
  ])
180
 
 
 
 
 
 
 
181
  def get_collection_files(collection_id: str, user_id: str) -> str:
182
- """Get list of files in the specified collection using the external API"""
 
 
 
183
  try:
184
- url = f"https://pvanand-documind-api-v2.hf.space/rag/get_collection_files"
185
  params = {
186
  "collection_id": collection_id,
187
  "user_id": user_id
@@ -189,16 +198,28 @@ def get_collection_files(collection_id: str, user_id: str) -> str:
189
  headers = {
190
  'accept': 'application/json'
191
  }
192
- response = requests.post(url, params=params, headers=headers, data='')
 
 
 
 
193
 
194
  if response.status_code == 200:
 
195
  return response.text
196
  else:
197
- logger.error(f"Error from API: {response.text}")
198
- return f"Error getting files: {response.text}"
 
 
 
 
 
 
 
199
  except Exception as e:
200
- logger.error(f"Error getting collection files: {str(e)}")
201
- return f"Error getting files: {str(e)}"
202
 
203
  def format_for_model(state: dict, config: Optional[RunnableConfig] = None) -> list[BaseMessage]:
204
  """
@@ -216,15 +237,28 @@ def format_for_model(state: dict, config: Optional[RunnableConfig] = None) -> li
216
  collection_id = thread_config.get("collection_id")
217
  user_id = thread_config.get("user_id")
218
 
219
- # Get files in the collection
220
- collection_files = get_collection_files(collection_id, user_id) if collection_id and user_id else "No files available"
221
- logger.info(f"Fetching collection for userid {user_id} and collection_id {collection_id} || Results: {collection_files}")
222
-
223
- # Format using the prompt template
224
- return prompt.invoke({
225
- "collection_files": collection_files,
226
- "messages": state.get("messages", []) # Safely get messages with default empty list
227
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
  async def clean_tool_input(tool_input: str):
230
  # Use regex to parse the first key and value
 
178
  ("placeholder", "{messages}"),
179
  ])
180
 
181
+ import requests
182
+ from requests.exceptions import RequestException, Timeout
183
+ import logging
184
+ from typing import Optional
185
+
186
+
187
  def get_collection_files(collection_id: str, user_id: str) -> str:
188
+ """
189
+ Synchronously get list of files in the specified collection using the external API
190
+ with proper timeout and error handling.
191
+ """
192
  try:
193
+ url = "https://pvanand-documind-api-v2.hf.space/rag/get_collection_files"
194
  params = {
195
  "collection_id": collection_id,
196
  "user_id": user_id
 
198
  headers = {
199
  'accept': 'application/json'
200
  }
201
+
202
+ logger.debug(f"Requesting collection files for user {user_id}, collection {collection_id}")
203
+
204
+ # Set timeout to 5 seconds
205
+ response = requests.post(url, params=params, headers=headers, data='', timeout=5)
206
 
207
  if response.status_code == 200:
208
+ logger.info(f"Successfully retrieved collection files: {response.text[:100]}...")
209
  return response.text
210
  else:
211
+ logger.error(f"API error (status {response.status_code}): {response.text}")
212
+ return f"Error fetching files (status {response.status_code})"
213
+
214
+ except Timeout:
215
+ logger.error("Timeout while fetching collection files")
216
+ return "Error: Request timed out"
217
+ except RequestException as e:
218
+ logger.error(f"Network error fetching collection files: {str(e)}")
219
+ return f"Error: Network issue - {str(e)}"
220
  except Exception as e:
221
+ logger.error(f"Error fetching collection files: {str(e)}", exc_info=True)
222
+ return f"Error fetching files: {str(e)}"
223
 
224
  def format_for_model(state: dict, config: Optional[RunnableConfig] = None) -> list[BaseMessage]:
225
  """
 
237
  collection_id = thread_config.get("collection_id")
238
  user_id = thread_config.get("user_id")
239
 
240
+ try:
241
+ # Get files in the collection with timeout protection
242
+ if collection_id and user_id:
243
+ collection_files = get_collection_files(collection_id, user_id)
244
+ else:
245
+ collection_files = "No files available"
246
+
247
+ logger.info(f"Fetching collection for userid {user_id} and collection_id {collection_id} || Results: {collection_files[:100]}...")
248
+
249
+ # Format using the prompt template
250
+ return prompt.invoke({
251
+ "collection_files": collection_files,
252
+ "messages": state.get("messages", [])
253
+ })
254
+
255
+ except Exception as e:
256
+ logger.error(f"Error in format_for_model: {str(e)}", exc_info=True)
257
+ # Return a basic format if there's an error
258
+ return prompt.invoke({
259
+ "collection_files": "Error fetching files",
260
+ "messages": state.get("messages", [])
261
+ })
262
 
263
  async def clean_tool_input(tool_input: str):
264
  # Use regex to parse the first key and value