Spaces:
Configuration error
Configuration error
Update app.py
Browse files
app.py
CHANGED
@@ -1,196 +1,194 @@
|
|
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 ---
|
9 |
-
DEFAULT_API_URL
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
# ---
|
12 |
-
|
13 |
-
|
14 |
-
def __init__(self):
|
15 |
-
print("BasicAgent initialized.")
|
16 |
-
def __call__(self, question: str) -> str:
|
17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
18 |
-
fixed_answer = "This is a default answer."
|
19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
20 |
-
return fixed_answer
|
21 |
|
22 |
-
|
|
|
|
|
|
|
23 |
"""
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
26 |
"""
|
27 |
-
|
28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
print("User not logged in.")
|
35 |
-
return "Please Login to Hugging Face with the button.", None
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
submit_url = f"{api_url}/submit"
|
40 |
|
41 |
-
|
|
|
|
|
42 |
try:
|
43 |
-
|
|
|
|
|
|
|
44 |
except Exception as e:
|
45 |
-
|
46 |
-
return f"
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
-
|
50 |
|
51 |
-
#
|
52 |
-
print(f"Fetching questions from: {questions_url}")
|
53 |
try:
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
if not questions_data:
|
58 |
-
print("Fetched questions list is empty.")
|
59 |
-
return "Fetched questions list is empty or invalid format.", None
|
60 |
-
print(f"Fetched {len(questions_data)} questions.")
|
61 |
-
except requests.exceptions.RequestException as e:
|
62 |
-
print(f"Error fetching questions: {e}")
|
63 |
-
return f"Error fetching questions: {e}", None
|
64 |
-
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
66 |
-
print(f"Response text: {response.text[:500]}")
|
67 |
-
return f"Error decoding server response for questions: {e}", None
|
68 |
except Exception as e:
|
69 |
-
|
70 |
-
return f"
|
71 |
-
|
72 |
-
# 3. Run your Agent
|
73 |
-
results_log = []
|
74 |
-
answers_payload = []
|
75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
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:
|
87 |
-
print(f"Error running agent on task {task_id}: {e}")
|
88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
89 |
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
-
print(status_update)
|
98 |
|
99 |
-
#
|
100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
101 |
try:
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
106 |
f"Submission Successful!\n"
|
107 |
-
f"User: {
|
108 |
-
f"
|
109 |
-
f"({
|
110 |
-
f"
|
|
|
111 |
)
|
112 |
-
|
113 |
-
results_df = pd.DataFrame(results_log)
|
114 |
-
return final_status, results_df
|
115 |
-
except requests.exceptions.HTTPError as e:
|
116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
117 |
-
try:
|
118 |
-
error_json = e.response.json()
|
119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
120 |
-
except requests.exceptions.JSONDecodeError:
|
121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
-
status_message = f"Submission Failed: {error_detail}"
|
123 |
-
print(status_message)
|
124 |
-
results_df = pd.DataFrame(results_log)
|
125 |
-
return status_message, results_df
|
126 |
-
except requests.exceptions.Timeout:
|
127 |
-
status_message = "Submission Failed: The request timed out."
|
128 |
-
print(status_message)
|
129 |
-
results_df = pd.DataFrame(results_log)
|
130 |
-
return status_message, results_df
|
131 |
-
except requests.exceptions.RequestException as e:
|
132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
133 |
-
print(status_message)
|
134 |
-
results_df = pd.DataFrame(results_log)
|
135 |
-
return status_message, results_df
|
136 |
except Exception as e:
|
137 |
-
|
138 |
-
|
139 |
-
results_df = pd.DataFrame(results_log)
|
140 |
-
return status_message, results_df
|
141 |
|
|
|
142 |
|
143 |
-
# --- Build Gradio Interface using Blocks ---
|
144 |
with gr.Blocks() as demo:
|
145 |
-
gr.Markdown("#
|
146 |
-
gr.Markdown(
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
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).
|
157 |
-
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.
|
158 |
-
"""
|
159 |
-
)
|
160 |
-
|
161 |
gr.LoginButton()
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
# Removed max_rows=10 from DataFrame constructor
|
167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
168 |
-
|
169 |
-
run_button.click(
|
170 |
-
fn=run_and_submit_all,
|
171 |
-
outputs=[status_output, results_table]
|
172 |
-
)
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
-
|
176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
179 |
-
|
180 |
-
if space_host_startup:
|
181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
183 |
-
else:
|
184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
-
|
186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
-
else:
|
191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
192 |
-
|
193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
-
|
195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
import os
|
2 |
+
import logging
|
3 |
+
|
4 |
import gradio as gr
|
5 |
import requests
|
|
|
6 |
import pandas as pd
|
7 |
+
import openai
|
8 |
+
from openai import OpenAI
|
9 |
+
|
10 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, tool
|
11 |
+
from smolagents.models import OpenAIServerModel
|
12 |
+
|
13 |
+
# --- Logging ---
|
14 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
|
|
|
17 |
# --- Constants ---
|
18 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
19 |
+
OPENAI_MODEL_ID = os.getenv("OPENAI_MODEL_ID", "gpt-4.1")
|
20 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
21 |
+
if not OPENAI_API_KEY:
|
22 |
+
raise RuntimeError("Please set OPENAI_API_KEY in your Space secrets.")
|
23 |
|
24 |
+
# --- Configure OpenAI SDK (for tools if needed) ---
|
25 |
+
openai.api_key = "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"
|
26 |
+
client = OpenAI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
# --- Tools ---
|
29 |
+
|
30 |
+
@tool
|
31 |
+
def summarize_query(query: str) -> str:
|
32 |
"""
|
33 |
+
Reframes an unclear search query to improve relevance.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
query (str): The original search query.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
str: A concise, improved version.
|
40 |
"""
|
41 |
+
return f"Summarize and reframe: {query}"
|
|
|
42 |
|
43 |
+
@tool
|
44 |
+
def wikipedia_search(page: str) -> str:
|
45 |
+
"""
|
46 |
+
Fetches the summary extract of an English Wikipedia page.
|
|
|
|
|
47 |
|
48 |
+
Args:
|
49 |
+
page (str): e.g. 'Mercedes_Sosa_discography'
|
|
|
50 |
|
51 |
+
Returns:
|
52 |
+
str: The page’s extract text.
|
53 |
+
"""
|
54 |
try:
|
55 |
+
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{page}"
|
56 |
+
r = requests.get(url, timeout=10)
|
57 |
+
r.raise_for_status()
|
58 |
+
return r.json().get("extract", "")
|
59 |
except Exception as e:
|
60 |
+
logger.exception("Wikipedia lookup failed")
|
61 |
+
return f"Wikipedia error: {e}"
|
62 |
+
|
63 |
+
search_tool = DuckDuckGoSearchTool()
|
64 |
+
wiki_tool = wikipedia_search
|
65 |
+
summarize_tool = summarize_query
|
66 |
+
|
67 |
+
# --- ReACT Prompt ---
|
68 |
+
|
69 |
+
instruction_prompt = """
|
70 |
+
You are a ReACT agent with three tools:
|
71 |
+
• DuckDuckGoSearchTool(query: str)
|
72 |
+
• wikipedia_search(page: str)
|
73 |
+
• summarize_query(query: str)
|
74 |
+
|
75 |
+
Internally, for each question:
|
76 |
+
1. Thought: decide which tool to call.
|
77 |
+
2. Action: call the chosen tool.
|
78 |
+
3. Observation: record the result.
|
79 |
+
4. If empty/irrelevant:
|
80 |
+
Thought: retry with summarize_query + DuckDuckGoSearchTool.
|
81 |
+
Record new Observation.
|
82 |
+
5. Thought: integrate observations.
|
83 |
+
|
84 |
+
Finally, output your answer with the following template:
|
85 |
+
FINAL ANSWER: [YOUR FINAL ANSWER].
|
86 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
87 |
+
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.
|
88 |
+
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.
|
89 |
+
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.
|
90 |
+
|
91 |
+
"""
|
92 |
+
|
93 |
+
# --- Build the Agent with OpenAIServerModel ---
|
94 |
+
|
95 |
+
model = OpenAIServerModel(
|
96 |
+
model_id=OPENAI_MODEL_ID,
|
97 |
+
api_key=OPENAI_API_KEY
|
98 |
+
)
|
99 |
+
|
100 |
+
smart_agent = CodeAgent(
|
101 |
+
tools=[search_tool, wiki_tool, summarize_tool],
|
102 |
+
model=model
|
103 |
+
)
|
104 |
+
|
105 |
+
# --- Gradio Wrapper ---
|
106 |
+
|
107 |
+
class BasicAgent:
|
108 |
+
def __init__(self):
|
109 |
+
logger.info("Initialized SmolAgent with OpenAI GPT-4.1")
|
110 |
+
|
111 |
+
def __call__(self, question: str) -> str:
|
112 |
+
if not question.strip():
|
113 |
+
return "AGENT ERROR: empty question"
|
114 |
+
prompt = instruction_prompt.strip() + "\n\nQUESTION: " + question.strip()
|
115 |
+
try:
|
116 |
+
return smart_agent.run(prompt)
|
117 |
+
except Exception as e:
|
118 |
+
logger.exception("Agent run error")
|
119 |
+
return f"AGENT ERROR: {e}"
|
120 |
+
|
121 |
+
# --- Submission Logic ---
|
122 |
+
|
123 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
124 |
+
if not profile:
|
125 |
+
return "Please log in to Hugging Face.", None
|
126 |
+
|
127 |
+
username = profile.username
|
128 |
+
space_id = os.getenv("SPACE_ID", "")
|
129 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
130 |
+
agent = BasicAgent()
|
131 |
|
132 |
+
# fetch
|
|
|
133 |
try:
|
134 |
+
resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
|
135 |
+
resp.raise_for_status()
|
136 |
+
questions = resp.json() or []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
except Exception as e:
|
138 |
+
logger.exception("Failed fetch")
|
139 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
+
logs, payload = [], []
|
142 |
+
for item in questions:
|
143 |
+
tid = item.get("task_id")
|
144 |
+
q = item.get("question")
|
145 |
+
if not tid or not q:
|
146 |
+
continue
|
147 |
+
ans = agent(q)
|
148 |
+
logs.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})
|
149 |
+
payload.append({"task_id": tid, "submitted_answer": ans})
|
150 |
|
151 |
+
if not payload:
|
152 |
+
return "Agent did not produce any answers.", pd.DataFrame(logs)
|
|
|
|
|
153 |
|
154 |
+
# submit
|
|
|
155 |
try:
|
156 |
+
post = requests.post(
|
157 |
+
f"{DEFAULT_API_URL}/submit",
|
158 |
+
json={"username": username, "agent_code": agent_code, "answers": payload},
|
159 |
+
timeout=60
|
160 |
+
)
|
161 |
+
post.raise_for_status()
|
162 |
+
result = post.json()
|
163 |
+
status = (
|
164 |
f"Submission Successful!\n"
|
165 |
+
f"User: {result.get('username')}\n"
|
166 |
+
f"Score: {result.get('score','N/A')}%\n"
|
167 |
+
f"({result.get('correct_count','?')}/"
|
168 |
+
f"{result.get('total_attempted','?')})\n"
|
169 |
+
f"Message: {result.get('message','')}"
|
170 |
)
|
171 |
+
return status, pd.DataFrame(logs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
172 |
except Exception as e:
|
173 |
+
logger.exception("Submit failed")
|
174 |
+
return f"Submission Failed: {e}", pd.DataFrame(logs)
|
|
|
|
|
175 |
|
176 |
+
# --- Gradio App ---
|
177 |
|
|
|
178 |
with gr.Blocks() as demo:
|
179 |
+
gr.Markdown("# SmolAgent GAIA Runner 🚀")
|
180 |
+
gr.Markdown("""
|
181 |
+
**Instructions:**
|
182 |
+
1. Clone this space.
|
183 |
+
2. In Settings → Secrets, add `OPENAI_API_KEY` and (optionally) `OPENAI_MODEL_ID`.
|
184 |
+
3. Log in to Hugging Face.
|
185 |
+
4. Click **Run Evaluation & Submit All Answers**.
|
186 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
gr.LoginButton()
|
188 |
+
btn = gr.Button("Run Evaluation & Submit All Answers")
|
189 |
+
out_status = gr.Textbox(label="Status", lines=5, interactive=False)
|
190 |
+
out_table = gr.DataFrame(label="Questions & Answers", wrap=True)
|
191 |
+
btn.click(run_and_submit_all, outputs=[out_status, out_table])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
|
193 |
if __name__ == "__main__":
|
194 |
+
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|