Spaces:
Sleeping
Sleeping
wilson.fok@hk.ncs-i.com
commited on
Commit
·
f0ae93a
1
Parent(s):
0aa6fa5
Refractored codes.
Browse files- .gitattributes +35 -35
- .gitignore +1 -0
- README.md +50 -50
- agent_tools.py +89 -0
- app.py +397 -483
- requirements.txt +7 -5
.gitattributes
CHANGED
@@ -1,35 +1,35 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
__pycache__
|
README.md
CHANGED
@@ -1,51 +1,51 @@
|
|
1 |
-
---
|
2 |
-
title: LLM-Enhanced Internet Search Agent
|
3 |
-
emoji: 🕵🏻♂️
|
4 |
-
colorFrom: indigo
|
5 |
-
colorTo: indigo
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 5.25.2
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
hf_oauth: true
|
11 |
-
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
12 |
-
hf_oauth_expiration_minutes: 480
|
13 |
-
---
|
14 |
-
|
15 |
-
# LLM-Enhanced Internet Search Agent
|
16 |
-
|
17 |
-
This agent uses a two-step approach to answer questions:
|
18 |
-
|
19 |
-
1. **Question Breakdown**: The agent first uses an LLM (GPT-3.5) to break down complex questions into 2-3 key search queries
|
20 |
-
2. **Targeted Search**: Each search query is sent to Wikipedia's API to retrieve relevant information
|
21 |
-
3. **Answer Synthesis**: The agent then uses the LLM to synthesize a comprehensive answer based on all search results
|
22 |
-
|
23 |
-
## Features
|
24 |
-
|
25 |
-
- **Smart Query Generation**: Transforms natural language questions into optimized search queries
|
26 |
-
- **Parallel Search Processing**: Searches for multiple key aspects of the question simultaneously
|
27 |
-
- **Knowledge Synthesis**: Combines information from multiple sources into a cohesive answer
|
28 |
-
- **Fallback Mechanisms**: Graceful handling of errors at each step of the process
|
29 |
-
|
30 |
-
## Setup Requirements
|
31 |
-
|
32 |
-
1. Clone this repository
|
33 |
-
2. Install required packages: `pip install -r requirements.txt`
|
34 |
-
3. Set your OpenAI API key as an environment variable: `OPENAI_API_KEY=your-api-key`
|
35 |
-
|
36 |
-
## How It Works
|
37 |
-
|
38 |
-
1. User submits a question
|
39 |
-
2. LLM breaks down the question into key search terms
|
40 |
-
3. Search terms are used to query Wikipedia API
|
41 |
-
4. Results from multiple searches are collected
|
42 |
-
5. LLM synthesizes the information into a comprehensive answer
|
43 |
-
6. Answer is returned to the user
|
44 |
-
|
45 |
-
This approach is more effective than direct internet searches because:
|
46 |
-
- It identifies the most relevant aspects of complex questions
|
47 |
-
- It can break multi-part questions into their components
|
48 |
-
- It leverages the LLM's understanding of natural language
|
49 |
-
- It provides more targeted and accurate search results
|
50 |
-
|
51 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
+
---
|
2 |
+
title: LLM-Enhanced Internet Search Agent
|
3 |
+
emoji: 🕵🏻♂️
|
4 |
+
colorFrom: indigo
|
5 |
+
colorTo: indigo
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 5.25.2
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
hf_oauth: true
|
11 |
+
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
12 |
+
hf_oauth_expiration_minutes: 480
|
13 |
+
---
|
14 |
+
|
15 |
+
# LLM-Enhanced Internet Search Agent
|
16 |
+
|
17 |
+
This agent uses a two-step approach to answer questions:
|
18 |
+
|
19 |
+
1. **Question Breakdown**: The agent first uses an LLM (GPT-3.5) to break down complex questions into 2-3 key search queries
|
20 |
+
2. **Targeted Search**: Each search query is sent to Wikipedia's API to retrieve relevant information
|
21 |
+
3. **Answer Synthesis**: The agent then uses the LLM to synthesize a comprehensive answer based on all search results
|
22 |
+
|
23 |
+
## Features
|
24 |
+
|
25 |
+
- **Smart Query Generation**: Transforms natural language questions into optimized search queries
|
26 |
+
- **Parallel Search Processing**: Searches for multiple key aspects of the question simultaneously
|
27 |
+
- **Knowledge Synthesis**: Combines information from multiple sources into a cohesive answer
|
28 |
+
- **Fallback Mechanisms**: Graceful handling of errors at each step of the process
|
29 |
+
|
30 |
+
## Setup Requirements
|
31 |
+
|
32 |
+
1. Clone this repository
|
33 |
+
2. Install required packages: `pip install -r requirements.txt`
|
34 |
+
3. Set your OpenAI API key as an environment variable: `OPENAI_API_KEY=your-api-key`
|
35 |
+
|
36 |
+
## How It Works
|
37 |
+
|
38 |
+
1. User submits a question
|
39 |
+
2. LLM breaks down the question into key search terms
|
40 |
+
3. Search terms are used to query Wikipedia API
|
41 |
+
4. Results from multiple searches are collected
|
42 |
+
5. LLM synthesizes the information into a comprehensive answer
|
43 |
+
6. Answer is returned to the user
|
44 |
+
|
45 |
+
This approach is more effective than direct internet searches because:
|
46 |
+
- It identifies the most relevant aspects of complex questions
|
47 |
+
- It can break multi-part questions into their components
|
48 |
+
- It leverages the LLM's understanding of natural language
|
49 |
+
- It provides more targeted and accurate search results
|
50 |
+
|
51 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agent_tools.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from bs4 import BeautifulSoup
|
3 |
+
|
4 |
+
def duckduckgo_search(query: str, num_results: int = 3) -> list:
|
5 |
+
"""
|
6 |
+
Perform a search using DuckDuckGo and return the results.
|
7 |
+
|
8 |
+
Args:
|
9 |
+
query: The search query string
|
10 |
+
num_results: Maximum number of results to return (default: 3)
|
11 |
+
|
12 |
+
Returns:
|
13 |
+
List of dictionaries containing search results with title, url, and snippet
|
14 |
+
"""
|
15 |
+
print(f"Performing DuckDuckGo search for: {query}")
|
16 |
+
|
17 |
+
try:
|
18 |
+
headers = {
|
19 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
20 |
+
}
|
21 |
+
|
22 |
+
# Format the query for the URL
|
23 |
+
formatted_query = query.replace(' ', '+')
|
24 |
+
url = f"https://html.duckduckgo.com/html/?q={formatted_query}"
|
25 |
+
|
26 |
+
# Send the request
|
27 |
+
response = requests.get(url, headers=headers, timeout=10)
|
28 |
+
response.raise_for_status()
|
29 |
+
|
30 |
+
# Parse the HTML response
|
31 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
32 |
+
|
33 |
+
# Extract search results
|
34 |
+
results = []
|
35 |
+
for result in soup.select('.result'):
|
36 |
+
title_elem = result.select_one('.result__title')
|
37 |
+
link_elem = result.select_one('.result__url')
|
38 |
+
snippet_elem = result.select_one('.result__snippet')
|
39 |
+
|
40 |
+
if title_elem and link_elem:
|
41 |
+
title = title_elem.get_text(strip=True)
|
42 |
+
url = link_elem.get('href') if link_elem.get('href') else link_elem.get_text(strip=True)
|
43 |
+
snippet = snippet_elem.get_text(strip=True) if snippet_elem else ""
|
44 |
+
|
45 |
+
results.append({
|
46 |
+
"title": title,
|
47 |
+
"url": url,
|
48 |
+
"snippet": snippet
|
49 |
+
})
|
50 |
+
|
51 |
+
if len(results) >= num_results:
|
52 |
+
break
|
53 |
+
|
54 |
+
print(f"Found {len(results)} results for query: {query}")
|
55 |
+
return results
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Error during DuckDuckGo search: {e}")
|
58 |
+
return []
|
59 |
+
|
60 |
+
# Dictionary mapping tool names to their functions
|
61 |
+
TOOLS_MAPPING = {
|
62 |
+
"duckduckgo_search": duckduckgo_search
|
63 |
+
}
|
64 |
+
|
65 |
+
# Tool definitions for LLM API
|
66 |
+
TOOLS_DEFINITION = [
|
67 |
+
{
|
68 |
+
"type": "function",
|
69 |
+
"function": {
|
70 |
+
"name": "duckduckgo_search",
|
71 |
+
"description": "Search the web using DuckDuckGo and return relevant results",
|
72 |
+
"parameters": {
|
73 |
+
"type": "object",
|
74 |
+
"properties": {
|
75 |
+
"query": {
|
76 |
+
"type": "string",
|
77 |
+
"description": "The search query string"
|
78 |
+
},
|
79 |
+
"num_results": {
|
80 |
+
"type": "integer",
|
81 |
+
"description": "Maximum number of results to return",
|
82 |
+
"default": 5
|
83 |
+
}
|
84 |
+
},
|
85 |
+
"required": ["query"]
|
86 |
+
}
|
87 |
+
}
|
88 |
+
}
|
89 |
+
]
|
app.py
CHANGED
@@ -1,483 +1,397 @@
|
|
1 |
-
import os
|
2 |
-
import gradio as gr
|
3 |
-
import requests
|
4 |
-
import json
|
5 |
-
import pandas as pd
|
6 |
-
from openai import OpenAI
|
7 |
-
from
|
8 |
-
|
9 |
-
|
10 |
-
# (Keep Constants as is)
|
11 |
-
# --- Constants ---
|
12 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
-
|
14 |
-
# --- Basic Agent Definition ---
|
15 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
16 |
-
class BasicAgent:
|
17 |
-
def __init__(self):
|
18 |
-
print("BasicAgent initialized.")
|
19 |
-
self.client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OR_TOKEN"))
|
20 |
-
|
21 |
-
def duckduckgo_search(self, query: str, num_results: int = 3) -> list:
|
22 |
-
"""
|
23 |
-
|
24 |
-
|
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 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
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 |
-
|
191 |
-
|
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 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
#
|
238 |
-
#
|
239 |
-
#
|
240 |
-
#
|
241 |
-
#
|
242 |
-
#
|
243 |
-
#
|
244 |
-
# '
|
245 |
-
# '
|
246 |
-
#
|
247 |
-
#
|
248 |
-
#
|
249 |
-
#
|
250 |
-
# '
|
251 |
-
# '
|
252 |
-
#
|
253 |
-
#
|
254 |
-
#
|
255 |
-
#
|
256 |
-
#
|
257 |
-
#
|
258 |
-
#
|
259 |
-
#
|
260 |
-
#
|
261 |
-
#
|
262 |
-
# '
|
263 |
-
# '
|
264 |
-
#
|
265 |
-
#
|
266 |
-
#
|
267 |
-
#
|
268 |
-
#
|
269 |
-
#
|
270 |
-
#
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
'
|
311 |
-
'
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
)
|
399 |
-
print("Submission successful.")
|
400 |
-
results_df = pd.DataFrame(results_log)
|
401 |
-
return final_status, results_df
|
402 |
-
except requests.exceptions.HTTPError as e:
|
403 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
404 |
-
try:
|
405 |
-
error_json = e.response.json()
|
406 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
407 |
-
except requests.exceptions.JSONDecodeError:
|
408 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
409 |
-
status_message = f"Submission Failed: {error_detail}"
|
410 |
-
print(status_message)
|
411 |
-
results_df = pd.DataFrame(results_log)
|
412 |
-
return status_message, results_df
|
413 |
-
except requests.exceptions.Timeout:
|
414 |
-
status_message = "Submission Failed: The request timed out."
|
415 |
-
print(status_message)
|
416 |
-
results_df = pd.DataFrame(results_log)
|
417 |
-
return status_message, results_df
|
418 |
-
except requests.exceptions.RequestException as e:
|
419 |
-
status_message = f"Submission Failed: Network error - {e}"
|
420 |
-
print(status_message)
|
421 |
-
results_df = pd.DataFrame(results_log)
|
422 |
-
return status_message, results_df
|
423 |
-
except Exception as e:
|
424 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
425 |
-
print(status_message)
|
426 |
-
results_df = pd.DataFrame(results_log)
|
427 |
-
return status_message, results_df
|
428 |
-
|
429 |
-
|
430 |
-
# --- Build Gradio Interface using Blocks ---
|
431 |
-
with gr.Blocks() as demo:
|
432 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
433 |
-
gr.Markdown(
|
434 |
-
"""
|
435 |
-
**Instructions:**
|
436 |
-
|
437 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
438 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
439 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
440 |
-
|
441 |
-
---
|
442 |
-
**Disclaimers:**
|
443 |
-
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).
|
444 |
-
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.
|
445 |
-
"""
|
446 |
-
)
|
447 |
-
|
448 |
-
gr.LoginButton()
|
449 |
-
|
450 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
451 |
-
|
452 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
453 |
-
# Removed max_rows=10 from DataFrame constructor
|
454 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
455 |
-
|
456 |
-
run_button.click(
|
457 |
-
fn=run_and_submit_all,
|
458 |
-
outputs=[status_output, results_table]
|
459 |
-
)
|
460 |
-
|
461 |
-
if __name__ == "__main__":
|
462 |
-
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
463 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
464 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
465 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
466 |
-
|
467 |
-
if space_host_startup:
|
468 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
469 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
470 |
-
else:
|
471 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
472 |
-
|
473 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
474 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
475 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
476 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
477 |
-
else:
|
478 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
479 |
-
|
480 |
-
print("-" * (60 + len(" App Starting ")) + "\n")
|
481 |
-
|
482 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
483 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import json
|
5 |
+
import pandas as pd
|
6 |
+
from openai import OpenAI
|
7 |
+
from agent_tools import duckduckgo_search, TOOLS_MAPPING, TOOLS_DEFINITION
|
8 |
+
|
9 |
+
|
10 |
+
# (Keep Constants as is)
|
11 |
+
# --- Constants ---
|
12 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
+
|
14 |
+
# --- Basic Agent Definition ---
|
15 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
16 |
+
class BasicAgent:
|
17 |
+
def __init__(self):
|
18 |
+
print("BasicAgent initialized.")
|
19 |
+
self.client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OR_TOKEN"))
|
20 |
+
|
21 |
+
def duckduckgo_search(self, query: str, num_results: int = 3) -> list:
|
22 |
+
"""Wrapper that calls the external duckduckgo_search function"""
|
23 |
+
return duckduckgo_search(query, num_results)
|
24 |
+
|
25 |
+
def __call__(self, question: str) -> str:
|
26 |
+
print(f"Agent received question: {question}")
|
27 |
+
|
28 |
+
try:
|
29 |
+
messages = [
|
30 |
+
{
|
31 |
+
"role": "system",
|
32 |
+
# "content": "You are a general AI assistant. I will ask you a question. Read the question carefully. Break down the question into multiple questions and use the tools available to you to answer the question. Do not report your thoughts, explanations, reasoning, or conclusion. Give only 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.",
|
33 |
+
"content": "Read the question carefully. Do not report your thoughts, explanations, reasoning, or conclusion. If you know the answer, give only 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. On the other hand, if you don't know the answer, break down the question and list all questions that you want to search in a string array.",
|
34 |
+
},
|
35 |
+
{
|
36 |
+
"role": "user",
|
37 |
+
"content": [
|
38 |
+
{
|
39 |
+
"type": "text",
|
40 |
+
"text": question
|
41 |
+
},
|
42 |
+
# {
|
43 |
+
# "type": "image_url",
|
44 |
+
# "image_url": {
|
45 |
+
# "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
|
46 |
+
# }
|
47 |
+
# }
|
48 |
+
]
|
49 |
+
}
|
50 |
+
]
|
51 |
+
|
52 |
+
# Execute once
|
53 |
+
for _ in range(3):
|
54 |
+
# Generate response
|
55 |
+
print("Using Inference API for generation...")
|
56 |
+
completion = self.client.chat.completions.create(
|
57 |
+
extra_headers={
|
58 |
+
"HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai.
|
59 |
+
"X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai.
|
60 |
+
},
|
61 |
+
extra_body={},
|
62 |
+
# model="meta-llama/llama-4-scout:free",
|
63 |
+
# model="meta-llama/llama-4-maverick:free",
|
64 |
+
# model="google/gemini-2.0-flash-exp:free",
|
65 |
+
# model="mistralai/mistral-small-3.1-24b-instruct:free",
|
66 |
+
model="deepseek/deepseek-chat-v3-0324:free",
|
67 |
+
tools=TOOLS_DEFINITION, # Use imported tools definition
|
68 |
+
messages=messages,
|
69 |
+
temperature=0.0,
|
70 |
+
max_tokens=1024,
|
71 |
+
)
|
72 |
+
|
73 |
+
messages.append(completion.choices[0].message)
|
74 |
+
print(f"Message after completion: {completion.choices[0].message}")
|
75 |
+
|
76 |
+
if completion.choices[0].message.tool_calls is None:
|
77 |
+
answer = completion.choices[0].message.content
|
78 |
+
print(f"Agent generated response: {answer}")
|
79 |
+
return answer
|
80 |
+
|
81 |
+
for tool_call in completion.choices[0].message.tool_calls:
|
82 |
+
tool_name = tool_call.function.name
|
83 |
+
tool_args = json.loads(tool_call.function.arguments)
|
84 |
+
tool_response = TOOLS_MAPPING[tool_name](**tool_args) # Use imported tools mapping
|
85 |
+
message = {
|
86 |
+
"role": "tool",
|
87 |
+
"tool_call_id": tool_call.id,
|
88 |
+
"name": tool_name,
|
89 |
+
"content": json.dumps(tool_response),
|
90 |
+
}
|
91 |
+
messages.append(message)
|
92 |
+
print(f"Message after tools call: {message}")
|
93 |
+
except Exception as e:
|
94 |
+
print(f"Error generating response: {e}")
|
95 |
+
fallback_answer = "I apologize, but I encountered an error when trying to answer your question."
|
96 |
+
print(f"Agent returning fallback answer: {fallback_answer}")
|
97 |
+
return fallback_answer
|
98 |
+
|
99 |
+
|
100 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
101 |
+
"""
|
102 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
103 |
+
and displays the results.
|
104 |
+
"""
|
105 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
106 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
107 |
+
|
108 |
+
if profile:
|
109 |
+
username = f"{profile.username}"
|
110 |
+
print(f"User logged in: {username}")
|
111 |
+
else:
|
112 |
+
print("User not logged in.")
|
113 |
+
return "Please Login to Hugging Face with the button.", None
|
114 |
+
|
115 |
+
api_url = DEFAULT_API_URL
|
116 |
+
questions_url = f"{api_url}/questions"
|
117 |
+
submit_url = f"{api_url}/submit"
|
118 |
+
|
119 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
120 |
+
try:
|
121 |
+
agent = BasicAgent()
|
122 |
+
except Exception as e:
|
123 |
+
print(f"Error instantiating agent: {e}")
|
124 |
+
return f"Error initializing agent: {e}", None
|
125 |
+
# 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)
|
126 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
127 |
+
print(agent_code)
|
128 |
+
|
129 |
+
# 2. Fetch Questions
|
130 |
+
print(f"Fetching questions from: {questions_url}")
|
131 |
+
# try:
|
132 |
+
# response = requests.get(questions_url, timeout=15)
|
133 |
+
# response.raise_for_status()
|
134 |
+
# questions_data = response.json()
|
135 |
+
# print(f"Questions: {questions_data}")
|
136 |
+
# if not questions_data:
|
137 |
+
# print("Fetched questions list is empty.")
|
138 |
+
# return "Fetched questions list is empty or invalid format.", None
|
139 |
+
# print(f"Fetched {len(questions_data)} questions.")
|
140 |
+
# except requests.exceptions.RequestException as e:
|
141 |
+
# print(f"Error fetching questions: {e}")
|
142 |
+
# return f"Error fetching questions: {e}", None
|
143 |
+
# except requests.exceptions.JSONDecodeError as e:
|
144 |
+
# print(f"Error decoding JSON response from questions endpoint: {e}")
|
145 |
+
# print(f"Response text: {response.text[:500]}")
|
146 |
+
# return f"Error decoding server response for questions: {e}", None
|
147 |
+
# except Exception as e:
|
148 |
+
# print(f"An unexpected error occurred fetching questions: {e}")
|
149 |
+
# return f"An unexpected error occurred fetching questions: {e}", None
|
150 |
+
questions_data = [
|
151 |
+
# {
|
152 |
+
# 'task_id': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be',
|
153 |
+
# 'question': 'How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.',
|
154 |
+
# 'Level': '1',
|
155 |
+
# 'file_name': ''
|
156 |
+
# },
|
157 |
+
# {
|
158 |
+
# 'task_id': 'a1e91b78-d3d8-4675-bb8d-62741b4b68a6',
|
159 |
+
# 'question': 'In the video https:\\/\\/www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?',
|
160 |
+
# 'Level': '1',
|
161 |
+
# 'file_name': ''
|
162 |
+
# },
|
163 |
+
# {
|
164 |
+
# 'task_id': '2d83110e-a098-4ebb-9987-066c06fa42d0',
|
165 |
+
# 'question': '.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI',
|
166 |
+
# 'Level': '1',
|
167 |
+
# 'file_name': ''
|
168 |
+
# },
|
169 |
+
# {
|
170 |
+
# 'task_id': 'cca530fc-4052-43b2-b130-b30968d8aa44',
|
171 |
+
# 'question': "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
|
172 |
+
# 'Level': '1',
|
173 |
+
# 'file_name': 'cca530fc-4052-43b2-b130-b30968d8aa44.png'
|
174 |
+
# },
|
175 |
+
# {
|
176 |
+
# 'task_id': '4fc2f1ae-8625-45b5-ab34-ad4433bc21f8',
|
177 |
+
# 'question': 'Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?',
|
178 |
+
# 'Level': '1',
|
179 |
+
# 'file_name': ''
|
180 |
+
# },
|
181 |
+
# {
|
182 |
+
# 'task_id': '6f37996b-2ac7-44b0-8e68-6d28256631b4',
|
183 |
+
# 'question': 'Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.',
|
184 |
+
# 'Level': '1',
|
185 |
+
# 'file_name': ''
|
186 |
+
# },
|
187 |
+
# {
|
188 |
+
# 'task_id': '9d191bce-651d-4746-be2d-7ef8ecadb9c2',
|
189 |
+
# 'question': 'Examine the video at https:\\/\\/www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal\'c say in response to the question "Isn\'t that hot?"',
|
190 |
+
# 'Level': '1',
|
191 |
+
# 'file_name': ''
|
192 |
+
# },
|
193 |
+
# {
|
194 |
+
# 'task_id': 'cabe07ed-9eca-40ea-8ead-410ef5e83f91',
|
195 |
+
# 'question': "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
|
196 |
+
# 'Level': '1',
|
197 |
+
# 'file_name': ''
|
198 |
+
# },
|
199 |
+
# {
|
200 |
+
# 'task_id': '3cef3a44-215e-4aed-8e3b-b1e3f08063b7',
|
201 |
+
# 'question': "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
|
202 |
+
# 'Level': '1',
|
203 |
+
# 'file_name': ''
|
204 |
+
# },
|
205 |
+
# {
|
206 |
+
# 'task_id': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3',
|
207 |
+
# 'question': 'Hi, I\'m making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I\'m not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can\'t quite make out what she\'s saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I\'ve attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for "a pinch of salt" or "two cups of ripe strawberries" the ingredients on the list would be "salt" and "ripe strawberries".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
|
208 |
+
# 'Level': '1',
|
209 |
+
# 'file_name': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3'
|
210 |
+
# },
|
211 |
+
# {
|
212 |
+
# 'task_id': '305ac316-eef6-4446-960a-92d80d542f82',
|
213 |
+
# 'question': 'Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.',
|
214 |
+
# 'Level': '1',
|
215 |
+
# 'file_name': ''
|
216 |
+
# },
|
217 |
+
# {
|
218 |
+
# 'task_id': 'f918266a-b3e0-4914-865d-4faa564f1aef',
|
219 |
+
# 'question': 'What is the final numeric output from the attached Python code?',
|
220 |
+
# 'Level': '1',
|
221 |
+
# 'file_name': 'f918266a-b3e0-4914-865d-4faa564f1aef.py'
|
222 |
+
# },
|
223 |
+
{
|
224 |
+
'task_id': '3f57289b-8c60-48be-bd80-01f8099ca449',
|
225 |
+
'question': 'How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?',
|
226 |
+
'Level': '1',
|
227 |
+
'file_name': ''
|
228 |
+
},
|
229 |
+
# {
|
230 |
+
# 'task_id': '1f975693-876d-457b-a649-393859e79bf3',
|
231 |
+
# 'question': "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
|
232 |
+
# 'Level': '1',
|
233 |
+
# 'file_name': '1f975693-876d-457b-a649-393859e79bf3.mp3'
|
234 |
+
# },
|
235 |
+
# {
|
236 |
+
# 'task_id': '840bfca7-4f7b-481a-8794-c560c340185d',
|
237 |
+
# 'question': 'On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?',
|
238 |
+
# 'Level': '1',
|
239 |
+
# 'file_name': ''
|
240 |
+
# },
|
241 |
+
# {
|
242 |
+
# 'task_id': 'bda648d7-d618-4883-88f4-3466eabd860e',
|
243 |
+
# 'question': "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
|
244 |
+
# 'Level': '1',
|
245 |
+
# 'file_name': ''
|
246 |
+
# },
|
247 |
+
# {
|
248 |
+
# 'task_id': 'cf106601-ab4f-4af9-b045-5295fe67b37d',
|
249 |
+
# 'question': "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
|
250 |
+
# 'Level': '1',
|
251 |
+
# 'file_name': ''
|
252 |
+
# },
|
253 |
+
# {
|
254 |
+
# 'task_id': 'a0c07678-e491-4bbc-8f0b-07405144218f',
|
255 |
+
# 'question': "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
|
256 |
+
# 'Level': '1',
|
257 |
+
# 'file_name': ''
|
258 |
+
# },
|
259 |
+
# {
|
260 |
+
# 'task_id': '7bd855d8-463d-4ed5-93ca-5fe35145f733',
|
261 |
+
# 'question': 'The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.',
|
262 |
+
# 'Level': '1',
|
263 |
+
# 'file_name': '7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx'
|
264 |
+
# },
|
265 |
+
# {
|
266 |
+
# 'task_id': '5a0c1adf-205e-4841-a666-7c3ef95def9d',
|
267 |
+
# 'question': 'What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?',
|
268 |
+
# 'Level': '1',
|
269 |
+
# 'file_name': ''
|
270 |
+
# },
|
271 |
+
]
|
272 |
+
|
273 |
+
# 3. Run your Agent
|
274 |
+
results_log = []
|
275 |
+
answers_payload = []
|
276 |
+
print(f"Running agent on {len(questions_data)} questions")
|
277 |
+
for item in questions_data:
|
278 |
+
task_id = item.get("task_id")
|
279 |
+
question_text = item.get("question")
|
280 |
+
if not task_id or question_text is None:
|
281 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
282 |
+
continue
|
283 |
+
try:
|
284 |
+
submitted_answer = agent(question_text)
|
285 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
286 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
287 |
+
except Exception as e:
|
288 |
+
print(f"Error running agent on task {task_id}: {e}")
|
289 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
290 |
+
|
291 |
+
if not answers_payload:
|
292 |
+
print("Agent did not produce any answers to submit.")
|
293 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
294 |
+
|
295 |
+
# 4. Prepare Submission
|
296 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
297 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'"
|
298 |
+
print(status_update)
|
299 |
+
|
300 |
+
# 5. Submit
|
301 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
302 |
+
try:
|
303 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
304 |
+
response.raise_for_status()
|
305 |
+
result_data = response.json()
|
306 |
+
final_status = (
|
307 |
+
f"Submission Successful!\n"
|
308 |
+
f"User: {result_data.get('username')}\n"
|
309 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
310 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
311 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
312 |
+
)
|
313 |
+
print("Submission successful.")
|
314 |
+
results_df = pd.DataFrame(results_log)
|
315 |
+
return final_status, results_df
|
316 |
+
except requests.exceptions.HTTPError as e:
|
317 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
318 |
+
try:
|
319 |
+
error_json = e.response.json()
|
320 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
321 |
+
except requests.exceptions.JSONDecodeError:
|
322 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
323 |
+
status_message = f"Submission Failed: {error_detail}"
|
324 |
+
print(status_message)
|
325 |
+
results_df = pd.DataFrame(results_log)
|
326 |
+
return status_message, results_df
|
327 |
+
except requests.exceptions.Timeout:
|
328 |
+
status_message = "Submission Failed: The request timed out."
|
329 |
+
print(status_message)
|
330 |
+
results_df = pd.DataFrame(results_log)
|
331 |
+
return status_message, results_df
|
332 |
+
except requests.exceptions.RequestException as e:
|
333 |
+
status_message = f"Submission Failed: Network error - {e}"
|
334 |
+
print(status_message)
|
335 |
+
results_df = pd.DataFrame(results_log)
|
336 |
+
return status_message, results_df
|
337 |
+
except Exception as e:
|
338 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
339 |
+
print(status_message)
|
340 |
+
results_df = pd.DataFrame(results_log)
|
341 |
+
return status_message, results_df
|
342 |
+
|
343 |
+
|
344 |
+
# --- Build Gradio Interface using Blocks ---
|
345 |
+
with gr.Blocks() as demo:
|
346 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
347 |
+
gr.Markdown(
|
348 |
+
"""
|
349 |
+
**Instructions:**
|
350 |
+
|
351 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
352 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
353 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
354 |
+
|
355 |
+
---
|
356 |
+
**Disclaimers:**
|
357 |
+
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).
|
358 |
+
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.
|
359 |
+
"""
|
360 |
+
)
|
361 |
+
|
362 |
+
gr.LoginButton()
|
363 |
+
|
364 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
365 |
+
|
366 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
367 |
+
# Removed max_rows=10 from DataFrame constructor
|
368 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
369 |
+
|
370 |
+
run_button.click(
|
371 |
+
fn=run_and_submit_all,
|
372 |
+
outputs=[status_output, results_table]
|
373 |
+
)
|
374 |
+
|
375 |
+
if __name__ == "__main__":
|
376 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
377 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
378 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
379 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
380 |
+
|
381 |
+
if space_host_startup:
|
382 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
383 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
384 |
+
else:
|
385 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
386 |
+
|
387 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
388 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
389 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
390 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
391 |
+
else:
|
392 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
393 |
+
|
394 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
395 |
+
|
396 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
397 |
+
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
-
gradio
|
2 |
-
requests
|
3 |
-
huggingface_hub
|
4 |
-
openai
|
5 |
-
bs4
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
requests
|
3 |
+
huggingface_hub
|
4 |
+
openai
|
5 |
+
bs4
|
6 |
+
itsdangerous
|
7 |
+
huggingface_hub[cli]
|