krim798 commited on
Commit
c35d17f
·
unverified ·
1 Parent(s): 1472a26
Files changed (11) hide show
  1. Gradio_UI.py +296 -0
  2. agent.json +53 -0
  3. app.py +67 -474
  4. main.py +0 -6
  5. prompts.yaml +321 -0
  6. pyproject.toml +2 -0
  7. requirements.txt +4 -12
  8. tools/final_answer.py +14 -0
  9. tools/visit_webpage.py +45 -0
  10. tools/web_search.py +27 -0
  11. uv.lock +47 -0
Gradio_UI.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import mimetypes
17
+ import os
18
+ import re
19
+ import shutil
20
+ from typing import Optional
21
+
22
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
23
+ from smolagents.agents import ActionStep, MultiStepAgent
24
+ from smolagents.memory import MemoryStep
25
+ from smolagents.utils import _is_package_available
26
+
27
+
28
+ def pull_messages_from_step(
29
+ step_log: MemoryStep,
30
+ ):
31
+ """Extract ChatMessage objects from agent steps with proper nesting"""
32
+ import gradio as gr
33
+
34
+ if isinstance(step_log, ActionStep):
35
+ # Output the step number
36
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
+ yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
+
39
+ # First yield the thought/reasoning from the LLM
40
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
+ # Clean up the LLM output
42
+ model_output = step_log.model_output.strip()
43
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
+ model_output = model_output.strip()
48
+ yield gr.ChatMessage(role="assistant", content=model_output)
49
+
50
+ # For tool calls, create a parent message
51
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
+ first_tool_call = step_log.tool_calls[0]
53
+ used_code = first_tool_call.name == "python_interpreter"
54
+ parent_id = f"call_{len(step_log.tool_calls)}"
55
+
56
+ # Tool call becomes the parent message with timing info
57
+ # First we will handle arguments based on type
58
+ args = first_tool_call.arguments
59
+ if isinstance(args, dict):
60
+ content = str(args.get("answer", str(args)))
61
+ else:
62
+ content = str(args).strip()
63
+
64
+ if used_code:
65
+ # Clean up the content by removing any end code tags
66
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
+ content = content.strip()
69
+ if not content.startswith("```python"):
70
+ content = f"```python\n{content}\n```"
71
+
72
+ parent_message_tool = gr.ChatMessage(
73
+ role="assistant",
74
+ content=content,
75
+ metadata={
76
+ "title": f"🛠️ Used tool {first_tool_call.name}",
77
+ "id": parent_id,
78
+ "status": "pending",
79
+ },
80
+ )
81
+ yield parent_message_tool
82
+
83
+ # Nesting execution logs under the tool call if they exist
84
+ if hasattr(step_log, "observations") and (
85
+ step_log.observations is not None and step_log.observations.strip()
86
+ ): # Only yield execution logs if there's actual content
87
+ log_content = step_log.observations.strip()
88
+ if log_content:
89
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
90
+ yield gr.ChatMessage(
91
+ role="assistant",
92
+ content=f"{log_content}",
93
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
+ )
95
+
96
+ # Nesting any errors under the tool call
97
+ if hasattr(step_log, "error") and step_log.error is not None:
98
+ yield gr.ChatMessage(
99
+ role="assistant",
100
+ content=str(step_log.error),
101
+ metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
+ )
103
+
104
+ # Update parent message metadata to done status without yielding a new message
105
+ parent_message_tool.metadata["status"] = "done"
106
+
107
+ # Handle standalone errors but not from tool calls
108
+ elif hasattr(step_log, "error") and step_log.error is not None:
109
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
+
111
+ # Calculate duration and token information
112
+ step_footnote = f"{step_number}"
113
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
+ token_str = (
115
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
+ )
117
+ step_footnote += token_str
118
+ if hasattr(step_log, "duration"):
119
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
+ step_footnote += step_duration
121
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
+ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
+ yield gr.ChatMessage(role="assistant", content="-----")
124
+
125
+
126
+ def stream_to_gradio(
127
+ agent,
128
+ task: str,
129
+ reset_agent_memory: bool = False,
130
+ additional_args: Optional[dict] = None,
131
+ ):
132
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
+ if not _is_package_available("gradio"):
134
+ raise ModuleNotFoundError(
135
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
136
+ )
137
+ import gradio as gr
138
+
139
+ total_input_tokens = 0
140
+ total_output_tokens = 0
141
+
142
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
143
+ # Track tokens if model provides them
144
+ if hasattr(agent.model, "last_input_token_count"):
145
+ total_input_tokens += agent.model.last_input_token_count
146
+ total_output_tokens += agent.model.last_output_token_count
147
+ if isinstance(step_log, ActionStep):
148
+ step_log.input_token_count = agent.model.last_input_token_count
149
+ step_log.output_token_count = agent.model.last_output_token_count
150
+
151
+ for message in pull_messages_from_step(
152
+ step_log,
153
+ ):
154
+ yield message
155
+
156
+ final_answer = step_log # Last log is the run's final_answer
157
+ final_answer = handle_agent_output_types(final_answer)
158
+
159
+ if isinstance(final_answer, AgentText):
160
+ yield gr.ChatMessage(
161
+ role="assistant",
162
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
163
+ )
164
+ elif isinstance(final_answer, AgentImage):
165
+ yield gr.ChatMessage(
166
+ role="assistant",
167
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
168
+ )
169
+ elif isinstance(final_answer, AgentAudio):
170
+ yield gr.ChatMessage(
171
+ role="assistant",
172
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
173
+ )
174
+ else:
175
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
176
+
177
+
178
+ class GradioUI:
179
+ """A one-line interface to launch your agent in Gradio"""
180
+
181
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
182
+ if not _is_package_available("gradio"):
183
+ raise ModuleNotFoundError(
184
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
185
+ )
186
+ self.agent = agent
187
+ self.file_upload_folder = file_upload_folder
188
+ if self.file_upload_folder is not None:
189
+ if not os.path.exists(file_upload_folder):
190
+ os.mkdir(file_upload_folder)
191
+
192
+ def interact_with_agent(self, prompt, messages):
193
+ import gradio as gr
194
+
195
+ messages.append(gr.ChatMessage(role="user", content=prompt))
196
+ yield messages
197
+ for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
198
+ messages.append(msg)
199
+ yield messages
200
+ yield messages
201
+
202
+ def upload_file(
203
+ self,
204
+ file,
205
+ file_uploads_log,
206
+ allowed_file_types=[
207
+ "application/pdf",
208
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
209
+ "text/plain",
210
+ ],
211
+ ):
212
+ """
213
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
214
+ """
215
+ import gradio as gr
216
+
217
+ if file is None:
218
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
219
+
220
+ try:
221
+ mime_type, _ = mimetypes.guess_type(file.name)
222
+ except Exception as e:
223
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
224
+
225
+ if mime_type not in allowed_file_types:
226
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
227
+
228
+ # Sanitize file name
229
+ original_name = os.path.basename(file.name)
230
+ sanitized_name = re.sub(
231
+ r"[^\w\-.]", "_", original_name
232
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
233
+
234
+ type_to_ext = {}
235
+ for ext, t in mimetypes.types_map.items():
236
+ if t not in type_to_ext:
237
+ type_to_ext[t] = ext
238
+
239
+ # Ensure the extension correlates to the mime type
240
+ sanitized_name = sanitized_name.split(".")[:-1]
241
+ sanitized_name.append("" + type_to_ext[mime_type])
242
+ sanitized_name = "".join(sanitized_name)
243
+
244
+ # Save the uploaded file to the specified folder
245
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
246
+ shutil.copy(file.name, file_path)
247
+
248
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
249
+
250
+ def log_user_message(self, text_input, file_uploads_log):
251
+ return (
252
+ text_input
253
+ + (
254
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
255
+ if len(file_uploads_log) > 0
256
+ else ""
257
+ ),
258
+ "",
259
+ )
260
+
261
+ def launch(self, **kwargs):
262
+ import gradio as gr
263
+
264
+ with gr.Blocks(fill_height=True) as demo:
265
+ stored_messages = gr.State([])
266
+ file_uploads_log = gr.State([])
267
+ chatbot = gr.Chatbot(
268
+ label="Agent",
269
+ type="messages",
270
+ avatar_images=(
271
+ None,
272
+ "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
273
+ ),
274
+ resizeable=True,
275
+ scale=1,
276
+ )
277
+ # If an upload folder is provided, enable the upload feature
278
+ if self.file_upload_folder is not None:
279
+ upload_file = gr.File(label="Upload a file")
280
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
281
+ upload_file.change(
282
+ self.upload_file,
283
+ [upload_file, file_uploads_log],
284
+ [upload_status, file_uploads_log],
285
+ )
286
+ text_input = gr.Textbox(lines=1, label="Chat Message")
287
+ text_input.submit(
288
+ self.log_user_message,
289
+ [text_input, file_uploads_log],
290
+ [stored_messages, text_input],
291
+ ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
292
+
293
+ demo.launch(debug=True, share=True, **kwargs)
294
+
295
+
296
+ __all__ = ["stream_to_gradio", "GradioUI"]
agent.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tools": [
3
+ "web_search",
4
+ "visit_webpage",
5
+ "final_answer"
6
+ ],
7
+ "model": {
8
+ "class": "HfApiModel",
9
+ "data": {
10
+ "max_tokens": 2096,
11
+ "temperature": 0.5,
12
+ "last_input_token_count": null,
13
+ "last_output_token_count": null,
14
+ "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct",
15
+ "custom_role_conversions": null
16
+ }
17
+ },
18
+ "prompt_templates": {
19
+ "system_prompt": "You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.\nTo do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.\n\nAt each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.\nThen in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.\nDuring each intermediate step, you can use 'print()' to save whatever important information you will then need.\nThese print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\nTask: \"Generate an image of the oldest person in this document.\"\n\nThought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.\nCode:\n```py\nanswer = document_qa(document=document, question=\"Who is the oldest person mentioned?\")\nprint(answer)\n```<end_code>\nObservation: \"The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland.\"\n\nThought: I will now generate an image showcasing the oldest person.\nCode:\n```py\nimage = image_generator(\"A portrait of John Doe, a 55-year-old man living in Canada.\")\nfinal_answer(image)\n```<end_code>\n\n---\nTask: \"What is the result of the following operation: 5 + 3 + 1294.678?\"\n\nThought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool\nCode:\n```py\nresult = 5 + 3 + 1294.678\nfinal_answer(result)\n```<end_code>\n\n---\nTask:\n\"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.\nYou have been provided with these additional arguments, that you can access using the keys as variables in your python code:\n{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}\"\n\nThought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.\nCode:\n```py\ntranslated_question = translator(question=question, src_lang=\"French\", tgt_lang=\"English\")\nprint(f\"The translated question is {translated_question}.\")\nanswer = image_qa(image=image, question=translated_question)\nfinal_answer(f\"The answer is {answer}\")\n```<end_code>\n\n---\nTask:\nIn a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.\nWhat does he say was the consequence of Einstein learning too much math on his creativity, in one word?\n\nThought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\")\nprint(pages)\n```<end_code>\nObservation:\nNo result found for query \"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\".\n\nThought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam\")\nprint(pages)\n```<end_code>\nObservation:\nFound 6 pages:\n[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)\n\n[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)\n\n(truncated)\n\nThought: I will read the first 2 pages to know more.\nCode:\n```py\nfor url in [\"https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/\", \"https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/\"]:\n whole_page = visit_webpage(url)\n print(whole_page)\n print(\"\\n\" + \"=\"*80 + \"\\n\") # Print separator between pages\n```<end_code>\nObservation:\nManhattan Project Locations:\nLos Alamos, NM\nStanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at\n(truncated)\n\nThought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: \"He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity.\" Let's answer in one word.\nCode:\n```py\nfinal_answer(\"diminished\")\n```<end_code>\n\n---\nTask: \"Which city has the highest population: Guangzhou or Shanghai?\"\n\nThought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.\nCode:\n```py\nfor city in [\"Guangzhou\", \"Shanghai\"]:\n print(f\"Population {city}:\", search(f\"{city} population\")\n```<end_code>\nObservation:\nPopulation Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']\nPopulation Shanghai: '26 million (2019)'\n\nThought: Now I know that Shanghai has the highest population.\nCode:\n```py\nfinal_answer(\"Shanghai\")\n```<end_code>\n\n---\nTask: \"What is the current age of the pope, raised to the power 0.36?\"\n\nThought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.\nCode:\n```py\npope_age_wiki = wiki(query=\"current pope age\")\nprint(\"Pope age as per wikipedia:\", pope_age_wiki)\npope_age_search = web_search(query=\"current pope age\")\nprint(\"Pope age as per google search:\", pope_age_search)\n```<end_code>\nObservation:\nPope age: \"The pope Francis is currently 88 years old.\"\n\nThought: I know that the pope is 88 years old. Let's compute the result using python code.\nCode:\n```py\npope_current_age = 88 ** 0.36\nfinal_answer(pope_current_age)\n```<end_code>\n\nAbove example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.\nGiven that this team member is a real human, you should be very verbose in your task.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere are the rules you should always follow to solve your task:\n1. Always provide a 'Thought:' sequence, and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence, else you will fail.\n2. Use only variables that you have defined!\n3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': \"What is the place where James Bond lives?\"})', but use the arguments directly as in 'answer = wiki(query=\"What is the place where James Bond lives?\")'.\n4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.\n5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.\n6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.\n7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.\n8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}\n9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.\n10. Don't give up! You're in charge of solving the task, not providing directions to solve it.\n\nNow Begin! If you solve the task correctly, you will receive a reward of $1,000,000.",
20
+ "planning": {
21
+ "initial_facts": "Below I will present you a task.\n\nYou will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.\nTo do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.\nDon't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:\n\n---\n### 1. Facts given in the task\nList here the specific facts given in the task that could help you (there might be nothing here).\n\n### 2. Facts to look up\nList here any facts that we may need to look up.\nAlso list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.\n\n### 3. Facts to derive\nList here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.\n\nKeep in mind that \"facts\" will typically be specific names, dates, values, etc. Your answer should use the below headings:\n### 1. Facts given in the task\n### 2. Facts to look up\n### 3. Facts to derive\nDo not add anything else.",
22
+ "initial_plan": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nHere is your task:\n\nTask:\n```\n{{task}}\n```\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.\nGiven that this team member is a real human, you should be very verbose in your request.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nList of facts that you know:\n```\n{{answer_facts}}\n```\n\nNow begin! Write your plan below.",
23
+ "update_facts_pre_messages": "You are a world expert at gathering known and unknown facts based on a conversation.\nBelow you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\nFind the task and history below:",
24
+ "update_facts_post_messages": "Earlier we've built a list of facts.\nBut since in your previous steps you may have learned useful new facts or invalidated some false ones.\nPlease update your list of facts based on the previous history, and provide these headings:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\n\nNow write your new list of facts below.",
25
+ "update_plan_pre_messages": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nYou have been given a task:\n```\n{{task}}\n```\n\nFind below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.\nIf the previous tries so far have met some success, you can make an updated plan based on these actions.\nIf you are stalled, you can make a completely new plan starting from scratch.",
26
+ "update_plan_post_messages": "You're still working towards solving this task:\n```\n{{task}}\n```\n\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere is the up to date list of facts that you know:\n```\n{{facts_update}}\n```\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nBeware that you have {remaining_steps} steps remaining.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nNow write your new plan below."
27
+ },
28
+ "managed_agent": {
29
+ "task": "You're a helpful agent named '{{name}}'.\nYou have been submitted this task by your manager.\n---\nTask:\n{{task}}\n---\nYou're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.\n\nYour final_answer WILL HAVE to contain these parts:\n### 1. Task outcome (short version):\n### 2. Task outcome (extremely detailed version):\n### 3. Additional context (if relevant):\n\nPut all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.\nAnd even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.",
30
+ "report": "Here is the final answer from your managed agent '{{name}}':\n{{final_answer}}"
31
+ }
32
+ },
33
+ "max_steps": 6,
34
+ "verbosity_level": 1,
35
+ "grammar": null,
36
+ "planning_interval": null,
37
+ "name": null,
38
+ "description": null,
39
+ "authorized_imports": [
40
+ "unicodedata",
41
+ "stat",
42
+ "datetime",
43
+ "random",
44
+ "pandas",
45
+ "itertools",
46
+ "math",
47
+ "statistics",
48
+ "queue",
49
+ "time",
50
+ "collections",
51
+ "re"
52
+ ]
53
+ }
app.py CHANGED
@@ -1,494 +1,87 @@
1
- import os
2
- import gradio as gr
3
  import requests
