Raffaele Terribile
commited on
Aggiungi utilizzo di modello locale
Browse files- app.py +231 -208
- requirements.txt +11 -1
app.py
CHANGED
@@ -4,7 +4,7 @@ import requests
|
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
|
7 |
-
from smolagents import CodeAgent,
|
8 |
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
@@ -12,232 +12,255 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
12 |
|
13 |
@tool
|
14 |
def invert_sentence(sentence: str) -> str:
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
|
24 |
# --- First Agent Definition ---
|
25 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
26 |
class FirstAgent:
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
# --- Basic Agent Definition ---
|
57 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
58 |
class BasicAgent:
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
|
69 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
|
189 |
|
190 |
# --- Build Gradio Interface using Blocks ---
|
191 |
with gr.Blocks() as demo:
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
|
208 |
-
|
209 |
|
210 |
-
|
211 |
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
|
221 |
if __name__ == "__main__":
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
|
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
|
7 |
+
from smolagents import CodeAgent, HfApiModel, VisitWebpageTool, PythonInterpreterTool, WebSearchTool, WikipediaSearchTool, FinalAnswerTool, Tool, tool # GoogleSearchTool (usa SERPAPI_API_KEY), DuckDuckGoSearchTool
|
8 |
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
|
|
12 |
|
13 |
@tool
|
14 |
def invert_sentence(sentence: str) -> str:
|
15 |
+
"""
|
16 |
+
Inverts the order of all characters in a sentence.
|
17 |
+
Args:
|
18 |
+
sentence (str): The sentence to invert.
|
19 |
+
Returns:
|
20 |
+
str: The sentence with characters in reverse order.
|
21 |
+
"""
|
22 |
+
return sentence[::-1]
|
23 |
|
24 |
# --- First Agent Definition ---
|
25 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
26 |
class FirstAgent:
|
27 |
+
### First Agent is the first attempt to develop an agent for the course. ###
|
28 |
+
def __init__(self):
|
29 |
+
# # Usa un modello Hugging Face gratuito
|
30 |
+
# token = os.getenv(os.getenv("TOKEN_NAME"))
|
31 |
+
# os.environ["HF_TOKEN"] = token
|
32 |
+
# model = InferenceClientModel(
|
33 |
+
# token=token
|
34 |
+
# )
|
35 |
+
|
36 |
+
# Configurazione con fallback multipli
|
37 |
+
model = None
|
38 |
+
|
39 |
+
# Try 1: Modello locale via Transformers
|
40 |
+
try:
|
41 |
+
from transformers import pipeline
|
42 |
+
model = HfApiModel(
|
43 |
+
model_id="microsoft/DialoGPT-small" # ~500MB, scaricato automaticamente
|
44 |
+
)
|
45 |
+
print("Using local DialoGPT model")
|
46 |
+
except Exception as e:
|
47 |
+
print(f"Local model failed: {e}")
|
48 |
+
|
49 |
+
# Try 2: Modello remoto gratuito
|
50 |
+
try:
|
51 |
+
model = LiteLLMModel(
|
52 |
+
model_id="groq/mixtral-8x7b-32768" # Gratuito con registrazione
|
53 |
+
)
|
54 |
+
print("Using Groq remote model")
|
55 |
+
except Exception as e:
|
56 |
+
print(f"Remote model failed: {e}")
|
57 |
+
raise Exception("No working model configuration found")
|
58 |
+
|
59 |
+
self.agent = CodeAgent(
|
60 |
+
model=model,
|
61 |
+
tools=[
|
62 |
+
# DuckDuckGoSearchTool(),
|
63 |
+
# GoogleSearchTool(),
|
64 |
+
WebSearchTool(),
|
65 |
+
PythonInterpreterTool(),
|
66 |
+
WikipediaSearchTool(),
|
67 |
+
VisitWebpageTool() #,
|
68 |
+
# FinalAnswerTool #,
|
69 |
+
# Tool(name="invert_sentence", func=invert_sentence, description="Inverts the order of characters in a sentence.")
|
70 |
+
]
|
71 |
+
)
|
72 |
+
print("FirstAgent initialized.")
|
73 |
+
def __call__(self, question: str) -> str:
|
74 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
75 |
+
answer = self.agent.run(question)
|
76 |
+
print(f"Agent returning fixed answer: {answer}")
|
77 |
+
return answer
|
78 |
|
79 |
# --- Basic Agent Definition ---
|
80 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
81 |
class BasicAgent:
|
82 |
+
### Basic Agent is a placeholder for a simple agent that always returns a fixed answer. ###
|
83 |
+
### It is used to demonstrate the structure of an agent. ###
|
84 |
+
def __init__(self):
|
85 |
+
print("BasicAgent initialized.")
|
86 |
+
def __call__(self, question: str) -> str:
|
87 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
88 |
+
fixed_answer = "This is a default answer."
|
89 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
90 |
+
return fixed_answer
|
91 |
|
92 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
93 |
+
"""
|
94 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
95 |
+
and displays the results.
|
96 |
+
"""
|
97 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
98 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
99 |
+
|
100 |
+
if profile:
|
101 |
+
username= f"{profile.username}"
|
102 |
+
print(f"User logged in: {username}")
|
103 |
+
else:
|
104 |
+
print("User not logged in.")
|
105 |
+
return "Please Login to Hugging Face with the button.", None
|
106 |
+
|
107 |
+
api_url = DEFAULT_API_URL
|
108 |
+
questions_url = f"{api_url}/questions"
|
109 |
+
submit_url = f"{api_url}/submit"
|
110 |
+
|
111 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
112 |
+
try:
|
113 |
+
agent = FirstAgent()
|
114 |
+
except Exception as e:
|
115 |
+
print(f"Error instantiating agent: {e}")
|
116 |
+
return f"Error initializing agent: {e}", None
|
117 |
+
# 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)
|
118 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
119 |
+
print(agent_code)
|
120 |
+
|
121 |
+
# 2. Fetch Questions
|
122 |
+
print(f"Fetching questions from: {questions_url}")
|
123 |
+
try:
|
124 |
+
response = requests.get(questions_url, timeout=15)
|
125 |
+
response.raise_for_status()
|
126 |
+
questions_data = response.json()
|
127 |
+
if not questions_data:
|
128 |
+
print("Fetched questions list is empty.")
|
129 |
+
return "Fetched questions list is empty or invalid format.", None
|
130 |
+
print(f"Fetched {len(questions_data)} questions.")
|
131 |
+
except requests.exceptions.RequestException as e:
|
132 |
+
print(f"Error fetching questions: {e}")
|
133 |
+
return f"Error fetching questions: {e}", None
|
134 |
+
except requests.exceptions.JSONDecodeError as e:
|
135 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
136 |
+
print(f"Response text: {response.text[:500]}")
|
137 |
+
return f"Error decoding server response for questions: {e}", None
|
138 |
+
except Exception as e:
|
139 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
140 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
141 |
+
|
142 |
+
# 3. Run your Agent
|
143 |
+
results_log = []
|
144 |
+
answers_payload = []
|
145 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
146 |
+
for item in questions_data:
|
147 |
+
task_id = item.get("task_id")
|
148 |
+
question_text = item.get("question")
|
149 |
+
if not task_id or question_text is None:
|
150 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
151 |
+
continue
|
152 |
+
try:
|
153 |
+
submitted_answer = agent(question_text)
|
154 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
155 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
156 |
+
except Exception as e:
|
157 |
+
print(f"Error running agent on task {task_id}: {e}")
|
158 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
159 |
+
|
160 |
+
if not answers_payload:
|
161 |
+
print("Agent did not produce any answers to submit.")
|
162 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
163 |
+
|
164 |
+
# 4. Prepare Submission
|
165 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
166 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
167 |
+
print(status_update)
|
168 |
+
|
169 |
+
# 5. Submit
|
170 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
171 |
+
try:
|
172 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
173 |
+
response.raise_for_status()
|
174 |
+
result_data = response.json()
|
175 |
+
final_status = (
|
176 |
+
f"Submission Successful!\n"
|
177 |
+
f"User: {result_data.get('username')}\n"
|
178 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
179 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
180 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
181 |
+
)
|
182 |
+
print("Submission successful.")
|
183 |
+
results_df = pd.DataFrame(results_log)
|
184 |
+
return final_status, results_df
|
185 |
+
except requests.exceptions.HTTPError as e:
|
186 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
187 |
+
try:
|
188 |
+
error_json = e.response.json()
|
189 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
190 |
+
except requests.exceptions.JSONDecodeError:
|
191 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
192 |
+
status_message = f"Submission Failed: {error_detail}"
|
193 |
+
print(status_message)
|
194 |
+
results_df = pd.DataFrame(results_log)
|
195 |
+
return status_message, results_df
|
196 |
+
except requests.exceptions.Timeout:
|
197 |
+
status_message = "Submission Failed: The request timed out."
|
198 |
+
print(status_message)
|
199 |
+
results_df = pd.DataFrame(results_log)
|
200 |
+
return status_message, results_df
|
201 |
+
except requests.exceptions.RequestException as e:
|
202 |
+
status_message = f"Submission Failed: Network error - {e}"
|
203 |
+
print(status_message)
|
204 |
+
results_df = pd.DataFrame(results_log)
|
205 |
+
return status_message, results_df
|
206 |
+
except Exception as e:
|
207 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
208 |
+
print(status_message)
|
209 |
+
results_df = pd.DataFrame(results_log)
|
210 |
+
return status_message, results_df
|
211 |
|
212 |
|
213 |
# --- Build Gradio Interface using Blocks ---
|
214 |
with gr.Blocks() as demo:
|
215 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
216 |
+
gr.Markdown(
|
217 |
+
"""
|
218 |
+
**Instructions:**
|
219 |
|
220 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
221 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
222 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
223 |
|
224 |
+
---
|
225 |
+
**Disclaimers:**
|
226 |
+
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).
|
227 |
+
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.
|
228 |
+
"""
|
229 |
+
)
|
230 |
|
231 |
+
gr.LoginButton()
|
232 |
|
233 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
234 |
|
235 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
236 |
+
# Removed max_rows=10 from DataFrame constructor
|
237 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
238 |
|
239 |
+
run_button.click(
|
240 |
+
fn=run_and_submit_all,
|
241 |
+
outputs=[status_output, results_table]
|
242 |
+
)
|
243 |
|
244 |
if __name__ == "__main__":
|
245 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
246 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
247 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
248 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
249 |
+
|
250 |
+
if space_host_startup:
|
251 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
252 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
253 |
+
else:
|
254 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
255 |
+
|
256 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
257 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
258 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
259 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
260 |
+
else:
|
261 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
262 |
+
|
263 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
264 |
+
|
265 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
266 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
CHANGED
@@ -3,5 +3,15 @@ requests
|
|
3 |
pandas
|
4 |
smolagents
|
5 |
wikipedia-api
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
# duckduckgo-search
|
7 |
-
#
|
|
|
|
3 |
pandas
|
4 |
smolagents
|
5 |
wikipedia-api
|
6 |
+
# Dipendenze per modelli locali
|
7 |
+
transformers
|
8 |
+
torch
|
9 |
+
tokenizers
|
10 |
+
# Dipendenze per LiteLLM (modelli multipli)
|
11 |
+
litellm
|
12 |
+
# Hugging Face Hub per download modelli
|
13 |
+
huggingface_hub
|
14 |
+
# Opzionali ma utili
|
15 |
# duckduckgo-search
|
16 |
+
# accelerate # Per modelli più grandi
|
17 |
+
# bitsandbytes # Per quantizzazione
|