课程目标理解 Agent 核心概念、工作逻辑掌握内置工具与自定义工具用法学会基础 Agent 搭建、运行与调试区分不同 Agent 类型及适用场景一、核心概念1. 什么是 Agent普通 LLM/Chain 只能被动执行预设逻辑Agent智能代理可以让大模型自主思考、自主选择工具、自主分步完成复杂任务。 核心流程思考 → 选工具 → 调用工具 → 拿到结果 → 再思考循环直到任务完成。2. 三大核心组成大模型 LLM负责思考、判断、生成执行指令工具 Tool具备特定能力的功能单元查时间、搜数据、计算、联网等代理执行器 AgentExecutor调度整个流程管理思考与工具调用二、内置常用工具 环境准备1. 安装依赖bash运行pip install langchain langchain-community langchain-openai2. 常用内置工具介绍LangChain 提供开箱即用工具举例Calculator数学计算DuckDuckGoSearchRun联网搜索PythonREPL执行 Python 代码WikipediaQueryRun维基百科查询三、实战 1最简单 Agent计算器 搜索完整代码python运行from langchain_openai import OpenAI from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import Calculator, DuckDuckGoSearchRun from langchain.prompts import PromptTemplate import os # 配置密钥 os.environ[OPENAI_API_KEY] 你的API_KEY # 1. 初始化模型 llm OpenAI(temperature0) # 2. 定义工具列表 tools [ Calculator(), # 数学计算工具 DuckDuckGoSearchRun() # 联网搜索工具 ] # 3. 定义PromptReact代理标准提示词 prompt PromptTemplate.from_template( Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} {agent_scratchpad} ) # 4. 创建React Agent 执行器 agent create_react_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 5. 执行复杂任务混合搜索计算 query 现在的北京气温是多少再加上25等于多少 result agent_executor.invoke({input: query}) print(\n最终答案, result[output])运行解读开启verboseTrue会打印完整思考过程模型思考需要先搜索北京气温调用搜索工具 → 获取气温数值再次思考需要数学计算调用计算器 → 算出结果输出最终答案四、工具详解1. 计算器 Calculator专门处理四则运算、复杂数学公式大模型直接计算容易出错交由工具保证精度。 示例任务(125 36) * 8 等于多少2. 联网搜索 DuckDuckGoSearchRun免费开源搜索引擎无需额外配置用来获取实时、外部知识大模型静态知识无法覆盖最新信息。五、自定义工具重点考点当内置工具不满足需求时可以自己封装工具固定写法继承BaseTool。示例自定义工具文本转大写python运行from langchain.tools.base import BaseTool from typing import Optional # 自定义工具类 class UpperTool(BaseTool): name TextUpper # 工具名称Agent 通过名称识别 description 将输入的英文文本全部转为大写字母 # 描述给LLM判断何时使用 def _run(self, tool_input: str) - str: # 工具核心逻辑 return tool_input.upper() # 异步方法可选同步场景可忽略 async def _arun(self, tool_input: str) - str: return self._run(tool_input) # 整合进Agent tools [UpperTool(), Calculator()] agent create_react_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 测试 res agent_executor.invoke({input: 把 hello world 转为大写}) print(res[output])自定义工具两大必填项name工具唯一名称description功能描述LLM 靠这段文字判断要不要调用该工具六、主流 Agent 类型考点ReAct Agent本节课使用特点思考 (Thought) 行动 (Action) 结合适用通用场景、学习、常规任务创建方式create_react_agentOpenAI Functions Agent特点依托 OpenAI 函数调用能力调用逻辑更稳定适用生产环境、依赖精准工具调用的项目七、关键易错点总结Agent 和 Chain 区别Chain流程固定预先定义好执行顺序Agent流程动态模型自主决策下一步操作工具的description至关重要描述不清会导致 LLM 不会调用工具AgentExecutor是 Agent 的运行入口所有交互都通过它执行verboseTrue调试必备可查看完整思考 工具调用链路八、课后作业基于内置Calculator 搜索工具编写 Agent完成任务圆周率保留2位小数乘以100等于多少自定义一个「文本长度统计工具」接入 Agent实现任务统计字符串 langchain agent 一共有多少个字符简述 Agent、LLM Chain 二者的区别。作业 1内置工具 Agent计算器 搜索python运行from langchain_openai import OpenAI from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import Calculator, DuckDuckGoSearchRun from langchain.prompts import PromptTemplate import os os.environ[OPENAI_API_KEY] 你的API_KEY # 1. 初始化模型 llm OpenAI(temperature0) # 2. 工具列表计算器 鸭鸭搜索 tools [ Calculator(), DuckDuckGoSearchRun() ] # 3. ReAct 标准提示词 prompt PromptTemplate.from_template( Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} {agent_scratchpad} ) # 4. 创建 Agent 和执行器 agent create_react_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 5. 执行任务圆周率保留2位小数乘以100等于多少 query 圆周率保留2位小数乘以100等于多少 result agent_executor.invoke({input: query}) print(\n最终答案, result[output])作业 2自定义文本长度统计工具python运行from langchain_openai import OpenAI from langchain.agents import AgentExecutor, create_react_agent from langchain.tools.base import BaseTool from langchain.prompts import PromptTemplate import os os.environ[OPENAI_API_KEY] 你的API_KEY # 1. 自定义工具文本长度统计 class TextLengthTool(BaseTool): name TextLengthCounter description 统计输入字符串的字符数量输入一段文本返回它的长度。 def _run(self, tool_input: str) - str: # 核心逻辑计算字符串长度 length len(tool_input) return f字符串 {tool_input} 的长度是 {length} 个字符。 async def _arun(self, tool_input: str) - str: return self._run(tool_input) # 2. 初始化模型 llm OpenAI(temperature0) # 3. 工具列表 tools [TextLengthTool()] # 4. ReAct 提示词 prompt PromptTemplate.from_template( Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} {agent_scratchpad} ) # 5. 创建 Agent agent create_react_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 6. 执行任务统计 langchain agent 的字符数 query 统计字符串 langchain agent 一共有多少个字符 result agent_executor.invoke({input: query}) print(\n最终答案, result[output])作业 3简答题标准答案题目简述 Agent 与 LLM Chain 的区别表格维度LLM ChainAgent执行逻辑流程固定按预设顺序执行流程动态模型自主决策下一步工具使用工具 / 步骤需要提前硬编码可根据任务自动选择、调用工具适用场景固定逻辑任务如翻译、摘要复杂、不确定的多步骤任务自主性被动执行主动思考、规划、执行一句话总结Chain是「按剧本走流程」Agent是「自己当导演边想边演」