Swarms 单 Agent 高级推理实战指南:自一致性、Agent 判定、GKP 与推理双引擎的完整示例解析
2026/9/17 21:09:56 网站建设 项目流程

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_name="gpt-5.4", max_loops=1) 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_loops=1,这里即一轮评审结论)。可以看到,使用方式与"单次采样"几乎一样简单,差别只在于:输入从任务变成了候选回答集合,输出从答案变成了评审意见。

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):当输入中出现correctgoodexcellentperfect等正向关键词时返回 1,否则返回 0。配合AgentJudge(..., return_score=True)即可把评审结果转成 0/1 标量奖励,用于强化学习或排序筛选。

2.3 自定义评估标准(Evaluation Criteria)

agent_judge_evaluation_criteria_example.py 展示了比基础用法更精细的控制——通过evaluation_criteria传入"指标: 权重"字典,让裁判按指定维度加权评审:

from swarms.agents.agent_judge import AgentJudge # 例1:通用回答评审 judge = AgentJudge( model_name="claude-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_name="code_judge",用code_correctness: 0.4code_efficiency: 0.3code_readability: 0.3评审一段 Kadane 算法实现。
  • 多回答横向对比:对同一问题(如 CAP 定理)的多个 Agent 回答,用accuracy: 0.6completeness: 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_loops=1, model_name="gpt-5.4", system_prompt="You are a helpful assistant that can answer questions and help with tasks.", description="You 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( name="reasoning-agent", description="A reasoning agent that can answer questions and help with tasks.", model_name="gpt-5.4", system_prompt="You are a helpful assistant that can answer questions and help with tasks.", max_loops=1, num_samples=3, # 独立采样的次数(默认值为 1) eval=False, # 是否开启评估模式 random_models_on=False, # 是否随机切换模型以增加多样性 majority_voting_prompt=None, # 自定义多数投票提示词,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.py(class SelfConsistencyAgent,L114)。其思路对应自一致性论文范式:让同一个 Agent 对同一问题做多次带随机性的采样,再通过多数投票或提示聚合得到更稳定的最终答案,可有效缓解单次推理被"自信的错误"带偏的问题。

四、GKPAgent:先"生成知识"再回答的提示增强

gpk_agent.py 演示了生成式知识提示(Generated Knowledge Prompting, GKP)Agent。它的核心思想是:面对开放问题先让模型生成若干条相关知识(knowledge items),再基于这些知识组织最终答案,从而为推理提供"外挂记忆"。

from swarms.agents.gkp_agent import GKPAgent # 初始化 GKP Agent agent = GKPAgent( agent_name="gkp-agent", model_name="gpt-5.4", # 底层模型 num_knowledge_items=6, # 每个查询生成 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 {i+1}: {queries[i]}") print(f"Answer: {result}")

关键参数是num_knowledge_items:它控制每个查询先被拆解出多少条知识线索。从 swarms/agents/gkp_agent.py(class GKPAgent,L311)的实现看,run()接收查询列表并逐条处理,num_knowledge_items会在默认值 6 的基础上按查询数量等比例放大生成的知识规模,再进入"知识 → 推理 → 回答"的链路。适合需要事实依据支撑的问答,例如物理、历史、法律类问题。

五、IterativeReflectiveExpansion:迭代反思式推理

iterative_agent.py 展示了迭代反思扩展(Iterative Reflective Expansion, IRE)算法:

from swarms.agents.i_agent import IterativeReflectiveExpansion agent = IterativeReflectiveExpansion( max_loops=1, # 反思-扩展循环的次数 ) agent.run("What is the 40th prime number?")

实现位于 swarms/agents/i_agent.py(class IterativeReflectiveExpansion,L40)。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_name="reasoning-agent", description="A reasoning agent that can answer questions and help with tasks.", model_name="gpt-5.4", system_prompt="You are a helpful assistant that can answer questions and help with tasks.", max_loops=1, swarm_type="self-consistency", # 关键:选择推理模式 num_samples=3, # 生成 3 份独立回答 eval=False, random_models_on=False, majority_voting_prompt=None, ) 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_name="qft_reasoning_agent", description="A specialized reasoning agent for answering questions and solving problems in quantum field theory.", model_name="groq/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_loops=1, swarm_type="reasoning-duo", # 双 Agent 推理模式 output_type="dict-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_types(L20-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反思(Reflexion)
"GKPAgent"_create_gkp_agent生成式知识提示

__init__中还会执行reliability_check()(L116-L134):max_loops必须大于 0、model_name非空、swarm_type非空,否则抛出ReasoningAgentInitializationError。路由器的其他参数包括:num_samples(自一致性采样数)、num_knowledge_items(GKP 知识条数)、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_prompt="You 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-20240620),max_loops控制协作轮数,output_type="dict-all-except-first"决定返回格式:

from swarms import ReasoningDuo router = ReasoningDuo( agent_name="qft_reasoning_agent", description="A specialized reasoning agent for ... quantum field theory.", model_name="claude-3-5-sonnet-20240620", system_prompt=("...QFT 领域提示词..."), max_loops=2, swarm_type="reasoning-duo", output_type="dict-all-except-first", reasoning_model_name="groq/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.py(class ReasoningDuo,L21)内部维护两个真正的 Agent:

  • reasoning_agent(L64-L73):名字自动加-reasoning后缀,使用 REASONING_PROMPT 作为系统提示词,负责深层分析与策略设计;
  • main_agent(L75-L84):名字加-main后缀,使用用户传入的system_prompt,负责把思考结果转化为最终执行答案。

两者共享一个 Conversation(L61),_run_agent()(L86-L117)把对话以"类型化聊天轮次"的方式交付:每个 Agent 把自己的历史输出读作assistant轮,把对方的输出读作带标签的user轮,避免把双方文本揉成一个扁平块。两个 Agent 都开启了dynamic_temperature_enabled=True,即在推理时动态调节采样温度。reasoning_model_name为 None 时(L58-L59),思考者模型会回退为model_names[0]

7.3 手写版 Think-Act 双 Agent

reasoning_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( f"From {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 框架运行,请先确认:

  1. 安装依赖:参照仓库 requirements.txt 与 pyproject.toml 安装;模型调用依赖 LiteLLM 生态,仓库已有 litellm_wrapper.py 等封装。
  2. 配置模型密钥:示例中的gpt-5.4claude-3-7-sonnet-20250219groq/moonshotai/kimi-k2-instructtogether_ai/...分别对应 OpenAI、Anthropic、Groq、Together 等提供方,需在环境变量中配置对应 API Key(如OPENAI_API_KEYANTHROPIC_API_KEYGROQ_API_KEYTOGETHER_API_KEY)。部分示例使用 dotenv 的load_dotenv()加载.env文件。
  3. 运行方式:在仓库根目录直接执行,例如:
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
  1. 模型可用性:示例中的具体模型名(如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_type="self-consistency",调大num_samples用多数投票压住方差;
  • 需要质量控制与迭代改进(代码评审、答案打分、RL 奖励信号)→ 使用 AgentJudge,必要时配合evaluation_criteriareturn_score=True
  • 需要先想后做(战略规划、方案落地)→ 使用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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询