拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Swarms 单智能体开发完全指南:从零配置到工具、RAG、推理与自治的全场景示例解析

Swarms 单智能体开发完全指南从零配置到工具、RAG、推理与自治的全场景示例解析【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms本文是基于当前仓库 examples/single_agent 目录编写的单智能体Single Agent实战指南。它系统梳理了 Swarms 框架中构建与配置单个Agent的全部示例资产从最小可运行程序、交互式 REPL、YAML 配置化启用到工具调用、Skills、RAG、视觉、流式输出、Prompt 缓存、推理模式、自治循环、Handoffs、Marketplace 集成与各类工具型示例。读完本文你将掌握Agent核心参数的作用、目录中每个示例的定位与用法并能据此快速搭建一个生产可用的单智能体应用。一、目录总览Single Agent 示例库的地图Swarms 是面向企业级的多智能体编排框架而单智能体Single Agent是这一切的原子单元。仓库中的 examples/single_agent 目录把可运行的示例按照先跑通、再深入、后组合的思路划分成几个顶层桶bucket便于快速扫描与检索single_agent/ ├── getting_started/ First runs: minimal agent, interactive mode, onboarding ├── capabilities/ What an agent can do: tools, skills, RAG, vision, streaming, prompt caching ├── reasoning/ Reasoning agents: judges, consistency, iterative, reasoning duo/router ├── autonomy/ Autonomous loops and agent-to-agent handoffs ├── integrations/ Marketplace prompts and external agent bridges ├── demos/ End-to-end applied demos └── utils/ Configuration, output formats, and misc helpers运行前提在运行任何示例之前请先设置对应的 API Key如OPENAI_API_KEY、ANTHROPIC_API_KEY或根据示例中指定的模型名称设置相应服务商的密钥例如TOGETHER_API_KEY。所有示例都通过 LiteLLM 统一接入各家模型具体模型以示例代码中的model_name为准。二、getting_started第一次运行从这里开始这一桶是First-run examples专门用于快速验证环境与理解Agent的基本用法共三个入口。2.1 最小单智能体simple_agent.py只需几行代码即可完成一个可用的智能体from swarms import Agent agent Agent( nameResearch Agent, descriptionA research agent that can answer questions, model_nameclaude-sonnet-4-20250514, streaming_onTrue, max_loops1, interactiveTrue, ) out agent.run( What are the best arbitrage trading strategies for altcoins? Give me research papers and articles on the topic. ) print(out)从 Agent 实现 的文档字符串可以看到Agent是连接 LLM 与工具、长期记忆的骨干支持注入任意类型文档PDF、Txt、Markdown、Json 等。核心参数说明max_loops智能体在一次任务中最多执行几轮思考-行动循环1表示单轮直答在自治模式下还可设为auto见 autonomy/autonomous_agents/auto_agent.py。streaming_on开启带格式化面板的基础流式输出。interactive开启交互模式配合run()传入任务使用。2.2 交互式 REPL 智能体interactive.pyfrom swarms import Agent agent Agent( agent_nameQuantitative-Trading-Agent-test, agent_descriptionAdvanced quantitative trading and algorithmic analysis agent, system_promptYou are a helpful assistant that can answer questions and help with tasks and your name is Quantitative-Trading-Agent, model_namegpt-5.4, max_loops5, interactiveTrue, ) out agent.run() print(out)这里展示了Agent构造参数的另外几种写法agent_name/agent_description/system_prompt本示例使用name/description简写两者均可max_loops5允许最多 5 轮循环。interactiveTrue时run()不传任务即可进入 REPL 式对话界面。2.3 YAML 配置化上手指南onboarding/这一子目录演示了通过 YAML 文件配置智能体的Onboarding最佳实践。入口脚本 onboard-basic.py 使用create_agents_from_yaml从配置文件批量创建智能体而不立即执行任务from dotenv import load_dotenv from loguru import logger from swarms import create_agents_from_yaml load_dotenv() yaml_file agents.yaml task_results create_agents_from_yaml( yaml_fileyaml_file, return_typeagents ) print(task_results)配置文件 agents.yaml 完整演示了Agent的字段与 YAML 键的对应关系agents: - agent_name: Financial-Analysis-Agent model: model_name: gpt-4 temperature: 0.1 max_tokens: 2000 system_prompt: financial_agent_sys_prompt max_loops: 1 autosave: true dashboard: false verbose: true dynamic_temperature_enabled: true saved_state_path: finance_agent.json user_name: swarms_corp retry_attempts: 1 context_length: 4000 return_step_meta: false output_type: str task: How can I establish a ROTH IRA to buy stocks and get a tax break? - agent_name: Stock-Analysis-Agent model: model_name: gpt-4 temperature: 0.2 max_tokens: 1500 system_prompt: stock_agent_sys_prompt max_loops: 2 autosave: true dashboard: false verbose: true dynamic_temperature_enabled: false saved_state_path: stock_agent.json user_name: stock_user retry_attempts: 3 context_length: 4000 return_step_meta: true output_type: json task: What is the best strategy for long-term stock investment? swarm_architecture: name: Financial-Advisory-Swarm description: A swarm of agents working together to provide comprehensive financial advice swarm_type: SequentialWorkflow max_loops: 2 task: Analyze ROTH IRA setup requirements and provide a comprehensive long-term investment strategy autosave: true return_json: false rules: | 1. Financial-Analysis-Agent first explains ROTH IRA setup process and requirements 2. Stock-Analysis-Agent then provides specific investment strategies suitable for ROTH IRA 3. Both agents should ensure advice is tax-aware and compliant with retirement account regulations 4. Focus on practical, actionable steps the user can take逐项解读这些配置字段对应 Agent 参数model.model_name / temperature / max_tokens模型选择与采样参数temperature控制随机性金融场景通常取低值如 0.1 保证稳定。system_prompt可引用仓库 swarms/prompts 中预置的系统提示词名称如financial_agent_sys_prompt、stock_agent_sys_prompt。max_loops单任务最大循环轮次。autosave/saved_state_path是否自动保存状态及状态文件路径。verbose是否输出详细日志。dynamic_temperature_enabled是否启用动态温度根据置信度自动调整。retry_attempts失败重试次数。context_length上下文窗口长度。return_step_meta是否返回每步元信息。output_type输出类型支持str、json等多种详见下文 utils 部分。swarm_architecture把多个单智能体编排成 Swarm 的声明方式swarm_type: SequentialWorkflow表示顺序执行rules定义智能体之间的协作顺序与约束——这正体现了单智能体是多智能体编排的基础原子的设计哲学。三、capabilities智能体能力的全景演示这一桶回答一个智能体能做什么按能力维度细分为 tools、skills、rag、vision、streaming、prompt_caching 六个子目录。3.1 tools/工具调用与外部系统集成示例说明agent_mcp.py通过 MCPModel Context Protocol挂载外部服务器工具agent_with_exa.py、exa_search_agent.py集成 Exa 搜索引擎multi_tool_usage_agent.py同时使用多个工具litellm_tool_example.pyLiteLLM 工具调用omni_modal_agent.py全模态智能体new_tools_examples.py最新工具模式example_async_vs_multithread.py异步 vs 多线程对比swarms_tools_example.pyswarms-tools 集成swarms_of_browser_agents.py浏览器自动化together_deepseek_agent.pyTogether AI 上的 DeepSeek 模型solana_tool/Solana 区块链工具solana_tool.py、solana_tool_test.pystructured_outputs/结构化输出structured_outputs_example.py、example_meaning_of_life_agents.pytools_examples/更多工具示例simple_tool_example.py、dex_screener.py、financial_news_agent.py、swarms_tool_example_simple.py以 MCP 为例agent_mcp.py 演示了如何把外部 MCP 服务器能力挂到单智能体上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)从源码可以看到Agent通过 MCPManager 管理mcp_urls并支持 MCPConnection、MCPOAuthConfig 等连接配置。这意味着单个智能体可以像拼接乐高一样接入任意符合 MCP 协议的工具服务器。3.2 skills/可复用的模块化技能SKILL.mdSkills 实现了 Anthropic 的 Agent Skills 框架——以SKILL.md文件定义模块化、可复用的能力智能体在相关任务出现时自动加载并遵循其中的指令。相关示例agent_with_skills.py带技能的单智能体agent_with_multiple_skills.py多技能agent_with_dynamic_skills.py动态技能加载agent_with_custom_skill.py自定义技能code-review/、data-visualization/、financial-analysis/三个示例SKILL.md定义技能加载的底层实现由 SkillsManager 提供Agent通过skills_dir参数指定技能目录每个子目录放一个含 YAML frontmatter 的SKILL.md技能会被自动注入系统提示词实现上下文感知的按需激活。agent_with_skills.py 的用法如下from pathlib import Path from swarms import Agent repo_root Path(__file__).parent.parent.parent skills_path repo_root / example_skills agent Agent( agent_nameFinancial Analyst, model_namegpt-4o, max_loops1, skills_dirstr(skills_path), ) response agent.run( Analyze Apples financials and provide a DCF valuation framework ) print(response)以 financial-analysis/SKILL.md 为例其 frontmatter 声明了技能的名称与描述正文则是标准化的分析方法论数据收集与校验、财务比率分析、DCF 估值模型、敏感性分析、输出规范等LLM 收到任务后会依据描述自动激活该技能并按其步骤执行。3.3 rag/检索增强生成RAG 相关示例位于 capabilities/ragsimple_example.py最小 RAG 流程基于 Qdrantfull_agent_rag_example.py完整的 RAG 智能体pinecone_example.py集成 Pineconeqdrant_agent.py / qdrant_rag_example.py集成 Qdrant以 simple_example.py 为例它演示了完整闭环构造样例文档如黄金 ETF 指南、市场分析、组合策略→ 通过 RAG Agent 的ingest_documents()摄入向量库 → 用query_documents()检索相关片段并打印相似度得分 → 调用run_analysis()做基于检索结果的综合分析 →get_database_stats()查看库统计。构造 RAG Agent 时可配置collection_name、chunk_size、chunk_overlap等参数控制切分粒度。3.4 vision/多模态与视觉能力视觉相关示例位于 capabilities/visionmultimodal_example.py多模态智能体anthropic_vision_test.pyAnthropic 视觉能力image_batch_example.py / multiple_image_processing.py批量图片处理vision_tools.py / vision_test.py视觉工具base_64_images/test_base64_image.py 演示 base64 图片输入Agent原生支持multi_modal参数见 Agent 参数结合多模态系统提示词如 MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1即可处理图片输入。3.5 streaming/流式输出streaming_example.pyToken 流式输出agent_streaming.py流式智能体example_streaming_tools.py带工具的流式输出test_agent_streaming_and_loop.py流式 循环从 Agent 参数 看流式相关参数包括streaming_on带格式化面板的基础流式、stream逐 Token 的详细流式附带 citations、tokens used 等元数据、streaming_callback实时接收流式 Token 的回调函数。3.6 prompt_caching/提示词缓存降本这是极具实战价值的一组示例相关文件位于 capabilities/prompt_cachingprompt_caching_example.py整体概览1_basic_anthropic.pyAnthropic 基础缓存2_one_hour_ttl.py1 小时 TTL 缓存3_cache_tools.py缓存工具定义4_system_only.py仅缓存系统提示词5_openai_caching.pyOpenAI 自动缓存6_all_options.py / cache_config_example.py完整cache_config配置在 prompt_caching_example.py 中只需在Agent上开启一个开关agent Agent( agent_nameCachedAnalyst, system_promptKNOWLEDGE_BASE, # 大而稳定的前缀如策略文档、样式指南、schema model_nameclaude-sonnet-4-6, max_loops1, prompt_cachingTrue, # 唯一需要的开关 persistent_memoryFalse, top_pNone, # Anthropic 拒绝同时发送 temperature 和 top_p )第一次调用会写入缓存按 cache-creation tokens 计费第二次调用则命中缓存按便宜的 cache-read tokens 计费。示例还演示了如何通过 LiteLLM 封装 直接读取usage中的cache_creation_input_tokens首次与prompt_tokens_details.cached_tokens命中字段来验证缓存是否真正生效——这是上线前验证降本效果的可靠方法。四、reasoning推理智能体模式这一桶展示增强推理能力的多种模式示例位于 reasoningreasoning_duo.py / reasoning_duo_example.py / reasoning_duo_test.py双智能体推理思考者 执行者reasoning_agent_router.py / reasoning_agent_router_now.py推理路由agent_judge_example.py / agent_judge_evaluation_criteria_example.py智能体充当评审Agent-as-judgeconsistency_agent.py / consistency_example.py自洽性Self-consistencyiterative_agent.py迭代推理gpk_agent.py生成式知识提示Generated-Knowledge Prompting以 reasoning_duo.py 为例它构建了思考者 执行者的双智能体流水线Strategic-Thinker负责深度问题分析与策略设计可指定如together_ai/deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free这类带前缀的模型路由到 TogetherAction-Executor则把策略转化为具体行动。二者通过run_reasoning_duo()串联先思考后执行def run_reasoning_duo(task: str): thinking_result thinking_agent.run(task) action_result action_agent.run( fFrom {thinking_agent.agent_name}: {thinking_result} ) return action_result这与仓库中 reasoning_duo.py 的实现相对应。相关的基础设施还包括 AgentJudge、ConsistencyAgent、ReasoningAgentRouter 与 GKPAgent 等实现类对应测试位于 tests/agents。五、autonomy自治循环与智能体交接这一桶聚焦无人值守地持续运行与智能体间交接两类能力。5.1 autonomous_agents/自治循环auto_agent.pymax_loopsauto的自动循环智能体autonomous_agent.py自治智能体example_autonomous_looper_run_bash.py带 bash 工具的自治循环sub_agent_test.py生成子智能体marketplace_and_auto_agent.py自治 Marketplace 组合max_loopsauto会启用仓库中的 AutonomousAgentLoop 机制让智能体持续自主运行直到满足停止条件停止条件包括停止词、停止函数如stop_when_repeats、parse_done_token见 agent.py、stopping_token、custom_exit_command等。其系统提示词定义在 autonomous_agent_prompt.py对应测试见 test_autonomous_loop.py。5.2 handoffs/智能体间任务交接handoff_example.py / handoffs_example.py基础交接duo_agent.py双智能体交接autonomous_agent_with_handoffs_example.py自治 交接组合Handoffs 的底层实现基于 handoffs_tool.py 与 handoffs_tool_schema.py并配套 handoffs_prompt.py 中的系统提示词。它让智能体在任务边界处把控制权与上下文交给另一个更合适的智能体是构建复杂工作流的基本衔接机制。六、integrationsMarketplace 提示词与外部智能体桥接这一桶演示单智能体如何与 Swarms 生态及外部系统集成marketplace/Marketplace提示词市场相关示例marketplace_prompt_example.py从 Marketplace 拉取提示词quant_trader_agent.py / zia_agent.pyMarketplace 支撑的智能体medical_agent_add_to_marketplace.py把智能体发布到 MarketplaceMarketplace 功能由 AgentMarketplaceHandler 实现对应的Agent参数是marketplace_prompt_id传入一个 UUID 即可自动从 Swarms Marketplace 拉取提示词作为系统提示词实现一行代码加载市场提示词需设置SWARMS_API_KEY环境变量。相关测试见 test_agent_marketplace_handler.py。external_agents/external_agents/README.md 详细说明了如何桥接非 Swarms 生态的外部智能体。七、demos端到端落地演示insurance_agent.py保险理赔处理persistent_legal_agent.py带持久记忆的法律智能体这两个示例把前几桶的能力组合起来展示真实业务场景下的端到端用法一个偏向流程化信息处理保险另一个强调长期记忆法律场景需要跨会话保持案情上下文。其中持久记忆依赖Agent的long_term_memory、persistent_memory等参数与 Conversation 机制。八、utils配置、输出格式与杂项辅助这一桶收录单智能体的进阶配置与输出格式控制示例位于 utilsasync_agent.py异步智能体custom_agent_base_url.py自定义 Base URL对接自建网关/代理dynamic_context_window.py动态上下文窗口agent_usage.pyToken 用量与成本统计fallback_test.py模型回退对应fallback_model_name/fallback_models参数见 Agent 参数grok_4_agent.pyGrok 4 智能体list_agent_output_types.py枚举输出类型markdown_agent.pyMarkdown 输出xml_output_example.pyXML 输出autosaving_examples/自动保存系列autosave_basic_example.py基础自动保存autosave_config_access_example.py自动保存配置访问autosave_directory_structure_example.py自动保存目录结构autosave_recovery_example.py状态恢复transform_prompts/提示词转换transforms_agent_example.pytransforms_examples.py其中output_type支持str、string、list、json、dict、yaml、xml等格式见 Agent 参数底层由 output_types.py 与 history_output_formatter.py 实现。自动保存依赖 SafeStateManager / SafeLoaderUtils可把智能体状态保存到 JSON 文件并在下次启动时恢复——这与 agents.yaml 中的autosave/saved_state_path字段相呼应。提示词转换则由 transforms.py 中的MessageTransforms、TransformConfig、handle_transforms实现用于应对上下文长度限制。九、从示例到实践单智能体选型路径建议结合目录的划分逻辑与Agent的底层实现可以按如下路径为你的场景选择示例作为起点跑通最小闭环先运行 simple_agent.py确认 API Key 与模型可用接入模型与工具根据业务选择 capabilities/tools 中的 MCP、搜索、浏览器或结构化输出示例注入领域知识用 capabilities/rag 接入企业文档用 capabilities/skills 固化领域方法论控制成本与体验用 capabilities/prompt_caching 缓存稳定前缀、用 capabilities/streaming 提供流式体验提升推理质量从 reasoning 中挑选双智能体、评审、自洽性或迭代推理模式走向无人值守与多智能体用 autonomy 开启自治循环与交接最终通过 onboarding/agents.yaml 中的swarm_architecture声明把单智能体编排为 Swarm。所有单智能体能力都是多智能体编排如 SequentialWorkflow、GroupChat、AgentRearrange 等 swarms/structs 中的结构的基石——先吃透本目录再向上组合即可从单个会干活的 Agent平滑演进到企业级多智能体系统。【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门