首页
看点啥
插画图片
首页 看点啥 Agent 构建 实战指南

Agent 构建 实战指南

2026-07-14 0

一、什么是 Agent

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

构建 Agent 实战指南

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

Agent 的核心特征:

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

二、何时该构建 Agent

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

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

三、Agent 设计基础

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

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

from agents import Agent, WebSearchTool, function_toolimport datetime@function_tooldef 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 至关重要,能减少歧义、改善决策、让工作流更顺畅。

最佳实践:

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

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 启动,循环直到:

Agents.run(agent,[UserMessage("What's the capital of the USA")])

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

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

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

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

拆分指引:

2. 多 Agent 系统

两类常见模式:

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

Manager 模式

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

from agents import Agent, Runnermanager_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 接管执行并按需与用户交互。

from agents import Agent, Runnertechnical_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. 护栏类型

2. 构建护栏

有效经验法则:

  1. 聚焦数据隐私与内容安全;
  2. 按真实边缘案例与失败新增护栏;
  3. 兼顾安全与体验,随 Agent 演进调整护栏。

from agents import (Agent, GuardrailFunctionOutput, InputGuardrailTripwireTriggered,RunContextWrapper, Runner, TResponseInputItem, input_guardrail,Guardrail, GuardrailTripwireTriggered,)from pydantic import BaseModelclass ChurnDetectionOutput(BaseModel):is_churn_risk: boolreasoning: strchurn_detection_agent = Agent(name="Churn Detection Agent",instructions="Identify if the user message indicates a potential customer churn risk.",output_type=ChurnDetectionOutput,)@input_guardrailasync 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 标志着工作流自动化的新时代——系统能在歧义中推理、跨工具行动、以高度自主性处理多步任务,适合复杂决策、非结构化数据或脆弱规则系统。

构建可靠 Agent 的要点:

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

喜欢(0)

上一篇

不写代码也能做 Skill:只要你会打字 30分钟就能跑出第一个

不写代码也能做 Skill:只要你会打字 30分钟就能跑出第一个

下一篇

dify Agent插件报错:save data failed: allocated size 超过 max storage size

dify Agent插件报错:save data failed: allocated size 超过 max storage size
猜你喜欢