尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

smolagents 多智能体系统编排实战:用 Managed Agents 构建协作式网络浏览器

smolagents 多智能体系统编排实战:用 Managed Agents 构建协作式网络浏览器 smolagents 多智能体系统编排实战用 Managed Agents 构建协作式网络浏览器【免费下载链接】smolagents smolagents: a barebones library for agents that think in code.项目地址: https://gitcode.com/gh_mirrors/smo/smolagents本文基于 smolagents 官方示例文档 multiagents.md讲解如何用CodeAgent、ToolCallingAgent与managed_agents机制搭建一个“管理者 网络搜索子代理”的多智能体multi-agent协作系统一个负责规划推理的 Manager 代理挂着一个封装了WebSearchTool与自定义VisitWebpageTool的受管代理Managed Agent。读完后你将掌握如何为子代理配置name/description使其被管理者当作“工具”调用、为什么按任务类型选择ToolCallingAgent或CodeAgent、以及 smolagents 在源码层面如何将代理“工具化”注入执行器的实现原理。一、整体架构一个 Manager 一个受管网络搜索代理官方示例的目标是构建一个multi-agent 网络浏览器——多个代理协作借助网络搜索解决问题。整体是一个简单的层次结构管理者代理Manager agent在自身具备代码解释器工具Code Interpreter tool的同时挂着一个受管代理Managed agent该受管代理内部封装了网页搜索工具与访问网页工具---------------- | Manager agent | ---------------- | _______________|______________ | | Code interpreter -------------------------------- tool | Managed agent | | ------------------ | | | Web Search agent | | | ------------------ | | | | | | Web Search tool | | | Visit webpage tool | --------------------------------这种“代理套代理”的分层设计是多智能体编排的核心思路每个子代理只负责一个窄域任务这里是网络搜索管理者负责规划、整合与最终计算从而把长任务拆成可独立迭代、可独立配置模型与步数的子任务。二、环境准备与模型接入2.1 安装依赖多代理示例依赖smolagents[toolkit]附加依赖提供搜索等工具链执行以下命令安装pip install smolagents[toolkit] --upgrade -q2.2 登录 Hugging Face 并选择推理模型示例通过 HF 的 Inference API 运行开源模型HF 的 Inference API 可以快速轻松地运行任何开源模型因此代理将使用库中的InferenceClientModel类来调用Qwen/Qwen3-Next-80B-A3B-Thinking模型。需要先登录 HF Hub 以获得 Inference API 的调用凭证from huggingface_hub import login login()注意基于多参数和部署模型的 Inference API 可能在没有预先通知的情况下更新或替换模型选型时应了解对应模型的可用性说明。指定模型model_id Qwen/Qwen3-Next-80B-A3B-ThinkingInferenceClientModel的实现在 models.py 中它与本地TransformersModel等模型类共享同一套接口因此在示例里模型对象可以直接同时传给ToolCallingAgent和CodeAgent。三、创建网络工具WebSearchTool与手写visit_webpage3.1 内置的WebSearchTool对于网页浏览smolagents 已提供内置的WebSearchTool可作为 Google 搜索的平替。查看其源码default_tools.py可以看到它的默认配置class WebSearchTool(Tool): def __init__(self, max_results: int 10, engine: str duckduckgo):max_results默认为10控制单次搜索返回的结果条数engine默认为duckduckgo源码中还实现了search_bing、search_exa等搜索路径见 default_tools.py可通过参数切换搜索引擎对外暴露的入口方法是search(query: str)见 default_tools.py。3.2 从零构建visit_webpage工具找到搜索结果的页面后还需要能“查看”页面内容。库内置了VisitWebpageTool但示例选择用markdownify从零重建一遍以便理解其工作原理。工具用tool装饰器声明函数签名与 docstring 会被解析为工具的输入 schema 和给模型的说明import re import requests from markdownify import markdownify from requests.exceptions import RequestException from smolagents import tool tool def visit_webpage(url: str) - str: Visits a webpage at the given URL and returns its content as a markdown string. Args: url: The URL of the webpage to visit. Returns: The content of the webpage converted to Markdown, or an error message if the request fails. try: # Send a GET request to the URL response requests.get(url) response.raise_for_status() # Raise an exception for bad status codes # Convert the HTML content to Markdown markdown_content markdownify(response.text).strip() # Remove multiple line breaks markdown_content re.sub(r\n{3,}, \n\n, markdown_content) return markdown_content except RequestException as e: return fError fetching the webpage: {str(e)} except Exception as e: return fAn unexpected error occurred: {str(e)}实现要点HTML → Markdown 转换markdownify(response.text)把原始 HTML 转成 Markdown再strip()去首尾空白压缩多余空行re.sub(r\n{3,}, \n\n, ...)把连续 3 行以上空行折叠为两行降低返回给 LLM 的 token 量错误兜底网络层错误RequestException与未知异常都捕获为字符串返回而不是抛出异常——这对代理很关键因为工具抛异常会中断步骤而返回错误信息可以让模型自行决策重试或换链接。初始化后可以先单独测试工具是否可用print(visit_webpage(https://en.wikipedia.org/wiki/Hugging_Face)[:500])四、构建子代理ToolCallingAgent版的网络搜索代理有了WebSearchTool()和visit_webpage两个工具后就可以创建 web agent 了。官方文档给出的选型理由值得记录网页浏览是单线程任务不需要并行工具调用JSON 工具调用JSON tool calling对此类任务非常有效因此选择ToolCallingAgent而非CodeAgent网页搜索有时需要探索许多页面才能找到正确答案因此把max_steps提高到 10。from smolagents import ( CodeAgent, ToolCallingAgent, InferenceClientModel, ManagedAgent, WebSearchTool, ) model InferenceClientModel(model_idmodel_id) web_agent ToolCallingAgent( tools[WebSearchTool(), visit_webpage], modelmodel, max_steps10, namesearch, descriptionRuns web searches for you. Give it your query as an argument., )关键配置说明参数示例取值作用tools[WebSearchTool(), visit_webpage]子代理可用的工具列表支持BaseTool实例与tool装饰函数modelInferenceClientModel(model_idmodel_id)推理模型这里管理者与子代理共用同一模型实例max_steps10允许探索多个页面步数上限调高namesearch必填管理者通过这个名字把该代理当作工具来调用descriptionRuns web searches for you. …必填写入管理者的系统提示词供模型判断何时调用name和description是使子代理可被管理者调用的必需属性——这一点由源码保证在 agents.py 的_setup_managed_agents中存在断言all(agent.name and agent.description ...)缺少任一项会直接抛出 All managed agents need both a name and a description!。五、构建管理者代理CodeAgentmanaged_agents创建管理代理时把受管代理通过managed_agents参数传入。选型上因为该代理的任务是规划与思考高级推理能力很有帮助所以选CodeAgent同时问题涉及当前年份和额外的数据计算所以添加additional_authorized_imports[time, numpy, pandas]以备代理需要用到这些包这些模块会被加入CodeAgent本地 Python 执行器的授权导入白名单。manager_agent CodeAgent( tools[], modelmodel, managed_agents[web_agent], additional_authorized_imports[time, numpy, pandas], )注意管理者自身tools[]——它并不直接拥有搜索工具唯一的“能力”就是代码解释器加对子代理的调用权。职责边界清晰搜索细节全部委托给web_agent。源码级原理受管代理是如何被“工具化”的从源码实现看受管代理并不是一个独立进程或消息通道而是被封装成管理者眼中的一种工具以 name 为键注册_setup_managed_agents把列表转成字典self.managed_agents {agent.name: agent ...}agents.py统一注入输入/输出契约框架为每个受管代理强制设置inputs包含task字符串参数——Long detailed description of the task.以及可选的additional_args对象参数——可传入图片、DataFrame 等上下文数据和output_type stringagents.py。因此管理者调用子代理的签名永远是name(task…, additional_args{...} | None) - str名称唯一性校验_validate_tools_and_managed_agents会检查工具名与受管代理名不重复冲突时抛出ValueError并列出重复的名称agents.py这正是示例中把子代理命名为search的原因——它是管理者工具命名空间中的一个工具名注入执行器CodeAgent执行代码前会执行self.python_executor.send_tools({**self.tools, **self.managed_agents})agents.py于是管理者写出的代码可以直接出现search(task...)这样的调用对ToolCallingAgent则通过tools_and_managed_agents属性把受管代理并入可调用工具集合agents.py任务下发与结果回收提示词框架为受管代理调用定义了专门的提示模板ManagedAgentPromptTemplate含task下发任务与report回收报告两段agents.py从源码结构看CodeAgent的系统提示词文件 code_agent.yaml 中也包含关于如何使用managed_agents的提示引导模型把长任务委派出去并要求子代理返回详细报告。这套机制解释了文档中层次图的语义Manager 与受管代理之间传递的不是原始消息流而是“任务描述字符串 → 完整执行 → 字符串报告”的工具调用闭环。六、运行系统一个需要“搜索 计算”的问题系统构建完成后直接运行选择一个同时需要研究和计算的问题出自 multiagents.mdanswer manager_agent.run( If LLM training continues to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What would that correspond to, compared to some countries? Please provide a source for any numbers used. )该问题刻意触发了两层协作管理者把“查数据、找来源”委托给search子代理后者内部再调用WebSearchTool与visit_webpage多轮迭代拿到数字后用本地 Python 执行器完成 GW/GWh 换算与国家用电量对比计算。官方文档记录的示例输出报告如下结果由模型基于当时检索到的数据生成仅作为协作流程的展示不代表精确预测Based on current growth projections and energy consumption estimates, if LLM trainings continue to scale up at the current rhythm until 2030: 1. The electric power required to power the biggest training runs by 2030 would be approximately 303.74 GW, which translates to about 2,660,762 GWh/year. 2. Comparing this to countries electricity consumption: - It would be equivalent to about 34% of Chinas total electricity consumption. - It would exceed the total electricity consumption of India (184%), Russia (267%), and Japan (291%). - It would be nearly 9 times the electricity consumption of countries like Italy or Mexico. 3. Source of numbers: - The initial estimate of 5 GW for future LLM training comes from AWS CEO Matt Garman. - The growth projection used a CAGR of 79.80% from market research by Springs. - Country electricity consumption data is from the U.S. Energy Information Administration, primarily for the year 2021.如果“scaling hypothesis”持续成立我们可能需要一些庞大的动力配置 ——而我们的代理们成功协作解决了这个任务。七、进一步实践扩展与调试扩展到更多代理文档提示可以轻松把这个编排扩展到更多 agent——一个执行代码、一个进行网页搜索、一个处理文件加载只需继续往managed_agents列表里加不同name/description的代理即可检查多代理运行轨迹仓库提供了 inspect_multiagent_run.py 示例演示如何加载多智能体运行的 memory 并逐步查看管理者与受管代理各自的步骤保存与加载从源码结构看CodeAgent的save/序列化路径会把每个受管代理单独存到managed_agents子目录见 agents.py 及 agents.py因此整个“管理者 子代理”体系可以作为一个整体持久化、复现选型经验单线程、按轮次推进的任务如网页浏览用ToolCallingAgent需要规划、多步计算和灵活工具组合的任务如本例的管理者用CodeAgent。两者可以任意嵌套组合唯一约束是每个受管代理必须拥有全局唯一的name和清晰的description。八、小结smolagents 的多智能体编排把“代理即工具”的抽象落到了非常具体的 API 上managed_agents参数 name/description契约 task/report提示模板。本文示例展示了一个最小可用的三层结构——CodeAgent管理者规划与计算、ToolCallingAgent受管代理搜索与浏览、WebSearchTool/visit_webpage工具数据获取——并给出了max_steps、additional_authorized_imports等关键参数的取舍依据。配合源码中_setup_managed_agents的注册与校验逻辑可以完整理解“子代理如何成为管理者的一个可调用工具”并据此扩展出更多专职子代理的协作网络。【免费下载链接】smolagents smolagents: a barebones library for agents that think in code.项目地址: https://gitcode.com/gh_mirrors/smo/smolagents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表