课程目标

  1. 理解 Agent 核心概念、工作逻辑
  2. 掌握内置工具与自定义工具用法
  3. 学会基础 Agent 搭建、运行与调试
  4. 区分不同 Agent 类型及适用场景

一、核心概念

1. 什么是 Agent

普通 LLM/Chain 只能被动执行预设逻辑Agent(智能代理) 可以让大模型自主思考、自主选择工具、自主分步完成复杂任务。 核心流程:思考 → 选工具 → 调用工具 → 拿到结果 → 再思考,循环直到任务完成。

2. 三大核心组成

  • 大模型 LLM:负责思考、判断、生成执行指令
  • 工具 Tool:具备特定能力的功能单元(查时间、搜数据、计算、联网等)
  • 代理执行器 AgentExecutor:调度整个流程,管理思考与工具调用

二、内置常用工具 & 环境准备

1. 安装依赖

bash

运行

pip install langchain langchain-community langchain-openai

2. 常用内置工具介绍

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(temperature=0)

# 2. 定义工具列表
tools = [
    Calculator(),          # 数学计算工具
    DuckDuckGoSearchRun()  # 联网搜索工具
]

# 3. 定义Prompt(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. 创建React Agent + 执行器
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 5. 执行复杂任务(混合搜索+计算)
query = "现在的北京气温是多少,再加上25等于多少?"
result = agent_executor.invoke({"input": query})
print("\n最终答案:", result["output"])

运行解读

开启 verbose=True 会打印完整思考过程:

  1. 模型思考:需要先搜索北京气温
  2. 调用搜索工具 → 获取气温数值
  3. 再次思考:需要数学计算
  4. 调用计算器 → 算出结果
  5. 输出最终答案

四、工具详解

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(agent=agent, tools=tools, verbose=True)

# 测试
res = agent_executor.invoke({"input": "把 hello world 转为大写"})
print(res["output"])

自定义工具两大必填项

  1. name:工具唯一名称
  2. description:功能描述,LLM 靠这段文字判断要不要调用该工具

六、主流 Agent 类型(考点)

  1. ReAct Agent(本节课使用)

    • 特点:思考 (Thought) + 行动 (Action) 结合
    • 适用:通用场景、学习、常规任务
    • 创建方式:create_react_agent
  2. OpenAI Functions Agent

    • 特点:依托 OpenAI 函数调用能力,调用逻辑更稳定
    • 适用:生产环境、依赖精准工具调用的项目

七、关键易错点总结

  1. Agent 和 Chain 区别
    • Chain:流程固定,预先定义好执行顺序
    • Agent:流程动态,模型自主决策下一步操作
  2. 工具的 description 至关重要,描述不清会导致 LLM 不会调用工具
  3. AgentExecutor 是 Agent 的运行入口,所有交互都通过它执行
  4. verbose=True 调试必备,可查看完整思考 + 工具调用链路

八、课后作业

  1. 基于内置 Calculator + 搜索工具,编写 Agent,完成任务:圆周率保留2位小数乘以100等于多少
  2. 自定义一个「文本长度统计工具」,接入 Agent,实现任务:统计字符串 langchain agent 一共有多少个字符
  3. 简述 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(temperature=0)
    
    # 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(agent=agent, tools=tools, verbose=True)
    
    # 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(temperature=0)
    
    # 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(agent=agent, tools=tools, verbose=True)
    
    # 6. 执行任务:统计 "langchain agent" 的字符数
    query = "统计字符串 'langchain agent' 一共有多少个字符?"
    result = agent_executor.invoke({"input": query})
    print("\n最终答案:", result["output"])
    

    作业 3:简答题标准答案

    题目:简述 Agent 与 LLM Chain 的区别

    表格

    维度 LLM Chain Agent
    执行逻辑 流程固定,按预设顺序执行 流程动态,模型自主决策下一步
    工具使用 工具 / 步骤需要提前硬编码 可根据任务自动选择、调用工具
    适用场景 固定逻辑任务(如翻译、摘要) 复杂、不确定的多步骤任务
    自主性 被动执行 主动思考、规划、执行

    一句话总结:

  4. Chain 是「按剧本走流程」
  5. Agent 是「自己当导演,边想边演」
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