
Swarms 880 版本新特性实战16 个官方示例逐类精讲与源码解析【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms本文围绕 Swarms 仓库中examples/changelogs/880_update_changelog_examples/目录下的 880 版本更新示例集展开先给出依赖安装与环境变量配置再按 README 的七大分类Marketplace 集成、多智能体结构、工作流编排、智能体管理、语音智能体、评估与辩论、路由与编排逐一讲解 16 个可直接运行的独立示例脚本并结合仓库源码说明marketplace_prompt_id、GraphWorkflow 的 rustworkx 后端、AgentRearrange 的 flow 模式等特性的底层实现帮助读者快速验证并复用本版本引入的全部新能力。一、目录定位与示例总览该目录examples/changelogs/880_update_changelog_examples/是 Swarms 最新版本880 更新新特性的官方演示库每个脚本均为独立可执行文件直接python运行即可看到特性效果。READMEREADME.md给出的完整示例索引如下#示例文件特性分类0101_marketplace_prompt_fetching.pyMarketplace Prompt FetchingMarketplace 集成0202_round_robin_swarm_routing.pyRound Robin Swarm Routing多智能体结构0303_graph_workflow_rustworkx.pyGraph Workflow with Rustworkx工作流编排0404_agent_rearrange.pyAgent Rearrangement多智能体结构0505_swarm_rearrange.pySwarm Rearrangement多智能体结构0606_spreadsheet_swarm.pySpreadsheetSwarm工作流编排0707_model_router.pyModelRouter智能体管理0808_self_moa_seq.pySelfMoASeq智能体管理0909_single_voice_agent.pySingle Voice Agent语音智能体1010_multi_agent_voice_debate.pyMulti-Agent Voice Debate语音智能体1111_hierarchical_voice_swarm.pyHierarchical Voice Swarm语音智能体1212_debate_with_judge.pyDebate with Judge评估与辩论1313_council_as_judge.pyCouncil as a Judge评估与辩论1414_swarm_router_round_robin.pySwarmRouter Round Robin路由与编排1515_graph_workflow_batch_agents.pyGraph Workflow Batch Agents工作流编排-autosaving_example.pyAutosaving Feature智能体管理路径说明README 的 Quick Start 中写的是examples/guides/880_update_changelog_examples/...但仓库内该目录的实际位置为examples/changelogs/880_update_changelog_examples/本文后续所有运行命令均以实际路径为准。二、前置条件、环境配置与运行方式2.1 安装依赖# 核心包 pip install -U swarms # 特定示例的可选依赖 pip install rustworkx # 图工作流示例03、15 pip install voice-agents # 语音智能体示例09、10、112.2 环境变量设置# 多数示例必需 export OPENAI_API_KEYyour-openai-api-key # Marketplace 示例01必需 export SWARMS_API_KEYyour-swarms-api-key # 可选其他提供商ModelRouter 等 export ANTHROPIC_API_KEYyour-anthropic-key export GOOGLE_API_KEYyour-google-key也可以在项目根目录创建.env文件OPENAI_API_KEYyour-openai-api-key SWARMS_API_KEYyour-swarms-api-key ANTHROPIC_API_KEYyour-anthropic-key GOOGLE_API_KEYyour-google-key2.3 快速开始每个示例都是独立 Python 脚本无需函数定义运行即产出结果# 方式一从仓库根目录 python examples/changelogs/880_update_changelog_examples/01_marketplace_prompt_fetching.py # 方式二进入目录后直接运行 cd examples/changelogs/880_update_changelog_examples python 01_marketplace_prompt_fetching.py批量顺序运行全部示例README 提供的方式cd examples/changelogs/880_update_changelog_examples for file in *.py; do echo Running $file... python $file echo --- done每个示例的执行流程固定为三步初始化所需的 Agent/Swarm 结构 → 执行任务 → 将结果打印到控制台输出形如[Feature Name] Result: [Output content here]三、Marketplace 集成marketplace_prompt_id 一行加载市场提示词3.1 示例代码01_marketplace_prompt_fetching.py 展示了如何用marketplace_prompt_id参数直接从 Swarms Marketplace 拉取提示词并作为系统提示词from swarms import Agent agent Agent( model_namegpt-5.4, marketplace_prompt_id6d165e47-1827-4abe-9a84-b25005d8e3b4, max_loopsauto, streaming_onTrue, interactiveTrue, ) response agent.run(Hello, what can you help me with?) print(response)关键特性一行加载 Marketplace 提示词系统提示词自动配置支持版本化的提示词编排。运行该示例需要SWARMS_API_KEY环境变量和一个有效的 marketplace prompt ID。3.2 源码层面的实现印证从源码结构看marketplace_prompt_id是Agent类的一等公民字段。在 swarms/structs/agent.py 中其文档字符串明确定义为 The unique UUID identifier of a prompt from the Swarms marketplace并在构造函数签名swarms/structs/agent.py与实例赋值swarms/structs/agent.py中完整贯通。实际的拉取逻辑位于 swarms/agents/agent_marketplace_handler.py处理函数会优先使用显式传入的prompt_id否则回退读取agent.marketplace_prompt_id再向 Marketplace 请求提示词内容。此外CLI 侧swarms/cli/main.py也支持该参数——当提供了marketplace_prompt_id时system_prompt不再是必填项说明这一机制同时服务于 Python API 与命令行两种入口。四、多智能体结构4.1 Round Robin Swarm Routing示例 0202_round_robin_swarm_routing.py 用SwarmRouter的swarm_typeRoundRobin实现公平循环执行、随机化每轮顺序、完整共享对话上下文是典型的 AutoGen 风格通信模式from swarms import Agent, SwarmRouter researcher Agent( agent_nameResearch-Specialist, system_promptYou research and gather factual information on topics., model_namegpt-5.4, max_loops1, ) analyst Agent( agent_nameData-Analyst, system_promptYou analyze data and identify patterns and insights., model_namegpt-5.4, max_loops1, ) strategist Agent( agent_nameBusiness-Strategist, system_promptYou develop strategic recommendations based on analysis., model_namegpt-5.4, max_loops1, ) swarm SwarmRouter( nameResearch-Analysis-Strategy-Swarm, agents[researcher, analyst, strategist], swarm_typeRoundRobin, max_loops1, verboseTrue, ) task Analyze the renewable energy market and provide strategic recommendations result swarm.run(task) print(Round Robin Swarm Result:) print(result)要点任务在三个专业化 Agent 之间轮转每个 Agent 都能读到前序对话max_loops1保证每个 Agent 只响应一轮。4.2 Agent Rearrangement示例 0404_agent_rearrange.py 演示AgentRearrange的运行时流程重排能力核心是 flow 模式字符串from swarms import Agent, AgentRearrange researcher Agent( agent_nameresearcher, system_promptYou research topics thoroughly and gather information., model_namegpt-5.4, max_loops1, ) writer Agent( agent_namewriter, system_promptYou write clear and engaging content based on research., model_namegpt-5.4, max_loops1, ) reviewer Agent( agent_namereviewer, system_promptYou review content for quality and accuracy., model_namegpt-5.4, max_loops1, ) flow researcher - writer, reviewer rearrange_system AgentRearrange( agents[researcher, writer, reviewer], flowflow, max_loops1, team_awarenessTrue, ) task Research and write a report on artificial intelligence trends result rearrange_system.run(task)flow 语法中-表示顺序执行researcher 先跑,表示并发执行writer 与 reviewer 并行。在 swarms/structs/agent_rearrange.py 的类文档中明确列出 Custom flow patterns with arrow (-) and comma (,) syntax 与 Team awareness and sequential flow information 两项能力team_awareness参数默认Falseswarms/structs/agent_rearrange.py开启后 Agent 可感知团队结构与执行流程。4.3 Swarm Rearrangement示例 0505_swarm_rearrange.py 将编排粒度提升到智能体群的智能体群两个不同类型的 SwarmRoundRobinSwarm与SequentialWorkflow作为节点通过flow Swarm1 - Swarm2串联from swarms import ( Agent, RoundRobinSwarm, SequentialWorkflow, SwarmRearrange, ) swarm1 RoundRobinSwarm( nameSwarm1, agents[agent1, agent2], max_loops1, ) swarm2 SequentialWorkflow( nameSwarm2, agents[agent3, agent4], max_loops1, ) flow Swarm1 - Swarm2 swarm_rearrange SwarmRearrange( swarms[swarm1, swarm2], flowflow, max_loops1, )这体现了 SwarmRearrange 的三个关键特性Swarm 级重排、flow 模式语法、多层级编排——与示例 04 的 flow 语法一致但操作对象从 Agent 换成了整个 Swarm 实例源码位于 swarms/structs/swarm_rearrange.py。4.4 Debate with Judge示例 12与 Council as a Judge示例 1312_debate_with_judge.py 使用DebateWithJudge的预设智能体模式正/反方 Agent 围绕议题辩论裁判 Agent 迭代精炼后综合出结论from swarms import DebateWithJudge debate DebateWithJudge( preset_agentsTrue, max_loops3, verboseTrue, ) task Should AI be regulated? result debate.run(task)preset_agentsTrue免去手工定义正反方与裁判max_loops3控制迭代精炼轮数。13_council_as_judge.py 则是多维度评估范式多个专业化评审 Agent 并行评估同一段任务输出再聚合成综合报告from swarms import CouncilAsAJudge council CouncilAsAJudge( nameEvaluation-Council, descriptionEvaluates responses across multiple dimensions, model_namegpt-5.4, max_loops1, ) task_response Artificial intelligence will transform healthcare by ... result council.run(task_response)两者的实现分别位于 swarms/structs/debate_with_judge.py 与 swarms/structs/council_as_judge.py。五、工作流编排5.1 GraphWorkflow rustworkx 后端示例 0303_graph_workflow_rustworkx.py 演示有向图结构的高性能工作流编排README 称该后端针对大规模工作流可实现 5-10 倍性能提升from swarms import Agent, GraphWorkflow workflow GraphWorkflow( nameResearch-Analysis-Pipeline, backendrustworkx, verboseTrue, ) workflow.add_nodes([research_agent, analysis_agent, synthesis_agent]) workflow.add_edge(ResearchAgent, AnalysisAgent) workflow.add_edge(AnalysisAgent, SynthesisAgent) task What are the latest trends in renewable energy technology? results workflow.run(task)源码印证swarms/structs/graph_workflow.py 中定义了抽象基类GraphBackend及两个具体实现——NetworkXBackend与RustworkxBackendswarms/structs/graph_workflow.py。Rustworkx 后端在初始化时若检测未安装会直接提示 rustworkx is not installed. Install it with: pip install rustworkx这与 README 故障排查章节一致rustworkx 不可用时可回退到 NetworkX 后端需已安装networkx。此外该后端实现了reverse()等方法以支持边反转swarms/structs/graph_workflow.py说明其并非简单封装而是完整的图算法实现。5.2 GraphWorkflow 批量添加与分层并行示例 1515_graph_workflow_batch_agents.py 展示批量添加 Agent 与 fan-out/fan-in 分层并行模式3 个数据收集 Agent 并行 → 3 个分析 Agent 并行 → 1 个综合 Agentworkflow GraphWorkflow( nameLayer-Based-Parallel-Workflow, backendrustworkx, ) all_agents [ data_collector_1, data_collector_2, data_collector_3, analyst_1, analyst_2, analyst_3, synthesis, ] for agent in all_agents: workflow.add_node(agent) # 第一层并行3 个收集器 - 3 个分析器对应连接 workflow.add_parallel_chain( [data_collector_1, data_collector_2, data_collector_3], [analyst_1, analyst_2, analyst_3], ) # 汇合3 个分析器 - 综合 Agent workflow.add_edges_to_target( [analyst_1, analyst_2, analyst_3], synthesis, ) results workflow.run(Process and analyze data in parallel layers)该脚本同时展示了两个批量 APIadd_parallel_chain两层节点按序建立并行边与add_edges_to_target多条入边指向同一目标两者都定义在 swarms/structs/graph_workflow.py 中。5.3 SpreadsheetSwarm示例 0606_spreadsheet_swarm.py 演示多 Agent 并发处理同一任务并自动以 CSV 追踪结果与元数据from swarms import Agent, SpreadSheetSwarm swarm SpreadSheetSwarm( nameMarket-Analysis-Swarm, descriptionA swarm of specialized financial analysis agents, agents[market_researcher, financial_analyst, risk_assessor], max_loops1, autosaveTrue, ) task What are the top 3 energy stocks to invest in 2024? Provide detailed analysis. result swarm.run(tasktask)autosaveTrue触发自动保存 CSV 输出实现位于 swarms/structs/spreadsheet_swarm.py。六、智能体管理6.1 ModelRouter示例 0707_model_router.py 展示基于任务要求的智能模型选择与执行支持多提供商与成本优化from swarms import ModelRouter router ModelRouter( max_tokens4000, temperature0.5, max_workers10, ) result1 router.run(Analyze the sentiment and key themes in this customer feedback: ...) result2 router.run(Write a creative short story about a robot learning to paint)max_workers10控制内部并发线程数核心参数为生成上限与采样温度。6.2 SelfMoASeq示例 0808_self_moa_seq.py 演示单模型自混合智能体Self-Mixture of Agents Sequential由同一个模型采样多次输出再用滑动窗口方式顺序聚合from swarms import SelfMoASeq self_moa SelfMoASeq( model_namegpt-5.4, temperature0.7, window_size6, reserved_slots3, num_samples10, max_loops5, verboseTrue, ) task Write a comprehensive analysis of the benefits and challenges of renewable energy result self_moa.run(tasktask)参数含义num_samples为初始采样数window_size为每轮聚合窗口大小reserved_slots为上下文预留槽位用于上下文长度管理max_loops为顺序合成轮数上限。实现位于 swarms/structs/self_moa_seq.py。6.3 Autosavingautosaving_example.pyautosaving_example.py 演示 Agent 的自动保存特性同时使用了动态温度与动态上下文窗口from swarms import Agent agent Agent( agent_nameQuantitative-Trading-Agent, agent_descriptionAdvanced quantitative trading and algorithmic analysis agent, model_namegpt-5.4, dynamic_temperature_enabledTrue, max_loops1, dynamic_context_windowTrue, autosaveTrue, ) out agent.run( taskWhat are the top five best energy stocks across nuclear, solar, gas, and other energy sources?, )七、语音智能体09 / 10 / 11三个语音示例统一依赖voice-agents包的StreamingTTSCallback将 Agent 的流式文本输出实时转换为 TTS 语音。7.1 单语音 Agent0909_single_voice_agent.py 是最小语音用例from swarms import Agent from voice_agents import StreamingTTSCallback tts_callback StreamingTTSCallback( voiceonyx, modelopenai/tts-1, ) agent Agent( agent_nameVoice-Agent, system_promptYou are a helpful assistant that speaks responses., model_namegpt-5.4, max_loops1, streaming_onTrue, streaming_callbacktts_callback, )要点streaming_onTrue开启流式输出streaming_callback把每个流式片段交给 TTS 回调实现边生成边朗读voice参数选择音色档案。7.2 多智能体语音辩论1010_multi_agent_voice_debate.py 让 Socrates 与 Simone 两个 Agent 以不同音色辩论并用Conversation结构跟踪对话历史from swarms.structs.conversation import Conversation from swarms.utils.history_output_formatter import history_output_formatter # Socratesvoiceonyx哲学视角Simonevoicenova务实视角 conversation Conversation() conversation.add(roleUser, contenttask) response1 agent1.run(task) conversation.add(roleSocrates, contentresponse1) response2 agent2.run(f{task}\n\nPrevious argument: {response1}) conversation.add(roleSimone, contentresponse2) result history_output_formatter(conversation.get_history(), str-all-except-first)这里引用了两个库内工具Conversationswarms/structs/conversation.py负责角色化历史管理history_output_formatterswarms/utils/history_output_formatter.py支持str-all-except-first等格式化策略将历史渲染为可读文本。不同音色实现了说话人可辨识的差异化输出。7.3 层级语音 Swarm1111_hierarchical_voice_swarm.py 将 Director-Worker 层级结构与 TTS 结合三个 WorkerResearch-Analyst、Data-Analyst、Strategy-Consultant各配一个音色Director 使用独立音色协调与汇总tts_callbacks { Research-Analyst: StreamingTTSCallback(voiceonyx, modelopenai/tts-1), Data-Analyst: StreamingTTSCallback(voicenova, modelopenai/tts-1), Strategy-Consultant: StreamingTTSCallback(voicealloy, modelopenai/tts-1), Director: StreamingTTSCallback(voiceecho, modelopenai/tts-1), } swarm HierarchicalSwarm( nameVoice-Hierarchical-Swarm, directordirector_agent, workers[research_agent, analysis_agent, strategy_agent], max_loops2, )HierarchicalSwarm的实现位于 swarms/structs/hiearchical_swarm.py。八、路由与编排SwarmRouter Round Robin示例 1414_swarm_router_round_robin.py 与示例 02 同属 Round Robin 路由区别在于max_loops2即整个循环执行两轮router SwarmRouter( nameRound-Robin-Router, agents[agent1, agent2, agent3], swarm_typeRoundRobin, max_loops2, verboseTrue, )SwarmRouter通过swarm_type参数支持多种 Swarm 类型swarms/structs/swarm_router.pymax_loops决定轮转轮数verboseTrue打印路由过程便于观察任务在 Agent 间的流转路径。九、常见故障排查README 总结了四类常见问题及处置方式Import 错误确认已执行pip install -U swarms按示例类别补齐可选依赖rustworkx / voice-agents。API Key 错误核对环境变量是否正确设置、Key 是否有效且余额充足。语音 Agent 问题确认voice-agents已安装并验证 OpenAI API Key 具备 TTS 访问权限。Graph Workflow 错误安装 rustworkxpip install rustworkx如需 NetworkX 回退方案确保networkx已安装。十、适用前提与小结本示例集全部示例默认使用gpt-5.4作为model_name因此运行前提是该模型对你所使用的提供商可用通常对应OPENAI_API_KEY示例 01 额外要求SWARMS_API_KEY示例 03/15 要求rustworkx示例 09-11 要求voice-agents与 TTS 权限。所有示例以简洁、教学为目的编写未包含复杂错误处理与生产级模式实际落地时需按自身场景加固。总体而言880 示例集覆盖了四个层面的新能力智能体层Marketplace 提示词、自动保存、动态温度/上下文窗口、编排层AgentRearrange / SwarmRearrange 的 flow 语法、GraphWorkflow 的 rustworkx 后端与批量 API、SwarmRouter 路由、评估层DebateWithJudge、CouncilAsAJudge、以及语音层StreamingTTSCallback 流式 TTS 回调配合 swarms/structs/ 下对应的实现源码与 tests/structs/ 下的测试用例如 test_agent_rearrange.py、test_graph_workflow.py、test_swarm_router.py可作为验证与深入理解本版本更新的完整路径。【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考