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