用 Laravel AI SDK 构建多智能体工作流
Anthropic 之前发布过一篇广泛传播的文章《Building Effective Agents》系统总结了构建生产级 AI 系统时最实用的几种模式。这些模式的共同点是都已经在真实场景中被反复验证实践性强而且采用范围很广。对 Laravel 开发者来说有个好消息这些模式每一种今天都能在 Laravel 里实现而且代码量很少。借助 Laravel AI SDKAnthropic 提到的五种典型 agent 模式都可以轻量落地。原文中的全部示例都只用了agent()这一个 helper 函数。一行代码就能拉起一个 agent而这本身已足以体现这些模式的表达能力。不过Laravel AI SDK 不止于此。你可以自带专门的 agent class挂接工具配置模型添加 middleware并按生产需求搭建任意复杂度的工作流。可以通过 Composer 安装 Laravel AI SDKcomposer require laravel/ai什么是多智能体工作流单次 LLM 调用非常适合简单任务。但复杂工作——比如代码审查、生成打磨过的邮件、或路由客服工单——你会希望多个 agent 协作各自专注特定任务。多智能体工作流可以帮你做到把任务拆成有序步骤并行执行独立步骤把输入路由给最合适的 specialist在循环中评估并优化输出五种常见模式以及如何用 Laravel AI SDK 实现Prompt Chaining上一位 agent 的输出会成为下一位 agent 的输入。可以把它理解成一条装配线。每一个步骤只负责一件事把结果交给下一步继续处理。这是最简单、也最常见的一种模式。示例Cold Email Generator可以先看一个简单工作流先起草再检查质量如果不达标就继续改写。在 Laravel AI SDK 中这三个 agent 通过Pipeline编排协调。每一步都会拿到完整 payload带着增强后的结果继续传递$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背后都可以对应一个专门的 agentuse 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最后根据复杂度选择成本更低或能力更强的模型。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 汇总结论。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 来创建、修改或删除文件。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只是它们拥有更聚焦的 instructionsuse 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可以把这个工作流理解为先写一段内容给它打分如果没有通过就继续改写最多循环三次。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 只有在approved为false时才会继续改写而且它能够明确知道要修正什么。适用场景适合那些具有清晰质量标准并且结果确实能从多轮迭代中获益的任务例如翻译、写作和代码生成。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适合必须通过迭代才能达到质量要求的任务
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2486147.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!