4
- import inspect
5
- import pandas as pd
6
- from firecrawl import FirecrawlApp
7
- from langchain_community.document_loaders.firecrawl import FireCrawlLoader
8
- from langchain_core.tools import tool
9
- from dotenv import load_dotenv
10
- import wikipedia
11
- from datetime import datetime
12
- from smolagents import Tool
13
- from docling.document_converter import DocumentConverter
14
- from docling.chunking import HierarchicalChunker
15
- from sentence_transformers import SentenceTransformer, util
16
- import torch
17
 
 
18
 
19
- class ContentRetrieverTool(Tool):
20
- name = "retrieve_content"
21
- description = """Retrieve the content of a webpage or document in markdown format. Supports PDF, DOCX, XLSX, HTML, images, and more."""
22
- inputs = {
23
- "url": {
24
- "type": "string",
25
- "description": "The URL or local path of the webpage or document to retrieve.",
26
- },
27
- "query": {
28
- "type": "string",
29
- "description": "The subject on the page you are looking for. The shorter the more relevant content is returned.",
30
- },
31
- }
32
- output_type = "string"
33
-
34
- def __init__(
35
- self,
36
- model_name: str | None = None,
37
- threshold: float = 0.2,
38
- **kwargs,
39
- ):
40
- self.threshold = threshold
41
- self._document_converter = DocumentConverter()
42
- self._model = SentenceTransformer(
43
- model_name if model_name is not None else "all-MiniLM-L6-v2"
44
- )
45
- self._chunker = HierarchicalChunker()
46
-
47
- super().__init__(**kwargs)
48
-
49
- def forward(self, url: str, query: str) -> str:
50
- document = self._document_converter.convert(url).document
51
-
52
- chunks = list(self._chunker.chunk(dl_doc=document))
53
- if len(chunks) == 0:
54
- return "No content found."
55
-
56
- chunks_text = [chunk.text for chunk in chunks]
57
- chunks_with_context = [self._chunker.contextualize(chunk) for chunk in chunks]
58
- chunks_context = [
59
- chunks_with_context[i].replace(chunks_text[i], "").strip()
60
- for i in range(len(chunks))
61
- ]
62
-
63
- chunk_embeddings = self._model.encode(chunks_text, convert_to_tensor=True)
64
- context_embeddings = self._model.encode(chunks_context, convert_to_tensor=True)
65
- query_embedding = self._model.encode(
66
- [term.strip() for term in query.split(",") if term.strip()],
67
- convert_to_tensor=True,
68
- )
69
-
70
- selected_indices = [] # aggregate indexes across chunks and context matches and for all queries
71
- for embeddings in [
72
- context_embeddings,
73
- chunk_embeddings,
74
- ]:
75
- # Compute cosine similarities (returns 1D tensor)
76
- for cos_scores in util.pytorch_cos_sim(query_embedding, embeddings):
77
- # Convert to softmax probabilities
78
- probabilities = torch.nn.functional.softmax(cos_scores, dim=0)
79
- # Sort by probability descending
80
- sorted_indices = torch.argsort(probabilities, descending=True)
81
- # Accumulate until total probability reaches threshold
82
-
83
- cumulative = 0.0
84
- for i in sorted_indices:
85
- cumulative += probabilities[i].item()
86
- selected_indices.append(i.item())
87
- if cumulative >= self.threshold:
88
- break
89
-
90
- selected_indices = list(
91
- dict.fromkeys(selected_indices)
92
- ) # remove duplicates and preserve order
93
- selected_indices = selected_indices[
94
- ::-1
95
- ] # make most relevant items last for better focus
96
-
97
- if len(selected_indices) == 0:
98
- return "No content found."
99
-
100
- return "\n\n".join([chunks_with_context[idx] for idx in selected_indices])
101
- from smolagents import Tool
102
- from googleapiclient.discovery import build
103
- import os
104
-
105
-
106
- class GoogleSearchTool(Tool):
107
- name = "web_search"
108
- description = """Performs a google web search for query then returns top search results in markdown format."""
109
- inputs = {
110
- "query": {
111
- "type": "string",
112
- "description": "The query to perform search.",
113
- },
114
- }
115
- output_type = "string"
116
-
117
- skip_forward_signature_validation = True
118
-
119
- def __init__(
120
- self,
121
- api_key: str | None = None,
122
- search_engine_id: str | None = None,
123
- num_results: int = 10,
124
- **kwargs,
125
- ):
126
- api_key = api_key if api_key is not None else os.getenv("GOOGLE_SEARCH_API_KEY")
127
- if not api_key:
128
- raise ValueError(
129
- "Please set the GOOGLE_SEARCH_API_KEY environment variable."
130
- )
131
- search_engine_id = (
132
- search_engine_id
133
- if search_engine_id is not None
134
- else os.getenv("GOOGLE_SEARCH_ENGINE_ID")
135
- )
136
- if not search_engine_id:
137
- raise ValueError(
138
- "Please set the GOOGLE_SEARCH_ENGINE_ID environment variable."
139
- )
140
-
141
- self.cse = build("customsearch", "v1", developerKey=api_key).cse()
142
- self.cx = search_engine_id
143
- self.num = num_results
144
- super().__init__(**kwargs)
145
-
146
- def _collect_params(self) -> dict:
147
- return {}
148
-
149
- def forward(self, query: str, *args, **kwargs) -> str:
150
- params = {
151
- "q": query,
152
- "cx": self.cx,
153
- "fields": "items(title,link,snippet)",
154
- "num": self.num,
155
- }
156
-
157
- params = params | self._collect_params(*args, **kwargs)
158
-
159
- response = self.cse.list(**params).execute()
160
- if "items" not in response:
161
- return "No results found."
162
-
163
- result = "\n\n".join(
164
- [
165
- f"[{item['title']}]({item['link']})\n{item['snippet']}"
166
- for item in response["items"]
167
- ]
168
- )
169
- return result
170
-
171
-
172
- class GoogleSiteSearchTool(GoogleSearchTool):
173
- name = "site_search"
174
- description = """Performs a google search within the website for query then returns top search results in markdown format."""
175
- inputs = {
176
- "query": {
177
- "type": "string",
178
- "description": "The query to perform search.",
179
- },
180
- "site": {
181
- "type": "string",
182
- "description": "The domain of the site on which to search.",
183
- },
184
- }
185
-
186
- def _collect_params(self, site: str) -> dict:
187
- return {
188
- "siteSearch": site,
189
- "siteSearchFilter": "i",
190
- }
191
-
192
-
193
-
194
- def get_one_word_answer(text: str) -> str:
195
- # Try to extract a single word (alphanumeric) from the response
196
- import re
197
- words = re.findall(r'\b\w+\b', text)
198
- return words[0] if words else text.strip()
199
- @tool
200
- def current_datetime(_: str = "") -> str:
201
- """
202
- Returns the current date and time.
203
- """
204
- return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
205
  @tool
