写点什么

AI Agent 设计原则与最佳实践

作者:方品
  • 2025-12-05
    上海
  • 本文字数:13739 字

    阅读完需:约 45 分钟

Agent 设计准则三大准则:透明:让用户感知 Agent 的存在,以及其行为可控:用户可以设置 agent 的偏好,并对 Agent 进行指令,以及监控其行为一致性:Agent 行为保持一致,避免用户对 Agent 行为产生困惑透明性设计透明性要求 Agent 在交互过程中清晰表达其意图、能力和限制:身份标识:Agent 应该明确告知用户其 AI 身份,避免误导能力边界:清楚说明 Agent 能做什么,不能做什么决策解释:在做出重要决策时,提供简要的推理过程状态反馈:及时告知用户当前正在执行的操作和进度可控性实现可控性确保用户能够有效指导和干预 Agent 的行为:偏好设置:允许用户设置个人偏好,如语言风格、详细程度等指令覆盖:用户指令应优先于 Agent 的默认行为中断机制:提供暂停、撤销、重置等控制选项监控面板:展示 Agent 的执行历史和决策依据一致性保障一致性避免用户产生困惑,建立可预期的交互体验:行为模式:保持相似场景下的一致响应模式语言风格:维持统一的沟通语气和专业程度决策逻辑:避免自相矛盾的决策和建议错误处理:统一优雅的错误提示和恢复机制工具使用设计模式工具使用分类:动态信息检索代码执行 workflow 自动流内容生成和编辑 agent 工具使用中需要实现的内容包括:function/tool schema 定义 tool 执行逻辑实现消息处理工具集成框架错误处理状态管理工具设计原则 Schema 设计最佳实践 schema 定义:告诉大模型工具的用途和用法:

Function description for the model to read

tools = [{"type": "function","function": {"name": "get_current_time","description": "Get the current time in a given location","parameters": {"type": "object","properties": {"location": {"type": "string","description": "The city name, e.g. San Francisco",},},"required": ["location"],},}}]工具命名规范语义化命名:函数名应准确反映其功能,如 calculate_mortgage_payment 动词开头:使用动词+名词的结构,如 get_weather_data 避免歧义:避免使用可能产生多种理解的名称保持一致:相似功能保持命名风格一致参数设计原则最小必要:只包含完成任务必需的参数类型明确:明确定义每个参数的数据类型默认值:为非必需参数提供合理的默认值验证规则:在描述中说明参数的取值范围和格式要求工具执行架构 tool 执行逻辑 def get_current_time(location):"""Get the current time for a given location"""print(f"get_current_time called with location: {location}")


location_lower = location.lower()


for key, timezone in TIMEZONE_DATA.items():    if key in location_lower:        print(f"Timezone found for {key}")          current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")        return json.dumps({            "location": location,            "current_time": current_time        })
print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"})
复制代码

Handle function calls

if response_message.tool_calls:for tool_call in response_message.tool_calls:if tool_call.function.name == "get_current_time":


         function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time( location=function_args.get("location") )
messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, })
复制代码


else:print("No tool calls were made by the model.")

Second API call: Get the final response from the model

final_response = client.chat.completions.create(model=deployment_name,messages=messages,)


return final_response.choices[0].message.content 错误处理机制输入验证:检查参数类型、范围和格式异常捕获:使用 try-except 捕获可能的异常友好提示:返回用户可理解的错误信息降级处理:在主功能失败时提供备选方案性能优化缓存机制:对频繁请求的数据实施缓存异步执行:耗时操作采用异步方式批量处理:支持批量请求以提高效率超时控制:设置合理的超时时间调用流程管理意图识别:Agent 判断是否需要调用工具参数提取:从用户输入中提取工具参数工具选择:选择最合适的工具执行执行监控:跟踪工具执行状态结果处理:解析和格式化工具返回结果上下文更新:将结果整合到对话上下文中 Agent Framework 示例好在通常我们不需要从零到一完成所有以上繁琐的工作,可以使用 agent framework 帮助我们完成通用工作,示例如下:import asynciofrom random import randint


