CatchAdmin PHP 后台管理框架 Logo CatchAdmin

用 Laravel AI SDK 构建多智能体工作流

Anthropic 之前发布过一篇广泛传播的文章《Building Effective Agents》,系统总结了构建生产级 AI 系统时最实用的几种模式。这些模式的共同点是:都已经在真实场景中被反复验证,实践性强,而且采用范围很广。

对 Laravel 开发者来说,有个好消息:这些模式每一种今天都能在 Laravel 里实现,而且代码量很少。借助 Laravel AI SDK,Anthropic 提到的五种典型 agent 模式,都可以轻量落地。

原文中的全部示例,都只用了 agent() 这一个 helper 函数。一行代码就能拉起一个 agent,而这本身已足以体现这些模式的表达能力。不过,Laravel AI SDK 不止于此。你可以自带专门的 agent class,挂接工具,配置模型,添加 middleware,并按生产需求搭建任意复杂度的工作流。

可以通过 Composer 安装 Laravel AI SDK:

bash
composer require laravel/ai

什么是多智能体工作流

单次 LLM 调用非常适合简单任务。但复杂工作——比如代码审查、生成打磨过的邮件、或路由客服工单——你会希望多个 agent 协作,各自专注特定任务。

多智能体工作流可以帮你做到:

  • 把任务拆成有序步骤
  • 并行执行独立步骤
  • 把输入路由给最合适的 specialist
  • 在循环中评估并优化输出

五种常见模式,以及如何用 Laravel AI SDK 实现

Prompt Chaining

上一位 agent 的输出,会成为下一位 agent 的输入。

可以把它理解成一条装配线。每一个步骤只负责一件事,把结果交给下一步继续处理。这是最简单、也最常见的一种模式。

示例:Cold Email Generator

可以先看一个简单工作流:先起草,再检查质量,如果不达标就继续改写。

在 Laravel AI SDK 中,这三个 agent 通过 Pipeline 编排协调。每一步都会拿到完整 payload,带着增强后的结果继续传递:

php
$result = Pipeline::send(['company' => $company, 'role' => $role, 'email' => '', 'review' => []])
    ->through([
        fn ($payload, $next) => $next([...$payload, 'email'  => $this->draftAgent($payload)]),
        fn ($payload, $next) => $next([...$payload, 'review' => $this->reviewAgent($payload)]),
        fn ($payload, $next) => $next($this->improveAgent($payload)),
    ])
    ->thenReturn();

而每一个 pipeline step,背后都可以对应一个专门的 agent:

php
use function Laravel\Ai\{agent};
 
// Agent 1: Draft
private function draftAgent(array $payload): string
{
    return agent(instructions: 'Expert B2B copywriter. Write a concise, personalised cold email.')
        ->prompt("Draft a cold email targeting the {$payload['role']} at {$payload['company']}.")
        ->text;
}
 
// Agent 2: Review (structured output)
private function reviewAgent(array $payload): mixed
{
    return agent(
        instructions: 'Cold email quality analyst. Be strict.',
        schema: fn (JsonSchema $schema) => [
            'hasPersonalisation'    => $schema->boolean()->required(),
            'toneScore'             => $schema->integer()->min(1)->max(10)->required(),
            'callToActionStrength'  => $schema->integer()->min(1)->max(10)->required(),
        ],
    )->prompt($payload['email']);
}
 
// Agent 3: Improve only if scores fall short
private function improveAgent(array $payload): array
{
    $review = $payload['review'];
 
    if ($review['hasPersonalisation'] && $review['toneScore'] >= 7 && $review['callToActionStrength'] >= 7) {
        return $payload;
    }
 
    return [
        ...$payload,
        'email' => agent(instructions: 'Expert B2B copywriter.')
            ->prompt("Rewrite with better personalisation and a stronger CTA:\n{$payload['email']}")
            ->text,
    ];
}

适用场景: 适合那些步骤顺序明确的任务,比如生成、校验、改写、格式化。每个步骤都应该只做一件事,而且尽量把这件事做好。

