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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""
|
| 3 |
+
Tool definitions for the agent
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
from typing import List, Dict, Any
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
class Tool:
|
| 11 |
+
"""Base tool class"""
|
| 12 |
+
def __init__(self, name: str, description: str, parameters: Dict[str, Any]):
|
| 13 |
+
self.name = name
|
| 14 |
+
self.description = description
|
| 15 |
+
self.parameters = parameters
|
| 16 |
+
|
| 17 |
+
def __call__(self, **kwargs):
|
| 18 |
+
raise NotImplementedError
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class WebSearchTool(Tool):
|
| 22 |
+
"""Web search using DuckDuckGo or similar"""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
super().__init__(
|
| 26 |
+
name="web_search",
|
| 27 |
+
description="Search the web for current information. Use this when you need to find facts, statistics, recent events, or any information not in your training data.",
|
| 28 |
+
parameters={
|
| 29 |
+
"type": "object",
|
| 30 |
+
"properties": {
|
| 31 |
+
"query": {
|
| 32 |
+
"type": "string",
|
| 33 |
+
"description": "The search query"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"required": ["query"]
|
| 37 |
+
}
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def __call__(self, query: str) -> str:
|
| 41 |
+
"""Perform web search using DuckDuckGo API"""
|
| 42 |
+
try:
|
| 43 |
+
# Using DuckDuckGo Instant Answer API (no key required)
|
| 44 |
+
url = "https://api.duckduckgo.com/"
|
| 45 |
+
params = {
|
| 46 |
+
"q": query,
|
| 47 |
+
"format": "json",
|
| 48 |
+
"no_html": 1,
|
| 49 |
+
"skip_disambig": 1
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
response = requests.get(url, params=params, timeout=10)
|
| 53 |
+
data = response.json()
|
| 54 |
+
|
| 55 |
+
# Extract relevant information
|
| 56 |
+
results = []
|
| 57 |
+
|
| 58 |
+
if data.get("Abstract"):
|
| 59 |
+
results.append(data["Abstract"])
|
| 60 |
+
|
| 61 |
+
if data.get("RelatedTopics"):
|
| 62 |
+
for topic in data["RelatedTopics"][:3]:
|
| 63 |
+
if isinstance(topic, dict) and topic.get("Text"):
|
| 64 |
+
results.append(topic["Text"])
|
| 65 |
+
|
| 66 |
+
if results:
|
| 67 |
+
return " ".join(results)
|
| 68 |
+
|
| 69 |
+
return f"No detailed results found for: {query}"
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
return f"Search error: {str(e)}"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class WikipediaSearchTool(Tool):
|
| 76 |
+
"""Wikipedia search"""
|
| 77 |
+
|
| 78 |
+
def __init__(self):
|
| 79 |
+
super().__init__(
|
| 80 |
+
name="wikipedia_search",
|
| 81 |
+
description="Search Wikipedia for encyclopedic knowledge about people, places, events, concepts, etc.",
|
| 82 |
+
parameters={
|
| 83 |
+
"type": "object",
|
| 84 |
+
"properties": {
|
| 85 |
+
"query": {
|
| 86 |
+
"type": "string",
|
| 87 |
+
"description": "The Wikipedia search query"
|
| 88 |
+
}
|
| 89 |
+
},
|
| 90 |
+
"required": ["query"]
|
| 91 |
+
}
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def __call__(self, query: str) -> str:
|
| 95 |
+
"""Search Wikipedia"""
|
| 96 |
+
try:
|
| 97 |
+
# Wikipedia API
|
| 98 |
+
url = "https://en.wikipedia.org/w/api.php"
|
| 99 |
+
params = {
|
| 100 |
+
"action": "query",
|
| 101 |
+
"list": "search",
|
| 102 |
+
"srsearch": query,
|
| 103 |
+
"format": "json",
|
| 104 |
+
"utf8": 1,
|
| 105 |
+
"srlimit": 1
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
response = requests.get(url, params=params, timeout=10)
|
| 109 |
+
data = response.json()
|
| 110 |
+
|
| 111 |
+
if data.get("query", {}).get("search"):
|
| 112 |
+
# Get the first result's page content
|
| 113 |
+
page_title = data["query"]["search"][0]["title"]
|
| 114 |
+
|
| 115 |
+
# Get page extract
|
| 116 |
+
extract_params = {
|
| 117 |
+
"action": "query",
|
| 118 |
+
"titles": page_title,
|
| 119 |
+
"prop": "extracts",
|
| 120 |
+
"exintro": True,
|
| 121 |
+
"explaintext": True,
|
| 122 |
+
"format": "json"
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
extract_response = requests.get(url, params=extract_params, timeout=10)
|
| 126 |
+
extract_data = extract_response.json()
|
| 127 |
+
|
| 128 |
+
pages = extract_data.get("query", {}).get("pages", {})
|
| 129 |
+
for page_id, page_data in pages.items():
|
| 130 |
+
extract = page_data.get("extract", "")
|
| 131 |
+
if extract:
|
| 132 |
+
# Return first 500 chars
|
| 133 |
+
return extract[:500] + ("..." if len(extract) > 500 else "")
|
| 134 |
+
|
| 135 |
+
return f"No Wikipedia results found for: {query}"
|
| 136 |
+
|
| 137 |
+
except Exception as e:
|
| 138 |
+
return f"Wikipedia search error: {str(e)}"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class CalculateTool(Tool):
|
| 142 |
+
"""Calculator for mathematical operations"""
|
| 143 |
+
|
| 144 |
+
def __init__(self):
|
| 145 |
+
super().__init__(
|
| 146 |
+
name="calculate",
|
| 147 |
+
description="Perform mathematical calculations. Supports basic arithmetic, percentages, and simple expressions.",
|
| 148 |
+
parameters={
|
| 149 |
+
"type": "object",
|
| 150 |
+
"properties": {
|
| 151 |
+
"expression": {
|
| 152 |
+
"type": "string",
|
| 153 |
+
"description": "The mathematical expression to evaluate (e.g., '2 + 2', '10 * 5', '100 / 4')"
|
| 154 |
+
}
|
| 155 |
+
},
|
| 156 |
+
"required": ["expression"]
|
| 157 |
+
}
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def __call__(self, expression: str) -> str:
|
| 161 |
+
"""Safely evaluate mathematical expression"""
|
| 162 |
+
try:
|
| 163 |
+
# Remove any potentially dangerous characters
|
| 164 |
+
safe_expr = re.sub(r'[^0-9+\-*/().\s]', '', expression)
|
| 165 |
+
result = eval(safe_expr)
|
| 166 |
+
return str(result)
|
| 167 |
+
except Exception as e:
|
| 168 |
+
return f"Calculation error: {str(e)}"
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def get_tools() -> List[Tool]:
|
| 172 |
+
"""Return list of available tools"""
|
| 173 |
+
return [
|
| 174 |
+
WebSearchTool(),
|
| 175 |
+
WikipediaSearchTool(),
|
| 176 |
+
CalculateTool()
|
| 177 |
+
]
|