from agent_framework import ChatAgent, ai_functionfrom agent_framework.openai import OpenAIChatClient


from util import get_model_endpoint


AGENT_NAME = "TravelAgent"


AGENT_INSTRUCTIONS = """You are a helpful AI Agent that can help plan vacations for customers.


Important: When users specify a destination, always plan for that location. Only suggest random destinations when the user hasn't specified a preference.


When the conversation begins, introduce yourself with this message:"Hello! I'm your TravelAgent assistant. I can help plan vacations and suggest interesting destinations for you. Here are some things you can ask me:


  1. Plan a day trip to a specific location

  2. Suggest a random vacation destination

  3. Find destinations with specific features (beaches, mountains, historical sites, etc.)

  4. Plan an alternative trip if you don't like my first suggestion


What kind of trip would you like me to help you plan today?"


Always prioritize user preferences. If they mention a specific destination like "Bali" or "Paris," focus your planning on that location rather than suggesting alternatives."""


@ai_function(name="get_random_destination",description="Get a random travel destination suggestion.",)def get_random_destination() -> str:destinations = ["Barcelona, Spain", # Mediterranean cultural hub"Paris, France", # European artistic center"Berlin, Germany", # Historical European capital"Tokyo, Japan", # Asian technology metropolis"Sydney, Australia", # Oceanic coastal city"New York, USA", # American urban center"Cairo, Egypt", # African historical capital"Cape Town, South Africa", # African scenic destination"Rio de Janeiro, Brazil", # South American beach city"Bali, Indonesia", # Southeast Asian island paradise]


# Factory Method Pattern: Create destination selection on demandreturn destinations[randint(0, len(destinations) - 1)]
复制代码


async def main():model_url, api_key, model_name = get_model_endpoint()


openai_chat_client = OpenAIChatClient(base_url=model_url, api_key=api_key, model_id=model_name)
tools = [get_random_destination]
agent = ChatAgent( name=AGENT_NAME, chat_client=openai_chat_client, instructions=AGENT_INSTRUCTIONS, tools=tools, tool_call_parser="llama3_json", tool_choice="auto",)
thread = agent.get_new_thread()
response = await agent.run("plan me a day trip", thread=thread)
last_message = response.messages[-1]text_content = last_message.contents[0].text
print("Travel plan: ", text_content)
复制代码


if name == "main":asyncio.run(main())主流 Agent Framework 对比 LangChain 特点:功能最全面,生态系统丰富优势:文档完善,社区活跃,集成度高适用:企业级应用,复杂工作流学习曲线:中等偏陡 Microsoft Agent Framework 特点:提供统一的 Agent 开发平台,融合了 Semantic Kernel 和 AutoGen 的理念优势:模块化设计,支持多 Agent 协作,易于集成和部署适用:构建复杂 AI Agent 应用,多 LLM 提供商集成学习曲线:中等 Framework 选择指南项目规模:小型项目选轻量级框架,大型项目选功能全面的框架团队经验:考虑团队技术栈和学习能力性能要求:高并发场景需要性能优化好的框架定制化需求:需要深度定制时选择扩展性强的框架 RAG (Retrieval-Augmented Generation)动态获取外部资源,作为生成的增强。RAG 核心原理 RAG 通过结合检索系统和生成模型,实现知识的动态获取:检索阶段:从知识库中检索相关信息增强阶段:将检索结果整合到提示词中生成阶段:基于增强后的提示词生成回答"Maker-Checker" 模式不是单次 检索 + 读取的模式,而是模型全权负责推理、错误处理(改写)、工具选择和调用、信息检索,并按需多次循环的过程。Maker-Checker 工作流程需求理解:分析用户查询的核心需求查询生成:构建合适的检索查询信息检索:执行检索操作质量检查:评估检索结果的相关性迭代优化:必要时调整查询重新检索答案生成:综合所有信息生成最终回答因为 Agent 高度自动化,因此需要在 agent 执行过程中保证:透明、可解释:记录检索过程和决策依据无变差、平衡的 retrieve:避免信息偏见和遗漏通常记录整体执行过程中的推理内容、query 生成、query 结果等,用作自动、人为监控。RAG 优化策略检索优化多路召回:同时使用多种检索策略重排序:对初步结果进行精细排序查询扩展:自动扩展和改写查询语义理解:使用嵌入向量提升语义匹配知识库优化文档切分:合理的文档粒度划分元数据标注:添加时间、来源等元信息版本管理:支持知识的更新和版本控制质量控制:建立知识审核和更新机制 Planning (规划)规划是 Agent 的核心能力之一,涉及任务分解、资源分配和执行策略制定。规划层次结构战略层规划目标设定:明确长期目标和成功标准资源评估:评估可用资源和时间限制风险评估:识别潜在风险和应对策略里程碑定义:设置关键检查点战术层规划任务分解:将大目标分解为可执行任务依赖分析:识别任务间的依赖关系优先级排序:确定任务执行顺序时间估算:评估各任务所需时间执行层规划具体步骤:制定详细的执行步骤异常处理:准备备选方案和应急措施监控机制:设置执行监控和反馈机制调整策略:制定动态调整计划的方法规划算法经典规划算法 HTN (Hierarchical Task Networks):分层任务网络规划 STRIPS:经典 AI 规划算法 PDDL:规划领域定义语言 A*:启发式搜索算法现代规划方法强化学习:通过试错学习最优策略蒙特卡洛树搜索:用于复杂决策场景进化算法:遗传算法等群体智能方法神经网络规划:使用深度学习进行规划规划挑战与解决不确定性处理概率规划:考虑不确定性的规划鲁棒优化:制定抗干扰的计划自适应规划:根据环境变化调整计划多场景规划:为不同情况制定预案动态环境适应在线规划:实时调整执行策略增量规划:逐步完善和更新计划重规划机制:当环境变化时重新规划学习机制:从历史经验中学习改进多智能体设计多智能体系统涉及多个 Agent 的协作、通信和协调。多智能体架构 agent communication:定义 Agent 间的通信协议和语言 agent 协作:制定协作策略和冲突解决机制 agent 架构:设计 Agent 的内部结构和交互接口多 agent 交互可感知:确保 Agent 能感知和理解其他 Agent 的行为多 agent 组织方式: 中心化、去中心化、分层人工参与:什么时候需要人工参与,什么形式参与多智能体组织方式中心化架构中央协调器:所有决策由中央 Agent 做出优点:统一控制,决策一致性高缺点:单点故障,扩展性有限适用:小规模,强一致性要求的场景去中心化架构自治决策:每个 Agent 独立做出决策优点:容错强劲,可扩展性好缺点:协调复杂,可能产生冲突适用:大规模,动态环境分层架构多级管理:不同层级负责不同粒度的决策优点:平衡了集中和分散的优势缺点:架构复杂,层级间通信开销适用:中等规模,需要分级管理的场景多智能体常见设计模式 group chat: 多智能体间可以直接相互沟通。hand-off: 如 workflow automation, customer support 场景。collaborative filtering: 协作过滤,多个 Agent 共同过滤和筛选信息通信机制通信类型直接通信:Agent 间点对点通信广播通信:一个 Agent 向所有其他 Agent 发送消息组播通信:向特定组的 Agent 发送消息间接通信:通过环境或其他媒介传递信息通信内容任务信息:任务分配、进度汇报状态信息:Agent 当前状态和能力协调信息:冲突解决、资源协商知识共享:经验、教训、最佳实践协作策略任务分配能力匹配:根据 Agent 能力分配任务负载均衡:考虑 Agent 当前负载优先级排序:根据任务紧急程度分配动态调整:根据执行情况动态重新分配冲突解决协商机制:通过谈判解决资源冲突仲裁机制:第三方仲裁解决争议投票机制:多数表决决定优先级机制:根据预设优先级解决冲突元认知 (Metacognition)元认知是 Agent 对自身认知过程的认知和调控能力。元认知层次监控层性能监控:实时监控自身表现错误检测:识别和诊断错误进度跟踪:跟踪任务执行进度资源监控:监控计算资源使用情况调控层策略调整:根据监控结果调整策略学习优化:从经验中学习改进资源重分配:动态调整资源分配目标修正:必要时修正目标和计划元认知能力实现自我评估置信度评估:对决策结果的可信度评估能力评估:对自身能力的准确认知局限性识别:识别自身知识和能力的局限不确定性量化:量化决策中的不确定性学习机制经验总结:从成功和失败中总结经验模式识别:识别问题解决的通用模式知识更新:不断更新和完善知识库策略优化:优化决策和执行策略元认知应用场景复杂问题解决:在复杂环境中进行深度推理学习新任务:快速适应和学习新任务异常处理:在异常情况下的自适应处理性能优化:持续优化自身性能表现 Agent 可观测与评估为什么需要观测 Agent 的执行过程和执行结果?:定位错误: 当 Agent 执行出错时,通过观测其执行过程可以快速定位错误发生的位置。评估 Agent 性能: 观测 Agent 的执行结果可以评估其性能,如准确率、召回率、F1 等指标。监控 Agent 行为: 观测 Agent 的执行过程可以监控其行为,如是否遵守指令、是否重复执行相同操作等。控制成本、时延:观测体系架构数据收集层日志记录:详细记录 Agent 的所有操作和决策指标采集:收集关键性能指标事件追踪:追踪重要事件的发生和处理状态快照:定期保存 Agent 状态数据处理层数据清洗:去除噪声和无效数据数据聚合:按时间、类型等维度聚合数据特征提取:提取有价值的特征信息异常检测:识别异常行为和模式可视化层实时监控:实时展示关键指标历史趋势:展示指标的历史变化趋势对比分析:支持不同 Agent 或不同时期的对比报告生成:自动生成观测报告评估指标体系常用检测指标:时延:响应时间、任务完成时间成本:计算资源消耗、API 调用成本正确率:任务完成准确率、决策正确性用户反馈:用户满意度、投诉率请求失败率:任务失败比例、错误类型分布技术指标任务成功率:成功完成的任务比例平均响应时间:从请求到响应的平均时间资源利用率:CPU、内存、网络等资源使用情况并发处理能力:同时处理多个任务的能力稳定性指标:系统可用时间、故障恢复时间业务指标用户满意度:用户对 Agent 服务的满意程度任务完成质量:完成任务的完整性和准确性成本效益比:投入成本与产出的比值学习改进速度:Agent 学习和改进的效率观测打点注入观测打点注入:使用 Trace 和 Span 的方式记录,比如 OpenTelemetry。Trace 设计调用链追踪:记录完整的调用链路时间戳记录:精确记录每个操作的时间上下文传递:在调用链中传递上下文信息异常标记:标记异常发生的位置和类型 Span 设计操作范围定义:定义每个 Span 的开始和结束标签添加:为 Span 添加有意义的标签事件记录:在 Span 中记录重要事件关系建立:建立 Span 之间的父子关系 Agent 评估方法 Agent 评估:离线评估:在测试环境中使用预设数据集进行评估在线评估:在生产环境中实时监控和评估离线评估基准测试:使用标准测试集进行评估对比实验:与其他 Agent 或基线方法对比 A/B 测试:对比不同版本或配置的效果压力测试:测试在高负载下的性能表现在线评估实时监控:持续监控生产环境表现用户反馈收集:收集和分析用户反馈渐进式 rollout:逐步发布新版本并监控效果快速回滚:在发现问题时快速回滚到稳定版本 Agent 成本管理 &优化 Agent 成本管理 &优化:使用更小的模型:通过 Agent 评估,对应特定任务选择性价比更高的大小合适的模型。智能路由:根据任务复杂度,路由到不同成本的模型上。缓存:常用请求、workflow 结果的缓存;可以引入专门的 Agent 进行请求相似度评估。成本优化策略模型选择优化任务分级:根据任务复杂度选择合适规模的模型动态切换:根据实时负载和性能要求切换模型混合部署:同时使用多个模型,根据需求分配任务模型蒸馏:使用大模型训练小模型,保持性能降低成本智能路由策略复杂度评估:自动评估任务复杂度负载均衡:考虑系统整体负载情况成本预测:预测不同处理方案的成本质量保障:确保在成本控制下维持服务质量缓存机制设计结果缓存:缓存常见问题的答案中间结果缓存:缓存计算过程中的中间结果模板缓存:缓存常用的响应模板智能预取:预测用户需求并提前准备 Agent 协议 Agent 协议定义了 Agent 之间以及 Agent 与外部系统之间的通信标准和交互规范。协议分类 MCP (Model Context Protocol)A2A (Agent to Agent protocol)NLWeb (Natural Language Web interaction)MCP (Model Context Protocol)MCP (model context protocol) 是一种开发协议,用来为大模型提供额外的上下文和工具能力,包括:指令(模板): 大模型需要执行的任务指令(模板),用作解决复杂工作流。工具: 大模型可以调用的外部工具,如计算器,代码执行器。数据:API 调用,数据查询等 MCP 架构模式 MCP 采用传统的 client-server 模式,其中:client: 大模型 Agent,负责执行指令、调用工具、处理数据等。server: 负责提供额外的上下文和工具能力,如指令模板、工具实现、数据查询等。host:对应的应用,比如 trae,vscode 等 MCP 优势分析使用 MCP 的优势,和解决的问题包括:解耦: 大模型 Agent 和 应用 之间解耦,应用可以根据需要定制指令、工具、数据等。可扩展性: 应用可以根据需要添加新的指令、工具、数据等,而不需要修改大模型 Agent 的代码。可维护性: 应用的代码和配置都在应用端,而不是大模型 Agent 端,方便维护和升级。性能: 大模型 Agent 只需要关注指令执行和工具调用,而不需要处理数据查询等。MCP 应用场景 IDE 集成:如 VS Code、Trae 等开发环境数据处理:结构化数据的查询和处理工具集成:各种外部工具和 API 的集成知识管理:企业知识库的访问和管理 A2A (Agent to Agent Protocol)Agent to Agent protocol (A2A) 是 agent 间相互交互的协议,用来帮助 agent 间相互协作。A2A 核心组件 A2A 中主要包括:Agent card:用于 Agent 对外展示自己自己的名字、描述、能力等。Agent executor:用于将上下文传递给 remote agent,或调用 LLM 解析收到的 contextArtifact:Agent 执行结果的标识 event queue:Agent 执行状态管理 A2A 解决问题 A2A 结局的问题:增强协作:支持不同平台、不同供应商直接的 Agent 的协作能力模型自由选择:不同 Agent 可以使用自己合适的不同地层 LLM。A2A 通信模式点对点通信:两个 Agent 直接通信发布订阅:Agent 发布消息,其他 Agent 订阅请求响应:一个 Agent 请求,另一个 Agent 响应事件驱动:基于事件的消息传递 NLWeb (Natural Language Web)通过自然语言与 web 页面交互。NLWeb 核心能力自然语言理解:理解用户的自然语言指令页面元素识别:识别网页上的可操作元素动作执行:执行点击、输入、滚动等操作结果反馈:将执行结果反馈给用户 NLWeb 应用场景自动化测试:使用自然语言描述测试用例网页自动化:自动化网页操作流程辅助工具:帮助用户完成复杂的网页操作数据采集:从网页中提取结构化数据上下文工程上下文工程是指管理 Agent 用来做计划、决策、执行所需要的全部信息。受限于 LLM 上下文大小、成本等因素,上下文窗口大小是优先的。上下文工程需要再上下文窗口中增加、删除、压缩信息。和提示词工程的区别联系提示词工程:静态的指令和规则上下文工程:动态信息管理(包括最初的提示词),用来保证随着时间推移 Agent 总能获取到为完成任务所需要的有效信息。上下文工程的内容指令:提示词、系统信息、few-shot 示例、工具描述知识:客观事实、RAG 信息查询、长短期记忆工具:外部函数、API、MCP servers 的定义,用户使用反馈等对话历史:LLM 对话历史用户偏好:外部存储的或者交互过程中收集到的用户偏好有效上下文管理的准则 Agent 备忘录:在单 session 中记录用户交互、当前任务相关信息等。记忆管理:外部存储用户单 session 内容,存储可以先压缩、总结;用作跨 session 加载用户的偏好、feedback 等上下文压缩:随着上下文增长,需要压缩、总结上下文,保持上下文窗口大小在可控范围内。常用总结或截断的方式,分别保留最相关和最近的上下文信息。Multi-Agent: multi-agent 是另一种上下文管理方式,因为每个 agent 有自己独立的上下文窗口,并且各自可以有着独立的上下文管理方式。上下文压缩技术摘要压缩关键信息提取:提取对话中的关键信息渐进式摘要:随着对话进行逐步更新摘要层次化摘要:按重要性层次组织摘要主题聚类:按主题对信息进行聚类压缩选择性保留时间权重:最近的信息权重更高重要性评分:根据信息重要性决定保留相关性过滤:过滤掉与当前任务无关的信息用户关注:保留用户特别关注的信息常见上下文管理失败原因上下文中毒 what:上下文中记录了 LLM 产生的错误信息。解决:对关键结论加入上下文前进行验证和校验。上下文滥用 what:上下文过多、过杂,导致模型无法使用模型中的知识,被上下文中的内容完全拖累。解决:定期上下文总结,仅保留关键内容,让 LLM focus 上下文困惑 what:通常提供过多的工具,让 llm 无法抓住重点。解决:管理工具的加载,比如利用 RAG 对工具进行粗过滤,防止提供过多工具让大模型困惑,抓不住重点。上下文冲突 what:上下文中存在相互冲突内容,导致最终推理和结论混乱解决:上下文剪枝,用最新的上下文替换掉冲突的旧上下文。Agent memory 为 Agent 提供存储和之后获取信息的能力。Agent memory 能够让应用更加自动化、智能化。内存类型短期记忆: 用于存储当前任务相关信息,通常在 session 结束后清除。用于存储当前任务相关信息。主要保存任务的需求、步骤、决策、实体等上下文长期记忆: 用于存储用户偏好、反馈、历史交互等,通常在多个 session 间长期保存。人设记忆:帮助 Agent 保持系统"人设",更好的以该"人设"完成任务(structured) RAG:Agent memory 的实现使用专用工具比如 mem0, 能够记录用户的偏好、交互上下文、成功失败历史等,是无状态的 agent 任务变成有状态的。主要过程分为两阶段:提取:利用 LLM 从用户交互中提取关键信息,比如用户需求、上下文、偏好等。更新:根据用户反馈和交互历史,更新长期记忆,包括新增、更新、删除记忆等。使用 RAG 工具存储记忆利用记忆的 Agent 自我进化设计范式引入专职的 “knowledge agent”。在 agent 与用户交互中自动:识别有用信息提取并压缩有用信息存储以上信息在后续 Agent 交互中利用存储的信息,增强 promt,来辅助完成任务。(类似 RAG)记忆优化延迟优化:使用更小的模型进行信息是否有价值的快速判断,作为粗过滤。知识存储优化:过时信息可以优化到“冷存储”中 Deep agent - 当前 Agent 设计的最佳实践赏析 Langchain 团队提出的概念,旨在解决传统 ReAct 模型中:单 agent 上下文容量不足,无法解决长上下文或复杂任务的问题;无法持久化存储任务相关信息,不支持回滚,time-travel 等问题。Deep agent 应该包含以下能力:精细化系统 prompt: 系统 prompt 中包含详细的描述,few-shot 示例等。可参考 claud code 中的系统 prompt 设计。planing tool: 能够根据任务自主进行计划,通常是一个 write todo tools. 可以拆解子任务、记录执行进度、动态调整计划等。sub agents: 根据领域,区分出专门的特有 agent,上下文高效独立管理持久化层:持久化上下文,执行过程、结果等。支持跨会话使用,回滚,错误恢复、单点重试、time-travel,human in the loop 等能力。最简单的实现是使用文件系统进行持久化。当设计一个 deep agent 时,核心需要考虑因素包括:core config:system prompttoolsmodelfeatures:backendsubagentsinterruptsfrom typing import Literalfrom tavily import TavilyClientimport osfrom deepagents import create_deep_agentfrom util import get_model_endpointfrom langchain_openai import ChatOpenAI


from pydantic import SecretStr


tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])


