Agent 多 Agent 路由与调度

July 18, 2026 · View on GitHub

在工作流中并行调度多个 Neuron Agent,路由策略与执行解耦:AgentRouterInterface 决定跑哪些 Agent,AgentScheduler 负责协程并发与结果汇聚。


目录结构

Agent/
├── AgentRouterInterface.php   # route(RouterContext): list<agentId>
├── AgentScheduler.php         # GoWaitGroup 并行执行 + 写入 state.agentOutputs
├── RouterContext.php          # runId / WorkflowState / availableAgents / timeout
├── Router/
│   ├── StaticRouter.php       # 固定列表
│   ├── RuleRouter.php         # Symfony EL / callable 规则
│   ├── WeightedRouter.php     # 加权随机
│   ├── CostAwareRouter.php    # 预算内最低成本
│   ├── RoundRobinRouter.php   # 轮询负载均衡
│   └── LLMRouter.php          # LLM 决策路由(需 Provider)
└── Tests/

核心原理

RouterContext ──route()──► [agentId, ...] ──AgentScheduler──► agentOutputs
                              │                    │
                         策略可插拔            协程外串行 / 协程内并行
组件职责
Router只读 WorkflowState,返回待执行 agentId 列表
Scheduler执行 tasks[agentId],异常包装为 ['error' => ...],写入 state.setAgentOutput

CLI / 单测无协程时自动串行执行,不依赖 Swoole Worker。


快速上手

use Swoolefy\Support\Agent\AgentScheduler;
use Swoolefy\Support\Agent\Router\StaticRouter;
use Swoolefy\Support\Agent\RouterContext;
use Swoolefy\Support\Neuron\NeuronFactory;
use Swoolefy\Support\Workflow\State\WorkflowState;

$scheduler = new AgentScheduler(new NeuronFactory());
$state = new WorkflowState(data: ['query' => 'hello']);
$ctx = new RouterContext(runId: 'run-1', state: $state, availableAgents: ['a', 'b']);

$results = $scheduler->runParallel($ctx, [
    'a' => fn ($ctx, $factory) => 'answer-a',
    'b' => fn ($ctx, $factory) => 'answer-b',
], new StaticRouter(['a', 'b']));

// $results['a'] === 'answer-a'
// $state->agentOutput('a') === 'answer-a'

路由策略对照

路由适用场景返回
StaticRouter固定并行集合声明的 agentId
RuleRouter按 state 字段分支命中规则的 agentId
WeightedRouter灰度 / A-B按权重随机子集
CostAwareRouter成本控制预算内最便宜的一个
RoundRobinRouter负载均衡轮询单个 agentId
LLMRouter复杂意图分流LLM 选出的 agentId

RoundRobinRouter 的游标写入当前 WorkflowState.meta,不是 Router 实例属性;即使 CompiledWorkflow 被 Worker 缓存复用,不同 Run 之间也不会共享轮询位置。

CostAwareRouter 读取 state.estimatedTokens(优先)或按 query 长度估算;单价为每 1k token 美元。

new CostAwareRouter([
    'cheap' => 0.001,
    'premium' => 0.03,
], budgetUsd: 0.01);

工作流内更常见的是通过 AgentParallelNodeSupport/AI)挂载 Router,无需手写 Scheduler。


运行测试

composer test:agent
# 或
composer test:agent
# 或 ./vendor/bin/phpunit --filter AgentModuleTest