构建 Agent 实战指南

基于 OpenAI《A practical guide to building agents》核心内容整理。

一、什么是 Agent

Agent 是能够独立替你完成任务的系统。

工作流(workflow)是为达成用户目标而需执行的一系列步骤,例如处理客服问题、预订餐厅、提交代码变更或生成报告。仅集成 LLM 但不用它控制工作流执行的应用(简单聊天机器人、单轮 LLM、情感分类器)不属于 Agent。

Agent 的核心特征:

  1. 用 LLM 管理工作流执行与决策------能识别工作流何时完成,必要时主动纠错;失败时可暂停并交还控制权给用户。
  2. 可访问各类工具------与外部系统交互以获取上下文或采取行动,根据当前状态动态选择工具,始终在明确的护栏内运行。

二、何时该构建 Agent

传统规则引擎像清单,按预设条件标记;LLM Agent 像资深调查员,能评估上下文、识别规则未覆盖的可疑模式。Agent 适合传统确定性方案失效的场景,优先考虑以下曾难以自动化的工作流:

  • 复杂决策:需细腻判断、例外处理或上下文敏感的决策,如客服退款审批。
  • 难维护的规则:规则集过于庞杂、更新成本高且易出错,如供应商安全审查。
  • 重度依赖非结构化数据:需解读自然语言、从文档提取含义或对话式交互,如家庭保险理赔处理。

构建前务必验证用例是否清晰满足上述条件,否则确定性方案即可。

三、Agent 设计基础

Agent 由三个核心组件构成:模型、工具、指令。

python 复制代码
weather_agent = Agent(
    name="Weather agent",
    instructions="You are a helpful agent who can talk to users about the weather",
    tools=[get_weather],
)

1. 选择模型

不同模型在任务复杂度、延迟、成本上各有取舍,工作流中不同任务可选用不同模型。简单检索或意图分类可用更小更快的模型,退款审批等难任务则用更强模型。

推荐做法:

  • 先用最强模型搭原型建性能基线;
  • 再尝试换小模型看是否仍达标,从而定位小模型的成败边界。

原则总结:

  1. 建立 evals 设性能基线;
  2. 用最强模型达成准确率目标;
  3. 在可能处用小模型优化成本与延迟。

2. 定义工具

工具通过底层应用或系统的 API 扩展 Agent 能力。无 API 的遗留系统可用计算机使用模型,像人一样直接操作 UI。每个工具应有标准化定义,便于工具与 Agent 间灵活多对多关系;文档完善、充分测试、可复用的工具能提升可发现性、简化版本管理、避免重复定义。

三类工具:

类型 说明 示例
Data(数据型) 获取执行工作流所需的上下文与信息 查询交易数据库或 CRM、读 PDF、搜索网页
Action(动作型) 与系统交互执行动作,如新增/更新记录、发消息 发邮件短信、更新 CRM、把客服工单转人工
Orchestration(编排型) Agent 本身作为其他 Agent 的工具(见 Manager 模式) 退款 Agent、研究 Agent、写作 Agent
python 复制代码
from agents import Agent, WebSearchTool, function_tool
import datetime

@function_tool
def save_results(output):
    db.insert({
        "output": output,
        "timestamp": datetime.datetime.now(),
    })
    return "File saved"

search_agent = Agent(
    name="Search agent",
    instructions="Help the user search the internet and save results if asked.",
    tools=[WebSearchTool(), save_results],
)

3. 配置指令

高质量指令对 Agent 至关重要,能减少歧义、改善决策、让工作流更顺畅。

最佳实践:

  • 复用现有文档:把操作流程、支持话术、政策文档转化为 LLM 友好的 routine。客服场景下 routine 大致对应知识库中的单篇文章。
  • 引导拆解任务:把密集资源拆成更小更清晰的步骤,减少歧义。
  • 明确动作:每一步对应具体动作或输出(如让用户提供订单号、调 API 取账户详情),连用户可见消息的措辞都要明确,减少解释误差。
  • 覆盖边缘情况:预判常见变体(信息不全、意外提问),用条件步骤或分支处理。

