SergeyO7 commited on
Commit
f34d3d9
·
verified ·
1 Parent(s): 2e0c36d

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +55 -30
agent.py CHANGED
@@ -16,32 +16,32 @@ import time
16
  import shutil
17
  import traceback
18
 
19
- # Simulated additional tools (implementation depends on external APIs or setup)
20
- #@tool
21
- #def GoogleSearchTool(query: str) -> str:
22
- # """Tool for performing Google searches using Custom Search JSON API
23
- # Args:
24
- # query (str): Search query string
25
- # Returns:
26
- # str: Formatted search results
27
- # """
28
- # cse_id = os.environ.get("GOOGLE_CSE_ID")
29
- # if not api_key or not cse_id:
30
- # raise ValueError("GOOGLE_API_KEY and GOOGLE_CSE_ID must be set in environment variables.")
31
- # url = "https://www.googleapis.com/customsearch/v1"
32
- # params = {
33
- # "key": api_key,
34
- # "cx": cse_id,
35
- # "q": query,
36
- # "num": 5 # Number of results to return
37
- # }
38
- # try:
39
- # response = requests.get(url, params=params)
40
- # response.raise_for_status()
41
- # results = response.json().get("items", [])
42
- # return "\n".join([f"{item['title']}: {item['link']}" for item in results]) or "No results found."
43
- # except Exception as e:
44
- # return f"Error performing Google search: {str(e)}"
45
 
46
  #@tool
47
  #def ImageAnalysisTool(question: str, model: LiteLLMModel) -> str:
@@ -64,6 +64,7 @@ import traceback
64
  # }
65
  # try:
66
  # response = requests.get(image_url, headers=headers)
 
67
  # response.raise_for_status()
68
  # image = Image.open(BytesIO(response.content)).convert("RGB")
69
  # except Exception as e:
@@ -83,6 +84,29 @@ import traceback
83
  #
84
  # return f"The image description: '{response}'"
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  class DownloadTaskAttachmentTool(Tool):
88
  name = "download_file"
@@ -254,12 +278,13 @@ class MagAgent:
254
  model= model,
255
  tools=[
256
  DownloadTaskAttachmentTool(rate_limiter=rate_limiter),
257
- DuckDuckGoSearchTool(),
258
  WikipediaSearchTool(),
259
  SpeechToTextTool,
260
- ExcelReaderTool(),
261
- PythonCodeReaderTool()
262
- # GoogleSearchTool,
 
263
  # ImageAnalysisTool,
264
  ],
265
  verbosity_level=3,
 
16
  import shutil
17
  import traceback
18
 
19
+
20
+ @tool
21
+ def GoogleSearchTool(query: str) -> str:
22
+ """Tool for performing Google searches using Custom Search JSON API
23
+ Args:
24
+ query (str): Search query string
25
+ Returns:
26
+ str: Formatted search results
27
+ """
28
+ cse_id = os.environ.get("GOOGLE_CSE_ID")
29
+ if not api_key or not cse_id:
30
+ raise ValueError("GOOGLE_API_KEY and GOOGLE_CSE_ID must be set in environment variables.")
31
+ url = "https://www.googleapis.com/customsearch/v1"
32
+ params = {
33
+ "key": api_key,
34
+ "cx": cse_id,
35
+ "q": query,
36
+ "num": 5 # Number of results to return
37
+ }
38
+ try:
39
+ response = requests.get(url, params=params)
40
+ response.raise_for_status()
41
+ results = response.json().get("items", [])
42
+ return "\n".join([f"{item['title']}: {item['link']}" for item in results]) or "No results found."
43
+ except Exception as e:
44
+ return f"Error performing Google search: {str(e)}"
45
 
46
  #@tool
47
  #def ImageAnalysisTool(question: str, model: LiteLLMModel) -> str:
 
64
  # }
65
  # try:
66
  # response = requests.get(image_url, headers=headers)
67
+
68
  # response.raise_for_status()
69
  # image = Image.open(BytesIO(response.content)).convert("RGB")
70
  # except Exception as e:
 
84
  #
85
  # return f"The image description: '{response}'"
86
 
87
+ class VisitWebpageTool(Tool):
88
+ name = "visit_webpage"
89
+ description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
90
+ inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}
91
+ output_type = "string"
92
+
93
+ def forward(self, url: str) -> str:
94
+ try:
95
+ response = requests.get(url, timeout=20)
96
+ response.raise_for_status()
97
+ markdown_content = markdownify(response.text).strip()
98
+ markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
99
+ from smolagents.utils import truncate_content
100
+ return truncate_content(markdown_content, 10000)
101
+ except requests.exceptions.Timeout:
102
+ return "The request timed out. Please try again later or check the URL."
103
+ except requests.exceptions.RequestException as e:
104
+ return f"Error fetching the webpage: {str(e)}"
105
+ except Exception as e:
106
+ return f"An unexpected error occurred: {str(e)}"
107
+
108
+ def __init__(self, *args, **kwargs):
109
+ self.is_initialized = False
110
 
111
  class DownloadTaskAttachmentTool(Tool):
112
  name = "download_file"
 
278
  model= model,
279
  tools=[
280
  DownloadTaskAttachmentTool(rate_limiter=rate_limiter),
281
+ # DuckDuckGoSearchTool(),
282
  WikipediaSearchTool(),
283
  SpeechToTextTool,
284
+ ExcelReaderTool,
285
+ VisitWebpageTool,
286
+ PythonCodeReaderTool,
287
+ GoogleSearchTool,
288
  # ImageAnalysisTool,
289
  ],
290
  verbosity_level=3,