一个最简单的 deep agent - deep research agent 示例:

create a search tool

def internet_search(query: str,topic: Literal["general", "finance", "news"] = "finance",max_ret: int = 5,include_raw_content: bool = False,):"""Perform an internet search using Tavily.


Args:    query (str): The search query.    topic (Literal["general", "finance", "news"], optional): The topic of the search. Defaults to "finance".    max_ret (int, optional): The maximum number of results to return. Defaults to 5.    include_raw_content (bool, optional): Whether to include raw content in the results. Defaults to False."""return tavily_client.search(    query=query,    max_results=max_ret,    topic=topic,    include_raw_content=include_raw_content,)
复制代码

system promt

research_instructions = """You are an expert researcher. Your job is to conduct thorough research and then write a polished report.


You have access to an internet search tool as your primary means of gathering information.

internet_search

Use this to run an internet search for a given query. You can specify the max number of results to return, the topic, and whether raw content should be included."""


model_url, api_key, model_name = get_model_endpoint()


chat_model = ChatOpenAI(base_url=model_url, api_key=SecretStr(api_key), model=model_name)

create agent

agent = create_deep_agent(model=chat_model, tools=[internet_search], system_prompt=research_instructions)

run agent

result = agent.invoke({"messages": [{"role": "user", "content": "What is deep agent?"}]})print(result["messages"][-1].content)示例输出如下:uv run deep_agents.py

