Update app.py
Browse files
app.py
CHANGED
@@ -1,8 +1,13 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
-
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
@@ -10,14 +15,86 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
10 |
|
11 |
# --- Basic Agent Definition ---
|
12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
@@ -40,7 +117,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
40 |
|
41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
42 |
try:
|
43 |
-
agent =
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
@@ -76,11 +153,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
76 |
for item in questions_data:
|
77 |
task_id = item.get("task_id")
|
78 |
question_text = item.get("question")
|
|
|
|
|
79 |
if not task_id or question_text is None:
|
80 |
print(f"Skipping item with missing task_id or question: {item}")
|
81 |
continue
|
82 |
try:
|
83 |
-
submitted_answer = agent(question_text)
|
|
|
|
|
|
|
|
|
|
|
84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
86 |
except Exception as e:
|
@@ -146,11 +230,9 @@ with gr.Blocks() as demo:
|
|
146 |
gr.Markdown(
|
147 |
"""
|
148 |
**Instructions:**
|
149 |
-
|
150 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
151 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
152 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
153 |
-
|
154 |
---
|
155 |
**Disclaimers:**
|
156 |
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).
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
|
|
3 |
import inspect
|
4 |
import pandas as pd
|
5 |
+
import importlib
|
6 |
+
from importlib import resources
|
7 |
+
import requests
|
8 |
+
import yaml
|
9 |
+
import numpy as np
|
10 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, WikipediaSearchTool, Tool, OpenAIServerModel, SpeechToTextTool
|
11 |
|
12 |
# (Keep Constants as is)
|
13 |
# --- Constants ---
|
|
|
15 |
|
16 |
# --- Basic Agent Definition ---
|
17 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
class GetTaskFileTool(Tool):
|
24 |
+
name = "get_task_file_tool"
|
25 |
+
description = """This tool downloads the file content associated with the given task_id if exists. Returns absolute file path"""
|
26 |
+
inputs = {
|
27 |
+
"task_id": {"type": "string", "description": "Task id"},
|
28 |
+
"file_name": {"type": "string", "description": "File name"},
|
29 |
+
}
|
30 |
+
output_type = "string"
|
31 |
+
|
32 |
+
def forward(self, task_id: str, file_name: str) -> str:
|
33 |
+
response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=15)
|
34 |
+
response.raise_for_status()
|
35 |
+
with open(file_name, 'wb') as file:
|
36 |
+
file.write(response.content)
|
37 |
+
return os.path.abspath(file_name)
|
38 |
+
|
39 |
+
class LoadXlsxFileTool(Tool):
|
40 |
+
name = "load_xlsx_file_tool"
|
41 |
+
description = """This tool loads xlsx file into pandas and returns it"""
|
42 |
+
inputs = {
|
43 |
+
"file_path": {"type": "string", "description": "File path"}
|
44 |
+
}
|
45 |
+
output_type = "object"
|
46 |
+
|
47 |
+
def forward(self, file_path: str) -> object:
|
48 |
+
return pd.read_excel(file_path)
|
49 |
+
|
50 |
+
class LoadTextFileTool(Tool):
|
51 |
+
name = "load_text_file_tool"
|
52 |
+
description = """This tool loads any text file"""
|
53 |
+
inputs = {
|
54 |
+
"file_path": {"type": "string", "description": "File path"}
|
55 |
+
}
|
56 |
+
output_type = "string"
|
57 |
+
|
58 |
+
def forward(self, file_path: str) -> object:
|
59 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
60 |
+
return file.read()
|
61 |
+
|
62 |
+
prompts = yaml.safe_load(
|
63 |
+
resources.files("smolagents.prompts").joinpath("code_agent.yaml").read_text()
|
64 |
+
)
|
65 |
+
|
66 |
+
prompts["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 such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. "
|
67 |
+
+ prompts["system_prompt"])
|
68 |
+
|
69 |
+
def init_agent():
|
70 |
+
gemini_model = OpenAIServerModel(
|
71 |
+
model_id="deepseek-ai/DeepSeek-R1-0528",
|
72 |
+
api_base="https://llm.chutes.ai/v1",
|
73 |
+
api_key=os.getenv("CHUTES_API_KEY"),
|
74 |
+
temperature=0.7
|
75 |
+
)
|
76 |
+
agent = CodeAgent(
|
77 |
+
tools=[
|
78 |
+
DuckDuckGoSearchTool(),
|
79 |
+
VisitWebpageTool(),
|
80 |
+
WikipediaSearchTool(),
|
81 |
+
GetTaskFileTool(),
|
82 |
+
SpeechToTextTool(),
|
83 |
+
LoadXlsxFileTool(),
|
84 |
+
LoadTextFileTool()
|
85 |
+
],
|
86 |
+
model=gemini_model,
|
87 |
+
prompt_templates=prompts,
|
88 |
+
max_steps=15,
|
89 |
+
additional_authorized_imports = ["pandas"]
|
90 |
+
)
|
91 |
+
return agent
|
92 |
+
|
93 |
+
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
|
98 |
|
99 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
100 |
"""
|
|
|
117 |
|
118 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
119 |
try:
|
120 |
+
agent = init_agent()
|
121 |
except Exception as e:
|
122 |
print(f"Error instantiating agent: {e}")
|
123 |
return f"Error initializing agent: {e}", None
|
|
|
153 |
for item in questions_data:
|
154 |
task_id = item.get("task_id")
|
155 |
question_text = item.get("question")
|
156 |
+
print(question_text)
|
157 |
+
file_name = item.get("file_name")
|
158 |
if not task_id or question_text is None:
|
159 |
print(f"Skipping item with missing task_id or question: {item}")
|
160 |
continue
|
161 |
try:
|
162 |
+
submitted_answer = agent.run(f"Task id: {task_id}. Task file: {file_name if file_name != '' else 'is absent'}. Task: " + question_text)
|
163 |
+
if isinstance(submitted_answer, (np.integer, np.floating)):
|
164 |
+
submitted_answer = submitted_answer.item() # Convert NumPy types to Python native types
|
165 |
+
elif isinstance(submitted_answer, list):
|
166 |
+
submitted_answer = [x.item() if isinstance(x, (np.integer, np.floating)) else x for x in submitted_answer]
|
167 |
+
submitted_answer = str(submitted_answer)
|
168 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
169 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
170 |
except Exception as e:
|
|
|
230 |
gr.Markdown(
|
231 |
"""
|
232 |
**Instructions:**
|
|
|
233 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
234 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
235 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
236 |
---
|
237 |
**Disclaimers:**
|
238 |
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).
|