Spaces:
Running
Running
ffreemt
commited on
Commit
·
dd9518b
1
Parent(s):
2027c04
Update mcp-searxng instead of DuckDuckGoSearchTool
Browse files- __pycache__/get_gemini_keys.cpython-312.pyc +0 -0
- __pycache__/get_model.cpython-312.pyc +0 -0
- __pycache__/openai_model.cpython-312.pyc +0 -0
- app.py +70 -39
- basic_agent.py +98 -73
- openai_model.py +7 -1
__pycache__/get_gemini_keys.cpython-312.pyc
CHANGED
Binary files a/__pycache__/get_gemini_keys.cpython-312.pyc and b/__pycache__/get_gemini_keys.cpython-312.pyc differ
|
|
__pycache__/get_model.cpython-312.pyc
CHANGED
Binary files a/__pycache__/get_model.cpython-312.pyc and b/__pycache__/get_model.cpython-312.pyc differ
|
|
__pycache__/openai_model.cpython-312.pyc
CHANGED
Binary files a/__pycache__/openai_model.cpython-312.pyc and b/__pycache__/openai_model.cpython-312.pyc differ
|
|
app.py
CHANGED
@@ -11,10 +11,11 @@ from mcp import StdioServerParameters
|
|
11 |
from smolagents import DuckDuckGoSearchTool, FinalAnswerTool, Tool, ToolCollection, VisitWebpageTool
|
12 |
from ycecream import y
|
13 |
|
14 |
-
from basic_agent import BasicAgent
|
15 |
from get_model import get_model
|
|
|
16 |
|
17 |
-
y.configure(sln=
|
18 |
print = rich.get_console().print
|
19 |
|
20 |
# (Keep Constants as is)
|
@@ -55,24 +56,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
55 |
questions_url = f"{api_url}/questions" # https://agents-course-unit4-scoring.hf.space/questions
|
56 |
submit_url = f"{api_url}/submit"
|
57 |
|
58 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
59 |
-
try:
|
60 |
-
agent = BasicAgent(
|
61 |
-
# model=get_model(cat="gemini"),
|
62 |
-
model=get_model(cat="llama"),
|
63 |
-
tools=[
|
64 |
-
DuckDuckGoSearchTool(),
|
65 |
-
VisitWebpageTool(),
|
66 |
-
# FinalAnswerTool(),
|
67 |
-
],
|
68 |
-
)
|
69 |
-
except Exception as e:
|
70 |
-
print(f"Error instantiating agent: {e}")
|
71 |
-
return f"Error initializing agent: {e}", None
|
72 |
-
# 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)
|
73 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
74 |
-
print(agent_code)
|
75 |
-
|
76 |
# 2. Fetch Questions
|
77 |
print(f"Fetching questions from: {questions_url}")
|
78 |
try:
|
@@ -95,27 +78,75 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
95 |
print(f"An unexpected error occurred fetching questions: {e}")
|
96 |
return f"An unexpected error occurred fetching questions: {e}", None
|
97 |
|
98 |
-
#
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
try:
|
109 |
-
|
110 |
-
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
except Exception as e:
|
113 |
-
print(f"Error
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
print(
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
# 4. Prepare Submission
|
121 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
11 |
from smolagents import DuckDuckGoSearchTool, FinalAnswerTool, Tool, ToolCollection, VisitWebpageTool
|
12 |
from ycecream import y
|
13 |
|
14 |
+
from basic_agent import BasicAgent, WikipediaSearchTool
|
15 |
from get_model import get_model
|
16 |
+
from openai_model import openai_model
|
17 |
|
18 |
+
y.configure(sln=0)
|
19 |
print = rich.get_console().print
|
20 |
|
21 |
# (Keep Constants as is)
|
|
|
56 |
questions_url = f"{api_url}/questions" # https://agents-course-unit4-scoring.hf.space/questions
|
57 |
submit_url = f"{api_url}/submit"
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
# 2. Fetch Questions
|
60 |
print(f"Fetching questions from: {questions_url}")
|
61 |
try:
|
|
|
78 |
print(f"An unexpected error occurred fetching questions: {e}")
|
79 |
return f"An unexpected error occurred fetching questions: {e}", None
|
80 |
|
81 |
+
# Prepare model and mcp_params
|
82 |
+
model = openai_model() # defautl llama4 scout
|
83 |
+
|
84 |
+
# messages = [{'role': 'user', 'content': 'Say this is a test.'}]
|
85 |
+
# print(model(messages))
|
86 |
+
|
87 |
+
# raise SystemExit("By intention")
|
88 |
+
|
89 |
+
mcp_searxng_params = StdioServerParameters(
|
90 |
+
**{
|
91 |
+
"command": "npx",
|
92 |
+
"args": [
|
93 |
+
"-y",
|
94 |
+
"mcp-searxng"
|
95 |
+
],
|
96 |
+
"env": {
|
97 |
+
"SEARXNG_URL": "https://searx.dattw.eu.org"
|
98 |
+
}
|
99 |
+
}
|
100 |
+
)
|
101 |
+
|
102 |
+
# with ToolCollection.from_mcp(mcp_searxng_params, trust_remote_code=True) as searxng_tool_collection, ToolCollection.from_mcp(mcp_markitdown_params, trust_remote_code=True) as markitdown_tools:
|
103 |
+
with ToolCollection.from_mcp(mcp_searxng_params, trust_remote_code=True) as searxng_tool_collection:
|
104 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
105 |
try:
|
106 |
+
agent = BasicAgent(
|
107 |
+
# model=get_model(cat="gemini"),
|
108 |
+
# model=get_model(cat="llama"),
|
109 |
+
model=model,
|
110 |
+
tools=[
|
111 |
+
*searxng_tool_collection.tools,
|
112 |
+
# DuckDuckGoSearchTool(),
|
113 |
+
VisitWebpageTool(),
|
114 |
+
WikipediaSearchTool(),
|
115 |
+
FinalAnswerTool(),
|
116 |
+
],
|
117 |
+
verbosity_level=1,
|
118 |
+
)
|
119 |
+
agent.agent.visualize()
|
120 |
except Exception as e:
|
121 |
+
print(f"Error instantiating agent: {e}")
|
122 |
+
return f"Error initializing agent: {e}", None
|
123 |
+
# 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)
|
124 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
125 |
+
print(agent_code)
|
126 |
+
|
127 |
+
# 3. Run your Agent
|
128 |
+
results_log = []
|
129 |
+
answers_payload = []
|
130 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
131 |
+
for item in questions_data:
|
132 |
+
task_id = item.get("task_id")
|
133 |
+
question_text = item.get("question")
|
134 |
+
if not task_id or question_text is None:
|
135 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
136 |
+
continue
|
137 |
+
try:
|
138 |
+
submitted_answer = agent(question_text)
|
139 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
140 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
141 |
+
except Exception as e:
|
142 |
+
print(f"Error running agent on task {task_id}: {e}")
|
143 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
144 |
+
|
145 |
+
if not answers_payload:
|
146 |
+
print("Agent did not produce any answers to submit.")
|
147 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
148 |
+
|
149 |
+
agent.agent.visualize()
|
150 |
|
151 |
# 4. Prepare Submission
|
152 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
basic_agent.py
CHANGED
@@ -11,7 +11,8 @@ import rich
|
|
11 |
import smolagents
|
12 |
import wikipediaapi
|
13 |
from loguru import logger
|
14 |
-
from
|
|
|
15 |
from smolagents import InferenceClientModel as HfApiModel
|
16 |
|
17 |
from get_model import get_model
|
@@ -78,6 +79,8 @@ class BasicAgent:
|
|
78 |
model: smolagents.models.Model = HfApiModel()
|
79 |
tools: list = field(default_factory=lambda: [])
|
80 |
verbosity_level: int = 0
|
|
|
|
|
81 |
# def __init__(self):
|
82 |
def __post_init__(self):
|
83 |
"""Run post_init."""
|
@@ -86,8 +89,8 @@ class BasicAgent:
|
|
86 |
tools=self.tools,
|
87 |
model=self.model,
|
88 |
verbosity_level=self.verbosity_level,
|
89 |
-
additional_authorized_imports=
|
90 |
-
planning_interval=
|
91 |
)
|
92 |
|
93 |
def get_answer(self, question: str):
|
@@ -122,53 +125,14 @@ def main():
|
|
122 |
|
123 |
space_id = f"{username}/{repo_name}"
|
124 |
|
125 |
-
# model = get_model(cat="gemini")
|
126 |
-
|
127 |
-
_ = (
|
128 |
-
"gemini-2.5-flash-preview-04-17",
|
129 |
-
# "https://api-proxy.me/gemini/v1beta",
|
130 |
-
"https://generativelanguage.googleapis.com/v1beta",
|
131 |
-
os.getenv("GEMINI_API_KEY"),
|
132 |
-
)
|
133 |
-
|
134 |
-
_ = (
|
135 |
-
"grok-3-beta",
|
136 |
-
"https://api.x.ai/v1",
|
137 |
-
os.getenv("XAI_API_KEY"),
|
138 |
-
)
|
139 |
-
|
140 |
-
# model = litellm_model(*_)
|
141 |
-
model = openai_model(*_)
|
142 |
-
|
143 |
-
messages = [{'role': 'user', 'content': 'Say this is a test.'}]
|
144 |
-
print(model(messages))
|
145 |
-
# raise SystemExit("By intention")
|
146 |
-
|
147 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
148 |
-
try:
|
149 |
-
# agent = BasicAgent()
|
150 |
-
agent = BasicAgent(
|
151 |
-
model=model,
|
152 |
-
tools=[
|
153 |
-
DuckDuckGoSearchTool(),
|
154 |
-
VisitWebpageTool(),
|
155 |
-
WikipediaSearchTool(),
|
156 |
-
FinalAnswerTool(),
|
157 |
-
]
|
158 |
-
)
|
159 |
-
agent.agent.visualize()
|
160 |
-
except Exception as e:
|
161 |
-
print(f"Error instantiating agent: {e}")
|
162 |
-
return f"Error initializing agent: {e}", None
|
163 |
-
|
164 |
# 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)
|
165 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
166 |
print(agent_code)
|
167 |
|
168 |
-
# 2. Fetch Questions
|
169 |
print(f"Fetching questions from: {questions_url}")
|
170 |
try:
|
171 |
-
response = requests.get(questions_url, timeout=
|
172 |
response.raise_for_status()
|
173 |
questions_data = response.json()
|
174 |
if not questions_data:
|
@@ -186,40 +150,101 @@ def main():
|
|
186 |
print(f"An unexpected error occurred fetching questions: {e}")
|
187 |
return f"An unexpected error occurred fetching questions: {e}", None
|
188 |
|
189 |
-
#
|
190 |
-
results_log = []
|
191 |
-
answers_payload = []
|
192 |
|
193 |
-
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
print(f"Error running agent on task {task_id}: {e}")
|
209 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
210 |
|
211 |
-
|
212 |
-
|
213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
214 |
|
215 |
-
#
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
|
221 |
-
|
222 |
-
|
223 |
|
224 |
if __name__ == "__main__":
|
225 |
main()
|
|
|
11 |
import smolagents
|
12 |
import wikipediaapi
|
13 |
from loguru import logger
|
14 |
+
from mcp import StdioServerParameters
|
15 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, Tool, ToolCollection, VisitWebpageTool
|
16 |
from smolagents import InferenceClientModel as HfApiModel
|
17 |
|
18 |
from get_model import get_model
|
|
|
79 |
model: smolagents.models.Model = HfApiModel()
|
80 |
tools: list = field(default_factory=lambda: [])
|
81 |
verbosity_level: int = 0
|
82 |
+
additional_authorized_imports: list = field(default_factory=lambda: AUTHORIZED_IMPORTS)
|
83 |
+
planning_interval: int = 4
|
84 |
# def __init__(self):
|
85 |
def __post_init__(self):
|
86 |
"""Run post_init."""
|
|
|
89 |
tools=self.tools,
|
90 |
model=self.model,
|
91 |
verbosity_level=self.verbosity_level,
|
92 |
+
additional_authorized_imports=self.additional_authorized_imports,
|
93 |
+
planning_interval=self.planning_interval,
|
94 |
)
|
95 |
|
96 |
def get_answer(self, question: str):
|
|
|
125 |
|
126 |
space_id = f"{username}/{repo_name}"
|
127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
# 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)
|
129 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
130 |
print(agent_code)
|
131 |
|
132 |
+
# 2. Fetch Questions: fetch before openai_model() which my set proxy
|
133 |
print(f"Fetching questions from: {questions_url}")
|
134 |
try:
|
135 |
+
response = requests.get(questions_url, timeout=120)
|
136 |
response.raise_for_status()
|
137 |
questions_data = response.json()
|
138 |
if not questions_data:
|
|
|
150 |
print(f"An unexpected error occurred fetching questions: {e}")
|
151 |
return f"An unexpected error occurred fetching questions: {e}", None
|
152 |
|
153 |
+
# model = get_model(cat="gemini")
|
|
|
|
|
154 |
|
155 |
+
_ = (
|
156 |
+
"gemini-2.5-flash-preview-04-17",
|
157 |
+
# "https://api-proxy.me/gemini/v1beta",
|
158 |
+
"https://generativelanguage.googleapis.com/v1beta",
|
159 |
+
os.getenv("GEMINI_API_KEY"),
|
160 |
+
)
|
161 |
|
162 |
+
_ = (
|
163 |
+
"grok-3-beta",
|
164 |
+
"https://api.x.ai/v1",
|
165 |
+
os.getenv("XAI_API_KEY"),
|
166 |
+
)
|
167 |
+
|
168 |
+
# model = litellm_model(*_)
|
169 |
+
# model = get_model()
|
170 |
+
|
171 |
+
model = openai_model() # defautl llama4 scout
|
172 |
+
|
173 |
+
# messages = [{'role': 'user', 'content': 'Say this is a test.'}]
|
174 |
+
# print(model(messages))
|
|
|
|
|
175 |
|
176 |
+
# raise SystemExit("By intention")
|
177 |
+
|
178 |
+
mcp_searxng_params = StdioServerParameters(
|
179 |
+
**{
|
180 |
+
"command": "npx",
|
181 |
+
"args": [
|
182 |
+
"-y",
|
183 |
+
"mcp-searxng"
|
184 |
+
],
|
185 |
+
"env": {
|
186 |
+
"SEARXNG_URL": "https://searx.dattw.eu.org"
|
187 |
+
}
|
188 |
+
}
|
189 |
+
)
|
190 |
|
191 |
+
# with ToolCollection.from_mcp(mcp_searxng_params, trust_remote_code=True) as searxng_tool_collection, ToolCollection.from_mcp(mcp_markitdown_params, trust_remote_code=True) as markitdown_tools:
|
192 |
+
with ToolCollection.from_mcp(mcp_searxng_params, trust_remote_code=True) as searxng_tool_collection:
|
193 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
194 |
+
try:
|
195 |
+
# agent = BasicAgent()
|
196 |
+
agent = BasicAgent(
|
197 |
+
model=model,
|
198 |
+
tools=[
|
199 |
+
*searxng_tool_collection.tools,
|
200 |
+
# DuckDuckGoSearchTool(),
|
201 |
+
VisitWebpageTool(),
|
202 |
+
WikipediaSearchTool(),
|
203 |
+
FinalAnswerTool(),
|
204 |
+
],
|
205 |
+
verbosity_level=1,
|
206 |
+
)
|
207 |
+
agent.agent.visualize()
|
208 |
+
except Exception as e:
|
209 |
+
print(f"Error instantiating agent: {e}")
|
210 |
+
return f"Error initializing agent: {e}", None
|
211 |
+
|
212 |
+
|
213 |
+
# 3. Run your Agent
|
214 |
+
results_log = []
|
215 |
+
answers_payload = []
|
216 |
+
|
217 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
218 |
+
|
219 |
+
# for item in questions_data:
|
220 |
+
# for item in questions_data[-1:]:
|
221 |
+
# for item in questions_data[14:15]:
|
222 |
+
for item in questions_data[-6:]:
|
223 |
+
task_id = item.get("task_id")
|
224 |
+
question_text = item.get("question")
|
225 |
+
if not task_id or question_text is None:
|
226 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
227 |
+
continue
|
228 |
+
try:
|
229 |
+
submitted_answer = agent(question_text)
|
230 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
231 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
232 |
+
except Exception as e:
|
233 |
+
print(f"Error running agent on task {task_id}: {e}")
|
234 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
235 |
+
|
236 |
+
if not answers_payload:
|
237 |
+
print("Agent did not produce any answers to submit.")
|
238 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
239 |
+
|
240 |
+
# 4. Prepare Submission
|
241 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} # noqa
|
242 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
243 |
+
print(status_update)
|
244 |
+
print(answers_payload)
|
245 |
|
246 |
+
agent.agent.visualize()
|
247 |
+
return None, None
|
248 |
|
249 |
if __name__ == "__main__":
|
250 |
main()
|
openai_model.py
CHANGED
@@ -26,7 +26,12 @@ def openai_model(
|
|
26 |
|
27 |
# default llama4
|
28 |
api_base = api_base or "https://api.llama.com/compat/v1"
|
|
|
29 |
api_key = api_key or os.getenv("LLAMA_API_KEY")
|
|
|
|
|
|
|
|
|
30 |
|
31 |
# "Llama-4-Maverick-17B-128E-Instruct-FP8"
|
32 |
# "Llama-4-Scout-17B-16E-Instruct-FP8"
|
@@ -43,10 +48,11 @@ def openai_model(
|
|
43 |
def main():
|
44 |
messages = [{'role': 'user', 'content': 'Say this is a test.'}]
|
45 |
logger.debug(sys.argv)
|
|
|
46 |
if not sys.argv[1:]:
|
|
|
47 |
model = openai_model()
|
48 |
logger.debug(model(messages))
|
49 |
-
return
|
50 |
|
51 |
if len(sys.argv[1:]) < 3:
|
52 |
raise SystemExit("Provide at least three args (model_id, api_base, api_key)")
|
|
|
26 |
|
27 |
# default llama4
|
28 |
api_base = api_base or "https://api.llama.com/compat/v1"
|
29 |
+
|
30 |
api_key = api_key or os.getenv("LLAMA_API_KEY")
|
31 |
+
if isinstance(api_key, str):
|
32 |
+
# LLAMA_API_KEY contains | and in win10 need to assign env var with ""
|
33 |
+
api_key = api_key.strip('"')
|
34 |
+
assert api_key, "LLAMA_API_KEY not set, set it and try again"
|
35 |
|
36 |
# "Llama-4-Maverick-17B-128E-Instruct-FP8"
|
37 |
# "Llama-4-Scout-17B-16E-Instruct-FP8"
|
|
|
48 |
def main():
|
49 |
messages = [{'role': 'user', 'content': 'Say this is a test.'}]
|
50 |
logger.debug(sys.argv)
|
51 |
+
|
52 |
if not sys.argv[1:]:
|
53 |
+
logger.debug("default llama4 scout")
|
54 |
model = openai_model()
|
55 |
logger.debug(model(messages))
|
|
|
56 |
|
57 |
if len(sys.argv[1:]) < 3:
|
58 |
raise SystemExit("Provide at least three args (model_id, api_base, api_key)")
|