大家好,我是一名前端工程师。都说前端“已死”,那与其担心被 AI 替代。不如打入敌人内部,于是我开始折腾 Agent 开发。
折腾下来发现。Agent 的主要不是算法,而是工程能力。这些恰好是我们擅长的事,
这个系列记录我从零搭建多 Agent 程序的完整过程。只聊技术知识和设计思路,代码交给 AI 写。如果你也想从应用层切入 AI。
读完本篇你将学到:
为什么需要多 Agent,单 Agent 的瓶颈在哪;
为什么选它;
多 Agent 架构设计:Dispatcher + 专业 Agent;不过,
串行和并行两种执行模式的实现;
背景与动机
使用者痛点 #1 – Prompt 膨胀失控:
把所有功能塞进一个 Agent,需要在 System Prompt 中列举所有工具、规则和场景;Prompt 越写越臃肿,LLM 容易混淆指令。
实际效果的观点是,调工具时不调、该调时乱调。
使用者痛点 #2 – 难以维护的单体逻辑:
类似让同一个人兼任厨师、服务员、收银员——忙得过来但质量堪忧。
代码容易变成“一团意大利面”。
解决思路 – 分工 + 调度:
让不同的 Agent 各管一摊,再加一个“调度员”决定把任务交给谁。但随之而来的新问题是:
数据传递:多个 Agent 如何共享信息?
执行顺序:如何确保先后次序?
条件路由:什么情况下走哪条方法?
If you keep using raw loops and if‑else statements,code quickly becomes unreadable. A dedicated framework is needed to keep workflow clear and maintainable.
主要概念
单 Agent vs 多 Agent 对比
单 Agent
多 Agent
Prompt
一个巨大的 System Prompt
每个 Agent 一个精简 Prompt
职责
什么都干
各司其职
调试成本
出错难定位
一目了然
性
改 Prompt 越改越乱
加新功能只需新增一个 Agent
SLA / 性能
还行
多了 Dispatcher 的一点开销。但可水平
无区别
多 Agent 架构设计示意图
The system consists of three专业Agent plus a Dispatcher:
"tools" 方法:a ReAct loop that can call external tools。
This tiny example already shows three core concepts:
Status : shared dict across nodes.
b*Node*: ordinary Python function that receives & returns partial state.
b*Edge*: declarative routing .
\end{ul
A conditional edge can decide next node based on state:
def should_continue:
if state>= 5:
return "done"
return "again"
graph.add_conditional_edges(
"greeter",should_continue,{
"again": "counter",# loop back
从"done"来看,END,},)
Step 1️⃣ – 定义统一状态结构
from typing import Annotated,Sequence
from typing_extensions import TypedDict
from langchain_core.messages import BaseMessage
import operator
class AgentState:
"""All nodes share this structure"""
messages: Annotated,operator.add] # 自动追加历史消息
intents: list # Dispatcher 填写的意图序列
说到mode,str # sequential | parallel
current_step: int # 正在处理第几个意图
The trick is using {operator.add}。which makes every node's returned “messages” automatically appended rar than overwritten – preserving conversation history without boilerplate.