206
- def calculator(expression: str) -> str:
207
- """
208
- Evaluates a mathematical expression and returns the result.
 
 
 
209
  """
210
- try:
211
- result = eval(expression, {"__builtins__": {}})
212
- return str(result)
213
- except Exception as e:
214
- return f"Calculation error: {e}"
215
- @tool
216
- def wikipedia_search(query: str) -> str:
217
- """
218
- Searches Wikipedia for the given query and returns the summary of the top result.
219
- """
220
- try:
221
- summary = wikipedia.summary(query, sentences=2)
222
- return summary
223
- except Exception as e:
224
- return f"Wikipedia search failed: {e}"
225
- load_dotenv()
226
- loader=FireCrawlLoader(
227
- api_key=os.environ.get('FIRECRAWL_API_KEY'),url='https://firecrawl.dev',mode='scrape')
228
- api_key=os.environ.get('FIRECRAWL_API_KEY')
229
- @tool
230
- def scraper(url:str)->str:
231
- """
232
- Uses Firecrawl to scrape the content of the given url.
233
- """
234
- loader=FireCrawlLoader(
235
- api_key=api_key,
236
- url=url,
237
- mode='scrape'
238
- )
239
- docs=loader.load()
240
- if docs:
241
- return docs[0].page_content[:1000]
242
- return "No content found or failed to scrape."
243
- @tool
244
- def web_search(query:str)->str:
245
- """
246
- Uses firecrawl to search for the given query and returns the top result's snippet.
247
- """
248
- app= FirecrawlApp(api_key=api_key)
249
- results=app.search(query)
250
- if results and results.get("results"):
251
- top=results["results"][0]
252
- return f"{top.get('title','')}:{top.get('snippet','')}({top.get('url','')})"
253
- return "No results found"
254
- # (Keep Constants as is)
255
- # --- Constants ---
256
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
257
-
258
- # --- Basic Agent Definition ---
259
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
260
-
261
-
262
- # ...existing code...
263
 
