Update app.py
Browse files
app.py
CHANGED
|
@@ -84,6 +84,9 @@ tools = [
|
|
| 84 |
PythonInterpreterTool(),
|
| 85 |
UserInputTool(),
|
| 86 |
]
|
|
|
|
|
|
|
|
|
|
| 87 |
# ---------------------- MAIN LOGIC ---------------------- #
|
| 88 |
|
| 89 |
class BasicAgent:
|
|
@@ -94,20 +97,9 @@ class BasicAgent:
|
|
| 94 |
|
| 95 |
)
|
| 96 |
print("BasicAgent initialized.")
|
| 97 |
-
|
| 98 |
-
# def __call__(self, question):
|
| 99 |
-
# if isinstance(question, dict):
|
| 100 |
-
# text = question.get("question", "")
|
| 101 |
-
# image = question.get("image", None)
|
| 102 |
-
# if image:
|
| 103 |
-
# question["image"] = {"type": "pil", "data": image}
|
| 104 |
-
# else:
|
| 105 |
-
# text = question
|
| 106 |
-
|
| 107 |
-
# print(f"Agent received question (first 50 chars): {text[:50]}...")
|
| 108 |
-
# answer = self.agent.run(text)
|
| 109 |
-
# return answer.strip()
|
| 110 |
def __call__(self, question):
|
|
|
|
| 111 |
if isinstance(question, dict):
|
| 112 |
text = question.get("question", "")
|
| 113 |
image = question.get("image", None)
|
|
@@ -118,17 +110,33 @@ class BasicAgent:
|
|
| 118 |
print(f"Agent received question (first 50 chars): {text[:50]}...")
|
| 119 |
|
| 120 |
prompt = system_prompt + "\n\nUser: " + text.strip()
|
|
|
|
| 121 |
inputs = {}
|
| 122 |
|
| 123 |
if image:
|
| 124 |
try:
|
| 125 |
image_caption = image_captioner(image=image, question=text)
|
| 126 |
prompt += f"\n\nThe image contains: {image_caption}"
|
|
|
|
| 127 |
inputs["image"] = image
|
| 128 |
except Exception as e:
|
| 129 |
print(f"Image captioning failed: {e}")
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
|
| 134 |
|
|
@@ -139,35 +147,37 @@ Your job is to:
|
|
| 139 |
- Search the web or Wikipedia if needed
|
| 140 |
- Perform Python calculations or date arithmetic
|
| 141 |
- Automatically search for and describe images if the question mentions or refers to one
|
| 142 |
-
|
| 143 |
Instructions:
|
| 144 |
1. Think step-by-step and use tools wisely.
|
| 145 |
2. If the question references an image (e.g. "What’s in this image of..."), search for a relevant image online and generate a caption to assist your reasoning.
|
| 146 |
3. Use the image caption internally to help answer the question, but do not include it in your response.
|
| 147 |
4. Always return a single, short, direct answer — no explanation, formatting, or extra information.
|
| 148 |
-
|
| 149 |
Examples:
|
| 150 |
- Q: What is the capital of France?
|
| 151 |
- A: Paris
|
| 152 |
-
|
| 153 |
- Q: What date is 30 days after January 1, 2023?
|
| 154 |
- A: January 31, 2023
|
| 155 |
-
|
| 156 |
- Q: What is 17 times 4?
|
| 157 |
- A: 68
|
| 158 |
-
|
| 159 |
- Q: What is the tallest building shown in the image of Dubai’s skyline?
|
| 160 |
- A: Burj Khalifa
|
| 161 |
-
|
| 162 |
- Q: What fruit is in the image of a bowl on the kitchen table?
|
| 163 |
- A: Bananas
|
| 164 |
-
|
| 165 |
- Q: What is shown in the picture of the moon landing?
|
| 166 |
- A: Astronaut on the Moon
|
| 167 |
-
|
| 168 |
Your output must be: a single clean answer string only.
|
| 169 |
"""
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
def find_image_online(query):
|
| 173 |
"""Use DuckDuckGo to find an image related to the query."""
|
|
@@ -187,35 +197,83 @@ def download_image(url):
|
|
| 187 |
except Exception:
|
| 188 |
return None
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
def ask_agent(question):
|
|
|
|
| 191 |
try:
|
| 192 |
-
prompt = system_prompt + "\n\nUser: " + question.strip()
|
| 193 |
|
|
|
|
|
|
|
| 194 |
image = None
|
| 195 |
image_caption = ""
|
| 196 |
-
|
| 197 |
-
keywords = ["image", "picture","photo","painting", "what's in this picture", "describe this picture"]
|
| 198 |
question_lower = question.lower()
|
|
|
|
| 199 |
if any(word in question_lower for word in keywords):
|
| 200 |
image_url = find_image_online(question)
|
| 201 |
if image_url:
|
| 202 |
image = download_image(image_url)
|
| 203 |
if image:
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
image_caption = image_captioner(image=image, question=question)
|
| 207 |
-
#Append the caption to the user's original question
|
| 208 |
-
prompt +=f"\n\nThe image contains: {image_caption}"
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
|
| 214 |
-
except Exception as e:
|
| 215 |
-
return f"Error: {e}"
|
| 216 |
-
|
| 217 |
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 221 |
"""
|
|
@@ -237,11 +295,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 237 |
submit_url = f"{api_url}/submit"
|
| 238 |
|
| 239 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
except Exception as e:
|
| 243 |
-
print(f"Error instantiating agent: {e}")
|
| 244 |
-
return f"Error initializing agent: {e}", None
|
| 245 |
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 246 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 247 |
print(agent_code)
|
|
@@ -360,11 +415,9 @@ with gr.Blocks() as demo:
|
|
| 360 |
gr.Markdown(
|
| 361 |
"""
|
| 362 |
**Instructions:**
|
| 363 |
-
|
| 364 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 365 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 366 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 367 |
-
|
| 368 |
---
|
| 369 |
**Disclaimers:**
|
| 370 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
|
@@ -408,286 +461,3 @@ if __name__ == "__main__":
|
|
| 408 |
|
| 409 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 410 |
demo.launch(debug=True, share=False)
|
| 411 |
-
|
| 412 |
-
# DEBUG TEST
|
| 413 |
-
agent = BasicAgent(model, tools)
|
| 414 |
-
print(agent("What is the capital of France?"))
|
| 415 |
-
# import os
|
| 416 |
-
# import pandas as pd
|
| 417 |
-
# import requests
|
| 418 |
-
# import smolagents
|
| 419 |
-
# print("SmolAgents version:", smolagents.__version__)
|
| 420 |
-
# from smolagents import Tool, CodeAgent, InferenceClientModel, load_tool
|
| 421 |
-
# from smolagents import DuckDuckGoSearchTool, WikipediaSearchTool, PythonInterpreterTool, UserInputTool
|
| 422 |
-
# import gradio as gr
|
| 423 |
-
# from PIL import Image
|
| 424 |
-
|
| 425 |
-
# # 🧠 Inference model
|
| 426 |
-
# model = InferenceClientModel("qwen/Qwen2.5-0.5B-Instruct", max_tokens=512)
|
| 427 |
-
# # (Keep Constants as is)
|
| 428 |
-
# # --- Constants ---
|
| 429 |
-
# DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 430 |
-
|
| 431 |
-
# # --- Basic Agent Definition ---
|
| 432 |
-
# # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 433 |
-
# # class BasicAgent:
|
| 434 |
-
# # def __init__(self):
|
| 435 |
-
# # print("BasicAgent initialized.")
|
| 436 |
-
# # def __call__(self, question: str) -> str:
|
| 437 |
-
# # print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 438 |
-
# # fixed_answer = "This is a default answer."
|
| 439 |
-
# # print(f"Agent returning fixed answer: {fixed_answer}")
|
| 440 |
-
# # return fixed_answer
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
# # class ImageCaptioningTool(Tool):
|
| 444 |
-
# # name = "image_captioner"
|
| 445 |
-
# # description = "Generate a caption for an image."
|
| 446 |
-
# # inputs = {"image": "image"}
|
| 447 |
-
# # output_type = "text"
|
| 448 |
-
|
| 449 |
-
# # def run(self, inputs: dict) -> str:
|
| 450 |
-
# # image = inputs.get("image")
|
| 451 |
-
# # if not image:
|
| 452 |
-
# # return "No image provided."
|
| 453 |
-
# # # You could run your model here instead
|
| 454 |
-
# # return "This is a placeholder caption for the uploaded image."
|
| 455 |
-
|
| 456 |
-
# class BasicAgent:
|
| 457 |
-
# def __init__(self):
|
| 458 |
-
# model = InferenceClientModel(
|
| 459 |
-
# "qwen/Qwen2.5-0.5B-Instruct",
|
| 460 |
-
# max_tokens=512,
|
| 461 |
-
# system_message="""
|
| 462 |
-
# You are a highly capable AI assistant designed to solve real-world, multi-step reasoning tasks in the GAIA benchmark.
|
| 463 |
-
# Your job is to:
|
| 464 |
-
# - Search the web or Wikipedia if needed
|
| 465 |
-
# - Perform Python calculations or date arithmetic
|
| 466 |
-
|
| 467 |
-
# Instructions:
|
| 468 |
-
# 1. Think step-by-step and use tools wisely.
|
| 469 |
-
# 2. Always return a short, direct answer — no explanation or formatting.
|
| 470 |
-
|
| 471 |
-
# Examples:
|
| 472 |
-
# - Q: What is the capital of France?
|
| 473 |
-
# - A: Paris
|
| 474 |
-
|
| 475 |
-
# Your output must be: a single clean answer string only.
|
| 476 |
-
|
| 477 |
-
# """
|
| 478 |
-
# )
|
| 479 |
-
# self.agent = CodeAgent(
|
| 480 |
-
# tools=[
|
| 481 |
-
# DuckDuckGoSearchTool(max_results=5, rate_limit=2.0),
|
| 482 |
-
# WikipediaSearchTool(user_agent="my-agent", language="en"),
|
| 483 |
-
# PythonInterpreterTool(),
|
| 484 |
-
# UserInputTool(),
|
| 485 |
-
# # ImageCaptioningTool(),
|
| 486 |
-
# ],
|
| 487 |
-
# model=model
|
| 488 |
-
|
| 489 |
-
# )
|
| 490 |
-
# print("BasicAgent initialized.")
|
| 491 |
-
# # print("Available tools:", [tool.name for tool in self.agent.tools])
|
| 492 |
-
# def __call__(self, question):
|
| 493 |
-
# if isinstance(question, dict):
|
| 494 |
-
# text = question.get("question", "")
|
| 495 |
-
# # ignoring image context for now since agent.run doesn't support it
|
| 496 |
-
# else:
|
| 497 |
-
# text = question
|
| 498 |
-
|
| 499 |
-
# print(f"Agent received question (first 50 chars): {text[:50]}...")
|
| 500 |
-
# answer = self.agent.run(text)
|
| 501 |
-
# return answer.strip()
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
# def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 506 |
-
# """
|
| 507 |
-
# Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 508 |
-
# and displays the results.
|
| 509 |
-
# """
|
| 510 |
-
# # --- Determine HF Space Runtime URL and Repo URL ---
|
| 511 |
-
# space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 512 |
-
|
| 513 |
-
# if profile:
|
| 514 |
-
# username= f"{profile.username}"
|
| 515 |
-
# print(f"User logged in: {username}")
|
| 516 |
-
# else:
|
| 517 |
-
# print("User not logged in.")
|
| 518 |
-
# return "Please Login to Hugging Face with the button.", None
|
| 519 |
-
|
| 520 |
-
# api_url = DEFAULT_API_URL
|
| 521 |
-
# questions_url = f"{api_url}/questions"
|
| 522 |
-
# submit_url = f"{api_url}/submit"
|
| 523 |
-
|
| 524 |
-
# # 1. Instantiate Agent ( modify this part to create your agent)
|
| 525 |
-
# try:
|
| 526 |
-
# agent = BasicAgent()
|
| 527 |
-
# except Exception as e:
|
| 528 |
-
# print(f"Error instantiating agent: {e}")
|
| 529 |
-
# return f"Error initializing agent: {e}", None
|
| 530 |
-
# # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 531 |
-
# agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 532 |
-
# print(agent_code)
|
| 533 |
-
|
| 534 |
-
# # 2. Fetch Questions
|
| 535 |
-
# print(f"Fetching questions from: {questions_url}")
|
| 536 |
-
# try:
|
| 537 |
-
# response = requests.get(questions_url, timeout=15)
|
| 538 |
-
# response.raise_for_status()
|
| 539 |
-
# questions_data = response.json()
|
| 540 |
-
# if not questions_data:
|
| 541 |
-
# print("Fetched questions list is empty.")
|
| 542 |
-
# return "Fetched questions list is empty or invalid format.", None
|
| 543 |
-
# print(f"Fetched {len(questions_data)} questions.")
|
| 544 |
-
# except requests.exceptions.RequestException as e:
|
| 545 |
-
# print(f"Error fetching questions: {e}")
|
| 546 |
-
# return f"Error fetching questions: {e}", None
|
| 547 |
-
# except requests.exceptions.JSONDecodeError as e:
|
| 548 |
-
# print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 549 |
-
# print(f"Response text: {response.text[:500]}")
|
| 550 |
-
# return f"Error decoding server response for questions: {e}", None
|
| 551 |
-
# except Exception as e:
|
| 552 |
-
# print(f"An unexpected error occurred fetching questions: {e}")
|
| 553 |
-
# return f"An unexpected error occurred fetching questions: {e}", None
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
# # question_text = item.get("question")
|
| 557 |
-
# # question_input = {"question": question_text}
|
| 558 |
-
# # if "image" in item:
|
| 559 |
-
# # question_input["image"] = item["image"]
|
| 560 |
-
# # submitted_answer = agent(question_input)
|
| 561 |
-
# # 3. Run your Agent
|
| 562 |
-
# results_log = []
|
| 563 |
-
# answers_payload = []
|
| 564 |
-
# print(f"Running agent on {len(questions_data)} questions...")
|
| 565 |
-
# for item in questions_data:
|
| 566 |
-
# task_id = item.get("task_id")
|
| 567 |
-
# question_text = item.get("question")
|
| 568 |
-
# image = item.get("image", None)
|
| 569 |
-
|
| 570 |
-
# if not task_id or question_text is None:
|
| 571 |
-
# print(f"Skipping item with missing task_id or question: {item}")
|
| 572 |
-
# continue
|
| 573 |
-
|
| 574 |
-
# try:
|
| 575 |
-
# question_input = {"question": question_text}
|
| 576 |
-
# if image:
|
| 577 |
-
# question_input["image"] = {"type": "image", "data": image}
|
| 578 |
-
# submitted_answer = agent(question_input)
|
| 579 |
-
|
| 580 |
-
# answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 581 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 582 |
-
|
| 583 |
-
# except Exception as e:
|
| 584 |
-
# print(f"Error running agent on task {task_id}: {e}")
|
| 585 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 586 |
-
|
| 587 |
-
# if not answers_payload:
|
| 588 |
-
# print("Agent did not produce any answers to submit.")
|
| 589 |
-
# return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 590 |
-
|
| 591 |
-
# # 4. Prepare Submission
|
| 592 |
-
# submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 593 |
-
# status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 594 |
-
# print(status_update)
|
| 595 |
-
|
| 596 |
-
# # 5. Submit
|
| 597 |
-
# print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 598 |
-
# try:
|
| 599 |
-
# response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 600 |
-
# response.raise_for_status()
|
| 601 |
-
# result_data = response.json()
|
| 602 |
-
# final_status = (
|
| 603 |
-
# f"Submission Successful!\n"
|
| 604 |
-
# f"User: {result_data.get('username')}\n"
|
| 605 |
-
# f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 606 |
-
# f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 607 |
-
# f"Message: {result_data.get('message', 'No message received.')}"
|
| 608 |
-
# )
|
| 609 |
-
# print("Submission successful.")
|
| 610 |
-
# results_df = pd.DataFrame(results_log)
|
| 611 |
-
# return final_status, results_df
|
| 612 |
-
# except requests.exceptions.HTTPError as e:
|
| 613 |
-
# error_detail = f"Server responded with status {e.response.status_code}."
|
| 614 |
-
# try:
|
| 615 |
-
# error_json = e.response.json()
|
| 616 |
-
# error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 617 |
-
# except requests.exceptions.JSONDecodeError:
|
| 618 |
-
# error_detail += f" Response: {e.response.text[:500]}"
|
| 619 |
-
# status_message = f"Submission Failed: {error_detail}"
|
| 620 |
-
# print(status_message)
|
| 621 |
-
# results_df = pd.DataFrame(results_log)
|
| 622 |
-
# return status_message, results_df
|
| 623 |
-
# except requests.exceptions.Timeout:
|
| 624 |
-
# status_message = "Submission Failed: The request timed out."
|
| 625 |
-
# print(status_message)
|
| 626 |
-
# results_df = pd.DataFrame(results_log)
|
| 627 |
-
# return status_message, results_df
|
| 628 |
-
# except requests.exceptions.RequestException as e:
|
| 629 |
-
# status_message = f"Submission Failed: Network error - {e}"
|
| 630 |
-
# print(status_message)
|
| 631 |
-
# results_df = pd.DataFrame(results_log)
|
| 632 |
-
# return status_message, results_df
|
| 633 |
-
# except Exception as e:
|
| 634 |
-
# status_message = f"An unexpected error occurred during submission: {e}"
|
| 635 |
-
# print(status_message)
|
| 636 |
-
# results_df = pd.DataFrame(results_log)
|
| 637 |
-
# return status_message, results_df
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
# # --- Build Gradio Interface using Blocks ---
|
| 641 |
-
# with gr.Blocks() as demo:
|
| 642 |
-
# gr.Markdown("# Basic Agent Evaluation Runner")
|
| 643 |
-
# gr.Markdown(
|
| 644 |
-
# """
|
| 645 |
-
# **Instructions:**
|
| 646 |
-
|
| 647 |
-
# 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 648 |
-
# 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 649 |
-
# 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 650 |
-
|
| 651 |
-
# ---
|
| 652 |
-
# **Disclaimers:**
|
| 653 |
-
# Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 654 |
-
# This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 655 |
-
# """
|
| 656 |
-
# )
|
| 657 |
-
|
| 658 |
-
# gr.LoginButton()
|
| 659 |
-
|
| 660 |
-
# run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 661 |
-
|
| 662 |
-
# status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 663 |
-
# # Removed max_rows=10 from DataFrame constructor
|
| 664 |
-
# results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 665 |
-
|
| 666 |
-
# run_button.click(
|
| 667 |
-
# fn=run_and_submit_all,
|
| 668 |
-
# outputs=[status_output, results_table]
|
| 669 |
-
# )
|
| 670 |
-
|
| 671 |
-
# if __name__ == "__main__":
|
| 672 |
-
# print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 673 |
-
# # Check for SPACE_HOST and SPACE_ID at startup for information
|
| 674 |
-
# space_host_startup = os.getenv("SPACE_HOST")
|
| 675 |
-
# space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 676 |
-
|
| 677 |
-
# if space_host_startup:
|
| 678 |
-
# print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 679 |
-
# print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 680 |
-
# else:
|
| 681 |
-
# print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 682 |
-
|
| 683 |
-
# if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 684 |
-
# print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 685 |
-
# print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 686 |
-
# print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 687 |
-
# else:
|
| 688 |
-
# print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 689 |
-
|
| 690 |
-
# print("-"*(60 + len(" App Starting ")) + "\n")
|
| 691 |
-
|
| 692 |
-
# print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 693 |
-
# demo.launch(debug=True, share=False)
|
|
|
|
| 84 |
PythonInterpreterTool(),
|
| 85 |
UserInputTool(),
|
| 86 |
]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
# ---------------------- MAIN LOGIC ---------------------- #
|
| 91 |
|
| 92 |
class BasicAgent:
|
|
|
|
| 97 |
|
| 98 |
)
|
| 99 |
print("BasicAgent initialized.")
|
| 100 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def __call__(self, question):
|
| 102 |
+
print("BasicAgent called")
|
| 103 |
if isinstance(question, dict):
|
| 104 |
text = question.get("question", "")
|
| 105 |
image = question.get("image", None)
|
|
|
|
| 110 |
print(f"Agent received question (first 50 chars): {text[:50]}...")
|
| 111 |
|
| 112 |
prompt = system_prompt + "\n\nUser: " + text.strip()
|
| 113 |
+
print("BasicAgent updated the prompt")
|
| 114 |
inputs = {}
|
| 115 |
|
| 116 |
if image:
|
| 117 |
try:
|
| 118 |
image_caption = image_captioner(image=image, question=text)
|
| 119 |
prompt += f"\n\nThe image contains: {image_caption}"
|
| 120 |
+
print("BasicAgent added the image caption to the prompt")
|
| 121 |
inputs["image"] = image
|
| 122 |
except Exception as e:
|
| 123 |
print(f"Image captioning failed: {e}")
|
| 124 |
+
|
| 125 |
+
inputs["question"] = prompt
|
| 126 |
+
print("running the agent with the BasicAgent prompt")
|
| 127 |
+
print(f"Prompt length (chars): {len(prompt)}")
|
| 128 |
+
try:
|
| 129 |
+
# result = self.agent(prompt).strip()
|
| 130 |
+
result = self.agent(inputs).strip()
|
| 131 |
+
print(f"Agent returned result: {result[:100]}")
|
| 132 |
+
print("Agent run completed")
|
| 133 |
+
return result
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error running the agent: {e}")
|
| 136 |
+
return "AGENT RUN ERROR"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
|
| 141 |
|
| 142 |
|
|
|
|
| 147 |
- Search the web or Wikipedia if needed
|
| 148 |
- Perform Python calculations or date arithmetic
|
| 149 |
- Automatically search for and describe images if the question mentions or refers to one
|
|
|
|
| 150 |
Instructions:
|
| 151 |
1. Think step-by-step and use tools wisely.
|
| 152 |
2. If the question references an image (e.g. "What’s in this image of..."), search for a relevant image online and generate a caption to assist your reasoning.
|
| 153 |
3. Use the image caption internally to help answer the question, but do not include it in your response.
|
| 154 |
4. Always return a single, short, direct answer — no explanation, formatting, or extra information.
|
|
|
|
| 155 |
Examples:
|
| 156 |
- Q: What is the capital of France?
|
| 157 |
- A: Paris
|
|
|
|
| 158 |
- Q: What date is 30 days after January 1, 2023?
|
| 159 |
- A: January 31, 2023
|
|
|
|
| 160 |
- Q: What is 17 times 4?
|
| 161 |
- A: 68
|
|
|
|
| 162 |
- Q: What is the tallest building shown in the image of Dubai’s skyline?
|
| 163 |
- A: Burj Khalifa
|
|
|
|
| 164 |
- Q: What fruit is in the image of a bowl on the kitchen table?
|
| 165 |
- A: Bananas
|
|
|
|
| 166 |
- Q: What is shown in the picture of the moon landing?
|
| 167 |
- A: Astronaut on the Moon
|
|
|
|
| 168 |
Your output must be: a single clean answer string only.
|
| 169 |
"""
|
| 170 |
|
| 171 |
+
# Agent initialization - moved here from the submit_and_run_all()
|
| 172 |
+
try:
|
| 173 |
+
agent = BasicAgent(model=model, tools=tools)
|
| 174 |
+
except Exception as e:
|
| 175 |
+
agent = None
|
| 176 |
+
print(f"Error instantiating agent: {e}")
|
| 177 |
+
# return f"Error initializing agent: {e}", None
|
| 178 |
+
|
| 179 |
+
# -----------------------------------------------------
|
| 180 |
+
|
| 181 |
|
| 182 |
def find_image_online(query):
|
| 183 |
"""Use DuckDuckGo to find an image related to the query."""
|
|
|
|
| 197 |
except Exception:
|
| 198 |
return None
|
| 199 |
|
| 200 |
+
# def ask_agent(question):
|
| 201 |
+
# try:
|
| 202 |
+
# prompt = system_prompt + "\n\nUser: " + question.strip()
|
| 203 |
+
|
| 204 |
+
# image = None
|
| 205 |
+
# image_caption = ""
|
| 206 |
+
# # Only try to get an image if the question mentions or implies one
|
| 207 |
+
# keywords = ["image", "picture","photo","painting", "what's in this picture", "describe this picture"]
|
| 208 |
+
# question_lower = question.lower()
|
| 209 |
+
# if any(word in question_lower for word in keywords):
|
| 210 |
+
# image_url = find_image_online(question)
|
| 211 |
+
# if image_url:
|
| 212 |
+
# image = download_image(image_url)
|
| 213 |
+
# if image:
|
| 214 |
+
# # Use the ImageCaptioningTool to get a caption
|
| 215 |
+
# image_captioner = [tool for tool in tools if tool.name == "image_captioner "][0]
|
| 216 |
+
# image_caption = image_captioner(image=image, question=question)
|
| 217 |
+
# #Append the caption to the user's original question
|
| 218 |
+
# prompt +=f"\n\nThe image contains: {image_caption}"
|
| 219 |
+
|
| 220 |
+
# #Run the agent (image is passed only if present; prompt always includes the caption if available)
|
| 221 |
+
# inputs = {"image":image} if image else{}
|
| 222 |
+
# return agent.run(prompt, inputs=inputs).strip()
|
| 223 |
+
|
| 224 |
+
# except Exception as e:
|
| 225 |
+
# return f"Error: {e}"
|
| 226 |
+
|
| 227 |
+
|
| 228 |
def ask_agent(question):
|
| 229 |
+
print("ask_agent called")
|
| 230 |
try:
|
|
|
|
| 231 |
|
| 232 |
+
prompt = "\n\nUser: " + question.strip()
|
| 233 |
+
print("ask_agent updated the prompt")
|
| 234 |
image = None
|
| 235 |
image_caption = ""
|
| 236 |
+
question_input ={}
|
| 237 |
+
keywords = ["image", "picture", "photo", "painting", "what's in this picture", "describe this picture"]
|
| 238 |
question_lower = question.lower()
|
| 239 |
+
|
| 240 |
if any(word in question_lower for word in keywords):
|
| 241 |
image_url = find_image_online(question)
|
| 242 |
if image_url:
|
| 243 |
image = download_image(image_url)
|
| 244 |
if image:
|
| 245 |
+
if image_captioner is None:
|
| 246 |
+
return "Image captioning tool is missing"
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
try:
|
| 249 |
+
image_caption = image_captioner(image=image, question=question)
|
| 250 |
+
prompt += f"\n\nThe image contains: {image_caption}"
|
| 251 |
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
+
|
| 254 |
+
print("ask_agent updated the prompt to include image caption")
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"Image captioning failed: {e}")
|
| 257 |
+
|
| 258 |
+
print("running agent with the ask_agent prompt")
|
| 259 |
+
result = agent(prompt)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
result = agent(prompt)
|
| 264 |
+
|
| 265 |
+
if not result or str(result).strip() == "":
|
| 266 |
+
return "I don't know"
|
| 267 |
+
return str(result).strip()
|
| 268 |
+
|
| 269 |
+
except Exception as e:
|
| 270 |
+
print(f"ask_agent error during agent call: {e}")
|
| 271 |
+
return "Error: Agent failed to generate a response."
|
| 272 |
+
|
| 273 |
+
except Exception as e:
|
| 274 |
+
print(f"ask_agent error: {e}")
|
| 275 |
+
return "Error: Unable to generate response."
|
| 276 |
+
|
| 277 |
|
| 278 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 279 |
"""
|
|
|
|
| 295 |
submit_url = f"{api_url}/submit"
|
| 296 |
|
| 297 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 298 |
+
# moved to the top of ask_agent() to keep the agent global
|
| 299 |
+
|
|
|
|
|
|
|
|
|
|
| 300 |
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 301 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 302 |
print(agent_code)
|
|
|
|
| 415 |
gr.Markdown(
|
| 416 |
"""
|
| 417 |
**Instructions:**
|
|
|
|
| 418 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 419 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 420 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 421 |
---
|
| 422 |
**Disclaimers:**
|
| 423 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
|
|
|
| 461 |
|
| 462 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 463 |
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|