What Are Deep Agents?

Deep Agents are an advanced architecture for AI agents designed to handle complex, multi-step tasks requiring sustained reasoning, tool use, context management, and collaborative workflows. Unlike traditional agents that rely on simple tool-calling loops, Deep Agents excel at planning, delegating subtasks to specialized sub-agents, and maintaining persistent memory across interactions. They are powered by frameworks like LangChain and enable applications like Claude Code, Deep Research, and Manus to tackle real-world challenges with precision and scalability.

Core Characteristics of Deep Agents

Deep Agents distinguish themselves through four key attributes:


  1. Planning Capability: Break large tasks into subtasks and adjust plans dynamically.

  2. Context Management: Retain and reference critical information across long interactions.

  3. Sub-Agent Delegation: Launch specialized agents for focused tasks (e.g., research, writing).

  4. File System Integration: Persist and share information across steps via a virtual file system, enabling true "memory" beyond conversation history.

Core Components of Deep Agents

Deep Agents rely on four foundational components to achieve their capabilities:

1. Detailed System Prompts

A comprehensive system prompt guides the agent through structured workflows. For example, the DEEP_AGENT_SYSTEM_PROMPT in the tutorial outlines:


  • Planning: Break tasks into subtasks with todo_write.

  • Research: Use web search tools (e.g., Tavily) to gather information.

  • Delegation: Spawn sub-agents for specialized work (e.g., job search, cover letter writing).

  • Documentation: Maintain notes in a virtual file system.