264
- TOOL_REGISTRY = {
265
- "calculator": calculator,
266
- "current_datetime": current_datetime,
267
- "wikipedia_search": wikipedia_search,
268
- "scraper": scraper,
269
- "web_search": web_search,
270
- "site_search": GoogleSiteSearchTool().forward,
271
- }
272
-
273
- def select_tool(question: str):
274
- import re
275
- # Tool selection logic (can be replaced by LLM prompt in advanced setups)
276
- if any(kw in question.lower() for kw in ["calculate", "compute", "evaluate", "+", "-", "*", "/", "^", "sqrt", "log", "sum", "product"]):
277
- return "calculator"
278
- if any(kw in question.lower() for kw in ["date", "time", "day", "month", "year", "current time", "current date"]):
279
- return "current_datetime"
280
- if "wikipedia" in question.lower() or "wiki" in question.lower():
281
- return "wikipedia_search"
282
- # Add more rules as needed
283
- return "web_search"
284
-
285
- class BasicAgent:
286
- def __init__(self):
287
- print("BasicAgent initialized.")
288
-
289
- def __call__(self, question: str) -> str:
290
- print(f"Agent received question (first 50 chars): {question[:50]}...")
291
- import re
292
-
293
- tool_name = select_tool(question)
294
- tool = TOOL_REGISTRY.get(tool_name, web_search)
295
- # For other tools, pass the question or relevant part
296
- if tool_name == "wikipedia_search":
297
- cleaned = question.lower().replace("wikipedia", "").replace("wiki", "").strip()
298
- return get_one_word_answer(tool(cleaned if cleaned else question))
299
- if tool_name == "calculator":
300
- return get_one_word_answer(tool(question))
301
- if tool_name == "current_datetime":
302
- return get_one_word_answer(tool())
303
- if tool_name == "scraper":
304
- return get_one_word_answer(tool(question))
305
- if tool_name == "site_search":
306
- # Example: expects "site:example.com query"
307
- parts = question.split("site:")
308
- if len(parts) == 2:
309
- site = parts[1].split()[0]
310
- query = parts[1][len(site):].strip()
311
- return get_one_word_answer(tool(query, site))
312
- else:
313
- return "No site specified."
314
- # Default: web_search
315
- result = tool(question)
316
- return get_one_word_answer(result)
317
-
318
- # ...existing code...
319
-
320
- def run_and_submit_all( profile: gr.OAuthProfile | None):
321
- """
322
- Fetches all questions, runs the BasicAgent on them, submits all answers,
323
- and displays the results.
324
  """
325
- # --- Determine HF Space Runtime URL and Repo URL ---
326
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
327
-
328
- if profile:
329
- username= f"{profile.username}"
330
- print(f"User logged in: {username}")
 
331
  else:
332
- print("User not logged in.")
333
- return "Please Login to Hugging Face with the button.", None
334
 
335
- api_url = DEFAULT_API_URL
336
- questions_url = f"{api_url}/questions"
337
- submit_url = f"{api_url}/submit"
338
-
339
- # 1. Instantiate Agent ( modify this part to create your agent)
340
- try:
341
- agent = BasicAgent()
342
- except Exception as e:
343
- print(f"Error instantiating agent: {e}")
344
- return f"Error initializing agent: {e}", None
345
- # 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)
346
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
347
- print(agent_code)
348
-
349
- # 2. Fetch Questions
350
- print(f"Fetching questions from: {questions_url}")
351
- try:
352
- response = requests.get(questions_url, timeout=15)
353
- response.raise_for_status()
354
- questions_data = response.json()
355
- if not questions_data:
356
- print("Fetched questions list is empty.")
357
- return "Fetched questions list is empty or invalid format.", None
358
- print(f"Fetched {len(questions_data)} questions.")
359
- except requests.exceptions.RequestException as e:
360
- print(f"Error fetching questions: {e}")
361
- return f"Error fetching questions: {e}", None
362
- except requests.exceptions.JSONDecodeError as e:
363
- print(f"Error decoding JSON response from questions endpoint: {e}")
364
- print(f"Response text: {response.text[:500]}")
365
- return f"Error decoding server response for questions: {e}", None
366
- except Exception as e:
367
- print(f"An unexpected error occurred fetching questions: {e}")
368
- return f"An unexpected error occurred fetching questions: {e}", None
369
-
370
- # 3. Run your Agent
371
- results_log = []
372
- answers_payload = []
373
- print(f"Running agent on {len(questions_data)} questions...")
374
- for item in questions_data:
375
- task_id = item.get("task_id")
376
- question_text = item.get("question")
377
- if not task_id or question_text is None:
378
- print(f"Skipping item with missing task_id or question: {item}")
379
- continue
380
- try:
381
- submitted_answer = agent(question_text)
382
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
383
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
384
- except Exception as e:
385
- print(f"Error running agent on task {task_id}: {e}")
386
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
387
-
388
- if not answers_payload:
389
- print("Agent did not produce any answers to submit.")
390
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
391
-
392
- # 4. Prepare Submission
393
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
394
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
395
- print(status_update)
396
-
397
- # 5. Submit
398
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
399
  try:
