GoodLuckChuck commited on
Commit
ffb1796
·
verified ·
1 Parent(s): d6a0e0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -143
app.py CHANGED
@@ -62,16 +62,21 @@ def api_download_file(task_id: str, file_name: str, download_dir: str = "downloa
62
  print(f"Error saving file for task {task_id}: {e}")
63
  return None
64
 
65
- def api_submit_answers(processed_answers: List[Dict[str, str]]) -> Dict[str, Any]:
66
  """Submit processed answers to the course API."""
67
  try:
 
68
  submission_data = {
69
  "username": USERNAME,
70
  "agent_code": AGENT_CODE_IDENTIFIER,
71
- "answers": processed_answers # Each answer now has task_id and submitted_answer fields
72
  }
73
 
74
- print(f"Submitting answers: {json.dumps(submission_data, indent=2)}") # Added logging
 
 
 
 
75
 
76
  response = requests.post(
77
  f"{API_BASE_URL}/submit",
@@ -81,32 +86,58 @@ def api_submit_answers(processed_answers: List[Dict[str, str]]) -> Dict[str, Any
81
  response.raise_for_status()
82
 
83
  result = response.json()
84
- print(f"Submission successful! API Response: {result}")
85
  return result
86
 
87
  except requests.exceptions.RequestException as e:
88
- print(f"Error submitting answers to API: {e}")
89
  if hasattr(e.response, 'text'):
90
  print(f"API Error Response: {e.response.text}")
91
  return {}
92
 
93
  # --- OpenAI Client Configuration ---
94
  try:
95
- OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY")
96
  if not OPENAI_API_KEY_VALUE:
97
  raise ValueError("OPENAI_API_KEY not found in environment variables")
98
 
99
- # Set the API key for the older version syntax
100
  openai.api_key = OPENAI_API_KEY_VALUE
101
- print("OpenAI client initialized successfully.")
 
 
 
 
 
 
 
102
  except Exception as e:
103
  print(f"Error initializing OpenAI client: {str(e)}")
104
- print("Please ensure OPENAI_API_KEY is properly set in Hugging Face Space secrets")
 
105
 
 
106
  LLM_MODEL = "gpt-3.5-turbo"
107
 
108
  # --- GAIA System Prompt ---
109
- GAIA_FINAL_ANSWER_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  # --- Pydantic Models ---
112
  class WebSearchInput(BaseModel):
@@ -198,105 +229,81 @@ class AIAgent:
198
  def process_question(self, task_id: str, question_text: str, file_name: Optional[str] = None, max_iterations: int = 5) -> Dict[str, Any]:
199
  self.reasoning_trace = []
200
 
201
- user_message_content = question_text
202
- if file_name:
203
- user_message_content += f" (Note: The file is located at '{file_name}')"
204
-
205
- if not self.client.api_key:
206
- self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
207
- return {
208
- "task_id": task_id,
209
- "model_answer": "ERROR: Agent configuration issue.",
210
- "reasoning_trace": self.reasoning_trace
211
- }
212
-
213
- self._log_step(f"Processing Task ID: {task_id}")
214
- self._log_step(f"Original Question: {question_text}")
215
- if file_name:
216
- self._log_step(f"Associated File: {file_name}")
217
-
218
- agent_system_prompt = (
219
- "You are a helpful AI assistant. Your goal is to answer the user's question accurately. "
220
- "Think step-by-step. If you need to use a tool to find information or perform a calculation, "
221
- "you will be given the option to call available functions. "
222
- "After any tool use, review the information and continue. "
223
- "When you have enough information to answer the question, provide your comprehensive thought process. "
224
- f"{GAIA_FINAL_ANSWER_SYSTEM_PROMPT}"
225
- )
226
-
227
- messages = [{"role": "system", "content": agent_system_prompt}]
228
- messages.append({"role": "user", "content": user_message_content})
229
-
230
- for iteration in range(max_iterations):
231
- self._log_step(f"\nIteration {iteration + 1}")
232
- try:
233
- self._log_step("🤖 Assistant thinking...", {"current_messages_for_llm_count": len(messages)})
234
- response = self.client.ChatCompletion.create(
235
- model=LLM_MODEL,
236
- messages=messages,
237
- functions=self.tools_available,
238
- function_call="auto"
239
- )
240
- response_message = response.choices[0].message
241
-
242
- # Convert the OpenAI response message to a dict for consistency
243
- if hasattr(response_message, 'to_dict'):
244
- response_message = response_message.to_dict()
245
- messages.append(response_message)
246
-
247
- if response_message.get('function_call'):
248
- self._log_step("🛠️ Assistant decided to use tools:")
249
- function_call = response_message['function_call']
250
- function_name = function_call['name']
251
- function_args = json.loads(function_call['arguments'])
252
- self._log_step(f" - Tool: {function_name}, Args: {function_args}")
253
-
254
- if function_name in self.tool_executors:
255
- tool_output = self.tool_executors[function_name](function_args)
256
- self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
257
- messages.append({
258
- "role": "function",
259
- "name": function_name,
260
- "content": json.dumps(tool_output)
261
- })
262
- else:
263
- self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
264
- messages.append({
265
- "role": "function",
266
- "name": function_name,
267
- "content": json.dumps({"error": f"Tool {function_name} not found."})
268
- })
269
- else:
270
- self._log_step("✅ Assistant providing final answer (or thought process leading to it).")
271
- llm_final_content = response_message.get('content', '')
272
- self._log_step("Raw LLM Final Content:\n" + "="*20 + f"\n{llm_final_content}\n" + "="*20)
273
-
274
- if "FINAL ANSWER:" in llm_final_content:
275
- final_answer_text = llm_final_content.split("FINAL ANSWER:", 1)[1].strip()
276
- else:
277
- self._log_step("Warning: 'FINAL ANSWER:' template not found in LLM response.")
278
- final_answer_text = llm_final_content
279
-
280
- return {
281
- "task_id": task_id,
282
- "model_answer": final_answer_text,
283
- "reasoning_trace": self.reasoning_trace,
284
- "full_llm_output": llm_final_content
285
- }
286
-
287
- except Exception as e:
288
- self._log_step(f"🚨 An error occurred during LLM call or tool execution: {str(e)}")
289
- return {
290
- "task_id": task_id,
291
- "model_answer": f"ERROR: An exception occurred - {str(e)}",
292
- "reasoning_trace": self.reasoning_trace
293
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
- self._log_step("⚠️ Agent reached maximum iterations without a conclusive answer.")
 
296
  return {
297
  "task_id": task_id,
298
- "model_answer": "ERROR: Agent reached maximum iterations.",
299
- "reasoning_trace": self.reasoning_trace
300
  }
301
 
302
  # --- FastAPI App ---
@@ -327,52 +334,90 @@ async def root():
327
 
328
  @app.post("/process")
329
  async def process_questions():
330
- """Endpoint to process questions and submit answers."""
331
- if not global_agent:
332
- raise HTTPException(status_code=500, detail="AI Agent not initialized")
333
-
334
  try:
335
- api_questions = api_get_questions()
336
- if not api_questions:
337
- return {"status": "error", "message": "No questions retrieved from API"}
338
-
339
- all_submission_answers = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
- for question_data in api_questions:
342
- task_id = question_data.get("task_id")
343
- question_text = question_data.get("question")
344
- original_file_name = question_data.get("file_name")
 
 
 
345
 
346
- if not task_id or not question_text:
 
347
  continue
348
 
349
- local_file_path = None
350
- if original_file_name:
351
- local_file_path = api_download_file(task_id, original_file_name)
352
-
353
- agent_result = global_agent.process_question(
354
- task_id=task_id,
355
- question_text=question_text,
356
- file_name=local_file_path
357
- )
358
 
359
- clean_answer = agent_result.get("model_answer", "ERROR: No answer from agent")
360
- all_submission_answers.append({
361
- "task_id": task_id,
362
- "submitted_answer": clean_answer # Changed from "answer" to "submitted_answer"
363
- })
 
 
 
 
 
 
364
 
365
- if all_submission_answers:
366
- submission_result = api_submit_answers(processed_answers=all_submission_answers)
367
- return {
368
- "status": "success",
369
- "processed_questions": len(all_submission_answers),
370
- "submission_result": submission_result
371
- }
372
- else:
373
- return {"status": "error", "message": "No answers were generated"}
374
-
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  except Exception as e:
 
376
  raise HTTPException(status_code=500, detail=str(e))
377
 
378
  if __name__ == "__main__":
 
62
  print(f"Error saving file for task {task_id}: {e}")
63
  return None
64
 
65
+ def api_submit_answers(processed_answers: List[Dict[str, Any]]) -> Dict[str, Any]:
66
  """Submit processed answers to the course API."""
67
  try:
68
+ # Format answers for submission
69
  submission_data = {
70
  "username": USERNAME,
71
  "agent_code": AGENT_CODE_IDENTIFIER,
72
+ "answers": processed_answers
73
  }
74
 
75
+ print("\n=== Submission Details ===")
76
+ print(f"Username: {USERNAME}")
77
+ print(f"Agent Code: {AGENT_CODE_IDENTIFIER}")
78
+ print(f"Number of Answers: {len(processed_answers)}")
79
+ print(f"Full Submission Data:\n{json.dumps(submission_data, indent=2)}")
80
 
81
  response = requests.post(
82
  f"{API_BASE_URL}/submit",
 
86
  response.raise_for_status()
87
 
88
  result = response.json()
89
+ print(f"\nSubmission Response:\n{json.dumps(result, indent=2)}")
90
  return result
91
 
92
  except requests.exceptions.RequestException as e:
93
+ print(f"\nError submitting answers to API: {str(e)}")
94
  if hasattr(e.response, 'text'):
95
  print(f"API Error Response: {e.response.text}")
96
  return {}
97
 
98
  # --- OpenAI Client Configuration ---
99
  try:
100
+ OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY", "").strip()
101
  if not OPENAI_API_KEY_VALUE:
102
  raise ValueError("OPENAI_API_KEY not found in environment variables")
103
 
104
+ # Configure OpenAI client
105
  openai.api_key = OPENAI_API_KEY_VALUE
106
+
107
+ # Test the API key with a simple completion to verify it works
108
+ test_response = openai.ChatCompletion.create(
109
+ model="gpt-3.5-turbo",
110
+ messages=[{"role": "user", "content": "test"}],
111
+ max_tokens=5
112
+ )
113
+ print("OpenAI client initialized and tested successfully.")
114
  except Exception as e:
115
  print(f"Error initializing OpenAI client: {str(e)}")
116
+ print("Please ensure OPENAI_API_KEY is properly set in environment variables")
117
+ openai.api_key = None
118
 
119
+ # --- Constants ---
120
  LLM_MODEL = "gpt-3.5-turbo"
121
 
122
  # --- GAIA System Prompt ---
123
+ GAIA_FINAL_ANSWER_SYSTEM_PROMPT = """You are a precise AI assistant focused on providing accurate, concise answers. Follow these rules strictly:
124
+
125
+ 1. For numerical answers:
126
+ - Use plain numbers without commas or units (unless specifically requested)
127
+ - Example: "FINAL ANSWER: 42" (not "FINAL ANSWER: 42%" or "FINAL ANSWER: 42.00")
128
+
129
+ 2. For text answers:
130
+ - Provide the shortest possible answer without articles or abbreviations
131
+ - Use full names for cities, countries, and proper nouns
132
+ - Example: "FINAL ANSWER: Paris" (not "FINAL ANSWER: The city of Paris")
133
+
134
+ 3. For list answers:
135
+ - Use comma-separated values without spaces after commas
136
+ - Follow number and text rules for each element
137
+ - Example: "FINAL ANSWER: 1,Paris,42,London"
138
+
139
+ Always end your response with:
140
+ FINAL ANSWER: [your answer following the above rules]"""
141
 
142
  # --- Pydantic Models ---
143
  class WebSearchInput(BaseModel):
 
229
  def process_question(self, task_id: str, question_text: str, file_name: Optional[str] = None, max_iterations: int = 5) -> Dict[str, Any]:
230
  self.reasoning_trace = []
231
 
232
+ try:
233
+ user_message_content = question_text
234
+ if file_name:
235
+ # Download and process file if needed
236
+ local_file_path = api_download_file(task_id, file_name)
237
+ if local_file_path:
238
+ user_message_content += f"\nFile content is available at: {local_file_path}"
239
+
240
+ if not self.client.api_key:
241
+ self._log_step("ERROR: OpenAI client not initialized.")
242
+ return self._format_answer(task_id, "ERROR: Agent configuration issue.", [])
243
+
244
+ self._log_step(f"Processing Task ID: {task_id}")
245
+ self._log_step(f"Question: {question_text}")
246
+
247
+ messages = [
248
+ {
249
+ "role": "system",
250
+ "content": GAIA_FINAL_ANSWER_SYSTEM_PROMPT
251
+ },
252
+ {
253
+ "role": "user",
254
+ "content": user_message_content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  }
256
+ ]
257
+
258
+ final_answer = None
259
+ for iteration in range(max_iterations):
260
+ try:
261
+ self._log_step(f"Iteration {iteration + 1}")
262
+ response = self.client.ChatCompletion.create(
263
+ model=LLM_MODEL,
264
+ messages=messages,
265
+ temperature=0.1,
266
+ max_tokens=1000
267
+ )
268
+
269
+ assistant_message = response.choices[0].message.content
270
+ self._log_step(f"Assistant response: {assistant_message}")
271
+
272
+ # Extract final answer if present
273
+ if "FINAL ANSWER:" in assistant_message:
274
+ final_answer = assistant_message.split("FINAL ANSWER:")[-1].strip()
275
+ self._log_step(f"Extracted final answer: {final_answer}")
276
+ break
277
+
278
+ messages.append({"role": "assistant", "content": assistant_message})
279
+
280
+ except Exception as e:
281
+ error_msg = str(e)
282
+ self._log_step(f"Error in iteration {iteration + 1}: {error_msg}")
283
+
284
+ # If it's an API key error, stop processing
285
+ if "api_key" in error_msg.lower() or "authentication" in error_msg.lower():
286
+ return self._format_answer(task_id, "ERROR: OpenAI API authentication failed", self.reasoning_trace)
287
+
288
+ # For other errors, try the next iteration
289
+ continue
290
+
291
+ if not final_answer:
292
+ self._log_step("No final answer found after all iterations")
293
+ return self._format_answer(task_id, "ERROR: No final answer generated", self.reasoning_trace)
294
+
295
+ return self._format_answer(task_id, final_answer, self.reasoning_trace)
296
+
297
+ except Exception as e:
298
+ self._log_step(f"Critical error processing question: {str(e)}")
299
+ return self._format_answer(task_id, f"ERROR: {str(e)}", self.reasoning_trace)
300
 
301
+ def _format_answer(self, task_id: str, answer: str, trace: List[Dict]) -> Dict[str, Any]:
302
+ """Format the answer according to the course API requirements."""
303
  return {
304
  "task_id": task_id,
305
+ "model_answer": answer.strip(),
306
+ "reasoning_trace": json.dumps(trace) # Convert trace to JSON string
307
  }
308
 
309
  # --- FastAPI App ---
 
334
 
335
  @app.post("/process")
336
  async def process_questions():
337
+ """Process all questions and submit answers."""
 
 
 
338
  try:
339
+ # Validate OpenAI API key
340
+ if not openai.api_key:
341
+ raise HTTPException(
342
+ status_code=500,
343
+ detail="OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
344
+ )
345
+
346
+ # Test API key validity
347
+ try:
348
+ test_response = openai.ChatCompletion.create(
349
+ model=LLM_MODEL,
350
+ messages=[{"role": "user", "content": "test"}],
351
+ max_tokens=5
352
+ )
353
+ except Exception as e:
354
+ raise HTTPException(
355
+ status_code=500,
356
+ detail=f"OpenAI API key validation failed: {str(e)}"
357
+ )
358
+
359
+ # Initialize agent
360
+ agent = AIAgent(openai)
361
+
362
+ # Fetch questions
363
+ questions = api_get_questions()
364
+ if not questions:
365
+ raise HTTPException(status_code=500, detail="Failed to fetch questions from API")
366
 
367
+ print(f"\nProcessing {len(questions)} questions...")
368
+ processed_answers = []
369
+
370
+ for question in questions:
371
+ task_id = question.get("task_id")
372
+ question_text = question.get("question")
373
+ file_name = question.get("file_name")
374
 
375
+ if not all([task_id, question_text]):
376
+ print(f"Skipping invalid question: {question}")
377
  continue
378
 
379
+ print(f"\nProcessing question {task_id}")
380
+ print(f"Question text: {question_text}")
381
+ if file_name:
382
+ print(f"Associated file: {file_name}")
 
 
 
 
 
383
 
384
+ try:
385
+ answer = agent.process_question(task_id, question_text, file_name)
386
+ processed_answers.append(answer)
387
+ print(f"Answer for {task_id}: {answer['model_answer']}")
388
+ except Exception as e:
389
+ print(f"Error processing question {task_id}: {str(e)}")
390
+ processed_answers.append({
391
+ "task_id": task_id,
392
+ "model_answer": f"ERROR: Failed to process question - {str(e)}",
393
+ "reasoning_trace": json.dumps([{"error": str(e)}])
394
+ })
395
 
396
+ if not processed_answers:
397
+ raise HTTPException(
398
+ status_code=500,
399
+ detail="No answers were generated for any questions"
400
+ )
401
+
402
+ # Submit answers
403
+ submission_result = api_submit_answers(processed_answers)
404
+ if not submission_result:
405
+ raise HTTPException(
406
+ status_code=500,
407
+ detail="Failed to submit answers to API"
408
+ )
409
+
410
+ return {
411
+ "status": "success",
412
+ "message": f"Processed {len(processed_answers)} questions",
413
+ "submission_result": submission_result,
414
+ "processed_answers": processed_answers
415
+ }
416
+
417
+ except HTTPException as he:
418
+ raise he
419
  except Exception as e:
420
+ print(f"Error in process_questions: {str(e)}")
421
  raise HTTPException(status_code=500, detail=str(e))
422
 
423
  if __name__ == "__main__":