Example: The job application assistant prompt specifies generating valid JSON job listings and concise cover letters.

2. Planning Tools

This forces the agent to explicitly plan steps, ensuring transparency and adjustability.

3. Sub-Agent Delegation

Deep Agents can spawn specialized sub-agents with unique prompts, tools, and descriptions. In the job application demo:


  • Job-Search Agent: Focuses on finding relevant job postings.

  • Cover-Letter Agent: Generates tailored cover letters for each job.


Example:


...

4. File System Integration

Agents use tools like read_file, write_file, and edit_file to manage state across steps and sub-agents. For example:


  • File Storage: Save job listings or cover letters in a virtual file system (e.g., cover_letters.md).

  • Shared Workspace: Sub-agents can read/write to the same files, enabling collaboration.

Demo: Job Application Assistant with Deep Agents

The tutorial demonstrates building a Deep Agent to automate job searches and cover letter drafting. Key steps include:

1. Setup & Dependencies

Install required libraries:

2. UI & Input Handling

Users upload resumes (PDF/DOCX/TXT), specify job title/location, and skills. The app extracts resume text using extract_text():

3. Tool Integration

  • Web Search: Use Tavily API to fetch job listings via internet_search().

  • LLM: OpenAI’s GPT-4o-mini for reasoning and content generation.

