
tags:/n - langchain智能体AgentTool Calling面试aliases:/n - Agent智能体开发05 Agents 智能体一、Agent 介绍Agent LLM Tools Memory能够自主决策调用什么工具、如何执行任务。Agent vs Chain对比ChainAgent执行模式固定流程动态决策灵活性低高适用场景简单确定性任务复杂多步骤任务Agent 工作流程用户提问 → LLM 决策 → 调用工具 → 获取结果 → LLM 继续决策 → ... → 最终回答工具定义方式方式说明适用场景tool装饰器简单快捷快速定义工具StructuredTool支持 Pydantic Schema需要详细参数描述MCP 工具标准化协议外部工具集成二、Agent 添加本地工具 Agent 本地工具演示 运行方式python 05_Agent本地工具.py fromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_tool_calling_agent,AgentExecutorfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.toolsimporttool# 定义工具tooldefget_weather(city:str,date:str)-str:查询指定城市和日期的天气weather_data{北京:晴朗 25°C,上海:多云 28°C}returnweather_data.get(city,f{city}天气数据暂无)tooldefcalculate(expression:str)-str:计算数学表达式try:returnf计算结果:{eval(expression)}exceptExceptionase:returnf计算错误:{e}# 创建 AgentllmChatOpenAI(modelqwen-plus,...)promptChatPromptTemplate.from_messages([(system,你是一个有用的助手),(human,{input}),(placeholder,{agent_scratchpad}),])tools[get_weather,calculate]agentcreate_tool_calling_agent(llm,tools,prompt)agent_executorAgentExecutor(agentagent,toolstools,verboseTrue)# 运行resultagent_executor.invoke({input:北京今天天气怎么样})print(f答案:{result[output]})三、Agent 添加 MCP 工具 MCP Stdio 方式本地 MCP Server 运行方式python 05_MCP工具.py fromlangchain_mcp_adapters.clientimportMultiServerMCPClientfromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_tool_calling_agent,AgentExecutorfromlangchain_core.promptsimportChatPromptTemplateasyncdefmain():# 连接 MCP ServerclientMultiServerMCPClient({weather:{transport:stdio,command:python,args:[./mcp_server.py],}})toolsawaitclient.get_tools()llmChatOpenAI(modelqwen-plus,...)promptChatPromptTemplate.from_messages([(system,你是一个有用的助手),(human,{input}),(placeholder,{agent_scratchpad}),])agentcreate_tool_calling_agent(llm,tools,prompt)agent_executorAgentExecutor(agentagent,toolstools,verboseTrue)resultagent_executor.invoke({input:帮我查天气})print(result[output])四、Agent 添加记忆 Agent 记忆演示多轮对话 运行方式python 05_Agent记忆.py fromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_tool_calling_agent,AgentExecutorfromlangchain_core.promptsimportChatPromptTemplate,MessagesPlaceholderfromlangchain_core.messagesimportHumanMessage,AIMessage llmChatOpenAI(modelqwen-plus,...)promptChatPromptTemplate.from_messages([(system,你是一个有用的助手),MessagesPlaceholder(variable_namechat_history),(human,{input}),(placeholder,{agent_scratchpad}),])agentcreate_tool_calling_agent(llm,[],prompt)agent_executorAgentExecutor(agentagent,verboseTrue)# 多轮对话chat_history[]# 第一轮result1agent_executor.invoke({input:我叫小明我是一个程序员,chat_history:chat_history,})print(fAI:{result1[output]})# 更新历史chat_history.append(HumanMessage(content我叫小明我是一个程序员))chat_history.append(AIMessage(contentresult1[output]))# 第二轮Agent 记得用户信息result2agent_executor.invoke({input:你还记得我是谁吗,chat_history:chat_history,})print(fAI:{result2[output]})五、Agent 中间件5.1 摘要中间件fromlangchain.agents.middlewareimportSummarizationMiddleware# 当消息超过 10 条时自动压缩summarizationSummarizationMiddleware(llmllm,max_messages10)agent_executorAgentExecutor(agentagent,middleware[summarization])5.2 人工审核中间件fromlangchain.agents.middlewareimportHumanInTheLoopMiddleware# 调用 delete_data 前需要人工确认human_middlewareHumanInTheLoopMiddleware(interrupt_tools[delete_data])agent_executorAgentExecutor(agentagent,middleware[human_middleware])相关笔记[[11-LangGraph/01-LangGraph概述与快速入门.md|LangGraph]] · [[01-LangChain概述]] · [[02-Model-IO与模型调用]] · [[03-提示词模板与Chains]] · [[04-RAG检索增强]]