Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,9 @@ 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"
|
|
@@ -182,68 +185,31 @@ def execute_image_analysis(image_url: Optional[str], file_name: Optional[str], p
|
|
| 182 |
|
| 183 |
# --- AI Agent Class ---
|
| 184 |
class AIAgent:
|
| 185 |
-
def __init__(self
|
| 186 |
-
|
| 187 |
self.reasoning_trace = []
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
"description": "Searches the web for information based on a query.",
|
| 195 |
-
"parameters": WebSearchInput.model_json_schema()
|
| 196 |
-
}
|
| 197 |
-
},
|
| 198 |
-
{
|
| 199 |
-
"type": "function",
|
| 200 |
-
"function": {
|
| 201 |
-
"name": "calculator",
|
| 202 |
-
"description": "Evaluates mathematical expressions.",
|
| 203 |
-
"parameters": CalculatorInput.model_json_schema()
|
| 204 |
-
}
|
| 205 |
-
},
|
| 206 |
-
{
|
| 207 |
-
"type": "function",
|
| 208 |
-
"function": {
|
| 209 |
-
"name": "image_analysis",
|
| 210 |
-
"description": "Analyzes an image given its file path.",
|
| 211 |
-
"parameters": ImageAnalysisInput.model_json_schema()
|
| 212 |
-
}
|
| 213 |
-
}
|
| 214 |
-
]
|
| 215 |
-
|
| 216 |
-
self.tool_executors = {
|
| 217 |
-
"web_search": lambda params: execute_web_search(**params),
|
| 218 |
-
"calculator": lambda params: execute_calculator(**params),
|
| 219 |
-
"image_analysis": lambda params: execute_image_analysis(**params)
|
| 220 |
-
}
|
| 221 |
|
| 222 |
def _log_step(self, message: str, data: Optional[Dict] = None):
|
|
|
|
| 223 |
print(message)
|
| 224 |
entry = {"message": message}
|
| 225 |
if data:
|
| 226 |
entry.update(data)
|
| 227 |
self.reasoning_trace.append(entry)
|
| 228 |
|
| 229 |
-
def
|
|
|
|
| 230 |
self.reasoning_trace = []
|
| 231 |
|
| 232 |
try:
|
| 233 |
-
|
| 234 |
-
|
| 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",
|
|
@@ -251,60 +217,33 @@ class AIAgent:
|
|
| 251 |
},
|
| 252 |
{
|
| 253 |
"role": "user",
|
| 254 |
-
"content":
|
| 255 |
}
|
| 256 |
]
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 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 |
-
|
| 299 |
-
|
| 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 ---
|
| 310 |
app = FastAPI(title="AI Agent API")
|
|
@@ -319,7 +258,7 @@ app.add_middleware(
|
|
| 319 |
|
| 320 |
# Initialize the AI Agent globally
|
| 321 |
if OPENAI_API_KEY_VALUE and openai.api_key:
|
| 322 |
-
global_agent = AIAgent(
|
| 323 |
else:
|
| 324 |
global_agent = None
|
| 325 |
|
|
@@ -376,7 +315,7 @@ async def process_questions():
|
|
| 376 |
print("OpenAI API key validated")
|
| 377 |
|
| 378 |
# Initialize agent
|
| 379 |
-
agent = AIAgent(
|
| 380 |
print("AI Agent initialized")
|
| 381 |
|
| 382 |
# Fetch questions
|
|
@@ -400,9 +339,9 @@ async def process_questions():
|
|
| 400 |
print(f"File: {file_name}")
|
| 401 |
|
| 402 |
try:
|
| 403 |
-
answer = agent
|
| 404 |
processed_answers.append(answer)
|
| 405 |
-
print(f"Answer generated: {answer[
|
| 406 |
except Exception as e:
|
| 407 |
error_msg = f"Error processing question {task_id}: {str(e)}"
|
| 408 |
print(error_msg)
|
|
@@ -443,6 +382,157 @@ async def process_questions():
|
|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.cors import CORSMiddleware
|
| 10 |
import uvicorn
|
| 11 |
from datetime import datetime
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import inspect
|
| 14 |
+
import pandas as pd
|
| 15 |
|
| 16 |
# --- API Configuration ---
|
| 17 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 185 |
|
| 186 |
# --- AI Agent Class ---
|
| 187 |
class AIAgent:
|
| 188 |
+
def __init__(self):
|
| 189 |
+
"""Initialize the AI Agent with OpenAI client."""
|
| 190 |
self.reasoning_trace = []
|
| 191 |
+
# Get API key from environment
|
| 192 |
+
api_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
| 193 |
+
if not api_key:
|
| 194 |
+
raise ValueError("OPENAI_API_KEY not found in environment variables")
|
| 195 |
+
openai.api_key = api_key
|
| 196 |
+
print("AIAgent initialized with OpenAI client.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
def _log_step(self, message: str, data: Optional[Dict] = None):
|
| 199 |
+
"""Log a step in the reasoning process."""
|
| 200 |
print(message)
|
| 201 |
entry = {"message": message}
|
| 202 |
if data:
|
| 203 |
entry.update(data)
|
| 204 |
self.reasoning_trace.append(entry)
|
| 205 |
|
| 206 |
+
def __call__(self, question: str) -> str:
|
| 207 |
+
"""Process a single question and return an answer."""
|
| 208 |
self.reasoning_trace = []
|
| 209 |
|
| 210 |
try:
|
| 211 |
+
self._log_step(f"Processing question: {question[:100]}...")
|
| 212 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
messages = [
|
| 214 |
{
|
| 215 |
"role": "system",
|
|
|
|
| 217 |
},
|
| 218 |
{
|
| 219 |
"role": "user",
|
| 220 |
+
"content": question
|
| 221 |
}
|
| 222 |
]
|
| 223 |
|
| 224 |
+
response = openai.ChatCompletion.create(
|
| 225 |
+
model=LLM_MODEL,
|
| 226 |
+
messages=messages,
|
| 227 |
+
temperature=0.1,
|
| 228 |
+
max_tokens=1000
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
assistant_message = response.choices[0].message.content
|
| 232 |
+
self._log_step(f"Assistant response: {assistant_message}")
|
| 233 |
+
|
| 234 |
+
# Extract final answer
|
| 235 |
+
if "FINAL ANSWER:" in assistant_message:
|
| 236 |
+
final_answer = assistant_message.split("FINAL ANSWER:")[-1].strip()
|
| 237 |
+
self._log_step(f"Extracted final answer: {final_answer}")
|
| 238 |
+
return final_answer
|
| 239 |
+
|
| 240 |
+
# If no final answer format found, return the full response
|
| 241 |
+
return assistant_message.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
except Exception as e:
|
| 244 |
+
error_msg = f"Error processing question: {str(e)}"
|
| 245 |
+
self._log_step(error_msg)
|
| 246 |
+
return f"ERROR: {error_msg}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
# --- FastAPI App ---
|
| 249 |
app = FastAPI(title="AI Agent API")
|
|
|
|
| 258 |
|
| 259 |
# Initialize the AI Agent globally
|
| 260 |
if OPENAI_API_KEY_VALUE and openai.api_key:
|
| 261 |
+
global_agent = AIAgent()
|
| 262 |
else:
|
| 263 |
global_agent = None
|
| 264 |
|
|
|
|
| 315 |
print("OpenAI API key validated")
|
| 316 |
|
| 317 |
# Initialize agent
|
| 318 |
+
agent = AIAgent()
|
| 319 |
print("AI Agent initialized")
|
| 320 |
|
| 321 |
# Fetch questions
|
|
|
|
| 339 |
print(f"File: {file_name}")
|
| 340 |
|
| 341 |
try:
|
| 342 |
+
answer = agent(question_text)
|
| 343 |
processed_answers.append(answer)
|
| 344 |
+
print(f"Answer generated: {answer[:100]}...")
|
| 345 |
except Exception as e:
|
| 346 |
error_msg = f"Error processing question {task_id}: {str(e)}"
|
| 347 |
print(error_msg)
|
|
|
|
| 382 |
print(error_msg)
|
| 383 |
raise HTTPException(status_code=500, detail=error_msg)
|
| 384 |
|
| 385 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 386 |
+
"""
|
| 387 |
+
Fetches all questions, runs the AIAgent on them, submits all answers,
|
| 388 |
+
and displays the results.
|
| 389 |
+
"""
|
| 390 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 391 |
+
space_id = os.getenv("SPACE_ID")
|
| 392 |
+
|
| 393 |
+
if profile:
|
| 394 |
+
username = f"{profile.username}"
|
| 395 |
+
print(f"User logged in: {username}")
|
| 396 |
+
else:
|
| 397 |
+
print("User not logged in.")
|
| 398 |
+
return "Please Login to Hugging Face with the button.", None
|
| 399 |
+
|
| 400 |
+
api_url = API_BASE_URL
|
| 401 |
+
questions_url = f"{api_url}/questions"
|
| 402 |
+
submit_url = f"{api_url}/submit"
|
| 403 |
+
|
| 404 |
+
# 1. Instantiate Agent
|
| 405 |
+
try:
|
| 406 |
+
agent = AIAgent()
|
| 407 |
+
except Exception as e:
|
| 408 |
+
print(f"Error instantiating agent: {e}")
|
| 409 |
+
return f"Error initializing agent: {e}", None
|
| 410 |
+
|
| 411 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 412 |
+
print(f"Agent code URL: {agent_code}")
|
| 413 |
+
|
| 414 |
+
# 2. Fetch Questions
|
| 415 |
+
print(f"Fetching questions from: {questions_url}")
|
| 416 |
+
try:
|
| 417 |
+
response = requests.get(questions_url, timeout=15)
|
| 418 |
+
response.raise_for_status()
|
| 419 |
+
questions_data = response.json()
|
| 420 |
+
if not questions_data:
|
| 421 |
+
print("Fetched questions list is empty.")
|
| 422 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 423 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 424 |
+
except Exception as e:
|
| 425 |
+
print(f"Error fetching questions: {e}")
|
| 426 |
+
return f"Error fetching questions: {e}", None
|
| 427 |
+
|
| 428 |
+
# 3. Run Agent
|
| 429 |
+
results_log = []
|
| 430 |
+
answers_payload = []
|
| 431 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 432 |
+
|
| 433 |
+
for item in questions_data:
|
| 434 |
+
task_id = item.get("task_id")
|
| 435 |
+
question_text = item.get("question")
|
| 436 |
+
if not task_id or question_text is None:
|
| 437 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 438 |
+
continue
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
submitted_answer = agent(question_text)
|
| 442 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 443 |
+
results_log.append({
|
| 444 |
+
"Task ID": task_id,
|
| 445 |
+
"Question": question_text,
|
| 446 |
+
"Submitted Answer": submitted_answer
|
| 447 |
+
})
|
| 448 |
+
print(f"Processed task {task_id}: {submitted_answer[:100]}...")
|
| 449 |
+
except Exception as e:
|
| 450 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 451 |
+
results_log.append({
|
| 452 |
+
"Task ID": task_id,
|
| 453 |
+
"Question": question_text,
|
| 454 |
+
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 455 |
+
})
|
| 456 |
+
|
| 457 |
+
if not answers_payload:
|
| 458 |
+
print("Agent did not produce any answers to submit.")
|
| 459 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 460 |
+
|
| 461 |
+
# 4. Submit Answers
|
| 462 |
+
submission_data = {
|
| 463 |
+
"username": username.strip(),
|
| 464 |
+
"agent_code": agent_code,
|
| 465 |
+
"answers": answers_payload
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 469 |
+
|
| 470 |
+
try:
|
| 471 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 472 |
+
response.raise_for_status()
|
| 473 |
+
result_data = response.json()
|
| 474 |
+
|
| 475 |
+
final_status = (
|
| 476 |
+
f"Submission Successful!\n"
|
| 477 |
+
f"User: {result_data.get('username')}\n"
|
| 478 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 479 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 480 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
print("Submission successful.")
|
| 484 |
+
results_df = pd.DataFrame(results_log)
|
| 485 |
+
return final_status, results_df
|
| 486 |
+
|
| 487 |
+
except Exception as e:
|
| 488 |
+
error_msg = f"Submission failed: {str(e)}"
|
| 489 |
+
print(error_msg)
|
| 490 |
+
results_df = pd.DataFrame(results_log)
|
| 491 |
+
return error_msg, results_df
|
| 492 |
+
|
| 493 |
+
# --- Build Gradio Interface using Blocks ---
|
| 494 |
+
with gr.Blocks() as demo:
|
| 495 |
+
gr.Markdown("# AI Agent Evaluation Runner")
|
| 496 |
+
gr.Markdown(
|
| 497 |
+
"""
|
| 498 |
+
**Instructions:**
|
| 499 |
+
1. Log in to your Hugging Face account using the button below.
|
| 500 |
+
2. Click 'Run Evaluation & Submit All Answers' to process all questions and see results.
|
| 501 |
+
3. The agent will use GPT-3.5-turbo to generate answers following strict formatting rules.
|
| 502 |
+
|
| 503 |
+
**Note:** Processing may take some time as each question requires an API call.
|
| 504 |
+
"""
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
gr.LoginButton()
|
| 508 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 509 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 510 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 511 |
+
|
| 512 |
+
run_button.click(
|
| 513 |
+
fn=run_and_submit_all,
|
| 514 |
+
outputs=[status_output, results_table]
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
if __name__ == "__main__":
|
| 518 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 519 |
+
|
| 520 |
+
space_host = os.getenv("SPACE_HOST")
|
| 521 |
+
space_id = os.getenv("SPACE_ID")
|
| 522 |
+
|
| 523 |
+
if space_host:
|
| 524 |
+
print(f"✅ SPACE_HOST found: {space_host}")
|
| 525 |
+
print(f" Runtime URL should be: https://{space_host}.hf.space")
|
| 526 |
+
else:
|
| 527 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 528 |
+
|
| 529 |
+
if space_id:
|
| 530 |
+
print(f"✅ SPACE_ID found: {space_id}")
|
| 531 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
|
| 532 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main")
|
| 533 |
+
else:
|
| 534 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?).")
|
| 535 |
+
|
| 536 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 537 |
+
print("Launching Gradio Interface...")
|
| 538 |
+
demo.launch(debug=True, share=False)
|