
Swarms 单 Agent 高级推理实战指南自一致性、Agent 判定、GKP 与推理双引擎的完整示例解析【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms本篇技术指南以仓库 examples/single_agent/reasoning 目录为骨架系统讲解 Swarms 框架中单 Agent 的高级推理能力从自一致性采样Self-Consistency、Agent 判定系统AgentJudge、生成式知识提示GKP、迭代反思扩展IRE到双 Agent 推理协作ReasoningDuo与可统一调度的推理路由器ReasoningAgentRouter。读完本文你将掌握每一类推理模式的实际代码写法、关键参数含义以及它们在底层源码中的运行机制可直接迁移到自己的 Agent 应用场景中。一、推理能力全景从一问一答到多路径深思传统 Agent 采用提示词 → 单次采样 → 直接输出的简单模式面对数学证明、金融策略、量子物理等复杂问题时容易陷入单一路径的偏差。Swarms 在 examples/single_agent/reasoning 目录下集中提供了 11 个示例覆盖四类推理范式推理范式核心思想对应示例文件自一致性Self-Consistency多次独立采样多数投票聚合降低单次采样方差consistency_agent.py、consistency_example.py评审判定Agent Judging由独立裁判模型评估输出质量并给出改进建议agent_judge_example.py、agent_judge_evaluation_criteria_example.py知识增强GKP / IRE先生成相关知识或迭代反思再作答gpk_agent.py、iterative_agent.py多角色协作Reasoning Duo / Router思考者与执行者分工或按类型动态路由reasoning_duo.py、reasoning_duo_example.py、reasoning_duo_test.py、reasoning_agent_router.py、reasoning_agent_router_now.py这些示例演示了超越简单提示-响应模式的复杂推理能力也是本文下面各节逐一生动的对象。二、AgentJudge让一个模型为另一个模型打分2.1 最小可用示例agent_judge_example.py 演示了最基础的判定用法收集多个 Agent 对同一数学任务的输出交给裁判模型统一评估。from swarms.agents.agent_judge import AgentJudge judge AgentJudge(model_namegpt-5.4, max_loops1) outputs [ 1. Agent CalculusMaster: After careful evaluation, I have computed the integral ..., 2. Agent DerivativeDynamo: In my analysis of the function sin(x) ..., 3. Agent LimitWizard: Upon evaluating the limit as x approaches 0 ..., # ... 更多 Agent 输出 ] print(judge.run(outputs))其中outputs是一个字符串列表每项是某个被评审 Agent 的完整回答。judge.run(outputs)会按轮次返回评估结果因为max_loops1这里即一轮评审结论。可以看到使用方式与单次采样几乎一样简单差别只在于输入从任务变成了候选回答集合输出从答案变成了评审意见。2.2 底层执行机制核心实现在 swarms/agents/agent_judge.py 中AgentJudge.__init__L193-L227内部封装了一个真正的 Agent 实例并把系统提示词设为get_agent_judge_prompt()返回的裁判协议L48-L90。该协议要求裁判先做上下文评估、输入校验、基于证据的分析最终以EVALUATION_COMPLETE \boxed{...}的固定格式给出结论。每次评审时step()L253-L320会用get_task_evaluation_prompt(outputs)L93-L113构造评审指令要求裁判依次给出优点Strengths、缺点Weaknesses、改进建议Suggestions、事实性错误指正。run()L322-L380会在max_loops内迭代每一轮把上一轮裁判结论以对话历史形式messages_for取历史、agent_answer记录回答回传给裁判实现迭代式评审 上下文累积。run_batched()L382-L399则批量处理多个任务返回每个任务对应的评审列表。值得注意的是源码中还内置了get_reward()L15-L45当输入中出现correct、good、excellent、perfect等正向关键词时返回 1否则返回 0。配合AgentJudge(..., return_scoreTrue)即可把评审结果转成 0/1 标量奖励用于强化学习或排序筛选。2.3 自定义评估标准Evaluation Criteriaagent_judge_evaluation_criteria_example.py 展示了比基础用法更精细的控制——通过evaluation_criteria传入指标: 权重字典让裁判按指定维度加权评审from swarms.agents.agent_judge import AgentJudge # 例1通用回答评审 judge AgentJudge( model_nameclaude-3-7-sonnet-20250219, evaluation_criteria{ correctness: 0.5, # 正确性权重 0.5 problem_solving_approach: 0.3, # 解题思路权重 0.3 explanation_clarity: 0.2, # 解释清晰度权重 0.2 }, ) evaluation judge.run(task_response) print(evaluation[0])该示例还提供了三种典型场景通用回答评审对二分查找时间复杂度这类问答进行多维打分上述代码。代码评审设置agent_namecode_judge用code_correctness: 0.4、code_efficiency: 0.3、code_readability: 0.3评审一段 Kadane 算法实现。多回答横向对比对同一问题如 CAP 定理的多个 Agent 回答用accuracy: 0.6、completeness: 0.4评判谁更优。从源码看evaluation_criteria会在两处生效enhanced_prompt()L240-L251把指标写入系统提示词Evaluation Criteria:\n- correctness: weight 0.5 ...step()L299-L309再把它拼进任务指令要求裁判请使用这些特定评估标准及其权重。所以权重本身并不参与数值运算而是以指令形式引导裁判的注意力分配——这一点在调参时值得留意。三、SelfConsistencyAgent多次采样 多数投票的可靠性提升3.1 基础用法consistency_agent.py 是最简形态from swarms import SelfConsistencyAgent agent SelfConsistencyAgent( max_loops1, model_namegpt-5.4, system_promptYou are a helpful assistant that can answer questions and help with tasks., descriptionYou are a helpful assistant that can answer questions and help with tasks., ) agent.run(Create a comprehensive proof for the The Birch and Swinnerton-Dyer Conjecture)3.2 带参数的完整配置consistency_example.py 给出了自一致性模式的核心参数适合直接复制到金融分析等需要稳健结论的场景from swarms import SelfConsistencyAgent reasoning_agent_router SelfConsistencyAgent( namereasoning-agent, descriptionA reasoning agent that can answer questions and help with tasks., model_namegpt-5.4, system_promptYou are a helpful assistant that can answer questions and help with tasks., max_loops1, num_samples3, # 独立采样的次数默认值为 1 evalFalse, # 是否开启评估模式 random_models_onFalse, # 是否随机切换模型以增加多样性 majority_voting_promptNone, # 自定义多数投票提示词None 表示使用默认提示 ) result reasoning_agent_router.run( What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf. ) print(Financial Strategy Result:) print(result)参数语义如下参数默认值作用num_samples1对同一问题生成多少份独立回答样本越多投票越稳健但成本线性上升evalFalse开启后对采样结果进行评估结合评审机制一般调试时开启random_models_onFalse开启后每个样本可能使用不同模型牺牲一致性换取多样性majority_voting_promptNone覆盖聚合阶段使用的多数投票提示词实现类位于 swarms/agents/consistency_agent.pyclass SelfConsistencyAgentL114。其思路对应自一致性论文范式让同一个 Agent 对同一问题做多次带随机性的采样再通过多数投票或提示聚合得到更稳定的最终答案可有效缓解单次推理被自信的错误带偏的问题。四、GKPAgent先生成知识再回答的提示增强gpk_agent.py 演示了生成式知识提示Generated Knowledge Prompting, GKPAgent。它的核心思想是面对开放问题先让模型生成若干条相关知识knowledge items再基于这些知识组织最终答案从而为推理提供外挂记忆。from swarms.agents.gkp_agent import GKPAgent # 初始化 GKP Agent agent GKPAgent( agent_namegkp-agent, model_namegpt-5.4, # 底层模型 num_knowledge_items6, # 每个查询生成 6 条相关知识 ) queries [ What are the implications of quantum entanglement on information theory?, ] results agent.run(queries) for i, result in enumerate(results): print(f\nQuery {i1}: {queries[i]}) print(fAnswer: {result})关键参数是num_knowledge_items它控制每个查询先被拆解出多少条知识线索。从 swarms/agents/gkp_agent.pyclass GKPAgentL311的实现看run()接收查询列表并逐条处理num_knowledge_items会在默认值 6 的基础上按查询数量等比例放大生成的知识规模再进入知识 → 推理 → 回答的链路。适合需要事实依据支撑的问答例如物理、历史、法律类问题。五、IterativeReflectiveExpansion迭代反思式推理iterative_agent.py 展示了迭代反思扩展Iterative Reflective Expansion, IRE算法from swarms.agents.i_agent import IterativeReflectiveExpansion agent IterativeReflectiveExpansion( max_loops1, # 反思-扩展循环的次数 ) agent.run(What is the 40th prime number?)实现位于 swarms/agents/i_agent.pyclass IterativeReflectiveExpansionL40。IRE 的思路是对一个问题先做一轮推理然后反思自己的回答发现缺口后再次扩展推理循环往复由max_loops控制轮数。相较于一次性作答它在每轮都把自己的输出作为下一轮输入从而逼近更深层的结论——对于40 以内的第 40 个素数这类需要精确逐步演算的问题尤其有效。六、ReasoningAgentRouter一个路由器调度所有推理模式6.1 自一致性路由示例reasoning_agent_router.py 通过统一接口调用自一致性模式from swarms.agents.reasoning_agent_router import ReasoningAgentRouter reasoning_agent_router ReasoningAgentRouter( agent_namereasoning-agent, descriptionA reasoning agent that can answer questions and help with tasks., model_namegpt-5.4, system_promptYou are a helpful assistant that can answer questions and help with tasks., max_loops1, swarm_typeself-consistency, # 关键选择推理模式 num_samples3, # 生成 3 份独立回答 evalFalse, random_models_onFalse, majority_voting_promptNone, ) result reasoning_agent_router.run( What is the best possible financial strategy to maximize returns but minimize risk? ... ) print(Financial Strategy Result:) print(result)6.2 推理双引擎路由示例领域定制reasoning_agent_router_now.py 展示了为特定领域量子场论 QFT定制系统提示词、并切换到reasoning-duo模式的写法同时演示了output_type参数from swarms.agents.reasoning_agent_router import ReasoningAgentRouter router ReasoningAgentRouter( agent_nameqft_reasoning_agent, descriptionA specialized reasoning agent for answering questions and solving problems in quantum field theory., model_namegroq/moonshotai/kimi-k2-instruct, system_prompt( You are a highly knowledgeable assistant specializing in quantum field theory (QFT). You can answer advanced questions, explain concepts, and help with tasks related to QFT, including but not limited to Lagrangians, Feynman diagrams, renormalization, quantum electrodynamics, quantum chromodynamics, and the Standard Model. Provide clear, accurate, and detailed explanations, and cite relevant equations or references when appropriate. ), max_loops1, swarm_typereasoning-duo, # 双 Agent 推理模式 output_typedict-all-except-first, # 输出除首轮外的全部轮次结果 ) out router.run( Explain the significance of spontaneous symmetry breaking in quantum field theory. ) print(out)6.3 路由器的工厂机制源码解析swarms/agents/reasoning_agent_router.py 的核心设计是一个工厂映射表L136-L154。swarm_type被定义为字面量联合类型agent_typesL20-L30支持以下取值swarm_type取值映射工厂对应推理模式reasoning-duo/reasoning-agent_create_reasoning_duo双 Agent 推理协作self-consistency/consistency-agent_create_consistency_agent自一致性多数投票ire/ire-agent_create_ire_agent迭代反思扩展AgentJudge_create_agent_judge评审判定ReflexionAgent_create_reflexion_agent反思ReflexionGKPAgent_create_gkp_agent生成式知识提示__init__中还会执行reliability_check()L116-L134max_loops必须大于 0、model_name非空、swarm_type非空否则抛出ReasoningAgentInitializationError。路由器的其他参数包括num_samples自一致性采样数、num_knowledge_itemsGKP 知识条数、memory_capacity记忆容量、reasoning_model_name双 Agent 模式中思考者的模型默认gpt-4o等。这意味着换一种推理模式只需改一个swarm_type参数其余配置模型、提示词、循环次数、输出格式保持统一非常适合做推理策略的 A/B 对比实验。七、ReasoningDuo思考者与执行者的分工协作7.1 库内置双 Agent 推理reasoning_duo_example.py 使用框架内置的ReasoningDuo并演示单任务run与批量batched_run两种入口from swarms.agents.reasoning_duo import ReasoningDuo reasoning_duo ReasoningDuo( system_promptYou are a helpful assistant that can answer questions and help with tasks., model_names[gpt-5.4, gpt-5.4], # 两个 Agent 的模型思考者 / 执行者 ) # 单任务 reasoning_duo.run( What is the best possible financial strategy to maximize returns but minimize risk? ... ) # 批量任务 reasoning_duo.batched_run( [ What is the best possible financial strategy to maximize returns but minimize risk? ..., What is the best possible financial strategy to maximize returns but minimize risk? ..., ] )reasoning_duo_test.py 则展示了更完整的参数面reasoning_model_name可以让思考者使用与主 Agent 不同的模型例如思考者用groq/moonshotai/kimi-k2-instruct主 Agent 用claude-3-5-sonnet-20240620max_loops控制协作轮数output_typedict-all-except-first决定返回格式from swarms import ReasoningDuo router ReasoningDuo( agent_nameqft_reasoning_agent, descriptionA specialized reasoning agent for ... quantum field theory., model_nameclaude-3-5-sonnet-20240620, system_prompt(...QFT 领域提示词...), max_loops2, swarm_typereasoning-duo, output_typedict-all-except-first, reasoning_model_namegroq/moonshotai/kimi-k2-instruct, ) out router.run( Explain the significance of spontaneous symmetry breaking in quantum field theory. ) print(out)7.2 双 Agent 的底层实现swarms/agents/reasoning_duo.pyclass ReasoningDuoL21内部维护两个真正的 Agentreasoning_agentL64-L73名字自动加-reasoning后缀使用 REASONING_PROMPT 作为系统提示词负责深层分析与策略设计main_agentL75-L84名字加-main后缀使用用户传入的system_prompt负责把思考结果转化为最终执行答案。两者共享一个 ConversationL61_run_agent()L86-L117把对话以类型化聊天轮次的方式交付每个 Agent 把自己的历史输出读作assistant轮把对方的输出读作带标签的user轮避免把双方文本揉成一个扁平块。两个 Agent 都开启了dynamic_temperature_enabledTrue即在推理时动态调节采样温度。当reasoning_model_name为 None 时L58-L59思考者模型会回退为model_names[0]。7.3 手写版 Think-Act 双 Agentreasoning_duo.py示例目录内是一份不依赖框架内置 ReasoningDuo的手写双 Agent 示例适合理解双 Agent 分工的本质。它用两个独立 Agent 实例Strategic-Thinker系统提示词强调问题拆解、多视角评估、风险评估、策略方案生成、决策矩阵、系统思维使用together_ai/deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free经 Together 路由读取TOGETHER_API_KEY等推理型模型Action-Executor系统提示词强调实施计划、资源优化、执行管理、风险管理、干系人管理、持续改进负责把思考结果落地为行动。串联逻辑在run_reasoning_duo(task)中只有两步def run_reasoning_duo(task: str): # Step 1: Thinking Agent 深度分析 thinking_result thinking_agent.run(task) # Step 2: Action Agent 基于思考结果执行 action_result action_agent.run( fFrom {thinking_agent.agent_name}: {thinking_result} ) return action_result if __name__ __main__: run_reasoning_duo(What is the best way to invest $1000?)这份示例的价值在于展示了双 Agent 协作的提示词工程模板一份完整的思考者提示词与执行者提示词可直接复用也直观说明了框架内置 ReasoningDuo 想自动化封装的分工逻辑。八、环境准备与运行前提以上示例均基于 Swarms 框架运行请先确认安装依赖参照仓库 requirements.txt 与 pyproject.toml 安装模型调用依赖 LiteLLM 生态仓库已有 litellm_wrapper.py 等封装。配置模型密钥示例中的gpt-5.4、claude-3-7-sonnet-20250219、groq/moonshotai/kimi-k2-instruct、together_ai/...分别对应 OpenAI、Anthropic、Groq、Together 等提供方需在环境变量中配置对应 API Key如OPENAI_API_KEY、ANTHROPIC_API_KEY、GROQ_API_KEY、TOGETHER_API_KEY。部分示例使用 dotenv 的load_dotenv()加载.env文件。运行方式在仓库根目录直接执行例如python examples/single_agent/reasoning/agent_judge_example.py python examples/single_agent/reasoning/consistency_example.py python examples/single_agent/reasoning/reasoning_agent_router.py模型可用性示例中的具体模型名如gpt-5.4以仓库当前代码为准实际运行时请替换为你账户可访问的模型标识若追求确定性可将dynamic_temperature_enabled关闭或固定 seed。九、测试与验证推理能力有据可查仓库在 tests/agents 下为这些推理组件提供了自动化测试可作为开箱即用的验证入口与实现对照test_agent_judge.py覆盖 AgentJudge 的初始化、step/run/run_batched以及评估结果结构test_reasoning_duo.py覆盖 ReasoningDuo 的单任务与批量运行test_consistency_agent.py在 tests/agents 目录中验证自一致性 Agent 的参数传递与运行链路test_context_compressor.py 等其余测试佐证相关 Agent 基础设施。此外ReasoningAgentRouter复用了 execution_utils.batched_run 实现批量执行其输出格式由 output_types.py 中的OutputType枚举如dict-all-except-first统一控制相关行为同样有测试覆盖。十、总结如何为你的任务挑选推理模式综合以上示例可以按任务特征做如下选型需要确定性答案数学、编码、金融配置→ 优先swarm_typeself-consistency调大num_samples用多数投票压住方差需要质量控制与迭代改进代码评审、答案打分、RL 奖励信号→ 使用 AgentJudge必要时配合evaluation_criteria与return_scoreTrue需要先想后做战略规划、方案落地→ 使用reasoning-duo让思考者与执行者各司其职也可参考手写版双 Agent 提示词模板定制角色需要事实支撑的开放问答物理、历史、法律→ 使用GKPAgent通过num_knowledge_items控制知识预生成规模需要逐步逼近深解证明题、多步推理→ 使用IterativeReflectiveExpansion适当增大max_loops需要快速切换多种策略做对比实验→ 统一走 ReasoningAgentRouter只改swarm_type即可切换全部模式。无论是接入手写双 Agent 的精细控制还是借助路由器的一键切换examples/single_agent/reasoning目录下的 11 个示例都提供了可直接运行、可继续改造的起点配合 tests/agents 中的测试用例足以支撑你在 Swarms 中构建稳健、可解释、可评测的高级推理 Agent。【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考