Spaces:
Sleeping
Sleeping
Commit
·
d0490ec
1
Parent(s):
7c48384
Update space
Browse files- app.py +438 -48
- requirements.txt +8 -1
app.py
CHANGED
@@ -1,64 +1,454 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
8 |
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import math
|
5 |
+
import inspect
|
6 |
+
import pandas as pd
|
7 |
+
import datetime
|
8 |
+
from dotenv import load_dotenv
|
9 |
|
10 |
+
from langchain.tools import tool, get_all_tools
|
11 |
+
from typing import TypedDict, Annotated
|
12 |
+
from langgraph.graph.message import add_messages
|
13 |
+
from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
|
14 |
+
from langgraph.prebuilt import ToolNode
|
15 |
+
from langgraph.graph import START, StateGraph, END
|
16 |
+
from langgraph.prebuilt import tools_condition
|
17 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
18 |
|
19 |
+
## # Load environment variables from .env file
|
20 |
+
# --- Constants ---
|
21 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
22 |
|
23 |
+
# Load the environment variables
|
24 |
+
load_dotenv()
|
25 |
+
HF_ACCESS_KEY = os.environ.get("HF_ACCESS_KEY")
|
26 |
+
WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
########## ----- DEFINING TOOLS -----##########
|
|
|
|
|
|
|
|
|
29 |
|
30 |
+
# --- TOOL 1: Web Search Tool (DuckDuckGo) ---
|
31 |
+
@tool
|
32 |
+
def search_tool(query: str) -> str:
|
33 |
+
"""Answer general knowledge or current events queries using DuckDuckGo."""
|
34 |
+
url = f"https://api.duckduckgo.com/?q={query}&format=json&no_html=1"
|
35 |
+
try:
|
36 |
+
resp = requests.get(url, timeout=20)
|
37 |
+
resp.raise_for_status()
|
38 |
+
data = resp.json()
|
39 |
+
for key in ["AbstractText", "Answer", "Definition"]:
|
40 |
+
if data.get(key):
|
41 |
+
return data[key].split(".")[0]
|
42 |
+
return "no_answer"
|
43 |
+
except Exception:
|
44 |
+
return "error"
|
45 |
|
46 |
+
# when you use the @tool decorator from langchain.tools, the tool.name and tool.description are automatically extracted from your function
|
47 |
+
# tool.name is set to the function name (e.g., `search_tool`), and
|
48 |
+
# tool.description is set to the docstring of the function (the triple-quoted string right under def ...) (e.g., "Answer general knowledge or current events queries using DuckDuckGo.").
|
49 |
|
50 |
+
# --- TOOL 2: Weather Tool (OpenWeatherMap) ---
|
51 |
+
@tool
|
52 |
+
def get_weather(city: str) -> str:
|
53 |
+
"""Get current temperature in Celsius for a city."""
|
54 |
+
import os
|
55 |
+
api_key = os.environ.get("WEATHER_API_KEY")
|
56 |
+
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"
|
57 |
+
try:
|
58 |
+
resp = requests.get(url, timeout=20)
|
59 |
+
resp.raise_for_status()
|
60 |
+
data = resp.json()
|
61 |
+
return str(round(data["main"]["temp"]))
|
62 |
+
except Exception:
|
63 |
+
return "error"
|
64 |
|
65 |
+
# --- TOOL 3: Calculator Tool ---
|
66 |
+
@tool
|
67 |
+
def calculator(expression: str) -> str:
|
68 |
+
"""Evaluate math expressions."""
|
69 |
+
try:
|
70 |
+
allowed = "0123456789+-*/(). "
|
71 |
+
if not all(c in allowed for c in expression):
|
72 |
+
return "error"
|
73 |
+
result = eval(expression, {"__builtins__": None}, {})
|
74 |
+
return str(result)
|
75 |
+
except Exception:
|
76 |
+
return "error"
|
77 |
+
|
78 |
+
# --- TOOL 4: Unit Conversion Tool ---
|
79 |
+
@tool
|
80 |
+
def convert_units(args: str) -> str:
|
81 |
+
"""
|
82 |
+
Convert between metric and imperial units (length, mass, temperature).
|
83 |
+
Input format: '<value> <from_unit> to <to_unit>', e.g. '10 meters to feet'
|
84 |
+
"""
|
85 |
+
try:
|
86 |
+
parts = args.lower().split()
|
87 |
+
value = float(parts[0])
|
88 |
+
from_unit = parts[1]
|
89 |
+
to_unit = parts[3]
|
90 |
+
conversions = {
|
91 |
+
("meters", "feet"): lambda v: v * 3.28084,
|
92 |
+
("feet", "meters"): lambda v: v / 3.28084,
|
93 |
+
("kg", "lb"): lambda v: v * 2.20462,
|
94 |
+
("lb", "kg"): lambda v: v / 2.20462,
|
95 |
+
("celsius", "fahrenheit"): lambda v: v * 9/5 + 32,
|
96 |
+
("fahrenheit", "celsius"): lambda v: (v - 32) * 5/9,
|
97 |
+
}
|
98 |
+
func = conversions.get((from_unit, to_unit))
|
99 |
+
if func:
|
100 |
+
return str(round(func(value), 2))
|
101 |
+
return "error"
|
102 |
+
except Exception:
|
103 |
+
return "error"
|
104 |
|
105 |
+
# --- TOOL 5: Date & Time Tool ---
|
106 |
+
@tool
|
107 |
+
def get_time(_: str = "") -> str:
|
108 |
+
"""Get current UTC time as HH:MM."""
|
109 |
+
return datetime.datetime.utc().strftime("%H:%M")
|
110 |
|
111 |
+
@tool
|
112 |
+
def get_date(_: str = "") -> str:
|
113 |
+
"""Get current date as YYYY-MM-DD."""
|
114 |
+
return datetime.datetime.utc().strftime("%Y-%m-%d")
|
115 |
+
|
116 |
+
# --- TOOL 6: Wikipedia Summary Tool ---
|
117 |
+
@tool
|
118 |
+
def wikipedia_summary(query: str) -> str:
|
119 |
+
"""Get a short summary of a topic from Wikipedia."""
|
120 |
+
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query.replace(' ', '_')}"
|
121 |
+
try:
|
122 |
+
resp = requests.get(url, timeout=20)
|
123 |
+
resp.raise_for_status()
|
124 |
+
data = resp.json()
|
125 |
+
return data.get("extract", "no_answer").split(".")[0]
|
126 |
+
except Exception:
|
127 |
+
return "error"
|
128 |
+
|
129 |
+
# --- TOOL 7: Dictionary Tool ---
|
130 |
+
@tool
|
131 |
+
def dictionary_lookup(word: str) -> str:
|
132 |
+
"""Get the definition of an English word."""
|
133 |
+
url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
|
134 |
+
try:
|
135 |
+
resp = requests.get(url, timeout=20)
|
136 |
+
resp.raise_for_status()
|
137 |
+
data = resp.json()
|
138 |
+
return data[0]["meanings"][0]["definitions"][0]["definition"]
|
139 |
+
except Exception:
|
140 |
+
return "error"
|
141 |
+
|
142 |
+
# --- TOOL 8: Currency Conversion Tool ---
|
143 |
+
@tool
|
144 |
+
def currency_convert(args: str) -> str:
|
145 |
+
"""
|
146 |
+
Convert an amount from one currency to another.
|
147 |
+
Input format: '<amount> <from_currency> to <to_currency>', e.g. '100 USD to EUR'
|
148 |
+
"""
|
149 |
+
try:
|
150 |
+
parts = args.upper().split()
|
151 |
+
amount = float(parts[0])
|
152 |
+
from_currency = parts[1]
|
153 |
+
to_currency = parts[3]
|
154 |
+
url = f"https://api.exchangerate.host/convert?from={from_currency}&to={to_currency}&amount={amount}"
|
155 |
+
resp = requests.get(url, timeout=20)
|
156 |
+
resp.raise_for_status()
|
157 |
+
data = resp.json()
|
158 |
+
return str(round(data["result"], 2))
|
159 |
+
except Exception:
|
160 |
+
return "error"
|
161 |
+
|
162 |
+
##-- Tool Discovery ---
|
163 |
+
# Use @tool for each function.
|
164 |
+
# Use get_all_tools() to auto-discover all decorated tools.
|
165 |
+
tools_list = get_all_tools()
|
166 |
+
|
167 |
+
tool_descriptions = "\n".join(f"- {tool.name}: {tool.description}" for tool in tools_list)
|
168 |
+
|
169 |
+
|
170 |
+
## --
|
171 |
+
# --- System Prompt for the Agent ---
|
172 |
+
system_prompt = f"""
|
173 |
+
You are an intelligent assistant with access to the following tools:
|
174 |
+
|
175 |
+
{tool_descriptions}
|
176 |
+
|
177 |
+
For every question, always follow this process (your internal thinking/execution process):
|
178 |
+
|
179 |
+
1. Thought: Reflect step by step on what the user is asking and what information or calculation is needed. Decide if you need to use a tool or can answer directly.
|
180 |
+
2. Action: If a tool is needed, specify which tool to use and with what input. If not, state "No action needed".
|
181 |
+
3. Observation: If you used a tool, report the tool's output here. If not, write "N/A".
|
182 |
+
4. Answer: Give the final answer as a single value (number, string, or comma-separated list), with no extra explanation or units unless requested.
|
183 |
+
|
184 |
+
Your Final Answer should be just [Answer] and should not include any additional text or explanation. Final Answer should be a single value (number, string, or comma-separated list).
|
185 |
+
|
186 |
+
Examples:
|
187 |
+
|
188 |
+
Q: What is 7 * (3 + 2)?
|
189 |
+
Thought: The user is asking for a math calculation. I should use the calculator tool.
|
190 |
+
Action: calculator("7 * (3 + 2)")
|
191 |
+
Observation: 35
|
192 |
+
Answer: 35
|
193 |
+
|
194 |
+
Your Output (Final Answer) for this question should be: '35'.
|
195 |
+
|
196 |
+
Q: What’s the weather in Tokyo?
|
197 |
+
Thought: The user wants the current temperature in Tokyo. I should use the get_weather tool.
|
198 |
+
Action: get_weather("Tokyo")
|
199 |
+
Observation: 22
|
200 |
+
Answer: 22
|
201 |
+
|
202 |
+
Your Output (Final Answer) for this question should be: '22'.
|
203 |
+
|
204 |
+
Q: What is the capital of France?
|
205 |
+
Thought: The user is asking for a factual answer. I can answer directly.
|
206 |
+
Action: No action needed
|
207 |
+
Observation: N/A
|
208 |
+
Answer: Paris
|
209 |
+
|
210 |
+
Your Output (Final Answer) for this question should be: 'Paris'.
|
211 |
+
|
212 |
+
Q: Convert 10 meters to feet.
|
213 |
+
Thought: The user wants to convert units. I should use the convert_units tool.
|
214 |
+
Action: convert_units("10 meters to feet")
|
215 |
+
Observation: 32.81
|
216 |
+
Answer: 32.81
|
217 |
+
|
218 |
+
Your Output (Final Answer) for this question should be: '32.81'.
|
219 |
+
|
220 |
+
Instructions:
|
221 |
+
- Always follow the Thought → Action → Observation → Answer for your internal reasoning and execution before giving final answer.
|
222 |
+
- Use a tool only if necessary, and don't use multiple tools in a call. Don't use a tool if you can answer directly without hallucination.
|
223 |
+
- Always return your final answer as a single value, with no extra explanation.
|
224 |
+
- Be concise and accurate.
|
225 |
"""
|
226 |
+
|
227 |
+
## --- Initialize Hugging Face Model ---
|
228 |
+
# Generate the chat interface, including the tools
|
229 |
+
llm = HuggingFaceEndpoint(
|
230 |
+
repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
231 |
+
huggingfacehub_api_token=HF_ACCESS_KEY,
|
232 |
+
system_prompt=system_prompt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
)
|
234 |
+
# chat = ChatHuggingFace(llm=llm, verbose=True)
|
235 |
+
# tools = [search_tool, fetch_weather]
|
236 |
+
# chat_with_tools = chat.bind_tools(tools)
|
237 |
+
|
238 |
+
|
239 |
+
##
|
240 |
+
# --- LANGGRAPH AGENT SETUP ---
|
241 |
+
|
242 |
+
# Define the state for the graph
|
243 |
+
class AgentState(dict):
|
244 |
+
pass
|
245 |
|
246 |
+
# Define the main node (agent logic)
|
247 |
+
def agent_node(state: AgentState) -> AgentState:
|
248 |
+
question = state["question"]
|
249 |
+
# The LLM will decide which tool to use based on the prompt and tools
|
250 |
+
# response = chat_with_tools.invoke(question) # use this if using ChatHuggingFace with binding option to tools
|
251 |
+
response = llm.invoke(question, tools=tools_list)
|
252 |
+
return AgentState({"question": question, "answer": response})
|
253 |
+
|
254 |
+
# Build the graph
|
255 |
+
graph = StateGraph(AgentState)
|
256 |
+
graph.add_node("agent", agent_node)
|
257 |
+
# graph.add_node("tools", ToolNode(tools)) #use this when using ChatHuggingFace with binding option to tools
|
258 |
+
# graph.add_edge(START, "agent") #alternatively use the below with set_entry_point
|
259 |
+
graph.set_entry_point("agent")
|
260 |
+
graph.add_edge("agent", END)
|
261 |
+
my_agent = graph.compile()
|
262 |
+
|
263 |
+
# Or try simply with Graph instead of StateGraph
|
264 |
+
# from langgraph.graph import Graph
|
265 |
+
# graph = Graph(llm=llm, tools=tools_list)
|
266 |
+
# def agent(question: str) -> str:
|
267 |
+
# return graph.run(question)
|
268 |
+
|
269 |
+
## --- AGENT CALL FUNCTION ---
|
270 |
+
def agent(question: str) -> str:
|
271 |
+
state = AgentState({"question": question})
|
272 |
+
result = my_agent.invoke(state)
|
273 |
+
return result["answer"]
|
274 |
+
|
275 |
+
|
276 |
+
|
277 |
+
## --
|
278 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
279 |
+
"""
|
280 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
281 |
+
and displays the results.
|
282 |
+
"""
|
283 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
284 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
285 |
+
|
286 |
+
if profile:
|
287 |
+
username= f"{profile.username}"
|
288 |
+
print(f"User logged in: {username}")
|
289 |
+
else:
|
290 |
+
print("User not logged in.")
|
291 |
+
return "Please Login to Hugging Face with the button.", None
|
292 |
+
|
293 |
+
api_url = DEFAULT_API_URL
|
294 |
+
questions_url = f"{api_url}/questions"
|
295 |
+
submit_url = f"{api_url}/submit"
|
296 |
+
|
297 |
+
"""
|
298 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
299 |
+
try:
|
300 |
+
agent = BasicAgent()
|
301 |
+
except Exception as e:
|
302 |
+
print(f"Error instantiating agent: {e}")
|
303 |
+
return f"Error initializing agent: {e}", None
|
304 |
+
# 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)
|
305 |
+
"""
|
306 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
307 |
+
print(agent_code)
|
308 |
+
|
309 |
+
# 2. Fetch Questions
|
310 |
+
print(f"Fetching questions from: {questions_url}")
|
311 |
+
try:
|
312 |
+
response = requests.get(questions_url, timeout=15)
|
313 |
+
response.raise_for_status()
|
314 |
+
questions_data = response.json()
|
315 |
+
if not questions_data:
|
316 |
+
print("Fetched questions list is empty.")
|
317 |
+
return "Fetched questions list is empty or invalid format.", None
|
318 |
+
print(f"Fetched {len(questions_data)} questions.")
|
319 |
+
except requests.exceptions.RequestException as e:
|
320 |
+
print(f"Error fetching questions: {e}")
|
321 |
+
return f"Error fetching questions: {e}", None
|
322 |
+
except requests.exceptions.JSONDecodeError as e:
|
323 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
324 |
+
print(f"Response text: {response.text[:500]}")
|
325 |
+
return f"Error decoding server response for questions: {e}", None
|
326 |
+
except Exception as e:
|
327 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
328 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
329 |
+
|
330 |
+
# 3. Run your Agent
|
331 |
+
results_log = []
|
332 |
+
answers_payload = []
|
333 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
334 |
+
for item in questions_data:
|
335 |
+
task_id = item.get("task_id")
|
336 |
+
question_text = item.get("question")
|
337 |
+
if not task_id or question_text is None:
|
338 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
339 |
+
continue
|
340 |
+
try:
|
341 |
+
submitted_answer = agent(question_text)
|
342 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
343 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
344 |
+
except Exception as e:
|
345 |
+
print(f"Error running agent on task {task_id}: {e}")
|
346 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
347 |
+
|
348 |
+
if not answers_payload:
|
349 |
+
print("Agent did not produce any answers to submit.")
|
350 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
351 |
+
|
352 |
+
# 4. Prepare Submission
|
353 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
354 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
355 |
+
print(status_update)
|
356 |
+
|
357 |
+
# 5. Submit
|
358 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
359 |
+
try:
|
360 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
361 |
+
response.raise_for_status()
|
362 |
+
result_data = response.json()
|
363 |
+
final_status = (
|
364 |
+
f"Submission Successful!\n"
|
365 |
+
f"User: {result_data.get('username')}\n"
|
366 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
367 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
368 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
369 |
+
)
|
370 |
+
print("Submission successful.")
|
371 |
+
results_df = pd.DataFrame(results_log)
|
372 |
+
return final_status, results_df
|
373 |
+
except requests.exceptions.HTTPError as e:
|
374 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
375 |
+
try:
|
376 |
+
error_json = e.response.json()
|
377 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
378 |
+
except requests.exceptions.JSONDecodeError:
|
379 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
380 |
+
status_message = f"Submission Failed: {error_detail}"
|
381 |
+
print(status_message)
|
382 |
+
results_df = pd.DataFrame(results_log)
|
383 |
+
return status_message, results_df
|
384 |
+
except requests.exceptions.Timeout:
|
385 |
+
status_message = "Submission Failed: The request timed out."
|
386 |
+
print(status_message)
|
387 |
+
results_df = pd.DataFrame(results_log)
|
388 |
+
return status_message, results_df
|
389 |
+
except requests.exceptions.RequestException as e:
|
390 |
+
status_message = f"Submission Failed: Network error - {e}"
|
391 |
+
print(status_message)
|
392 |
+
results_df = pd.DataFrame(results_log)
|
393 |
+
return status_message, results_df
|
394 |
+
except Exception as e:
|
395 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
396 |
+
print(status_message)
|
397 |
+
results_df = pd.DataFrame(results_log)
|
398 |
+
return status_message, results_df
|
399 |
+
|
400 |
+
|
401 |
+
# --- Build Gradio Interface using Blocks ---
|
402 |
+
with gr.Blocks() as demo:
|
403 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
404 |
+
gr.Markdown(
|
405 |
+
"""
|
406 |
+
**Instructions:**
|
407 |
+
|
408 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
409 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
410 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
411 |
+
|
412 |
+
---
|
413 |
+
**Disclaimers:**
|
414 |
+
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).
|
415 |
+
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.
|
416 |
+
"""
|
417 |
+
)
|
418 |
+
|
419 |
+
gr.LoginButton()
|
420 |
+
|
421 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
422 |
+
|
423 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
424 |
+
# Removed max_rows=10 from DataFrame constructor
|
425 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
426 |
+
|
427 |
+
run_button.click(
|
428 |
+
fn=run_and_submit_all,
|
429 |
+
outputs=[status_output, results_table]
|
430 |
+
)
|
431 |
|
432 |
if __name__ == "__main__":
|
433 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
434 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
435 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
436 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
437 |
+
|
438 |
+
if space_host_startup:
|
439 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
440 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
441 |
+
else:
|
442 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
443 |
+
|
444 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
445 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
446 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
447 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
448 |
+
else:
|
449 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
450 |
+
|
451 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
452 |
+
|
453 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
454 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
CHANGED
@@ -1 +1,8 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
requests
|
3 |
+
math
|
4 |
+
langchain
|
5 |
+
langgraph
|
6 |
+
langchainhub
|
7 |
+
huggingface-hub
|
8 |
+
langchain-huggingface
|