Routing

先对输入做分类,再把它交给合适的 agent。

与其让一个 agent 试图处理所有情况,不如先交给 classifier 判断输入类型,再根据分类结果选择最匹配的 specialist。不同类型的问题,对应不同 instructions;复杂度不同,也可以使用不同级别的模型。

示例:Customer Support

这个工作流可以理解为:先分类,再挑选合适的 instructions,最后根据复杂度选择成本更低或能力更强的模型。

php
use function Laravel\Ai\{agent};
 
$classification = agent(
    instructions: 'Classify customer support queries.',
    schema: fn (JsonSchema $schema) => [
        'type'       => $schema->string()->required(), // general | refund | technical
        'complexity' => $schema->string()->required(), // simple | complex
    ],
)->prompt("Classify: {$query}");
 
$instructions = match ($classification['type']) {
    'refund'    => 'Customer service agent specialising in refund requests...',
    'technical' => 'Technical support specialist with deep product knowledge...',
    default     => 'Friendly customer service agent...',
};
 
$agent = match ($classification['complexity']) {
    'complex' => new AdvancedSupportAgent($instructions),
    default   => new StandardSupportAgent($instructions), // #[UseCheapestModel]
};
 
return $agent->prompt($query)->text;

原文还提到,可以把 #[UseCheapestModel] attribute 加到 StandardSupportAgent 上,让简单请求使用更快、更便宜的模型,而复杂请求则交给完整模型。由 classifier 来决定哪类请求走哪条路径。

适用场景: 适合输入类型差异较大、复杂度跨度明显,而且单一 prompt 难以兼顾所有情况的任务。

Parallelization

让多个互不依赖的 agent 同时运行。

如果多个步骤之间没有依赖关系,就没有必要一个接一个执行。Laravel 中的 Concurrency::run(),相当于 PHP 里的 Promise.all(),可以同时启动多个 agent,并在所有结果返回后统一汇总。

示例:Code Review

这个工作流里,三个 specialist agent 会同时审查同一段代码,然后由第四个 agent 汇总结论。

php
use function Laravel\Ai\{agent};
 
[$security, $performance, $maintainability] = Concurrency::run([
    fn () => (new SecurityReviewAgent)->prompt($code),
    fn () => (new PerformanceReviewAgent)->prompt($code),
    fn () => (new MaintainabilityReviewAgent)->prompt($code),
]);
 
$summary = agent(instructions: 'Technical lead synthesising code reviews.')
    ->prompt("Summarise:\n" . json_encode([
        ['type' => 'security',        'review' => $security->text],
        ['type' => 'performance',     'review' => $performance->text],
        ['type' => 'maintainability', 'review' => $maintainability->text],
    ]))->text;

这里的三个 agent 会并行完成审查,而汇总代理只会在三份结果全部返回之后才运行,因此它拿到的是完整上下文。

适用场景: 适合同一份输入需要多个独立分析视角,或者希望让多个 specialist 同时审视同一个问题的场景。

Orchestrator-Workers

由一个 orchestrator 负责协调,worker agent 负责具体执行。

orchestrator 会理解完整任务,并判断需要做哪些事情;worker 则是单点专家,只处理自己负责的工作。orchestrator 会自动将这些 worker 作为 tool 调用,并根据任务需要,动态决定调用顺序。

示例:Feature Implementation

在这个例子里,orchestrator agent 接收一个 feature request,然后自动调用多个 worker agent 来创建、修改或删除文件。

php
use function Laravel\Ai\{agent};
 
$response = agent(
    instructions: 'You are a senior software architect. Analyze feature requests and use the available tools to implement each required file change.',
    tools: [
        new CreateFileAgentTool,
        new ModifyFileAgentTool,
        new DeleteFileAgentTool,
    ],
)->prompt("Implement this feature: {$featureRequest}");

这些 tool 本身也可以是 agent() 驱动的 sub-agent,只是它们拥有更聚焦的 instructions:

php
use function Laravel\Ai\{agent};
 
class CreateFileAgentTool implements Tool
{
    public function description(): Stringable|string
    {
        return 'Creates a new file with the appropriate code following best practices.';
    }
 
    public function schema(JsonSchema $schema): array
    {
        return [
            'filePath' => $schema->string()->required(),
            'purpose'  => $schema->string()->required(),
        ];
    }
 
    public function handle(Request $request): Stringable|string
    {
        return agent(
            instructions: 'You are an expert at implementing new files following best practices.',
        )->prompt("Create {$request['filePath']} to support: {$request['purpose']}")->text;
    }
}

这种模式的关键点在于:不需要把“应该改哪些文件”“先做哪一步”硬编码进流程里,orchestrator 会根据 feature request 自己规划并委派。

适用场景: 适合步骤无法提前完全确定、需要模型动态规划与委派的复杂任务。

Evaluator-Optimizer

这类模式遵循的是:先生成,再评估,再改进,而且会循环执行。

有些任务并不是一次生成就能达标。Evaluator-Optimizer 会先生成结果,再让 evaluator 按标准检查,如果不满足条件,就继续改写,直到达到质量门槛,或者达到迭代次数上限。

示例:Content Writer

可以把这个工作流理解为:先写一段内容,给它打分,如果没有通过就继续改写,最多循环三次。

php
use function Laravel\Ai\{agent};
 
$content = agent(instructions: 'You are a clear and concise writer.')
    ->prompt("Write a short paragraph about: {$topic}")->text;
 
$iterations = 0;
 
while ($iterations < 3) {
    $evaluation = agent(
        instructions: 'You are a writing quality evaluator.',
        schema: fn (JsonSchema $schema) => [
            'score'    => $schema->integer()->min(1)->max(10)->required(),
            'approved' => $schema->boolean()->required(),
            'issues'   => $schema->array()->items($schema->string())->required(),
        ],
    )->prompt("Rate this paragraph (approved if score >= 8): {$content}");
 
    if ($evaluation['approved']) {
        break;
    }
 
    $issues = implode(', ', $evaluation['issues']);
    $content = agent(instructions: 'You are a clear and concise writer.')
        ->prompt("Rewrite fixing these issues: {$issues} {$content}")
        ->text;
 
    $iterations++;
}

这个例子里,evaluator 会通过 structured output 返回分数、是否通过,以及具体问题列表;writer 只有在 approvedfalse 时才会继续改写,而且它能够明确知道要修正什么。

适用场景: 适合那些具有清晰质量标准,并且结果确实能从多轮迭代中获益的任务,例如翻译、写作和代码生成。

Laravel AI SDK 如何简化多智能体工作

Anthropic 之所以强调这些模式,是因为它们已经在生产环境里证明了可行性。对于 Laravel 开发者来说,更值得注意的一点是:借助 Laravel AI SDK,这些模式的实现成本并不高。

模式适用场景
Prompt Chaining步骤顺序固定
Routing输入类型或复杂度差异较大
Parallelization独立任务可以同时执行
Orchestrator-Workers需要动态规划与委派
Evaluator-Optimizer需要通过迭代达到质量门槛

先从简单开始。一个 agent() 调用就能处理大多数任务。只有当任务确实需要时,再去主动采用这些模式,你会发现它们实现起来很直接。

如果把上面的对应关系翻成更直白的工程语境,大致可以理解为:

  • Prompt Chaining:适合固定顺序的步骤
  • Routing:适合输入类型或复杂度差异明显的场景
  • Parallelization:适合彼此独立、可以同时执行的任务
  • Orchestrator-Workers:适合需要动态规划和委派的复杂流程
  • Evaluator-Optimizer:适合必须通过迭代才能达到质量要求的任务

Laravel AI SDK 可以通过 Composer 安装,命令如下:

bash
composer require laravel/ai
本作品采用《CC 协议》,转载必须注明作者和本文链接