
Swarms 单 Agent 工具集成实战从搜索、金融数据到区块链与结构化输出【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms本指南以 swarms 仓库examples/single_agent/capabilities/tools目录下的全部示例为核心系统讲解如何为单个 Agent 装配搜索、金融行情、浏览器自动化、区块链交互与结构化输出等工具涵盖tools[...]、tools_list_dictionary、BaseTool三种接入方式及底层执行原理。读完本文你可以照抄示例为 Agent 接入真实可用的工具链并理解工具 Schema 转换、错误处理与并发执行的最佳实践。目录概览tools 目录里有什么examples/single_agent/capabilities/tools/是 swarms 仓库中单 Agent 工具集成的一站式示例集围绕一个核心问题展开如何让一个 Agent 在推理之外真正动手——搜索网页、查询行情、操作浏览器、读写区块链。从 README.md 可以看到目录按用途分为三类顶层示例9 个覆盖搜索exa_search_agent.py、LiteLLM 工具litellm_tool_example.py、多工具 Agentmulti_tool_usage_agent.py、最新工具用法new_tools_examples.py、多模态omni_modal_agent.py、浏览器自动化集群swarms_of_browser_agents.py、Swarms 工具库swarms_tools_example.py、Together AI 与 DeepSeektogether_deepseek_agent.py、异步 vs 多线程对比example_async_vs_multithread.py三个子目录Solana 区块链工具solana_tool/、结构化输出structured_outputs/、更多工具示例tools_examples/含 DEX Screener、金融新闻、极简工具等。README 的 Overview 一句话点明了这些示例的共同目标展示工具定义、使用与错误处理的最佳实践。下面我们按接入方式、典型场景、底层原理三条线逐一深入。工具接入的三种方式swarms 的 Agent 支持多种把工具喂给模型的方式示例中至少展示了三种方式一tools[callable]—— 把普通函数直接变成工具最直接的方式是传入一个可调用对象Agent 会负责把它转换为模型可识别的 Function Calling Schema。例如 exa_search_agent.pyfrom swarms import Agent from swarms_tools import exa_search agent Agent( agent_nameExa Search Agent, model_namegpt-5.4, tools[exa_search], ) agent.run(What are the latest experimental treatments for diabetes?)这里exa_search是一个带完整 docstring 与类型注解的普通 Python 函数其定义见 agent_with_exa.pyAgent 会依据函数签名、类型提示与文档字符串自动生成 OpenAI 风格的函数 Schema。这正是工具定义最佳实践的第一条写好 docstring、写清参数类型Schema 质量就高。同类例子还有 swarms_tools_example.py它从swarms_tools.finance.okx_tool引入现成的okx_api_tool几行代码就让 Agent 具备用 OKX 查询比特币价格的能力from swarms import Agent from swarms_tools.finance.okx_tool import okx_api_tool agent Agent( agent_nameFinancial-Analysis-Agent, agent_descriptionPersonal finance advisor agent, max_loops1, model_namegpt-5.4, tools[okx_api_tool], dynamic_temperature_enabledTrue, ) agent.run(fetch the current price of bitcoin with okx)注意这里结合了dynamic_temperature_enabledTrue按任务动态调整温度与max_loops1单轮工具调用适合一问一答的查询型任务。方式二tools_list_dictionary—— 直接传入手写 JSON Schema如果你已经拥有标准 OpenAI Function Calling 格式的 JSON 描述可以用tools_list_dictionary直接注入免去转换环节。structured_outputs/structured_outputs_example.py 演示了一个手写的get_stock_price工具from swarms import Agent from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT tools [ { type: function, function: { name: get_stock_price, description: Retrieve the current stock price and related information for a specified company., parameters: { type: object, properties: { ticker: {type: string, description: The stock ticker symbol of the company, e.g. AAPL for Apple Inc.}, include_history: {type: boolean, description: Whether to include historical price data.}, time: {type: string, format: date-time, description: Optional ISO 8601 time.}, }, required: [ticker, include_history, time], }, }, } ] agent Agent( agent_nameFinancial-Analysis-Agent, agent_descriptionPersonal finance advisor agent, system_promptFINANCIAL_AGENT_SYS_PROMPT, max_loops1, tools_list_dictionarytools, ) out agent.run(What is the current stock price for Apple Inc. (AAPL)? Include historical price data.) print(out)这种方式的价值在于你可以在不写任何 Python 实现的情况下先定义工具契约也便于把其他系统如 OpenAPI 生成器产出的 Schema 直接复用。required字段、format如date-time、布尔与字符串属性的语义都严格遵循 OpenAI Function Calling 规范。example_meaning_of_life_agents.py 进一步展示了它的进阶用法——用同一个手写 Schemaselect_agent驱动一个哲学辩论多 Agent 场景每个带人设的 Agent 都通过tools_list_dictionary共享同一个路由工具从而让工具不仅服务于数据获取还服务于 Agent 间的选择与转发逻辑。方式三BaseTool—— 底层统一工具管理类第三种方式绕过Agent层直接使用 swarms 的工具管理核心类BaseTool。litellm_tool_example.py 展示了完整的函数 → Schema → 模型调用链路from swarms.tools.base_tool import BaseTool import requests from swarms.utils.litellm_wrapper import LiteLLM def get_stock_data(symbol: str) - str: Fetches stock data from Yahoo Finance for a given stock symbol. Args: symbol (str): The stock symbol to fetch data for (e.g., AAPL). Returns: Dict[str, Any]: A dictionary containing stock data. url fhttps://query1.finance.yahoo.com/v7/finance/quote?symbols{symbol} response requests.get(url) if response.status_code ! 200: raise ValueError(fError fetching data for symbol: {symbol}) data response.json() if quoteResponse not in data or not data[quoteResponse][result]: raise ValueError(fNo data found for symbol: {symbol}) return str(data[quoteResponse][result][0]) tool_schema BaseTool(tools[get_stock_data]).convert_tool_into_openai_schema() tool_schema tool_schema[functions][0] llm LiteLLM(model_namegpt-5.4) print(llm.run(What is the stock data for Apple Inc. (AAPL)?, tools[tool_schema]))从源码看swarms/tools/base_tool.py 是一个基于 Pydantic 的完整工具管理系统它的职责包括把函数转换为 OpenAI Function Calling Schema、管理 Pydantic 模型、带校验地执行工具、缓存昂贵操作。其中convert_tool_into_openai_schema()正是顶层tools[...]背后所走的同一条 Schema 生成路径——这也解释了为什么tools方式要求函数有清晰的类型注解与 docstring底层py_func_to_openai_func_str与pydantic_to_json模块正是依据这些元数据来生成name / description / parameters / required结构。搜索与金融数据工具让 Agent 拿到实时信息Exa 语义搜索Exa 是示例中出现频率最高的搜索工具。除了swarms_tools提供的现成版本agent_with_exa.py 里还给出了手写 Exa 工具的完整实现非常值得学习import os import httpx from loguru import logger from swarms.utils.any_to_str import any_to_str def exa_search(query: str) - str: Exa Web Search Tool Accepts natural language queries... Returns structured, summarized results suitable for automated research workflows. api_key os.getenv(EXA_API_KEY) if not api_key: raise ValueError(EXA_API_KEY environment variable is not set) characters 20 sources 2 headers {x-api-key: api_key, content-type: application/json} payload { query: query, type: auto, numResults: sources, contents: { text: True, summary: {schema: {type: object, required: [answer], properties: {answer: {type: string, description: Key insights and findings}}}}, context: {maxCharacters: characters}, }, } try: logger.info(f[SEARCH] Executing Exa search for: {query[:50]}...) response httpx.post(https://api.exa.ai/search, jsonpayload, headersheaders, timeout30) response.raise_for_status() return any_to_str(response.json()) except Exception as e: logger.error(fExa search failed: {e}) return fSearch failed: {str(e)}. Please try again.这段代码浓缩了工具开发的关键要点密钥管理从环境变量读取EXA_API_KEY缺失时抛出带说明的ValueError而不是静默失败参数收敛sources2、maxCharacters20控制返回规模防止响应过大挤占上下文Agent 的 context 是宝贵的结构化摘要通过summary.schema让 Exa 返回精简的answer字段而不是整页正文双层容错外层 try/except 把异常转成模型可读的字符串返回保证 Agent 不会因工具崩溃而中断。配套的 exa_search_agent.py 与 simple_tool_example.py 展示了两种调用风格前者用gpt-5.4 默认配置后者用claude-sonnet-4-20250514并开启了dynamic_context_windowTrue、streaming_onFalse。可见同一个搜索工具可以适配不同模型与上下文策略。CoinGecko 加密货币工具new_tools_examples.py 演示了如何自己动手写三个金融工具并挂到一个 Agent 上get_coin_price(coin_id, vs_currency)查询单币种实时价格与市值、24h 成交量、涨跌幅get_top_cryptocurrencies(limit, vs_currency)按市值取 Top N校验1 limit 250越界抛ValueErrorsearch_cryptocurrencies(query)按名称或符号搜索结果裁剪到前 10 条。其 Agent 配置集中体现了工具型 Agent 的常用参数组合agent Agent( agent_nameFinancial-Analysis-Agent, agent_descriptionPersonal finance advisor agent with cryptocurrency market analysis capabilities, system_promptYou are a personal finance advisor agent with access to real-time cryptocurrency data from CoinGecko..., max_loops1, model_namegpt-5.4, dynamic_temperature_enabledTrue, output_typefinal, tool_call_summaryTrue, tools[get_coin_price], ) out agent.run(What is the price of Bitcoin?)值得注意tool_call_summaryTrue在输出中汇总工具调用信息与output_typefinal的组合前者让工具调用的过程透明可审计后者只返回最终答案避免把原始 JSON 塞给用户。system_prompt明确告诉模型你有实时数据访问权、要解释行情数据这是引导模型主动使用工具的关键——很多 Agent 不调工具问题出在 system prompt 没说清楚自己有什么能力。swarms_tools 现成工具库多个示例都从swarms_tools直接导入生产可用的金融工具financial_news_agent.pyyahoo_finance_api分析 Nvidia 最新指标并配置了retry_attempts3、context_length8192、max_tokens4000、output_typestrswarms_tool_example_simple.pycoin_gecko_coin_apifetch_htx_data把行情数据直接拼进任务字符串喂给 Agent让模型基于内联的真实数据做分析——这是一种不依赖函数调用、纯数据注入的轻量策略dex_screener.pyswarms_tools.finance.dex_screener.fetch_dex_screener_profiles拉取 DEX 代币画像Agent 再结合提示词做 Top 5 潜力分析together_deepseek_agent.py组合fetch_htx_data与coin_gecko_coin_api并配了一套覆盖技术面、基本面、市场情绪、风险、链上数据的加密货币分析师 system prompt。这些示例共同说明金融类工具是工具集成最典型的落地场景而 swarms 生态把 OKX、CoinGecko、HTX、DexScreener、Yahoo Finance 等都已封装好可直接复用。结构化输出给工具加上 Schema 约束结构化输出子目录专门演示如何用 Schema 约束模型的输出格式。上文提到的tools_list_dictionary手写 JSON Schema 就是其中一种。它的核心价值在于契约先行工具输入输出都有明确 JSON 结构模型按properties与required生成参数显著降低幻觉与格式错误可编程消费output_type可切换str / json / dict / csv / yaml等格式见 financial_news_agent.py 中的注释方便下游直接解析多 Agent 协同结构化工具不仅能取数据还能做路由决策——example_meaning_of_life_agents.py里所有辩论者共享一个select_agent工具输出agent_nameresponsereasoning让工具本身成为 Agent 间消息传递的载体。Solana 区块链工具企业级的稳健实现swarms/tools 之外 的solana_tool/子目录是高质量工具工程的范例。solana_tool.py 值得逐点拆解多 RPC 端点 故障切换维护RPC_ENDPOINTS列表get_working_endpoint()依次探测返回第一个可用端点规避单一节点故障重试策略通过requests.Session urllib3Retry配置total3、backoff_factor0.5并对429/500/502/503/504状态码自动重试应对限流与瞬时错误结构化错误定义SolanaAPIException自定义异常与TransactionErrordataclass含error_type / message / timestamp让错误信息可机器解析日志管理用 loguru 输出到solana_transactions.log配置rotation500 MB、retention10 days避免日志无限膨胀。配套的 solana_tool_test.py 提供了工具测试呼应了 README错误处理最佳实践的主旨——生产级工具必须可测试、可观测、可重试。多模态生成工具把 Agent 能力扩展到图像、视频与音乐omni_modal_agent.py 演示了一个基于 Replicate API 的多模态路由工具。核心是一个generate_content(modality, prompt)函数通过Modality枚举IMAGE / VIDEO / MUSIC把请求路由到不同模型图像 → Flux Schnell视频 → Luma Ray音乐 → Flux Music额外带save_spectrogram参数。实现要点包括使用Enum而非裸字符串约束合法取值、统一封装Authorization请求头、对非 200 响应抛出带状态码的RuntimeError、docstring 里附上可执行示例。文件后半部分还有一段被注释掉的MUSE系统提示词展示了创意媒体生成代理应该如何理解用户意图并针对不同模型做 Prompt 工程——这是多模态工具 专用 system prompt完整方案的雏形。MCP 工具连接外部工具服务器工具不仅可以是本地函数还可以通过 MCPModel Context Protocol连接远程服务器。agent_mcp.py 展示了极简接入方式from swarms import Agent from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT agent Agent( agent_nameFinancial-Analysis-Agent, agent_descriptionPersonal finance advisor agent, system_promptFINANCIAL_AGENT_SYS_PROMPT, max_loops1, mcp_urls[http://0.0.0.0:5932/mcp], model_namegpt-5.4, output_typeall, ) out agent.run( Use the discover agent tools to find what agents are available and provide a summary ) print(out)只需在mcp_urls里列出服务器地址Agent 就能自动发现并调用远程暴露的工具这里是发现可用 Agent的服务。这与仓库中 swarms/tools/mcp_manager.py 的管理逻辑呼应MCP 是连接异构工具生态的标准化通道尤其适合团队内部共享的工具服务。更完整的 MCP 客户端/服务端示例可参考 examples/mcp 目录。浏览器自动化并发浏览器 Agent 集群swarms_of_browser_agents.py 把工具集成推向了另一个维度——不是给一个 Agent 装工具而是把整个浏览器自动化 Agent 当作工作流节点import asyncio from browser_use import Agent from dotenv import load_dotenv from langchain_openai import ChatOpenAI from swarms import ConcurrentWorkflow class BrowserAgent: def __init__(self, agent_name: str BrowserAgent): self.agent_name agent_name async def browser_agent_test(self, task: str): agent Agent(tasktask, llmChatOpenAI(modelgpt-5.4)) result await agent.run() return result def run(self, task: str): return asyncio.run(self.browser_agent_test(task)) swarm ConcurrentWorkflow(agents[BrowserAgent() for _ in range(10)]) swarm.run(Go to coinpost.jp and find the latest news about the crypto market.)这里用browser_use的 Agent 封装成统一run()接口再喂给 swarms 的ConcurrentWorkflow并发执行 10 个实例。注意两点一是每个节点都要实现同步的run入口以便编排器统一调度内部再asyncio.run转异步二是并发抓取适用于同一来源批量采集的场景示例用同一任务并发出多个浏览器实例。异步 vs 多线程工具调用的性能调优example_async_vs_multithread.py 关注的是工具/Agent 调用的执行形态。它用一个measure_time_and_memory装饰器记录每次调用的耗时与内存占用对比两条路径异步路径asyncio.to_thread(agent.run, task)把阻塞的 Agent 调用扔到线程池事件循环不被卡死多线程路径再包一层asyncio.run()在独立事件循环中运行。同时它示范了 Agent 的长上下文配置context_length200000、retry_attempts1、autosaveTrue、saved_state_pathfinance_agent.json、return_step_metaFalse、streaming_onFalse。这告诉我们当单个 Agent 调用耗时长如金融分析多步推理应优先考虑异步/线程化调度并结合retry_attempts控制失败成本、context_length控制上下文预算。多工具规划与执行ToolAgent 的完整范式multi_tool_usage_agent.py 是目录中工程最完整的示例——它实现了一个ToolAgent类演示规划 → 执行 → 分析的完整多工具流水线工具自省extract_tool_info()用inspect.signature、typing.get_type_hints、inspect.getdoc自动提取函数名、参数类型、默认值、必填参数与 docstring生成ToolDefinition规格分析_analyze_functions()解析 docstring 中的:param与:return:标记构建FunctionSpec含参数类型、描述、是否必填动态提示词_create_system_prompt()把全部函数规格渲染进系统提示词并规定两种输出格式——planning阶段输出分步计划 JSONexecution阶段输出continue / request_input / complete决策类型安全执行_execute_function()在调用前把参数强制转换到声明类型转换失败抛出带参数名的ValueError带日志的编排run()维护ExecutionContext逐步执行、记录每步结果与分析最终汇总成含task / start_time / steps / final_result的执行日志异常时success: Falseerror字段。示例末尾用它完成了计算 1 万美元按 7% 年利率投资 10 年的复合收益任务def calculate_investment_return(principal: float, rate: float, years: int) - float: Calculate investment return with compound interest. :param principal: Initial investment amount in dollars :param rate: Annual interest rate as decimal (e.g., 0.07 for 7%) :param years: Number of years to invest :return: Final investment value return principal * (1 rate) ** years agent ToolAgent(functions[calculate_investment_return], openai_api_keyos.getenv(OPENAI_API_KEY)) result agent.run(Calculate returns for $10000 invested at 7% for 10 years)这个模式的价值在于它把多工具调用从一次性 prompt 提升为可审计、可断点、可复用的执行框架很适合需要多步骤数据流水线的场景查询 → 计算 → 汇总 → 报告。底层原理工具是如何被执行的理解示例背后的执行链路有助于排查工具没被调用参数传错了等问题。以 swarms 的BaseTool为例swarms/tools/base_tool.py 的核心职责在类 docstring 中写得很清楚将函数转换为 OpenAI Function Calling Schema底层由swarms/tools/py_func_to_openai_func_str.py的get_openai_function_schema_from_func等函数完成管理 Pydantic BaseModel 与其 JSON Schema执行工具时做校验与错误处理对昂贵操作做缓存。真正的解析 JSON 并调用函数由 swarms/tools/tool_parse_exec.py 的parse_and_execute_json()完成。从源码看它的处理逻辑包括兼容functions/function/ 裸对象三种 JSON 形态通过函数名在function_dict中查找目标找不到返回Error: Function not found而不是抛异常对每次调用支持max_retries重试默认 3 次把每个函数的返回结果转成字符串汇总进results。这条模型产出 JSON → 解析 → 按名查找 → 重试执行 → 汇总返回的链路正是tools[...]方式下所有示例共同依赖的执行内核。需要自定义执行逻辑时如加鉴权、加缓存直接继承或组合BaseTool即可。最佳实践清单综合 README 概述与全部示例源码可以把 swarms 工具集成的最佳实践归纳为以下几条写好 docstring 与类型注解工具 Schema 由函数元数据生成注释即契约:param/:return:标记会被ToolAgent._analyze_functions这类代码直接解析见 multi_tool_usage_agent.py错误永不静默、也永不致命网络请求raise_for_status()后主动抛出带上下文的异常但在工具边界处用 try/except 转成模型可读的字符串见 agent_with_exa.py保证 Agent 流程不断密钥走环境变量EXA_API_KEY、REPLICATE_API_KEY、OPENAI_API_KEY一律os.getenv()读取缺失时抛出明确提示约束返回体量限制搜索结果数numResults2、上下文截断maxCharacters、列表裁剪Top 10保护上下文窗口重试与端点冗余对金融/区块链等外部依赖配置重试策略与多端点切换见 solana_tool.py用 system prompt 交代能力边界告诉模型你有 X 工具、何时用、如何解释结果见 new_tools_examples.py按任务形态选执行方式单轮查询用max_loops1output_typefinal多步流水线用规划-执行框架ToolAgent批量采集用ConcurrentWorkflow 异步包装swarms_of_browser_agents.py测试先行为工具写独立测试如 solana_tool_test.py并善用tool_call_summaryTrue观测真实调用情况。小结examples/single_agent/capabilities/tools目录用十余个可运行示例覆盖了单 Agent 工具集成的完整光谱从最简单的tools[func]到手写 Schema 的tools_list_dictionary再到底层BaseTool与parse_and_execute_json的执行内核从 Exa 搜索、CoinGecko/OKX/HTX/DexScreener 等金融数据到 Solana 区块链、Replicate 多模态、MCP 远程工具、浏览器自动化集群以及异步/多线程性能调优与多步骤规划执行框架。这些示例既可以直接复制使用也是理解 swarms 工具体系——swarms/tools/base_tool.py、swarms/tools/tool_parse_exec.py、swarms/tools/py_func_to_openai_func_str.py——的最佳入口。按上文的最佳实践清单组织自己的工具即可为 Agent 打开真实世界的数据与行动能力。【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考