Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,42 +4,50 @@ import requests
|
|
| 4 |
from typing import List, Dict, Any, Optional
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
from openai import OpenAI
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
from fastapi import FastAPI, HTTPException
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
import uvicorn
|
| 11 |
from datetime import datetime
|
| 12 |
|
| 13 |
-
# --- API Configuration
|
| 14 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
HEADERS = {"Content-Type": "application/json", "accept": "application/json"}
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# --- API Interaction Functions ---
|
| 18 |
def api_get_questions() -> List[Dict[str, Any]]:
|
| 19 |
"""Fetch questions from the course API."""
|
| 20 |
try:
|
|
|
|
| 21 |
response = requests.get(f"{API_BASE_URL}/questions", headers=HEADERS)
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
questions = response.json()
|
|
|
|
|
|
|
| 24 |
return questions
|
| 25 |
except requests.exceptions.RequestException as e:
|
| 26 |
print(f"Error fetching questions from API: {e}")
|
| 27 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def api_download_file(task_id: str, file_name: str, download_dir: str = "downloaded_gaia_files") -> Optional[str]:
|
| 30 |
"""Download a file associated with a task from the course API."""
|
| 31 |
try:
|
| 32 |
-
# Create download directory if it doesn't exist
|
| 33 |
os.makedirs(download_dir, exist_ok=True)
|
| 34 |
-
|
| 35 |
-
# Construct the file download URL
|
| 36 |
download_url = f"{API_BASE_URL}/file/{task_id}"
|
| 37 |
|
| 38 |
-
# Download the file
|
| 39 |
response = requests.get(download_url, headers=HEADERS)
|
| 40 |
response.raise_for_status()
|
| 41 |
|
| 42 |
-
# Save the file
|
| 43 |
local_file_path = os.path.join(download_dir, file_name)
|
| 44 |
with open(local_file_path, 'wb') as f:
|
| 45 |
f.write(response.content)
|
|
@@ -54,12 +62,12 @@ def api_download_file(task_id: str, file_name: str, download_dir: str = "downloa
|
|
| 54 |
print(f"Error saving file for task {task_id}: {e}")
|
| 55 |
return None
|
| 56 |
|
| 57 |
-
def api_submit_answers(
|
| 58 |
"""Submit processed answers to the course API."""
|
| 59 |
try:
|
| 60 |
submission_data = {
|
| 61 |
-
"username":
|
| 62 |
-
"agent_code":
|
| 63 |
"answers": processed_answers
|
| 64 |
}
|
| 65 |
|
|
@@ -81,7 +89,7 @@ def api_submit_answers(username: str, agent_code_identifier: str, processed_answ
|
|
| 81 |
# --- OpenAI Client Configuration ---
|
| 82 |
OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY")
|
| 83 |
if not OPENAI_API_KEY_VALUE:
|
| 84 |
-
print("OPENAI_API_KEY not found in environment variables. Attempting to load from a local .env file
|
| 85 |
load_dotenv()
|
| 86 |
OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY")
|
| 87 |
|
|
@@ -102,25 +110,22 @@ LLM_MODEL = "gpt-3.5-turbo"
|
|
| 102 |
# --- GAIA System Prompt ---
|
| 103 |
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"""
|
| 104 |
|
| 105 |
-
# ---
|
| 106 |
class WebSearchInput(BaseModel):
|
| 107 |
query: str = Field(..., description="The search query to find information on the web.")
|
| 108 |
|
| 109 |
class CalculatorInput(BaseModel):
|
| 110 |
-
expression: str = Field(..., description="The mathematical expression to evaluate
|
| 111 |
|
| 112 |
class ImageAnalysisInput(BaseModel):
|
| 113 |
image_url: Optional[str] = Field(None, description="The URL of the image to analyze.")
|
| 114 |
-
file_name: Optional[str] = Field(None, description="The file name of the image
|
| 115 |
prompt: str = Field(..., description="Specific question or instruction for analyzing the image.")
|
| 116 |
|
| 117 |
-
# ---
|
| 118 |
-
# In a real scenario, these would interact with actual services or models.
|
| 119 |
-
|
| 120 |
def execute_web_search(query: str) -> Dict[str, Any]:
|
| 121 |
"""Mock web search tool."""
|
| 122 |
print(f" 🔎 [Tool Called] WebSearch with query: '{query}'")
|
| 123 |
-
# Simulate finding information
|
| 124 |
if "capital of france" in query.lower():
|
| 125 |
return {"result": "Paris is the capital of France.", "source": "mock_wikipedia.org"}
|
| 126 |
elif "tallest building" in query.lower():
|
|
@@ -131,8 +136,6 @@ def execute_calculator(expression: str) -> Dict[str, Any]:
|
|
| 131 |
"""Mock calculator tool."""
|
| 132 |
print(f" 🧮 [Tool Called] Calculator with expression: '{expression}'")
|
| 133 |
try:
|
| 134 |
-
# IMPORTANT: eval() is unsafe with arbitrary user input.
|
| 135 |
-
# A production system would use a dedicated math parsing library.
|
| 136 |
result = eval(expression, {"__builtins__": {}}, {})
|
| 137 |
return {"result": str(result)}
|
| 138 |
except Exception as e:
|
|
@@ -148,14 +151,12 @@ def execute_image_analysis(image_url: Optional[str], file_name: Optional[str], p
|
|
| 148 |
return {"description": "The image contains various fruits, possibly apples and bananas.", "objects_detected": ["apple", "banana"]}
|
| 149 |
return {"description": f"Could not analyze image '{identifier}' for prompt '{prompt}'. Details unavailable.", "objects_detected": []}
|
| 150 |
|
| 151 |
-
# ---
|
| 152 |
-
|
| 153 |
class AIAgent:
|
| 154 |
def __init__(self, openai_client):
|
| 155 |
self.client = openai_client
|
| 156 |
self.reasoning_trace = []
|
| 157 |
-
|
| 158 |
-
# Update image analysis parameters in tools
|
| 159 |
self.tools_available = [
|
| 160 |
{
|
| 161 |
"type": "function",
|
|
@@ -178,23 +179,11 @@ class AIAgent:
|
|
| 178 |
"function": {
|
| 179 |
"name": "image_analysis",
|
| 180 |
"description": "Analyzes an image given its file path.",
|
| 181 |
-
"parameters":
|
| 182 |
-
"type": "object",
|
| 183 |
-
"properties": {
|
| 184 |
-
"image_identifier": {
|
| 185 |
-
"type": "string",
|
| 186 |
-
"description": "The file path of the image to analyze"
|
| 187 |
-
},
|
| 188 |
-
"prompt": {
|
| 189 |
-
"type": "string",
|
| 190 |
-
"description": "Specific question or instruction for analyzing the image"
|
| 191 |
-
}
|
| 192 |
-
},
|
| 193 |
-
"required": ["prompt"]
|
| 194 |
-
}
|
| 195 |
}
|
| 196 |
}
|
| 197 |
]
|
|
|
|
| 198 |
self.tool_executors = {
|
| 199 |
"web_search": lambda params: execute_web_search(**params),
|
| 200 |
"calculator": lambda params: execute_calculator(**params),
|
|
@@ -211,18 +200,9 @@ class AIAgent:
|
|
| 211 |
def process_question(self, task_id: str, question_text: str, file_name: Optional[str] = None, max_iterations: int = 5) -> Dict[str, Any]:
|
| 212 |
self.reasoning_trace = []
|
| 213 |
|
| 214 |
-
# Handle file path for the agent
|
| 215 |
-
file_path_for_agent = None
|
| 216 |
-
if file_name:
|
| 217 |
-
file_path_for_agent = os.path.join('/home/nik/hf-agent-class/final test', file_name)
|
| 218 |
-
if not os.path.exists(file_path_for_agent):
|
| 219 |
-
self._log_step(f"Warning: File not found at {file_path_for_agent}")
|
| 220 |
-
file_path_for_agent = None
|
| 221 |
-
|
| 222 |
-
# Update user message to include file information
|
| 223 |
user_message_content = question_text
|
| 224 |
-
if
|
| 225 |
-
user_message_content += f" (Note: The file is located at '{
|
| 226 |
|
| 227 |
if not self.client:
|
| 228 |
self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
|
|
@@ -234,20 +214,16 @@ class AIAgent:
|
|
| 234 |
|
| 235 |
self._log_step(f"Processing Task ID: {task_id}")
|
| 236 |
self._log_step(f"Original Question: {question_text}")
|
| 237 |
-
if
|
| 238 |
-
self._log_step(f"Associated File: {
|
| 239 |
|
| 240 |
-
# Initial system prompt for the agent's overall behavior,
|
| 241 |
-
# including the GAIA final answer format from the start.
|
| 242 |
-
# This encourages the LLM to structure its thoughts and final output correctly.
|
| 243 |
-
# (This is Option A from the thought process - integrating GAIA format early)
|
| 244 |
agent_system_prompt = (
|
| 245 |
"You are a helpful AI assistant. Your goal is to answer the user's question accurately. "
|
| 246 |
"Think step-by-step. If you need to use a tool to find information or perform a calculation, "
|
| 247 |
"you will be given the option to call available functions. "
|
| 248 |
"After any tool use, review the information and continue. "
|
| 249 |
"When you have enough information to answer the question, provide your comprehensive thought process. "
|
| 250 |
-
f"{GAIA_FINAL_ANSWER_SYSTEM_PROMPT}"
|
| 251 |
)
|
| 252 |
|
| 253 |
messages = [{"role": "system", "content": agent_system_prompt}]
|
|
@@ -261,30 +237,26 @@ class AIAgent:
|
|
| 261 |
model=LLM_MODEL,
|
| 262 |
messages=messages,
|
| 263 |
tools=self.tools_available,
|
| 264 |
-
tool_choice="auto"
|
| 265 |
)
|
| 266 |
response_message = response.choices[0].message
|
| 267 |
-
messages.append(response_message)
|
| 268 |
|
| 269 |
if response_message.tool_calls:
|
| 270 |
self._log_step("🛠️ Assistant decided to use tools:")
|
| 271 |
for tool_call in response_message.tool_calls:
|
| 272 |
function_name = tool_call.function.name
|
| 273 |
-
function_args = json.loads(tool_call.function.arguments)
|
| 274 |
self._log_step(f" - Tool: {function_name}, Args: {function_args}")
|
| 275 |
|
| 276 |
if function_name in self.tool_executors:
|
| 277 |
-
# Automatically pass file_name to image_analysis if it's not in args but available
|
| 278 |
-
if function_name == "image_analysis" and 'file_name' not in function_args and file_path_for_agent:
|
| 279 |
-
function_args['image_identifier'] = file_path_for_agent
|
| 280 |
-
|
| 281 |
tool_output = self.tool_executors[function_name](function_args)
|
| 282 |
self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
|
| 283 |
messages.append({
|
| 284 |
"tool_call_id": tool_call.id,
|
| 285 |
"role": "tool",
|
| 286 |
"name": function_name,
|
| 287 |
-
"content": json.dumps(tool_output)
|
| 288 |
})
|
| 289 |
else:
|
| 290 |
self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
|
|
@@ -294,20 +266,16 @@ class AIAgent:
|
|
| 294 |
"name": function_name,
|
| 295 |
"content": json.dumps({"error": f"Tool {function_name} not found."})
|
| 296 |
})
|
| 297 |
-
else:
|
| 298 |
self._log_step("✅ Assistant providing final answer (or thought process leading to it).")
|
| 299 |
llm_final_content = response_message.content
|
| 300 |
self._log_step("Raw LLM Final Content:\n" + "="*20 + f"\n{llm_final_content}\n" + "="*20)
|
| 301 |
|
| 302 |
-
# Extract the answer part after "FINAL ANSWER:"
|
| 303 |
-
# The GAIA_FINAL_ANSWER_SYSTEM_PROMPT should guide the LLM to produce this.
|
| 304 |
if "FINAL ANSWER:" in llm_final_content:
|
| 305 |
final_answer_text = llm_final_content.split("FINAL ANSWER:", 1)[1].strip()
|
| 306 |
else:
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
self._log_step("Warning: 'FINAL ANSWER:' template not found in LLM response. Using entire content with a note.")
|
| 310 |
-
final_answer_text = llm_final_content + " (Warning: FINAL ANSWER template not strictly followed by LLM)"
|
| 311 |
|
| 312 |
return {
|
| 313 |
"task_id": task_id,
|
|
@@ -331,11 +299,9 @@ class AIAgent:
|
|
| 331 |
"reasoning_trace": self.reasoning_trace
|
| 332 |
}
|
| 333 |
|
| 334 |
-
|
| 335 |
-
# Initialize FastAPI app
|
| 336 |
app = FastAPI(title="AI Agent API")
|
| 337 |
|
| 338 |
-
# Add CORS middleware
|
| 339 |
app.add_middleware(
|
| 340 |
CORSMiddleware,
|
| 341 |
allow_origins=["*"],
|
|
@@ -366,14 +332,12 @@ async def process_questions():
|
|
| 366 |
raise HTTPException(status_code=500, detail="AI Agent not initialized")
|
| 367 |
|
| 368 |
try:
|
| 369 |
-
# Fetch questions
|
| 370 |
api_questions = api_get_questions()
|
| 371 |
if not api_questions:
|
| 372 |
return {"status": "error", "message": "No questions retrieved from API"}
|
| 373 |
|
| 374 |
all_submission_answers = []
|
| 375 |
|
| 376 |
-
# Process each question
|
| 377 |
for question_data in api_questions:
|
| 378 |
task_id = question_data.get("task_id")
|
| 379 |
question_text = question_data.get("question")
|
|
@@ -386,7 +350,6 @@ async def process_questions():
|
|
| 386 |
if original_file_name:
|
| 387 |
local_file_path = api_download_file(task_id, original_file_name)
|
| 388 |
|
| 389 |
-
# Process question
|
| 390 |
agent_result = global_agent.process_question(
|
| 391 |
task_id=task_id,
|
| 392 |
question_text=question_text,
|
|
@@ -399,13 +362,8 @@ async def process_questions():
|
|
| 399 |
"answer": clean_answer
|
| 400 |
})
|
| 401 |
|
| 402 |
-
# Submit answers
|
| 403 |
if all_submission_answers:
|
| 404 |
-
submission_result = api_submit_answers(
|
| 405 |
-
username=GoodLuckChuck,
|
| 406 |
-
agent_code_identifier=GoodLuckChuck_Agent_v1,
|
| 407 |
-
processed_answers=all_submission_answers
|
| 408 |
-
)
|
| 409 |
return {
|
| 410 |
"status": "success",
|
| 411 |
"processed_questions": len(all_submission_answers),
|
|
@@ -417,109 +375,6 @@ async def process_questions():
|
|
| 417 |
except Exception as e:
|
| 418 |
raise HTTPException(status_code=500, detail=str(e))
|
| 419 |
|
| 420 |
-
|
| 421 |
-
# --- Main Execution Example ---
|
| 422 |
-
# ... (all your previous code: GAIA_FINAL_ANSWER_SYSTEM_PROMPT, Pydantic models, Tool functions, AIAgent class,
|
| 423 |
-
# and the API interaction functions: api_get_questions, api_download_file, api_submit_answers
|
| 424 |
-
# should be defined above this block) ...
|
| 425 |
-
|
| 426 |
-
# --- Main Execution Block (Using API for Questions) ---
|
| 427 |
-
|
| 428 |
-
|
| 429 |
if __name__ == "__main__":
|
| 430 |
-
print("
|
| 431 |
-
|
| 432 |
-
# !!! ACTION REQUIRED: Set your username and agent_code identifier here !!!
|
| 433 |
-
YOUR_USERNAME = GoodLuckChuck # Replace with your actual username for the course platform
|
| 434 |
-
YOUR_AGENT_CODE_IDENTIFIER = "NikAgent_HF_App_v1" # A name for your agent submission
|
| 435 |
-
|
| 436 |
-
if not OPENAI_API_KEY_VALUE:
|
| 437 |
-
print("CRITICAL: OpenAI API Key is not available. Main execution cannot proceed.")
|
| 438 |
-
elif not client:
|
| 439 |
-
print("CRITICAL: OpenAI client failed to initialize. Main execution cannot proceed.")
|
| 440 |
-
else:
|
| 441 |
-
agent = AIAgent(openai_client=client)
|
| 442 |
-
all_submission_answers = [] # To collect {"task_id": ..., "answer": ...} dicts
|
| 443 |
-
|
| 444 |
-
# 1. Fetch questions from the API
|
| 445 |
-
print("\nSTEP 1: Fetching questions from API...")
|
| 446 |
-
api_questions = api_get_questions() # This function calls the course API
|
| 447 |
-
|
| 448 |
-
if api_questions:
|
| 449 |
-
print(f"Fetched {len(api_questions)} questions from the API.")
|
| 450 |
-
# You might want to process a subset for testing during development:
|
| 451 |
-
# questions_to_process = api_questions[:1] # Example: process only the first question
|
| 452 |
-
questions_to_process = api_questions
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
for question_data_from_api in questions_to_process:
|
| 456 |
-
task_id = question_data_from_api.get("task_id")
|
| 457 |
-
# Ensure you are using the correct key for question text from the API response.
|
| 458 |
-
# Common keys: "question", "text", "query". Check API docs or a sample response.
|
| 459 |
-
question_text = question_data_from_api.get("question")
|
| 460 |
-
|
| 461 |
-
# Check the structure of question_data_from_api to see how file info is provided.
|
| 462 |
-
# It might be 'file_name', 'filename', 'associated_file', 'has_file', etc.
|
| 463 |
-
original_file_name_from_api = question_data_from_api.get("file_name") # Assuming 'file_name'
|
| 464 |
-
local_downloaded_file_path = None
|
| 465 |
-
|
| 466 |
-
if not task_id or not question_text:
|
| 467 |
-
print(f"Skipping question due to missing task_id or question text in API response: {question_data_from_api}")
|
| 468 |
-
continue
|
| 469 |
-
|
| 470 |
-
print(f"\n-----------------------------------\nProcessing Task ID: {task_id}")
|
| 471 |
-
|
| 472 |
-
# 2. Download file if it's indicated by the API response for the current question
|
| 473 |
-
if original_file_name_from_api:
|
| 474 |
-
print(f"STEP 2: File indicated by API ({original_file_name_from_api}). Attempting download...")
|
| 475 |
-
# Files will be downloaded into 'downloaded_gaia_files' relative to where app.py runs in the Space
|
| 476 |
-
local_downloaded_file_path = api_download_file(
|
| 477 |
-
task_id,
|
| 478 |
-
original_file_name_from_api,
|
| 479 |
-
download_dir="downloaded_gaia_files" # This will be created inside your HF Space app directory
|
| 480 |
-
)
|
| 481 |
-
else:
|
| 482 |
-
print(f"STEP 2: No file indicated by API for task {task_id}.")
|
| 483 |
-
|
| 484 |
-
# 3. Process the question with your AI Agent
|
| 485 |
-
print(f"\nSTEP 3: Processing task {task_id} with AI Agent...")
|
| 486 |
-
agent_result = agent.process_question(
|
| 487 |
-
task_id=task_id,
|
| 488 |
-
question_text=question_text,
|
| 489 |
-
file_name=local_downloaded_file_path # Pass the path of the downloaded file
|
| 490 |
-
)
|
| 491 |
-
|
| 492 |
-
# agent_result["model_answer"] should be the clean answer, stripped of "FINAL ANSWER:"
|
| 493 |
-
clean_answer = agent_result.get("model_answer", "ERROR: No answer from agent")
|
| 494 |
-
|
| 495 |
-
print(f"Agent's Clean Answer for {task_id}: {clean_answer}")
|
| 496 |
-
|
| 497 |
-
all_submission_answers.append({
|
| 498 |
-
"task_id": task_id,
|
| 499 |
-
"answer": clean_answer
|
| 500 |
-
})
|
| 501 |
-
|
| 502 |
-
# Optional: Add a small delay if processing many questions to be kind to APIs
|
| 503 |
-
# import time
|
| 504 |
-
# time.sleep(0.5)
|
| 505 |
-
|
| 506 |
-
# 4. Submit all collected answers
|
| 507 |
-
if all_submission_answers:
|
| 508 |
-
print("\nSTEP 4: Submitting all processed answers...")
|
| 509 |
-
submission_result = api_submit_answers(
|
| 510 |
-
username=YOUR_USERNAME,
|
| 511 |
-
agent_code_identifier=YOUR_AGENT_CODE_IDENTIFIER,
|
| 512 |
-
processed_answers=all_submission_answers
|
| 513 |
-
)
|
| 514 |
-
if submission_result:
|
| 515 |
-
print("\n--- Submission Summary Received from API ---")
|
| 516 |
-
# Process/display submission_result as needed (e.g., score)
|
| 517 |
-
else:
|
| 518 |
-
print("Submission attempt failed or no result returned from submission API.")
|
| 519 |
-
else:
|
| 520 |
-
print("No answers were generated to submit.")
|
| 521 |
-
|
| 522 |
-
else:
|
| 523 |
-
print("Could not fetch questions from API. Exiting.")
|
| 524 |
-
|
| 525 |
-
print("\n===== Application Finished =====")
|
|
|
|
| 4 |
from typing import List, Dict, Any, Optional
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
from openai import OpenAI
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
from fastapi import FastAPI, HTTPException
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
import uvicorn
|
| 11 |
from datetime import datetime
|
| 12 |
|
| 13 |
+
# --- API Configuration ---
|
| 14 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
HEADERS = {"Content-Type": "application/json", "accept": "application/json"}
|
| 16 |
|
| 17 |
+
# --- Constants ---
|
| 18 |
+
USERNAME = "GoodLuckChuck"
|
| 19 |
+
AGENT_CODE_IDENTIFIER = "GoodLuckChuck_Agent_v1"
|
| 20 |
+
|
| 21 |
# --- API Interaction Functions ---
|
| 22 |
def api_get_questions() -> List[Dict[str, Any]]:
|
| 23 |
"""Fetch questions from the course API."""
|
| 24 |
try:
|
| 25 |
+
print(f"Attempting to fetch questions from: {API_BASE_URL}/questions")
|
| 26 |
response = requests.get(f"{API_BASE_URL}/questions", headers=HEADERS)
|
| 27 |
+
print(f"API Response Status Code: {response.status_code}")
|
| 28 |
+
|
| 29 |
+
response.raise_for_status()
|
| 30 |
questions = response.json()
|
| 31 |
+
if not questions:
|
| 32 |
+
print("Warning: API returned empty questions list")
|
| 33 |
return questions
|
| 34 |
except requests.exceptions.RequestException as e:
|
| 35 |
print(f"Error fetching questions from API: {e}")
|
| 36 |
return []
|
| 37 |
+
except json.JSONDecodeError as e:
|
| 38 |
+
print(f"Error decoding API response: {e}")
|
| 39 |
+
print(f"Response content: {response.text[:500]}...")
|
| 40 |
+
return []
|
| 41 |
|
| 42 |
def api_download_file(task_id: str, file_name: str, download_dir: str = "downloaded_gaia_files") -> Optional[str]:
|
| 43 |
"""Download a file associated with a task from the course API."""
|
| 44 |
try:
|
|
|
|
| 45 |
os.makedirs(download_dir, exist_ok=True)
|
|
|
|
|
|
|
| 46 |
download_url = f"{API_BASE_URL}/file/{task_id}"
|
| 47 |
|
|
|
|
| 48 |
response = requests.get(download_url, headers=HEADERS)
|
| 49 |
response.raise_for_status()
|
| 50 |
|
|
|
|
| 51 |
local_file_path = os.path.join(download_dir, file_name)
|
| 52 |
with open(local_file_path, 'wb') as f:
|
| 53 |
f.write(response.content)
|
|
|
|
| 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
|
| 72 |
}
|
| 73 |
|
|
|
|
| 89 |
# --- OpenAI Client Configuration ---
|
| 90 |
OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY")
|
| 91 |
if not OPENAI_API_KEY_VALUE:
|
| 92 |
+
print("OPENAI_API_KEY not found in environment variables. Attempting to load from a local .env file...")
|
| 93 |
load_dotenv()
|
| 94 |
OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY")
|
| 95 |
|
|
|
|
| 110 |
# --- GAIA System Prompt ---
|
| 111 |
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"""
|
| 112 |
|
| 113 |
+
# --- Pydantic Models ---
|
| 114 |
class WebSearchInput(BaseModel):
|
| 115 |
query: str = Field(..., description="The search query to find information on the web.")
|
| 116 |
|
| 117 |
class CalculatorInput(BaseModel):
|
| 118 |
+
expression: str = Field(..., description="The mathematical expression to evaluate.")
|
| 119 |
|
| 120 |
class ImageAnalysisInput(BaseModel):
|
| 121 |
image_url: Optional[str] = Field(None, description="The URL of the image to analyze.")
|
| 122 |
+
file_name: Optional[str] = Field(None, description="The file name of the image.")
|
| 123 |
prompt: str = Field(..., description="Specific question or instruction for analyzing the image.")
|
| 124 |
|
| 125 |
+
# --- Tool Functions ---
|
|
|
|
|
|
|
| 126 |
def execute_web_search(query: str) -> Dict[str, Any]:
|
| 127 |
"""Mock web search tool."""
|
| 128 |
print(f" 🔎 [Tool Called] WebSearch with query: '{query}'")
|
|
|
|
| 129 |
if "capital of france" in query.lower():
|
| 130 |
return {"result": "Paris is the capital of France.", "source": "mock_wikipedia.org"}
|
| 131 |
elif "tallest building" in query.lower():
|
|
|
|
| 136 |
"""Mock calculator tool."""
|
| 137 |
print(f" 🧮 [Tool Called] Calculator with expression: '{expression}'")
|
| 138 |
try:
|
|
|
|
|
|
|
| 139 |
result = eval(expression, {"__builtins__": {}}, {})
|
| 140 |
return {"result": str(result)}
|
| 141 |
except Exception as e:
|
|
|
|
| 151 |
return {"description": "The image contains various fruits, possibly apples and bananas.", "objects_detected": ["apple", "banana"]}
|
| 152 |
return {"description": f"Could not analyze image '{identifier}' for prompt '{prompt}'. Details unavailable.", "objects_detected": []}
|
| 153 |
|
| 154 |
+
# --- AI Agent Class ---
|
|
|
|
| 155 |
class AIAgent:
|
| 156 |
def __init__(self, openai_client):
|
| 157 |
self.client = openai_client
|
| 158 |
self.reasoning_trace = []
|
| 159 |
+
|
|
|
|
| 160 |
self.tools_available = [
|
| 161 |
{
|
| 162 |
"type": "function",
|
|
|
|
| 179 |
"function": {
|
| 180 |
"name": "image_analysis",
|
| 181 |
"description": "Analyzes an image given its file path.",
|
| 182 |
+
"parameters": ImageAnalysisInput.model_json_schema()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
}
|
| 184 |
}
|
| 185 |
]
|
| 186 |
+
|
| 187 |
self.tool_executors = {
|
| 188 |
"web_search": lambda params: execute_web_search(**params),
|
| 189 |
"calculator": lambda params: execute_calculator(**params),
|
|
|
|
| 200 |
def process_question(self, task_id: str, question_text: str, file_name: Optional[str] = None, max_iterations: int = 5) -> Dict[str, Any]:
|
| 201 |
self.reasoning_trace = []
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
user_message_content = question_text
|
| 204 |
+
if file_name:
|
| 205 |
+
user_message_content += f" (Note: The file is located at '{file_name}')"
|
| 206 |
|
| 207 |
if not self.client:
|
| 208 |
self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
|
|
|
|
| 214 |
|
| 215 |
self._log_step(f"Processing Task ID: {task_id}")
|
| 216 |
self._log_step(f"Original Question: {question_text}")
|
| 217 |
+
if file_name:
|
| 218 |
+
self._log_step(f"Associated File: {file_name}")
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
agent_system_prompt = (
|
| 221 |
"You are a helpful AI assistant. Your goal is to answer the user's question accurately. "
|
| 222 |
"Think step-by-step. If you need to use a tool to find information or perform a calculation, "
|
| 223 |
"you will be given the option to call available functions. "
|
| 224 |
"After any tool use, review the information and continue. "
|
| 225 |
"When you have enough information to answer the question, provide your comprehensive thought process. "
|
| 226 |
+
f"{GAIA_FINAL_ANSWER_SYSTEM_PROMPT}"
|
| 227 |
)
|
| 228 |
|
| 229 |
messages = [{"role": "system", "content": agent_system_prompt}]
|
|
|
|
| 237 |
model=LLM_MODEL,
|
| 238 |
messages=messages,
|
| 239 |
tools=self.tools_available,
|
| 240 |
+
tool_choice="auto"
|
| 241 |
)
|
| 242 |
response_message = response.choices[0].message
|
| 243 |
+
messages.append(response_message)
|
| 244 |
|
| 245 |
if response_message.tool_calls:
|
| 246 |
self._log_step("🛠️ Assistant decided to use tools:")
|
| 247 |
for tool_call in response_message.tool_calls:
|
| 248 |
function_name = tool_call.function.name
|
| 249 |
+
function_args = json.loads(tool_call.function.arguments)
|
| 250 |
self._log_step(f" - Tool: {function_name}, Args: {function_args}")
|
| 251 |
|
| 252 |
if function_name in self.tool_executors:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
tool_output = self.tool_executors[function_name](function_args)
|
| 254 |
self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
|
| 255 |
messages.append({
|
| 256 |
"tool_call_id": tool_call.id,
|
| 257 |
"role": "tool",
|
| 258 |
"name": function_name,
|
| 259 |
+
"content": json.dumps(tool_output)
|
| 260 |
})
|
| 261 |
else:
|
| 262 |
self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
|
|
|
|
| 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.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,
|
|
|
|
| 299 |
"reasoning_trace": self.reasoning_trace
|
| 300 |
}
|
| 301 |
|
| 302 |
+
# --- FastAPI App ---
|
|
|
|
| 303 |
app = FastAPI(title="AI Agent API")
|
| 304 |
|
|
|
|
| 305 |
app.add_middleware(
|
| 306 |
CORSMiddleware,
|
| 307 |
allow_origins=["*"],
|
|
|
|
| 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")
|
|
|
|
| 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,
|
|
|
|
| 362 |
"answer": clean_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),
|
|
|
|
| 375 |
except Exception as e:
|
| 376 |
raise HTTPException(status_code=500, detail=str(e))
|
| 377 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
if __name__ == "__main__":
|
| 379 |
+
print(f"Starting server at {datetime.now()}")
|
| 380 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|