Update app.py
Browse files
app.py
CHANGED
|
@@ -3,143 +3,35 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
| 7 |
-
import io
|
| 8 |
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
-
class AttachmentDownloadTool(Tool):
|
| 13 |
-
name = "attachment-downloader"
|
| 14 |
-
description = "Downloads the file associated with the given task_id. If it does not exist, return None. input: task_id。output: attachment files or None"
|
| 15 |
-
inputs = {
|
| 16 |
-
"task_id": {
|
| 17 |
-
"type": "str",
|
| 18 |
-
"description": "task_id that needs to download attachment files."
|
| 19 |
-
}
|
| 20 |
-
}
|
| 21 |
-
output_type = io.BytesIO
|
| 22 |
-
|
| 23 |
-
def forward(self, task_id):
|
| 24 |
-
download_url = f"{api_url}/files/"
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
response = requests.get(download_url + task_id, stream=True, timeout=15)
|
| 28 |
-
if response.status_code != 200:
|
| 29 |
-
return None
|
| 30 |
-
file_obj = io.BytesIO(response.content)
|
| 31 |
-
file_obj.seek(0)
|
| 32 |
-
return file_obj
|
| 33 |
-
except Exception as e:
|
| 34 |
-
return None
|
| 35 |
-
|
| 36 |
-
class ImageCaptionTool(Tool):
|
| 37 |
-
name = "image-captioner"
|
| 38 |
-
description = "Identify the content of the input image and describe it in natural language. Input: image. Output: description text."
|
| 39 |
-
inputs = {
|
| 40 |
-
"image": {
|
| 41 |
-
"type": "image",
|
| 42 |
-
"description": "Images that need to be identified and described"
|
| 43 |
-
}
|
| 44 |
-
}
|
| 45 |
-
output_type = str
|
| 46 |
-
|
| 47 |
-
def setup(self):
|
| 48 |
-
self.model = OpenAIServerModel(
|
| 49 |
-
model_id="Qwen/Qwen2.5-VL-32B-Instruct",
|
| 50 |
-
api_base="https://api.siliconflow.cn/v1/",
|
| 51 |
-
api_key=os.getenv('MODEL_TOKEN'),
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
def forward(self, image):
|
| 55 |
-
prompt = "Please describe the content of this picture in detail."
|
| 56 |
-
return self.model(prompt, images=[image])
|
| 57 |
-
|
| 58 |
-
class AudioToTextTool(Tool):
|
| 59 |
-
name = "audio-to-text"
|
| 60 |
-
description = "Convert the input audio content to text. Input: audio. Output: text."
|
| 61 |
-
inputs = {
|
| 62 |
-
"audio": {
|
| 63 |
-
"type": "audio",
|
| 64 |
-
"description": "The audio file that needs to be transcribed"
|
| 65 |
-
}
|
| 66 |
-
}
|
| 67 |
-
output_type = str
|
| 68 |
-
|
| 69 |
-
def setup(self):
|
| 70 |
-
# 使用 HuggingFace Hub 上的 Whisper 大模型
|
| 71 |
-
self.model = HfApiModel(model_id="openai/whisper-large-v3") # 或其他支持音频转写的模型
|
| 72 |
-
|
| 73 |
-
def forward(self, audio):
|
| 74 |
-
prompt = "Please transcribe this audio content into text."
|
| 75 |
-
return self.model(prompt, audios=[audio])
|
| 76 |
|
| 77 |
# --- Basic Agent Definition ---
|
| 78 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 79 |
-
# class BasicAgent:
|
| 80 |
-
# def __init__(self):
|
| 81 |
-
# print("BasicAgent initialized.")
|
| 82 |
-
# def __call__(self, question: str) -> str:
|
| 83 |
-
# print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 84 |
-
# fixed_answer = "This is a default answer."
|
| 85 |
-
# print(f"Agent returning fixed answer: {fixed_answer}")
|
| 86 |
-
# return fixed_answer
|
| 87 |
class BasicAgent:
|
| 88 |
-
def __init__(self):
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
api_base="https://api.siliconflow.cn/v1/",
|
| 98 |
-
api_key=os.getenv('MODEL_TOKEN'),
|
| 99 |
-
)
|
| 100 |
-
# self.vision_model = OpenAIServerModel(
|
| 101 |
-
# model_id="Qwen/Qwen2.5-VL-32B-Instruct",
|
| 102 |
-
# api_base="https://api.siliconflow.cn/v1/",
|
| 103 |
-
# api_key=os.getenv('MODEL_TOKEN'),
|
| 104 |
-
# )
|
| 105 |
-
|
| 106 |
-
self.tools = [AttachmentDownloadTool, ImageCaptionTool, AudioToTextTool]
|
| 107 |
-
|
| 108 |
-
web_agent = ToolCallingAgent(
|
| 109 |
-
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
|
| 110 |
-
model=self.base_model,
|
| 111 |
-
max_steps=10,
|
| 112 |
-
name="web_search_agent",
|
| 113 |
-
description="Runs web searches for you.",
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
self.agent = CodeAgent(
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
managed_agents=[web_agent,],
|
| 120 |
-
additional_authorized_imports=["time", "numpy", "pandas"],
|
| 121 |
-
max_steps=20
|
| 122 |
)
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def __call__(self, question: str, images=None) -> str:
|
| 126 |
-
|
| 127 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
result = self.agent.run(question, images=images)
|
| 132 |
-
else:
|
| 133 |
-
result = self.agent.run(question)
|
| 134 |
-
|
| 135 |
-
print(f"Agent returning answer: {result}")
|
| 136 |
-
return result
|
| 137 |
-
except Exception as e:
|
| 138 |
-
print(f"Agent error: {e}")
|
| 139 |
-
return f"AGENT ERROR: {e}"
|
| 140 |
|
| 141 |
-
|
| 142 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 143 |
"""
|
| 144 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 145 |
and displays the results.
|
|
@@ -160,7 +52,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 160 |
|
| 161 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 162 |
try:
|
| 163 |
-
agent = BasicAgent()
|
| 164 |
except Exception as e:
|
| 165 |
print(f"Error instantiating agent: {e}")
|
| 166 |
return f"Error initializing agent: {e}", None
|
|
@@ -268,24 +160,27 @@ with gr.Blocks() as demo:
|
|
| 268 |
**Instructions:**
|
| 269 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 270 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 271 |
-
3.
|
|
|
|
| 272 |
---
|
| 273 |
**Disclaimers:**
|
| 274 |
-
Once clicking on the "submit button, it can take quite some time (
|
| 275 |
-
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
|
| 276 |
"""
|
| 277 |
)
|
| 278 |
|
| 279 |
gr.LoginButton()
|
| 280 |
|
|
|
|
|
|
|
| 281 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 282 |
|
| 283 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 284 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 285 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 286 |
|
| 287 |
run_button.click(
|
| 288 |
fn=run_and_submit_all,
|
|
|
|
| 289 |
outputs=[status_output, results_table]
|
| 290 |
)
|
| 291 |
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
|
|
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# --- Basic Agent Definition ---
|
| 13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
+
def __init__(self, openai_key):
|
| 16 |
+
self.openai_key = openai_key
|
| 17 |
+
print("BasicAgent initialized.")
|
| 18 |
+
# Initialize the model
|
| 19 |
+
#model = HfApiModel()
|
| 20 |
+
model = OpenAIServerModel(model_id="gpt-4.1", api_key=self.openai_key)
|
| 21 |
+
# Initialize the search tool
|
| 22 |
+
search_tool = DuckDuckGoSearchTool()
|
| 23 |
+
# Initialize Agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
self.agent = CodeAgent(
|
| 25 |
+
model = model,
|
| 26 |
+
tools=[search_tool]
|
|
|
|
|
|
|
|
|
|
| 27 |
)
|
| 28 |
+
def __call__(self, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
| 29 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 30 |
+
fixed_answer =self.agent.run(question)
|
| 31 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 32 |
+
return fixed_answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None, openai_key: str):
|
|
|
|
| 35 |
"""
|
| 36 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 37 |
and displays the results.
|
|
|
|
| 52 |
|
| 53 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 54 |
try:
|
| 55 |
+
agent = BasicAgent(openai_key)
|
| 56 |
except Exception as e:
|
| 57 |
print(f"Error instantiating agent: {e}")
|
| 58 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 160 |
**Instructions:**
|
| 161 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 162 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 163 |
+
3. Enter your OpenAI key below (if required by your agent).
|
| 164 |
+
4. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 165 |
---
|
| 166 |
**Disclaimers:**
|
| 167 |
+
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).
|
| 168 |
+
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 separate action or even to answer the questions in async.
|
| 169 |
"""
|
| 170 |
)
|
| 171 |
|
| 172 |
gr.LoginButton()
|
| 173 |
|
| 174 |
+
openai_key_box = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...", lines=1)
|
| 175 |
+
|
| 176 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 177 |
|
| 178 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 179 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 180 |
|
| 181 |
run_button.click(
|
| 182 |
fn=run_and_submit_all,
|
| 183 |
+
inputs=[openai_key_box],
|
| 184 |
outputs=[status_output, results_table]
|
| 185 |
)
|
| 186 |
|