400
- response = requests.post(submit_url, json=submission_data, timeout=60)
401
- response.raise_for_status()
402
- result_data = response.json()
403
- final_status = (
404
- f"Submission Successful!\n"
405
- f"User: {result_data.get('username')}\n"
406
- f"Overall Score: {result_data.get('score', 'N/A')}% "
407
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
408
- f"Message: {result_data.get('message', 'No message received.')}"
409
- )
410
- print("Submission successful.")
411
- results_df = pd.DataFrame(results_log)
412
- return final_status, results_df
413
- except requests.exceptions.HTTPError as e:
414
- error_detail = f"Server responded with status {e.response.status_code}."
415
- try:
416
- error_json = e.response.json()
417
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
418
- except requests.exceptions.JSONDecodeError:
419
- error_detail += f" Response: {e.response.text[:500]}"
420
- status_message = f"Submission Failed: {error_detail}"
421
- print(status_message)
422
- results_df = pd.DataFrame(results_log)
423
- return status_message, results_df
424
- except requests.exceptions.Timeout:
425
- status_message = "Submission Failed: The request timed out."
426
- print(status_message)
427
- results_df = pd.DataFrame(results_log)
428
- return status_message, results_df
429
- except requests.exceptions.RequestException as e:
430
- status_message = f"Submission Failed: Network error - {e}"
431
- print(status_message)
432
- results_df = pd.DataFrame(results_log)
433
- return status_message, results_df
434
  except Exception as e:
435
- status_message = f"An unexpected error occurred during submission: {e}"
436
- print(status_message)
437
- results_df = pd.DataFrame(results_log)
438
- return status_message, results_df
439
-
440
-
441
- # --- Build Gradio Interface using Blocks ---
442
- with gr.Blocks() as demo:
443
- gr.Markdown("# Basic Agent Evaluation Runner")
444
- gr.Markdown(
445
- """
446
- **Instructions:**
447
 
448
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
449
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
450
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
451
 
452
- ---
453
- **Disclaimers:**
454
- 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).
455
- 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.
456
- """
457
- )
458
 
459
- gr.LoginButton()
 
460
 
461
- run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
 
 
 
462
 
463
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
464
- # Removed max_rows=10 from DataFrame constructor
465
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
466
 
467
- run_button.click(
468
- fn=run_and_submit_all,
469
- outputs=[status_output, results_table]
470
- )
471
 
472
- if __name__ == "__main__":
473
- print("\n" + "-"*30 + " App Starting " + "-"*30)
474
- # Check for SPACE_HOST and SPACE_ID at startup for information
475
- space_host_startup = os.getenv("SPACE_HOST")
476
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
477
-
478
- if space_host_startup:
479
- print(f"✅ SPACE_HOST found: {space_host_startup}")
480
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
481
- else:
482
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
483
-
484
- if space_id_startup: # Print repo URLs if SPACE_ID is found
485
- print(f"✅ SPACE_ID found: {space_id_startup}")
486
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
487
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
488
- else:
489
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
490
 
491
- print("-"*(60 + len(" App Starting ")) + "\n")
492
 
493
- print("Launching Gradio Interface for Basic Agent Evaluation...")
494
- demo.launch(debug=True, share=False)
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
+ import datetime
3
  import requests
4
+ import pytz
5
+ import yaml
6
+ from tools.final_answer import FinalAnswerTool
 
 
 
 
 
 
 
 
 
 
7
 
8
+ from Gradio_UI import GradioUI
9
 
10
+ # Below is an example of a tool that does nothing. Amaze us with your creativity !
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  @tool
12
+ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
+ #Keep this format for the description / args / args description but feel free to modify the tool
14
+ """A tool that does nothing yet
15
+ Args:
16
+ arg1: the first argument
17
+ arg2: the second argument
18
  """
19
+ return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ @tool
22
+ def days_until(date_str: str) -> str:
23
+ """Calculates days from today until the given date (YYYY-MM-DD).
24
+ If the date is in the past, calculates how many days has passed since the given date (YYYY-MM-DD)
25
+ Args:
26
+ date_str: a string representing a date in the following format (YYYY-MM-DD)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  """
28
+ target = datetime.datetime.strptime(date_str, "%Y-%m-%d")
29
+ now = datetime.datetime.now()
30
+ DaysRemaining = (target - now).days
31
+ if DaysRemaining > 0:
32
+ return f"There are {DaysRemaining} days remaining until {date_str}!"
33
+ elif DaysRemaining == 0:
34
+ return "Today is the date!"
35
  else:
36
+ return f"The date {date_str} was {(DaysRemaining * -1)} days ago."
 
37
 