可用 o1/o3-mini 等模型自动从现有文档生成指令:

text 复制代码
You are an expert in writing instructions for an LLM agent.
Convert the following help center document into a clear set of instructions,
written in a numbered list.
The document will be a policy followed by an LLM.
Ensure that there is no ambiguity, and that the instructions are written as directions for an agent.
The help center document to convert is the following {{help_center_doc}}

四、编排(Orchestration)

不要一上来就建全自主复杂架构,客户通常用增量方式更易成功。编排分两类:单 Agent 系统、多 Agent 系统。

1. 单 Agent 系统

单 Agent 通过逐步增加工具即可承担许多任务,复杂度可控、评估与维护更简单。每个新工具扩展能力,而非过早引入多 Agent。

任何编排都需要「run」概念------通常是一个循环,让 Agent 运行直到满足退出条件:工具调用、特定结构化输出、错误、或达到最大轮数。

在 Agents SDK 中,Agent 通过 Runner.run 启动,循环直到:

  • 调用了定义特定输出类型的 final-output 工具;
  • 模型返回不带工具调用的响应(如直接回复用户)。
python 复制代码
Agents.run(
    agent,
    [UserMessage("What's the capital of the USA")]
)

这个 while 循环是 Agent 运行的核心。多 Agent 系统中也允许模型跑多步直到满足退出条件。

管理复杂度的有效策略是提示词模板:用单个灵活基础提示词接受策略变量,而非为各场景维护多个提示词。新场景只需更新变量而非重写整个工作流。