4. Agent Configuration

The main agent is created with sub-agents for job search and cover letters:


...

5. Execution & Results

The agent processes the task prompt (resume, skills, job criteria), generates JSON-formatted job listings, and writes cover letters to cover_letters.md. Users download the output as a Word document.

Key Takeaways

Deep Agents represent a paradigm shift in AI, enabling multi-step, context-aware, and collaborative workflows that traditional agents cannot handle. By combining detailed system prompts, planning tools, sub-agent delegation, and file system integration, they excel at complex tasks like job applications, research, and code development. Frameworks like LangChain’s deepagents package make this architecture accessible, allowing developers to build production-ready agents with minimal effort.


For practical implementation, explore the tutorial’s demo project to see how Deep Agents transform manual job applications into automated, AI-driven workflows!


Source: Adapted from LangChain’s Deep Agents tutorial by Aashi Dutt (DataCamp).deep agents 必要 tools 一个 deep agent 应该支持至少一下 tool:todo_write: 用于创建任务列表,支持子任务拆解。read_file: 用于读取 agent 的文件系统中的文件内容。ls: 列出文件列表 glob/grep: 文件内容检索 write_file: 用于写入 agent 的文件系统中的文件内容。edit_file: 用于编辑 agent 的文件系统中的文件内容。task: 创建 subagent 用户处理任务。[optional] internet_search: 用于互联网搜索.subagentssub-agents 的对比单 agent 主要优势:上下文独立 -> 更大的上下文窗口并行执行特化能力: 独立工具等 -> 上下文独立 -> 更大的上下文窗口 token 节省 subagents 工作原理:main agent 拥有一个 task tool,这个 tool 可以创建 sub agent,并注入专用上下文。 sub agent 执行完成后返回结果给 main agent,sub agent 是无状态的。除默认“通用“sub-agent 外,用户应该根据场景按需定义更多专用 sub-agent 和专用 tool。human in the loop 一些关键、敏感 tool 需要用户 approve 才能执行,可以利用 langraph 的持久化能力实现。from langchain.tools import toolfrom deepagents import create_deep_agentfrom langgraph.checkpoint.memory import MemorySaver


@tooldef delete_file(path: str) -> str:"""Delete a file from the filesystem."""return f"Deleted {path}"


@tooldef read_file(path: str) -> str:"""Read a file from the filesystem."""return f"Contents of {path}"


@tooldef send_email(to: str, subject: str, body: str) -> str:"""Send an email."""return f"Sent email to {to}"

Checkpointer is REQUIRED for human-in-the-loop

checkpointer = MemorySaver()


agent = create_deep_agent(model="claude-sonnet-4-5-20250929",tools=[delete_file, read_file, send_email],interrupt_on={"delete_file": True, # Default: approve, edit, reject"read_file": False, # No interrupts needed"send_email": {"allowed_decisions": ["approve", "reject"]}, # No editing},checkpointer=checkpointer # Required!)

用户头像

方品

关注

还未添加个人签名 2025-11-16 加入

还未添加个人简介

评论

发布
暂无评论
AI Agent 设计原则与最佳实践_方品_InfoQ写作社区