38
+ @tool
39
+ def get_current_time_in_timezone(timezone: str) -> str:
40
+ """A tool that fetches the current local time in a specified timezone.
41
+ Args:
42
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
43
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  try:
45
+ # Create timezone object
46
+ tz = pytz.timezone(timezone)
47
+ # Get current time in that timezone
48
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
49
+ return f"The current local time in {timezone} is: {local_time}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  except Exception as e:
51
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
53
 
54
+ final_answer = FinalAnswerTool()
55
+ search_tool = DuckDuckGoSearchTool()
 
 
 
 
56
 
57
+ # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
58
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
59
 
60
+ model = HfApiModel(
61
+ max_tokens=2096,
62
+ temperature=0.5,
63
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
64
+ custom_role_conversions=None,
65
+ )
66
 
 
 
 
67
 
68
+ # Import tool from Hub
69
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
70
 
71
+ with open("prompts.yaml", 'r') as stream:
72
+ prompt_templates = yaml.safe_load(stream)
73
+
74
+ agent = CodeAgent(
75
+ model=model,
76
+ tools=[final_answer, search_tool, get_current_time_in_timezone, days_until], ## add your tools here (don't remove final answer)
77
+ max_steps=6,
78
+ verbosity_level=1,
79
+ grammar=None,
80
+ planning_interval=None,
81
+ name=None,
82
+ description=None,
83
+ prompt_templates=prompt_templates
84
+ )
 
 
 
 
85
 
 
86
 
87
+ GradioUI(agent).launch()
 
main.py DELETED
@@ -1,6 +0,0 @@
1
- def main():
2
- print("Hello from final-assignment-template!")
3
-
4
-
5
- if __name__ == "__main__":
6
- main()
 
 
 
 
 
 
 
prompts.yaml ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "system_prompt": |-
2
+ You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
3
+ To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
4
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
5
+
6
+ At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
7
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
8
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
9
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
10
+ In the end you have to return a final answer using the `final_answer` tool.
11
+
12
+ Here are a few examples using notional tools:
13
+ ---
14
+ Task: "Generate an image of the oldest person in this document."
15
+
16
+ Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
17
+ Code:
18
+ ```py
19
+ answer = document_qa(document=document, question="Who is the oldest person mentioned?")
20
+ print(answer)
21
+ ```<end_code>
22
+ Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
23
+
24
+ Thought: I will now generate an image showcasing the oldest person.
25
+ Code:
26
+ ```py
27
+ image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
28
+ final_answer(image)
29
+ ```<end_code>
30
+
31
+ ---
32
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
33
+
34
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
35
+ Code:
36
+ ```py
37
+ result = 5 + 3 + 1294.678
38
+ final_answer(result)
39
+ ```<end_code>
40
+
41
+ ---
42
+ Task:
43
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
44
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
45
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
46
+
47
+ Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
48
+ Code:
49
+ ```py
50
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
51
+ print(f"The translated question is {translated_question}.")
52
+ answer = image_qa(image=image, question=translated_question)
53
+ final_answer(f"The answer is {answer}")
54
+ ```<end_code>
55
+
56
+ ---
57
+ Task:
58
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
59
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
60
+
61
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
62
+ Code:
63
+ ```py
64
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
65
+ print(pages)
66
+ ```<end_code>
67
+ Observation:
68
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
69
+
70
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
71
+ Code:
72
+ ```py
73
+ pages = search(query="1979 interview Stanislaus Ulam")
74
+ print(pages)
75
+ ```<end_code>
76
+ Observation:
77
+ Found 6 pages:
78
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
79
+
80
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
81
+
82
+ (truncated)
83
+
84
+ Thought: I will read the first 2 pages to know more.
85
+ Code:
86
+ ```py
87
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
88
+ whole_page = visit_webpage(url)
89
+ print(whole_page)
90
+ print("\n" + "="*80 + "\n") # Print separator between pages
91
+ ```<end_code>
92
+ Observation:
93
+ Manhattan Project Locations:
94
+ Los Alamos, NM
95
+ Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
96
+ (truncated)
97
+
98
+ Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
99
+ Code:
100
+ ```py
101
+ final_answer("diminished")
102
+ ```<end_code>
103
+
104
+ ---
105
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
106
+
107
+ Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
108
+ Code:
109
+ ```py
110
+ for city in ["Guangzhou", "Shanghai"]:
111
+ print(f"Population {city}:", search(f"{city} population")
112
+ ```<end_code>
113
+ Observation:
114
+ Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
115
+ Population Shanghai: '26 million (2019)'
116
+
117
+ Thought: Now I know that Shanghai has the highest population.
118
+ Code:
119
+ ```py
120
+ final_answer("Shanghai")
121
+ ```<end_code>
122
+
123
+ ---
124
+ Task: "What is the current age of the pope, raised to the power 0.36?"
125
+
126
+ Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
127
+ Code:
128
+ ```py
129
+ pope_age_wiki = wiki(query="current pope age")
130
+ print("Pope age as per wikipedia:", pope_age_wiki)
131
+ pope_age_search = web_search(query="current pope age")
132
+ print("Pope age as per google search:", pope_age_search)
133
+ ```<end_code>
134
+ Observation:
135
+ Pope age: "The pope Francis is currently 88 years old."
136
+
137
+ Thought: I know that the pope is 88 years old. Let's compute the result using python code.
138
+ Code:
139
+ ```py
140
+ pope_current_age = 88 ** 0.36
141
+ final_answer(pope_current_age)
142
+ ```<end_code>
143
+
144
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
145
+ {%- for tool in tools.values() %}
146
+ - {{ tool.name }}: {{ tool.description }}
147
+ Takes inputs: {{tool.inputs}}
148
+ Returns an output of type: {{tool.output_type}}
149
+ {%- endfor %}
150
+
151
+ {%- if managed_agents and managed_agents.values() | list %}
152
+ You can also give tasks to team members.
153
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
154
+ Given that this team member is a real human, you should be very verbose in your task.
155
+ Here is a list of the team members that you can call:
156
+ {%- for agent in managed_agents.values() %}
157
+ - {{ agent.name }}: {{ agent.description }}
158
+ {%- endfor %}
159
+ {%- else %}
160
+ {%- endif %}
161
+
162
+ Here are the rules you should always follow to solve your task:
163
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
164
+ 2. Use only variables that you have defined!
165
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
166
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
167
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
168
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
169
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
170
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
171
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
172
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
173
+
174
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
175
+ "planning":
176
+ "initial_facts": |-
177
+ Below I will present you a task.
178
+
179
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
180
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
181
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
182
+
183
+ ---
184
+ ### 1. Facts given in the task
185
+ List here the specific facts given in the task that could help you (there might be nothing here).
186
+
187
+ ### 2. Facts to look up
188
+ List here any facts that we may need to look up.
189
+ Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
190
+
191
+ ### 3. Facts to derive
192
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
193
+
194
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
195
+ ### 1. Facts given in the task
196
+ ### 2. Facts to look up
197
+ ### 3. Facts to derive
198
+ Do not add anything else.
199
+ "initial_plan": |-
200
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
201
+
202
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
203
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
204
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
205
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
206
+
207
+ Here is your task:
208
+
209
+ Task:
210
+ ```
211
+ {{task}}
212
+ ```
213
+ You can leverage these tools:
214
+ {%- for tool in tools.values() %}
215
+ - {{ tool.name }}: {{ tool.description }}
216
+ Takes inputs: {{tool.inputs}}
217
+ Returns an output of type: {{tool.output_type}}
218
+ {%- endfor %}
219
+
220
+ {%- if managed_agents and managed_agents.values() | list %}
221
+ You can also give tasks to team members.
222
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
223
+ Given that this team member is a real human, you should be very verbose in your request.
224
+ Here is a list of the team members that you can call:
225
+ {%- for agent in managed_agents.values() %}
226
+ - {{ agent.name }}: {{ agent.description }}
227
+ {%- endfor %}
228
+ {%- else %}
229
+ {%- endif %}
230
+
231
+ List of facts that you know:
232
+ ```
233
+ {{answer_facts}}
234
+ ```
235
+
236
+ Now begin! Write your plan below.
237
+ "update_facts_pre_messages": |-
238
+ You are a world expert at gathering known and unknown facts based on a conversation.
239
+ Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
240
+ ### 1. Facts given in the task
241
+ ### 2. Facts that we have learned
242
+ ### 3. Facts still to look up
243
+ ### 4. Facts still to derive
244
+ Find the task and history below:
245
+ "update_facts_post_messages": |-
246
+ Earlier we've built a list of facts.
247
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
248
+ Please update your list of facts based on the previous history, and provide these headings:
249
+ ### 1. Facts given in the task
250
+ ### 2. Facts that we have learned
251
+ ### 3. Facts still to look up
252
+ ### 4. Facts still to derive
253
+
254
+ Now write your new list of facts below.
255
+ "update_plan_pre_messages": |-
256
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
257
+
258
+ You have been given a task:
259
+ ```
260
+ {{task}}
261
+ ```
262
+
263
+ Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
264
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
265
+ If you are stalled, you can make a completely new plan starting from scratch.
266
+ "update_plan_post_messages": |-
267
+ You're still working towards solving this task:
268
+ ```
269
+ {{task}}
270
+ ```
271
+
272
+ You can leverage these tools:
273
+ {%- for tool in tools.values() %}
274
+ - {{ tool.name }}: {{ tool.description }}
275
+ Takes inputs: {{tool.inputs}}
276
+ Returns an output of type: {{tool.output_type}}
277
+ {%- endfor %}
278
+
279
+ {%- if managed_agents and managed_agents.values() | list %}
280
+ You can also give tasks to team members.
281
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
282
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
283
+ Here is a list of the team members that you can call:
284
+ {%- for agent in managed_agents.values() %}
285
+ - {{ agent.name }}: {{ agent.description }}
286
+ {%- endfor %}
287
+ {%- else %}
288
+ {%- endif %}
289
+
290
+ Here is the up to date list of facts that you know:
291
+ ```
292
+ {{facts_update}}
293
+ ```
294
+
295
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
296
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
297
+ Beware that you have {remaining_steps} steps remaining.
298
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
299
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
300
+
301
+ Now write your new plan below.
302
+ "managed_agent":
303
+ "task": |-
304
+ You're a helpful agent named '{{name}}'.
305
+ You have been submitted this task by your manager.
306
+ ---
307
+ Task:
308
+ {{task}}
309
+ ---
310
+ You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
311
+
312
+ Your final_answer WILL HAVE to contain these parts:
313
+ ### 1. Task outcome (short version):
314
+ ### 2. Task outcome (extremely detailed version):
315
+ ### 3. Additional context (if relevant):
316
+
317
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
318
+ And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
319
+ "report": |-
320
+ Here is the final answer from your managed agent '{{name}}':
321
+ {{final_answer}}
pyproject.toml CHANGED
@@ -7,12 +7,14 @@ requires-python = ">=3.11"
7
  dependencies = [
8
  "docling>=2.39.0",
9
  "dotenv>=0.9.9",
 
10
  "firecrawl-py>=2.12.0",
11
  "google>=3.0.0",
12
  "gradio>=5.35.0",
13
  "huggingface-hub>=0.33.1",
14
  "langchain>=0.3.26",
15
  "langchain-community>=0.3.26",
 
16
  "requests>=2.32.4",
17
  "ruff>=0.12.1",
18
  "sentence-transformers>=4.1.0",
 
7
  dependencies = [
8
  "docling>=2.39.0",
9
  "dotenv>=0.9.9",
10
+ "duckduckgo-search>=8.0.4",
11
  "firecrawl-py>=2.12.0",
12
  "google>=3.0.0",
13
  "gradio>=5.35.0",
14
  "huggingface-hub>=0.33.1",
15
  "langchain>=0.3.26",
16
  "langchain-community>=0.3.26",
17
+ "markdownify>=1.1.0",
18
  "requests>=2.32.4",
19
  "ruff>=0.12.1",
20
  "sentence-transformers>=4.1.0",
requirements.txt CHANGED
@@ -1,13 +1,5 @@
1
- gradio
 
2
  requests
3
- langchain
4
- dotenv
5
- langchain_community
6
- firecrawl_py
7
- wikipedia
8
- torch
9
- transformers
10
- sentence_transformers
11
- docling
12
- smolagents
13
- google
 
1
+ markdownify
2
+ smolagents==1.13.0
3
  requests
4
+ duckduckgo_search
5
+ pandas
 
 
 
 
 
 
 
 
 
tools/final_answer.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+ from smolagents.tools import Tool
3
+
4
+ class FinalAnswerTool(Tool):
5
+ name = "final_answer"
6
+ description = "Provides a final answer to the given problem."
7
+ inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
8
+ output_type = "any"
9
+
10
+ def forward(self, answer: Any) -> Any:
11
+ return answer
12
+
13
+ def __init__(self, *args, **kwargs):
14
+ self.is_initialized = False
tools/visit_webpage.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+ from smolagents.tools import Tool
3
+ import requests
4
+ import markdownify
5
+ import smolagents
6
+
7
+ class VisitWebpageTool(Tool):
8
+ name = "visit_webpage"
9
+ description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
10
+ inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}
11
+ output_type = "string"
12
+
13
+ def forward(self, url: str) -> str:
14
+ try:
15
+ import requests
16
+ from markdownify import markdownify
17
+ from requests.exceptions import RequestException
18
+
19
+ from smolagents.utils import truncate_content
20
+ except ImportError as e:
21
+ raise ImportError(
22
+ "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
23
+ ) from e
24
+ try:
25
+ # Send a GET request to the URL with a 20-second timeout
26
+ response = requests.get(url, timeout=20)
27
+ response.raise_for_status() # Raise an exception for bad status codes
28
+
29
+ # Convert the HTML content to Markdown
30
+ markdown_content = markdownify(response.text).strip()
31
+
32
+ # Remove multiple line breaks
33
+ markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
34
+
35
+ return truncate_content(markdown_content, 10000)
36
+
37
+ except requests.exceptions.Timeout:
38
+ return "The request timed out. Please try again later or check the URL."
39
+ except RequestException as e:
40
+ return f"Error fetching the webpage: {str(e)}"
41
+ except Exception as e:
42
+ return f"An unexpected error occurred: {str(e)}"
43
+
44
+ def __init__(self, *args, **kwargs):
45
+ self.is_initialized = False
tools/web_search.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+ from smolagents.tools import Tool
3
+ import duckduckgo_search
4
+
5
+ class DuckDuckGoSearchTool(Tool):
6
+ name = "web_search"
7
+ description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."
8
+ inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}
9
+ output_type = "string"
10
+
11
+ def __init__(self, max_results=10, **kwargs):
12
+ super().__init__()
13
+ self.max_results = max_results
14
+ try:
15
+ from duckduckgo_search import DDGS
16
+ except ImportError as e:
17
+ raise ImportError(
18
+ "You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."
19
+ ) from e
20
+ self.ddgs = DDGS(**kwargs)
21
+
22
+ def forward(self, query: str) -> str:
23
+ results = self.ddgs.text(query, max_results=self.max_results)
24
+ if len(results) == 0:
25
+ raise Exception("No results found! Try a less restrictive/shorter query.")
26
+ postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
27
+ return "## Search Results\n\n" + "\n\n".join(postprocessed_results)
uv.lock CHANGED
@@ -469,6 +469,20 @@ wheels = [
469
  { url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892 },
470
  ]
471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  [[package]]
473
  name = "easyocr"
474
  version = "1.7.2"
@@ -548,12 +562,14 @@ source = { virtual = "." }
548
  dependencies = [
549
  { name = "docling" },
550
  { name = "dotenv" },
 
551
  { name = "firecrawl-py" },
552
  { name = "google" },
553
  { name = "gradio" },
554
  { name = "huggingface-hub" },
555
  { name = "langchain" },
556
  { name = "langchain-community" },
 
557
  { name = "requests" },
558
  { name = "ruff" },
559
  { name = "sentence-transformers" },
@@ -566,12 +582,14 @@ dependencies = [
566
  requires-dist = [
567
  { name = "docling", specifier = ">=2.39.0" },
568
  { name = "dotenv", specifier = ">=0.9.9" },
 
569
  { name = "firecrawl-py", specifier = ">=2.12.0" },
570
  { name = "google", specifier = ">=3.0.0" },
571
  { name = "gradio", specifier = ">=5.35.0" },
572
  { name = "huggingface-hub", specifier = ">=0.33.1" },
573
  { name = "langchain", specifier = ">=0.3.26" },
574
  { name = "langchain-community", specifier = ">=0.3.26" },
 
575
  { name = "requests", specifier = ">=2.32.4" },
576
  { name = "ruff", specifier = ">=0.12.1" },
577
  { name = "sentence-transformers", specifier = ">=4.1.0" },
@@ -1176,6 +1194,19 @@ wheels = [
1176
  { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 },
1177
  ]
1178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1179
  [[package]]
1180
  name = "marko"
1181
  version = "2.1.4"
@@ -1825,6 +1856,22 @@ wheels = [
1825
  { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 },
1826
  ]
1827
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828
  [[package]]
1829
  name = "propcache"
1830
  version = "0.3.2"
 
469
  { url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892 },
470
  ]
471
 
472
+ [[package]]
473
+ name = "duckduckgo-search"
474
+ version = "8.0.4"
475
+ source = { registry = "https://pypi.org/simple" }
476
+ dependencies = [
477
+ { name = "click" },
478
+ { name = "lxml" },
479
+ { name = "primp" },
480
+ ]
481
+ sdist = { url = "https://files.pythonhosted.org/packages/dc/ad/11f1b4e984f2230d3857914d6b496a6ec24c768f9f57e120b135c7ee8e4e/duckduckgo_search-8.0.4.tar.gz", hash = "sha256:02aee731d05056a6bbf217c51faddd0b9565c5ce1e94d0278cbd2fbcc0e41b95", size = 21843 }
482
+ wheels = [
483
+ { url = "https://files.pythonhosted.org/packages/14/f0/1332de2dc7e7cbcabcf3993b3383dbce6b43d91cb3759fb53916be02845d/duckduckgo_search-8.0.4-py3-none-any.whl", hash = "sha256:22490e83c0ca885998d6623d8274f24934faffc43dac3c3482fe24ea4f6799bb", size = 18219 },
484
+ ]
485
+
486
  [[package]]
487
  name = "easyocr"
488
  version = "1.7.2"
 
562
  dependencies = [
563
  { name = "docling" },
564
  { name = "dotenv" },
565
+ { name = "duckduckgo-search" },
566
  { name = "firecrawl-py" },
567
  { name = "google" },
568
  { name = "gradio" },
569
  { name = "huggingface-hub" },
570
  { name = "langchain" },
571
  { name = "langchain-community" },
572
+ { name = "markdownify" },
573
  { name = "requests" },
574
  { name = "ruff" },
575
  { name = "sentence-transformers" },
 
582
  requires-dist = [
583
  { name = "docling", specifier = ">=2.39.0" },
584
  { name = "dotenv", specifier = ">=0.9.9" },
585
+ { name = "duckduckgo-search", specifier = ">=8.0.4" },
586
  { name = "firecrawl-py", specifier = ">=2.12.0" },
587
  { name = "google", specifier = ">=3.0.0" },
588
  { name = "gradio", specifier = ">=5.35.0" },
589
  { name = "huggingface-hub", specifier = ">=0.33.1" },
590
  { name = "langchain", specifier = ">=0.3.26" },
591
  { name = "langchain-community", specifier = ">=0.3.26" },
592
+ { name = "markdownify", specifier = ">=1.1.0" },
593
  { name = "requests", specifier = ">=2.32.4" },
594
  { name = "ruff", specifier = ">=0.12.1" },
595
  { name = "sentence-transformers", specifier = ">=4.1.0" },
 
1194
  { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 },
1195
  ]
1196
 
1197
+ [[package]]
1198
+ name = "markdownify"
1199
+ version = "1.1.0"
1200
+ source = { registry = "https://pypi.org/simple" }
1201
+ dependencies = [
1202
+ { name = "beautifulsoup4" },
1203
+ { name = "six" },
1204
+ ]
1205
+ sdist = { url = "https://files.pythonhosted.org/packages/2f/78/c48fed23c7aebc2c16049062e72de1da3220c274de59d28c942acdc9ffb2/markdownify-1.1.0.tar.gz", hash = "sha256:449c0bbbf1401c5112379619524f33b63490a8fa479456d41de9dc9e37560ebd", size = 17127 }
1206
+ wheels = [
1207
+ { url = "https://files.pythonhosted.org/packages/64/11/b751af7ad41b254a802cf52f7bc1fca7cabe2388132f2ce60a1a6b9b9622/markdownify-1.1.0-py3-none-any.whl", hash = "sha256:32a5a08e9af02c8a6528942224c91b933b4bd2c7d078f9012943776fc313eeef", size = 13901 },
1208
+ ]
1209
+
1210
  [[package]]
1211
  name = "marko"
1212
  version = "2.1.4"
 
1856
  { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 },
1857
  ]
1858
 
1859
+ [[package]]
1860
+ name = "primp"
1861
+ version = "0.15.0"
1862
+ source = { registry = "https://pypi.org/simple" }
1863
+ sdist = { url = "https://files.pythonhosted.org/packages/56/0b/a87556189da4de1fc6360ca1aa05e8335509633f836cdd06dd17f0743300/primp-0.15.0.tar.gz", hash = "sha256:1af8ea4b15f57571ff7fc5e282a82c5eb69bc695e19b8ddeeda324397965b30a", size = 113022 }
1864
+ wheels = [
1865
+ { url = "https://files.pythonhosted.org/packages/f5/5a/146ac964b99ea7657ad67eb66f770be6577dfe9200cb28f9a95baffd6c3f/primp-0.15.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:1b281f4ca41a0c6612d4c6e68b96e28acfe786d226a427cd944baa8d7acd644f", size = 3178914 },
1866
+ { url = "https://files.pythonhosted.org/packages/bc/8a/cc2321e32db3ce64d6e32950d5bcbea01861db97bfb20b5394affc45b387/primp-0.15.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:489cbab55cd793ceb8f90bb7423c6ea64ebb53208ffcf7a044138e3c66d77299", size = 2955079 },
1867
+ { url = "https://files.pythonhosted.org/packages/c3/7b/cbd5d999a07ff2a21465975d4eb477ae6f69765e8fe8c9087dab250180d8/primp-0.15.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c18b45c23f94016215f62d2334552224236217aaeb716871ce0e4dcfa08eb161", size = 3281018 },
1868
+ { url = "https://files.pythonhosted.org/packages/1b/6e/a6221c612e61303aec2bcac3f0a02e8b67aee8c0db7bdc174aeb8010f975/primp-0.15.0-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:e985a9cba2e3f96a323722e5440aa9eccaac3178e74b884778e926b5249df080", size = 3255229 },
1869
+ { url = "https://files.pythonhosted.org/packages/3b/54/bfeef5aca613dc660a69d0760a26c6b8747d8fdb5a7f20cb2cee53c9862f/primp-0.15.0-cp38-abi3-manylinux_2_34_armv7l.whl", hash = "sha256:6b84a6ffa083e34668ff0037221d399c24d939b5629cd38223af860de9e17a83", size = 3014522 },
1870
+ { url = "https://files.pythonhosted.org/packages/ac/96/84078e09f16a1dad208f2fe0f8a81be2cf36e024675b0f9eec0c2f6e2182/primp-0.15.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:592f6079646bdf5abbbfc3b0a28dac8de943f8907a250ce09398cda5eaebd260", size = 3418567 },
1871
+ { url = "https://files.pythonhosted.org/packages/6c/80/8a7a9587d3eb85be3d0b64319f2f690c90eb7953e3f73a9ddd9e46c8dc42/primp-0.15.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5a728e5a05f37db6189eb413d22c78bd143fa59dd6a8a26dacd43332b3971fe8", size = 3606279 },
1872
+ { url = "https://files.pythonhosted.org/packages/0c/dd/f0183ed0145e58cf9d286c1b2c14f63ccee987a4ff79ac85acc31b5d86bd/primp-0.15.0-cp38-abi3-win_amd64.whl", hash = "sha256:aeb6bd20b06dfc92cfe4436939c18de88a58c640752cf7f30d9e4ae893cdec32", size = 3149967 },
1873
+ ]
1874
+
1875
  [[package]]
1876
  name = "propcache"
1877
  version = "0.3.2"