text 复制代码
""" You are a call center agent. You are interacting with
{{user_first_name}} who has been a member for {{user_tenure}}. The user's
most common complains are about {{user_complaint_categories}}. Greet the
user, thank them for being a loyal customer, and answer any questions the
user may have!

何时考虑拆分多 Agent:先最大化单 Agent 能力。多 Agent 能直观分隔概念,但带来额外复杂度与开销,往往单 Agent + 工具已足够。当 Agent 跟不住复杂指令或持续选错工具时,再拆分。

拆分指引:

  • 复杂逻辑:提示词含大量条件分支(if-then-else)、模板难扩展时,按逻辑段拆分。
  • 工具过载:问题不在工具数量而在相似/重叠。有人能管理 15+ 个清晰独立的工具,有人不到 10 个重叠工具就失效。若改进命名、参数、描述仍不行,再用多 Agent。

2. 多 Agent 系统

两类常见模式:

  • Manager(Agent 作为工具):中心「manager」Agent 通过工具调用协调多个专门 Agent,每个处理特定任务/领域。
  • Decentralized(Agent 间 handoff):多个 Agent 对等协作,按专长把任务转交给彼此。

多 Agent 系统可建模为图:Manager 模式中边是工具调用,Decentralized 模式中边是 handoff(转交执行权)。无论哪种模式,都应保持组件灵活、可组合、由清晰结构化提示词驱动。

Manager 模式

中心 LLM(manager)通过工具调用编排专门 Agent 网络,按需委派任务并综合结果,提供统一用户体验。适合只需一个 Agent 控制工作流执行并面向用户的场景。

python 复制代码
from agents import Agent, Runner

manager_agent = Agent(
    name="manager_agent",
    instructions=(
        "You are a translation agent. You use tools given to you to translate. "
        "If asked for multiple translations, you call the relevant tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="translate_to_spanish",
            tool_description="Translate the user's message to Spanish",
        ),
        french_agent.as_tool(
            tool_name="translate_to_french",
            tool_description="Translate the user's message to French",
        ),
        italian_agent.as_tool(
            tool_name="translate_to_italian",
            tool_description="Translate the user's message to Italian",
        ),
    ],
)

async def main():
    msg = input("Translate 'hello' to Spanish, French and Italian for me!")
    orchestrator_output = await Runner.run(manager_agent, msg)
    for message in orchestrator_output.new_messages:
        print(f"- Translation step: {message.content}")

声明式 vs 非声明式图:声明式框架要求预先显式定义每个分支、循环、条件,可视化清晰但随工作流变复杂会变得繁琐、需学 DSL。Agents SDK 采用代码优先方式,直接用熟悉的编程结构表达工作流逻辑,无需预定义整张图,更动态灵活。

Decentralized 模式

Agent 间可相互 handoff 执行权。Handoff 是单向转交,调用 handoff 函数即立即在目标 Agent 上开始执行并传递最新会话状态。适合无需单一 Agent 维持中央控制或综合的场景,让每个 Agent 接管执行并按需与用户交互。

python 复制代码
from agents import Agent, Runner

technical_support_agent = Agent(
    name="Technical Support Agent",
    instructions=(
        "You provide expert assistance with resolving technical issues, "
        "system outages, or product troubleshooting."
    ),
    tools=[search_knowledge_base],
)

sales_assistant_agent = Agent(
    name="Sales Assistant Agent",
    instructions=(
        "You help enterprise clients browse the product catalog, "
        "recommend suitable solutions, and facilitate purchase transactions."
    ),
    tools=[initiate_purchase_order],
)

order_management_agent = Agent(
    name="Order Management Agent",
    instructions=(
        "You assist clients with inquiries regarding order tracking, "
        "delivery schedules, and processing returns or refunds."
    ),
    tools=[track_order_status, initiate_refund_process],
)

triage_agent = Agent(
    name="Triage Agent",
    instructions=(
        "You act as the first point of contact, assessing customer queries "
        "and directing them promptly to the correct specialized agent."
    ),
    handoffs=[
        technical_support_agent,
        sales_assistant_agent,
        order_management_agent,
    ],
)

result = await Runner.run(
    triage_agent,
    input("Could you please provide an update on the delivery timeline for our recent purchase?")
)

初始消息发给 triage_agent,识别到与近期采购相关后 handoff 给 order_management_agent 转交控制权。此模式特别适合会话分流,或希望专门 Agent 完全接管某些任务而原 Agent 无需继续参与。可给第二个 Agent 配置 handoff 回原 Agent,必要时再次转交。

五、护栏(Guardrails)

设计良好的护栏帮助管理数据隐私风险(如防止系统提示泄露)或声誉风险(如强制品牌一致行为)。先针对已识别风险建护栏,发现新漏洞再加层。护栏是任何 LLM 部署的关键组件,但应与强认证授权、严格访问控制、标准软件安全措施配合。

护栏是分层防御------单个护栏通常不足以提供充分保护,多个专门护栏组合才能更坚韧。

1. 护栏类型

  • 相关性分类(Relevance classifier):标记越界查询,确保响应在预期范围内。如「帝国大厦多高」属越界。
  • 安全分类(Safety classifier):检测越狱或提示注入等不安全输入。如试图套出系统指令的消息会被标记为不安全。
  • PII 过滤:审查模型输出,避免不必要暴露个人身份信息。
  • 内容审核(Moderation):标记仇恨、骚扰、暴力等有害或不当输入。
  • 工具风险分级(Tool safeguards):按只读/写、可逆性、所需权限、财务影响给每个工具评低/中/高风险,据此触发自动动作------如高风险函数执行前暂停做护栏检查或升级人工。
  • 规则防护(Rules-based):黑名单、输入长度限制、正则过滤等确定性措施,防已知威胁如禁用词或 SQL 注入。
  • 输出校验(Output validation):通过提示工程与内容检查确保响符合品牌价值观,防止损害品牌。

2. 构建护栏

有效经验法则:

  1. 聚焦数据隐私与内容安全;
  2. 按真实边缘案例与失败新增护栏;
  3. 兼顾安全与体验,随 Agent 演进调整护栏。
python 复制代码
from agents import (
    Agent, GuardrailFunctionOutput, InputGuardrailTripwireTriggered,
    RunContextWrapper, Runner, TResponseInputItem, input_guardrail,
    Guardrail, GuardrailTripwireTriggered,
)
from pydantic import BaseModel

class ChurnDetectionOutput(BaseModel):
    is_churn_risk: bool
    reasoning: str

churn_detection_agent = Agent(
    name="Churn Detection Agent",
    instructions="Identify if the user message indicates a potential customer churn risk.",
    output_type=ChurnDetectionOutput,
)

@input_guardrail
async def churn_detection_tripwire(
    ctx: RunContextWrapper[None],
    agent: Agent,
    input: str | list[TResponseInputItem],
) -> GuardrailFunctionOutput:
    result = await Runner.run(churn_detection_agent, input, context=ctx.context)
    return GuardrailFunctionOutput(
        output_info=result.final_output,
        tripwire_triggered=result.final_output.is_churn_risk,
    )

customer_support_agent = Agent(
    name="Customer Support Agent",
    instructions="You are a customer support agent. You help customers with their questions.",
    input_guardrails=[Guardrail(guardrail_function=churn_detection_tripwire)],
)

async def main():
    await Runner.run(customer_support_agent, "Hello!")
    print("Hello message passed")

    try:
        await Runner.run(customer_support_agent, "I think I might cancel my subscription")
        print("Guardrail didn't trip - this is unexpected")
    except GuardrailTripwireTriggered:
        print("Churn detection guardrail tripped")

Agents SDK 把护栏作为一等概念,默认乐观执行:主 Agent 主动产出,护栏并发运行,违规即抛异常。护栏可是函数或 Agent,强制防越狱、相关性校验、关键词过滤、黑名单、安全分类等策略。

3. 人工干预

人工干预是关键保障,尤其部署早期,帮助识别失败、发现边缘案例、建立稳健评估周期。它让 Agent 无法完成任务时优雅转交控制权------客服场景升级给人工,编码场景交回用户。两类常见触发:

  • 超失败阈值:限制 Agent 重试或动作次数,超限(如多次未能理解用户意图)即升级人工。
  • 高风险动作:敏感、不可逆或高 stakes 动作在 Agent 可靠性建立前应触发人工监督,如取消用户订单、授权大额退款、付款。

六、结论

Agent 标志着工作流自动化的新时代------系统能在歧义中推理、跨工具行动、以高度自主性处理多步任务,适合复杂决策、非结构化数据或脆弱规则系统。

构建可靠 Agent 的要点:

  • 打好基础------强模型 + 定义良好的工具 + 清晰结构化指令;
  • 编排匹配复杂度------从单 Agent 起步,仅在需要时演进到多 Agent;
  • 全程护栏------从输入过滤、工具使用到人工干预,确保安全可预测。

部署路径非全有或全无:从小处起步、用真实用户验证、逐步扩展能力

相关推荐
RockHopper20251 小时前
企业智能体为何应面向“活动”而非“数据”——一个架构范式的转变
大数据·人工智能·智能体·活动驱动
研來如此1 小时前
图像文件大小
人工智能·算法·计算机视觉
2zcode1 小时前
项目文档:基于语音信号分析与机器学习的帕金森病智能检测系统
人工智能·机器学习·帕金森病
liang89991 小时前
Anconda常用命令
linux·人工智能·conda
JustNow_Man1 小时前
【openspec】存量项目中如何使用进行开发
大数据·人工智能
minge00011 小时前
【世界杯中的AI】(2026-07-12)狂野逆转与AI神预测:世界杯1/4决赛夜,科技如何“封神”?
人工智能·科技·世界杯
枫叶丹41 小时前
Hermes Agent 搭建全流程:从本机试跑到可持续运行的个人 AI Agent
人工智能·microsoft·hermes
xd1855785551 小时前
鸿蒙PC时代的AI快递查询应用:基于鸿蒙Flutter框架的跨端创新实践
人工智能·flutter·华为·harmonyos·鸿蒙
陈嘿萌2 小时前
ICML 2026 | MobileFusion:仅4K参数,通过结构重参数化让图像融合跑上移动端
人工智能·计算机视觉·图像融合·厦门大学·icml2026·mobilefusion