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
| from typing import Callable import requests import json
class Tool: """工具基类""" def __init__(self, name: str, description: str): self.name = name self.description = description def __call__(self, **kwargs): raise NotImplementedError
class GoogleSearchTool(Tool): """Google搜索工具""" def __init__(self): super().__init__( name="google_search", description="搜索Google获取最新信息,输入查询字符串,返回搜索结果摘要" ) def __call__(self, query: str, num_results: int = 5) -> str: results = self._search_google(query, num_results) return "\n".join([ f"{i+1}. {r['title']}\n {r['snippet']}" for i, r in enumerate(results) ]) def _search_google(self, query: str, num: int): return [ {"title": f"结果{i+1}", "snippet": f"关于{query}的信息..."} for i in range(num) ]
class WebScraperTool(Tool): """网页抓取工具""" def __init__(self): super().__init__( name="web_scraper", description="抓取指定URL的网页内容,返回页面文本" ) def __call__(self, url: str) -> str: try: response = requests.get(url, timeout=10) return self._extract_text(response.text) except Exception as e: return f"抓取失败: {str(e)}" def _extract_text(self, html: str) -> str: import re text = re.sub(r'<script.*?</script>', '', html, flags=re.DOTALL) text = re.sub(r'<style.*?</style>', '', text, flags=re.DOTALL) text = re.sub(r'<[^>]+>', '', text) return text[:5000]
class FileWriteTool(Tool): """文件写入工具""" def __init__(self, base_path: str = "./outputs"): super().__init__( name="file_write", description="将内容写入文件" ) self.base_path = base_path def __call__(self, filename: str, content: str) -> str: import os os.makedirs(self.base_path, exist_ok=True) filepath = os.path.join(self.base_path, filename) with open(filepath, 'w', encoding='utf-8') as f: f.write(content) return f"文件已保存: {filepath}"
class CodeExecutorTool(Tool): """代码执行工具""" def __init__(self): super().__init__( name="code_executor", description="执行Python代码,返回执行结果" ) def __call__(self, code: str) -> str: try: import io from contextlib import redirect_stdout output = io.StringIO() exec(code, {'__name__': '__main__'}) with redirect_stdout(output): exec(code) return output.getvalue() or "代码执行成功,无输出" except Exception as e: return f"执行错误: {str(e)}"
|