mjschock commited on
Commit
a3a55bb
·
unverified ·
1 Parent(s): 2579190

Refactor main_v2.py to remove unused tools and agents, replacing them with the new SmartSearchTool for improved search functionality. Update prompt template loading to use the modified YAML file. Clean up imports and enhance overall code organization for better maintainability.

Browse files
main_v2.py CHANGED
@@ -1,4 +1,3 @@
1
- import importlib
2
  import logging
3
  import os
4
 
@@ -10,17 +9,10 @@ from openinference.instrumentation.smolagents import SmolagentsInstrumentor
10
  from phoenix.otel import register
11
 
12
  # from smolagents import CodeAgent, LiteLLMModel, LiteLLMRouterModel
13
- from smolagents import CodeAgent, LiteLLMModel, ToolCallingAgent
14
- from smolagents.default_tools import (
15
- DuckDuckGoSearchTool,
16
- VisitWebpageTool,
17
- WikipediaSearchTool,
18
- )
19
  from smolagents.monitoring import LogLevel
20
 
21
- from agents.data_agent.agent import create_data_agent
22
- from agents.media_agent.agent import create_media_agent
23
- from agents.web_agent.agent import create_web_agent
24
  from utils import extract_final_answer
25
 
26
  _disable_debugging()
@@ -57,7 +49,7 @@ model = LiteLLMModel(
57
  # description="This is an agent that can do web search.",
58
  # )
59
 
60
- prompt_templates = yaml.safe_load(open("prompts/code_agent.yaml", "r"))
61
 
62
  agent = CodeAgent(
63
  # add_base_tools=True,
@@ -75,9 +67,8 @@ agent = CodeAgent(
75
  model=model,
76
  prompt_templates=prompt_templates,
77
  tools=[
78
- DuckDuckGoSearchTool(max_results=3),
79
- VisitWebpageTool(max_output_length=1024),
80
- WikipediaSearchTool(),
81
  ],
82
  step_callbacks=None,
83
  verbosity_level=LogLevel.ERROR,
 
 
1
  import logging
2
  import os
3
 
 
9
  from phoenix.otel import register
10
 
11
  # from smolagents import CodeAgent, LiteLLMModel, LiteLLMRouterModel
12
+ from smolagents import CodeAgent, LiteLLMModel
 
 
 
 
 
13
  from smolagents.monitoring import LogLevel
14
 
15
+ from tools.smart_search.tool import SmartSearchTool
 
 
16
  from utils import extract_final_answer
17
 
18
  _disable_debugging()
 
49
  # description="This is an agent that can do web search.",
50
  # )
51
 
52
+ prompt_templates = yaml.safe_load(open("prompts/code_agent_modified.yaml", "r"))
53
 
54
  agent = CodeAgent(
55
  # add_base_tools=True,
 
67
  model=model,
68
  prompt_templates=prompt_templates,
69
  tools=[
70
+ SmartSearchTool(),
71
+ # VisitWebpageTool(max_output_length=1024),
 
72
  ],
73
  step_callbacks=None,
74
  verbosity_level=LogLevel.ERROR,
prompts/code_agent_modified.yaml ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 the available tools:
13
+ ---
14
+ Task: "What is the current age of the pope?"
15
+
16
+ Thought: I will use the smart_search tool to find information about the pope's age. This tool will automatically check both web search and Wikipedia if available.
17
+ Code:
18
+ ```py
19
+ result = smart_search(query="current pope age")
20
+ print("Search result:", result)
21
+ ```<end_code>
22
+ Observation:
23
+ Wikipedia result:
24
+ Pope Francis is currently 88 years old.
25
+
26
+ Web search result:
27
+ Pope Francis, born 17 December 1936, is currently 88 years old.
28
+
29
+ Thought: I can now provide the final answer based on the reliable information found.
30
+ Code:
31
+ ```py
32
+ final_answer("88 years old")
33
+ ```<end_code>
34
+
35
+ ---
36
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
37
+
38
+ Thought: I will use smart_search to find the population information for both cities.
39
+ Code:
40
+ ```py
41
+ for city in ["Guangzhou", "Shanghai"]:
42
+ print(f"Population {city}:", smart_search(f"{city} population"))
43
+ ```<end_code>
44
+ Observation:
45
+ Population Guangzhou:
46
+ Web search result:
47
+ Guangzhou has a population of 15 million inhabitants as of 2021.
48
+
49
+ Population Shanghai:
50
+ Web search result:
51
+ Shanghai has a population of 26 million as of 2019.
52
+
53
+ Thought: Now I know that Shanghai has the highest population.
54
+ Code:
55
+ ```py
56
+ final_answer("Shanghai")
57
+ ```<end_code>
58
+
59
+ ---
60
+ Task: "What is the capital of France?"
61
+
62
+ Thought: I will use smart_search to find information about France's capital. This tool will automatically check both web search and Wikipedia if available.
63
+ Code:
64
+ ```py
65
+ result = smart_search(query="capital of France")
66
+ print("Search result:", result)
67
+ ```<end_code>
68
+ Observation:
69
+ Wikipedia result:
70
+ Paris is the capital and most populous city of France.
71
+
72
+ Web search result:
73
+ Paris is the capital city of France, located in the north-central part of the country.
74
+
75
+ Thought: I can now provide the final answer based on the reliable information found.
76
+ Code:
77
+ ```py
78
+ final_answer("Paris")
79
+ ```<end_code>
80
+
81
+ ---
82
+ Task: "What is the average lifespan of a domestic cat?"
83
+
84
+ Thought: I will use smart_search to find information about cat lifespans.
85
+ Code:
86
+ ```py
87
+ result = smart_search(query="average lifespan of domestic cat")
88
+ print("Search result:", result)
89
+ ```<end_code>
90
+ Observation:
91
+ Web search result:
92
+ The average lifespan of a domestic cat is 12-15 years, though some can live into their 20s with proper care.
93
+
94
+ Thought: I can now provide the final answer based on the search results.
95
+ Code:
96
+ ```py
97
+ final_answer("12-15 years")
98
+ ```<end_code>
99
+
100
+ You have access to these tools, behaving like regular python functions:
101
+ ```python
102
+ {%- for tool in tools.values() %}
103
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
104
+ """{{ tool.description }}
105
+
106
+ Args:
107
+ {%- for arg_name, arg_info in tool.inputs.items() %}
108
+ {{ arg_name }}: {{ arg_info.description }}
109
+ {%- endfor %}
110
+ """
111
+ {% endfor %}
112
+ ```
113
+
114
+ {%- if managed_agents and managed_agents.values() | list %}
115
+ You can also give tasks to team members.
116
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
117
+ 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.
118
+ Here is a list of the team members that you can call:
119
+ ```python
120
+ {%- for agent in managed_agents.values() %}
121
+ def {{ agent.name }}("Your query goes here.") -> str:
122
+ """{{ agent.description }}"""
123
+ {% endfor %}
124
+ ```
125
+ {%- endif %}
126
+
127
+ Here are the rules you should always follow to solve your task:
128
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
129
+ 2. Use only variables that you have defined!
130
+ 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?")'.
131
+ 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.
132
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
133
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
134
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
135
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
136
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
137
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
138
+
139
+ Now Begin!
140
+ planning:
141
+ initial_plan : |-
142
+ You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
143
+ Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
144
+
145
+ ## 1. Facts survey
146
+ You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
147
+ These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
148
+ ### 1.1. Facts given in the task
149
+ List here the specific facts given in the task that could help you (there might be nothing here).
150
+
151
+ ### 1.2. Facts to look up
152
+ List here any facts that we may need to look up.
153
+ 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.
154
+
155
+ ### 1.3. Facts to derive
156
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
157
+
158
+ Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
159
+
160
+ ## 2. Plan
161
+ Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
162
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
163
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
164
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
165
+
166
+ You can leverage these tools, behaving like regular python functions:
167
+ ```python
168
+ {%- for tool in tools.values() %}
169
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
170
+ """{{ tool.description }}
171
+
172
+ Args:
173
+ {%- for arg_name, arg_info in tool.inputs.items() %}
174
+ {{ arg_name }}: {{ arg_info.description }}
175
+ {%- endfor %}
176
+ """
177
+ {% endfor %}
178
+ ```
179
+
180
+ {%- if managed_agents and managed_agents.values() | list %}
181
+ You can also give tasks to team members.
182
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
183
+ 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.
184
+ Here is a list of the team members that you can call:
185
+ ```python
186
+ {%- for agent in managed_agents.values() %}
187
+ def {{ agent.name }}("Your query goes here.") -> str:
188
+ """{{ agent.description }}"""
189
+ {% endfor %}
190
+ ```
191
+ {%- endif %}
192
+
193
+ ---
194
+ Now begin! Here is your task:
195
+ ```
196
+ {{task}}
197
+ ```
198
+ First in part 1, write the facts survey, then in part 2, write your plan.
199
+ update_plan_pre_messages: |-
200
+ You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
201
+ You have been given the following task:
202
+ ```
203
+ {{task}}
204
+ ```
205
+
206
+ Below you will find a history of attempts made to solve this task.
207
+ You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
208
+ If the previous tries so far have met some success, your updated plan can build on these results.
209
+ If you are stalled, you can make a completely new plan starting from scratch.
210
+
211
+ Find the task and history below:
212
+ update_plan_post_messages: |-
213
+ Now write your updated facts below, taking into account the above history:
214
+ ## 1. Updated facts survey
215
+ ### 1.1. Facts given in the task
216
+ ### 1.2. Facts that we have learned
217
+ ### 1.3. Facts still to look up
218
+ ### 1.4. Facts still to derive
219
+
220
+ Then write a step-by-step high-level plan to solve the task above.
221
+ ## 2. Plan
222
+ ### 2. 1. ...
223
+ Etc.
224
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
225
+ Beware that you have {remaining_steps} steps remaining.
226
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
227
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
228
+
229
+ You can leverage these tools, behaving like regular python functions:
230
+ ```python
231
+ {%- for tool in tools.values() %}
232
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
233
+ """{{ tool.description }}
234
+
235
+ Args:
236
+ {%- for arg_name, arg_info in tool.inputs.items() %}
237
+ {{ arg_name }}: {{ arg_info.description }}
238
+ {%- endfor %}"""
239
+ {% endfor %}
240
+ ```
241
+
242
+ {%- if managed_agents and managed_agents.values() | list %}
243
+ You can also give tasks to team members.
244
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
245
+ 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.
246
+ Here is a list of the team members that you can call:
247
+ ```python
248
+ {%- for agent in managed_agents.values() %}
249
+ def {{ agent.name }}("Your query goes here.") -> str:
250
+ """{{ agent.description }}"""
251
+ {% endfor %}
252
+ ```
253
+ {%- endif %}
254
+
255
+ Now write your updated facts survey below, then your new plan.
256
+ managed_agent:
257
+ task: |-
258
+ You're a helpful agent named '{{name}}'.
259
+ You have been submitted this task by your manager.
260
+ ---
261
+ Task:
262
+ {{task}}
263
+ ---
264
+ 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.
265
+
266
+ Your final_answer WILL HAVE to contain these parts:
267
+ ### 1. Task outcome (short version):
268
+ ### 2. Task outcome (extremely detailed version):
269
+ ### 3. Additional context (if relevant):
270
+
271
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
272
+ 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.
273
+ report: |-
274
+ Here is the final answer from your managed agent '{{name}}':
275
+ {{final_answer}}
276
+ final_answer:
277
+ pre_messages: |-
278
+ An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
279
+ post_messages: |-
280
+ Based on the above, please provide an answer to the following user task:
281
+ {{task}}
tools/__init__.py CHANGED
@@ -1,23 +0,0 @@
1
- from .analyze_image import analyze_image
2
- from .browse_webpage import browse_webpage
3
- from .extract_dates import extract_dates
4
- from .find_in_page import find_in_page
5
- from .parse_csv import parse_csv
6
- from .perform_calculation import perform_calculation
7
- from .read_pdf import read_pdf
8
- from .web_search import web_search
9
- from .wiki_search.tool import wiki
10
- from .wikipedia_rag import WikipediaRAGTool
11
-
12
- __all__ = [
13
- "WikipediaRAGTool",
14
- "web_search",
15
- "browse_webpage",
16
- "analyze_image",
17
- "read_pdf",
18
- "parse_csv",
19
- "find_in_page",
20
- "extract_dates",
21
- "perform_calculation",
22
- "wiki",
23
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/analyze_image/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import analyze_image
2
-
3
- __all__ = ["analyze_image"]
 
 
 
 
tools/analyze_image/tool.py DELETED
@@ -1,41 +0,0 @@
1
- import io
2
- from typing import Any, Dict
3
-
4
- import requests
5
- from PIL import Image
6
- from smolagents import tool
7
-
8
-
9
- @tool
10
- def analyze_image(image_url: str) -> Dict[str, Any]:
11
- """
12
- Analyze an image and extract information from it.
13
-
14
- Args:
15
- image_url: URL of the image to analyze
16
-
17
- Returns:
18
- Dictionary containing information about the image
19
- """
20
- try:
21
- # Download the image
22
- response = requests.get(image_url)
23
- response.raise_for_status()
24
-
25
- # Open the image
26
- img = Image.open(io.BytesIO(response.content))
27
-
28
- # Extract basic image information
29
- width, height = img.size
30
- format_type = img.format
31
- mode = img.mode
32
-
33
- return {
34
- "width": width,
35
- "height": height,
36
- "format": format_type,
37
- "mode": mode,
38
- "aspect_ratio": width / height,
39
- }
40
- except Exception as e:
41
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/browse_webpage/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import browse_webpage
2
-
3
- __all__ = ["browse_webpage"]
 
 
 
 
tools/browse_webpage/tool.py DELETED
@@ -1,45 +0,0 @@
1
- from typing import Any, Dict
2
-
3
- import requests
4
- from bs4 import BeautifulSoup
5
- from smolagents import tool
6
-
7
-
8
- @tool
9
- def browse_webpage(url: str) -> Dict[str, Any]:
10
- """
11
- Browse a webpage and extract its content.
12
-
13
- Args:
14
- url: URL of the webpage to browse
15
-
16
- Returns:
17
- Dictionary containing title, text content, and links from the webpage
18
- """
19
- try:
20
- headers = {
21
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
22
- }
23
- response = requests.get(url, headers=headers)
24
- response.raise_for_status()
25
-
26
- soup = BeautifulSoup(response.text, "html.parser")
27
-
28
- # Extract title
29
- title = soup.title.string if soup.title else "No title found"
30
-
31
- # Extract main text content
32
- paragraphs = soup.find_all("p")
33
- text_content = "\n".join([p.get_text().strip() for p in paragraphs])
34
-
35
- # Extract links
36
- links = []
37
- for link in soup.find_all("a", href=True):
38
- href = link["href"]
39
- text = link.get_text().strip()
40
- if href.startswith("http"):
41
- links.append({"text": text, "href": href})
42
-
43
- return {"title": title, "content": text_content, "links": links}
44
- except Exception as e:
45
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/extract_dates/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import extract_dates
2
-
3
- __all__ = ["extract_dates"]
 
 
 
 
tools/extract_dates/tool.py DELETED
@@ -1,32 +0,0 @@
1
- import re
2
- from typing import List
3
-
4
- from smolagents import tool
5
-
6
-
7
- @tool
8
- def extract_dates(text: str) -> List[str]:
9
- """
10
- Extract dates from text content.
11
-
12
- Args:
13
- text: Text content to extract dates from
14
-
15
- Returns:
16
- List of date strings found in the text
17
- """
18
- # Simple regex patterns for date extraction
19
- # These patterns can be expanded for better coverage
20
- date_patterns = [
21
- r"\d{1,2}/\d{1,2}/\d{2,4}", # MM/DD/YYYY or DD/MM/YYYY
22
- r"\d{1,2}-\d{1,2}-\d{2,4}", # MM-DD-YYYY or DD-MM-YYYY
23
- r"\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? \d{4}\b", # Month DD, YYYY
24
- r"\b\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{4}\b", # DD Month YYYY
25
- ]
26
-
27
- results = []
28
- for pattern in date_patterns:
29
- matches = re.findall(pattern, text, re.IGNORECASE)
30
- results.extend(matches)
31
-
32
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/find_in_page/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import find_in_page
2
-
3
- __all__ = ["find_in_page"]
 
 
 
 
tools/find_in_page/tool.py DELETED
@@ -1,30 +0,0 @@
1
- import re
2
- from typing import Any, Dict, List
3
-
4
- from smolagents import tool
5
-
6
-
7
- @tool
8
- def find_in_page(page_content: Dict[str, Any], query: str) -> List[str]:
9
- """
10
- Find occurrences of a query string in page content.
11
-
12
- Args:
13
- page_content: Page content returned by browse_webpage
14
- query: String to search for in the page
15
-
16
- Returns:
17
- List of sentences or sections containing the query
18
- """
19
- results = []
20
- if "content" in page_content:
21
- content = page_content["content"]
22
- # Split content into sentences
23
- sentences = re.split(r"(?<=[.!?])\s+", content)
24
-
25
- # Find sentences containing the query
26
- for sentence in sentences:
27
- if query.lower() in sentence.lower():
28
- results.append(sentence)
29
-
30
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/parse_csv/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import parse_csv
2
-
3
- __all__ = ["parse_csv"]
 
 
 
 
tools/parse_csv/tool.py DELETED
@@ -1,40 +0,0 @@
1
- import io
2
- from typing import Any, Dict
3
-
4
- import pandas as pd
5
- import requests
6
- from smolagents import tool
7
-
8
-
9
- @tool
10
- def parse_csv(csv_url: str) -> Dict[str, Any]:
11
- """
12
- Parse a CSV file and return its content as structured data.
13
-
14
- Args:
15
- csv_url: URL of the CSV file to parse
16
-
17
- Returns:
18
- Dictionary containing parsed CSV data
19
- """
20
- try:
21
- # Download the CSV
22
- response = requests.get(csv_url)
23
- response.raise_for_status()
24
-
25
- # Parse the CSV
26
- df = pd.read_csv(io.StringIO(response.text))
27
-
28
- # Convert to dictionary format
29
- columns = df.columns.tolist()
30
- data = df.to_dict(orient="records")
31
-
32
- # Return basic statistics and preview
33
- return {
34
- "columns": columns,
35
- "row_count": len(data),
36
- "preview": data[:5] if len(data) > 5 else data,
37
- "column_dtypes": {col: str(df[col].dtype) for col in columns},
38
- }
39
- except Exception as e:
40
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/perform_calculation/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import perform_calculation
2
-
3
- __all__ = ["perform_calculation"]
 
 
 
 
tools/perform_calculation/tool.py DELETED
@@ -1,40 +0,0 @@
1
- import math
2
- from typing import Any, Dict
3
-
4
- from smolagents import tool
5
-
6
-
7
- @tool
8
- def perform_calculation(expression: str) -> Dict[str, Any]:
9
- """
10
- Safely evaluate a mathematical expression.
11
-
12
- Args:
13
- expression: Mathematical expression to evaluate
14
-
15
- Returns:
16
- Dictionary containing the result or error message
17
- """
18
- try:
19
- # Define allowed names
20
- allowed_names = {
21
- "abs": abs,
22
- "round": round,
23
- "min": min,
24
- "max": max,
25
- "sum": sum,
26
- "len": len,
27
- "pow": pow,
28
- "math": math,
29
- }
30
-
31
- # Clean the expression
32
- cleaned_expr = expression.strip()
33
-
34
- # Evaluate using safer methods (this is still a simplified example)
35
- # In a real implementation, use a proper math expression parser
36
- result = eval(cleaned_expr, {"__builtins__": {}}, allowed_names)
37
-
38
- return {"result": result}
39
- except Exception as e:
40
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/read_pdf/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import read_pdf
2
-
3
- __all__ = ["read_pdf"]
 
 
 
 
tools/read_pdf/tool.py DELETED
@@ -1,25 +0,0 @@
1
- import requests
2
- from smolagents import tool
3
-
4
-
5
- @tool
6
- def read_pdf(pdf_url: str) -> str:
7
- """
8
- Extract text content from a PDF document.
9
-
10
- Args:
11
- pdf_url: URL of the PDF to read
12
-
13
- Returns:
14
- Text content extracted from the PDF
15
- """
16
- try:
17
- # Download the PDF
18
- response = requests.get(pdf_url)
19
- response.raise_for_status()
20
-
21
- # This is a placeholder - in a real implementation, you would use a PDF parsing library
22
- # such as PyPDF2, pdfplumber, or pdf2text
23
- return "PDF content extraction would happen here in a real implementation"
24
- except Exception as e:
25
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/smart_search/__init__.py ADDED
File without changes
tools/smart_search/tool.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ from smolagents import Tool
4
+ from smolagents.default_tools import DuckDuckGoSearchTool, WikipediaSearchTool
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class SmartSearchTool(Tool):
10
+ name = "smart_search"
11
+ description = """A smart search tool that first performs a web search and then, if a Wikipedia article is found,
12
+ uses Wikipedia search for more reliable information."""
13
+ inputs = {"query": {"type": "string", "description": "The search query to find information"}}
14
+ output_type = "string"
15
+
16
+ def __init__(self):
17
+ super().__init__()
18
+ self.web_search_tool = DuckDuckGoSearchTool(max_results=1)
19
+ self.wiki_tool = WikipediaSearchTool(
20
+ user_agent="SmartSearchTool ([email protected])",
21
+ language="en",
22
+ # content_type="summary",
23
+ content_type="text",
24
+ extract_format="WIKI"
25
+ )
26
+
27
+ def forward(self, query: str) -> str:
28
+ logger.info(f"Starting smart search for query: {query}")
29
+
30
+ # First perform a web search with a single result
31
+ web_result = self.web_search_tool.forward(query)
32
+ logger.info(f"Web search result: {web_result[:100]}...")
33
+
34
+ # Check if the result contains a Wikipedia link
35
+ if "wikipedia.org" in web_result.lower():
36
+ logger.info("Wikipedia link found in web search results")
37
+ # Extract the Wikipedia page title from the URL using regex
38
+ wiki_match = re.search(r'wikipedia\.org/wiki/([^)\s]+)', web_result)
39
+ if wiki_match:
40
+ wiki_title = wiki_match.group(1)
41
+ logger.info(f"Extracted Wikipedia title: {wiki_title}")
42
+
43
+ # Use Wikipedia search for more reliable information
44
+ wiki_result = self.wiki_tool.forward(wiki_title)
45
+ logger.info(f"Wikipedia search result: {wiki_result[:100]}...")
46
+
47
+ if wiki_result and "No Wikipedia page found" not in wiki_result:
48
+ logger.info("Successfully retrieved Wikipedia content")
49
+ return f"Web search result:\n{web_result}\n\nWikipedia result:\n{wiki_result}"
50
+ else:
51
+ logger.warning("Wikipedia search failed or returned no results")
52
+ else:
53
+ logger.warning("Could not extract Wikipedia title from URL")
54
+
55
+ # If no Wikipedia link was found or Wikipedia search failed, return the web search result
56
+ logger.info("Returning web search result only")
57
+ return f"Web search result:\n{web_result}"
tools/web_search/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import web_search
2
-
3
- __all__ = ["web_search"]
 
 
 
 
tools/web_search/tool.py DELETED
@@ -1,18 +0,0 @@
1
- from smolagents import tool
2
- from smolagents.default_tools import DuckDuckGoSearchTool
3
-
4
-
5
- @tool
6
- def web_search(query: str) -> str:
7
- """
8
- Search the web for information.
9
-
10
- Args:
11
- query: Search query to find information
12
-
13
- Returns:
14
- Search results as text
15
- """
16
- search_tool = DuckDuckGoSearchTool(max_results=3)
17
- results = search_tool.execute(query)
18
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/wiki_search/tool.py DELETED
@@ -1,40 +0,0 @@
1
- import wikipediaapi
2
- from smolagents import tool
3
-
4
-
5
- @tool
6
- def wiki(query: str) -> str:
7
- """
8
- Search and retrieve information from Wikipedia using the Wikipedia-API library.
9
-
10
- Args:
11
- query: The search query to look up on Wikipedia
12
-
13
- Returns:
14
- A string containing the Wikipedia page summary and relevant sections
15
- """
16
- # Initialize Wikipedia API with a user agent
17
- wiki_wiki = wikipediaapi.Wikipedia(
18
- user_agent="HF-Agents-Course (https://huggingface.co/courses/agents-course)",
19
- language="en",
20
- )
21
-
22
- # Search for the page
23
- page = wiki_wiki.page(query)
24
-
25
- if not page.exists():
26
- return f"No Wikipedia page found for query: {query}"
27
-
28
- # Get the page summary
29
- result = f"Title: {page.title}\n\n"
30
- result += f"Summary: {page.summary}\n\n"
31
-
32
- # Add the first few sections if they exist
33
- if page.sections:
34
- result += "Sections:\n"
35
- for section in page.sections[
36
- :3
37
- ]: # Limit to first 3 sections to avoid too much text
38
- result += f"\n{section.title}:\n{section.text[:500]}...\n"
39
-
40
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/wikipedia_rag/README.md DELETED
@@ -1,52 +0,0 @@
1
- # Wikipedia RAG Tool
2
-
3
- A Retrieval-Augmented Generation (RAG) tool for searching and retrieving information from Wikipedia articles.
4
-
5
- ## Features
6
-
7
- - Loads and processes Wikipedia articles from a structured dataset
8
- - Uses BM25 retrieval for finding relevant articles
9
- - Returns formatted results with article metadata
10
- - Can be used standalone or integrated with an agent
11
-
12
- ## Usage
13
-
14
- ### Standalone Usage
15
-
16
- ```bash
17
- python run.py --query "Your search query here" --dataset-path path/to/dataset
18
- ```
19
-
20
- ### Integration with Agent
21
-
22
- ```python
23
- from tools.wikipedia_rag import WikipediaRAGTool
24
-
25
- # Initialize the tool
26
- wikipedia_tool = WikipediaRAGTool(dataset_path="path/to/dataset")
27
-
28
- # Use with an agent
29
- agent = CodeAgent(
30
- model=model,
31
- tools=[wikipedia_tool],
32
- )
33
- ```
34
-
35
- ## Requirements
36
-
37
- - pandas
38
- - langchain
39
- - langchain-community
40
- - smolagents
41
-
42
- ## Dataset Format
43
-
44
- The tool expects a CSV file with the following columns:
45
- - title: Article title
46
- - content: Article content
47
- - url: Article URL
48
- - category: Article category (optional)
49
-
50
- ## License
51
-
52
- MIT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/wikipedia_rag/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from .tool import WikipediaRAGTool
2
-
3
- __all__ = ["WikipediaRAGTool"]
 
 
 
 
tools/wikipedia_rag/run.py DELETED
@@ -1,37 +0,0 @@
1
- import argparse
2
- import os
3
-
4
- from dotenv import load_dotenv
5
- from tool import WikipediaRAGTool
6
-
7
-
8
- def main():
9
- # Load environment variables
10
- load_dotenv()
11
-
12
- # Set up argument parser
13
- parser = argparse.ArgumentParser(description="Run Wikipedia RAG Tool")
14
- parser.add_argument(
15
- "--query", type=str, required=True, help="Search query for Wikipedia articles"
16
- )
17
- parser.add_argument(
18
- "--dataset-path",
19
- type=str,
20
- default="wikipedia-structured-contents",
21
- help="Path to the Wikipedia dataset",
22
- )
23
- args = parser.parse_args()
24
-
25
- # Initialize the tool
26
- tool = WikipediaRAGTool(dataset_path=args.dataset_path)
27
-
28
- # Run the query
29
- print(f"\nQuery: {args.query}")
30
- print("-" * 50)
31
- result = tool.forward(args.query)
32
- print(f"Result: {result}")
33
- print("-" * 50)
34
-
35
-
36
- if __name__ == "__main__":
37
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/wikipedia_rag/tool.py DELETED
@@ -1,83 +0,0 @@
1
- import os
2
- from typing import List, Optional
3
-
4
- import pandas as pd
5
- from langchain.docstore.document import Document
6
- from langchain_community.retrievers import BM25Retriever
7
- from smolagents import Tool
8
-
9
-
10
- class WikipediaRAGTool(Tool):
11
- name = "wikipedia_rag"
12
- description = "Retrieves relevant information from Wikipedia articles using RAG."
13
- inputs = {
14
- "query": {
15
- "type": "string",
16
- "description": "The search query to find relevant Wikipedia content.",
17
- }
18
- }
19
- output_type = "string"
20
-
21
- def __init__(self, dataset_path: str = "wikipedia-structured-contents"):
22
- self.is_initialized = False
23
- self.dataset_path = dataset_path
24
- self.docs: List[Document] = []
25
- self.retriever: Optional[BM25Retriever] = None
26
-
27
- def _load_documents(self) -> None:
28
- """Load and process the Wikipedia dataset into Document objects."""
29
- try:
30
- # Load the dataset
31
- df = pd.read_csv(os.path.join(self.dataset_path, "wikipedia_articles.csv"))
32
-
33
- # Convert each article into a Document
34
- self.docs = [
35
- Document(
36
- page_content=f"Title: {row['title']}\n\nContent: {row['content']}",
37
- metadata={
38
- "title": row["title"],
39
- "url": row["url"],
40
- "category": row.get("category", ""),
41
- },
42
- )
43
- for _, row in df.iterrows()
44
- ]
45
-
46
- # Initialize the retriever
47
- self.retriever = BM25Retriever.from_documents(self.docs)
48
- self.is_initialized = True
49
-
50
- except Exception as e:
51
- print(f"Error loading documents: {e}")
52
- raise
53
-
54
- def forward(self, query: str) -> str:
55
- """Process the query and return relevant Wikipedia content."""
56
- if not self.is_initialized:
57
- self._load_documents()
58
-
59
- if not self.retriever:
60
- return "Error: Retriever not initialized properly."
61
-
62
- try:
63
- # Get relevant documents
64
- results = self.retriever.get_relevant_documents(query)
65
-
66
- if not results:
67
- return "No relevant Wikipedia articles found."
68
-
69
- # Format the results
70
- formatted_results = []
71
- for doc in results[:3]: # Return top 3 most relevant results
72
- metadata = doc.metadata
73
- formatted_results.append(
74
- f"Title: {metadata['title']}\n"
75
- f"URL: {metadata['url']}\n"
76
- f"Category: {metadata['category']}\n"
77
- f"Content: {doc.page_content[:500]}...\n"
78
- )
79
-
80
- return "\n\n".join(formatted_results)
81
-
82
- except Exception as e:
83
- return f"Error retrieving information: {str(e)}"