LangChain 快速入门:从基础到生产级AI智能体搭建

本快速入门教程将带你在几分钟内,从简单的环境配置开始,一步步搭建出一个功能完整的AI智能体。如果使用AI编码助手或集成开发环境(如Claude Code、Cursor),建议安装LangChain Docs MCP服务器,能让你的智能体获取最新的LangChain文档和示例,发挥最佳效果。

准备工作

搭建示例中的智能体,需要完成以下三步基础配置,示例中使用Anthropic的Claude大模型,也可替换为LangChain支持的任意模型,仅需修改代码中的模型名并配置对应模型的API密钥即可。

  1. 安装LangChain Python包;

  2. 注册Anthropic的Claude账号,获取对应的API密钥;

  3. 在终端中设置ANTHROPIC_API_KEY环境变量,供LangChain调用。

一、搭建基础AI智能体

首先创建一个基础智能体,该智能体具备基础的问答能力和工具调用能力,核心使用Claude Sonnet 4.5作为语言模型,自定义一个简单的天气查询函数作为工具,并通过基础系统提示词规范智能体行为。

基础智能体完整代码

from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"

# 创建智能体实例
agent = create_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[get_weather],
    system_prompt="You are a helpful assistant",
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)

代码逐行详解

  1. 导入智能体创建核心函数from langchain.agents import create_agent,该函数是LangChain中创建智能体的核心入口,可快速整合模型、工具、提示词等组件。

  2. 定义工具函数:自定义get_weather函数,接收city(城市名)参数,返回固定格式的天气信息,函数的文档字符串"""Get weather for a given city."""是关键,LangChain会将其作为工具描述传递给大模型,让模型理解工具的用途。

  3. 创建智能体:调用create_agent传入三个核心参数
    • model:指定使用的大模型标识,此处为Claude Sonnet 4.5的最新版本;

    • tools:传入智能体可调用的工具列表,支持多个工具传入;

    • system_prompt:系统提示词,定义智能体的基础角色(此处为“贴心助手”)。

  4. 运行智能体:调用agent.invoke()方法触发智能体执行,入参为字典格式,messages是对话消息列表,包含用户角色(user)和具体的查询内容,此处查询旧金山(sf)的天气。

二、搭建生产级实用智能体

基于基础智能体,进一步搭建具备生产环境核心特性的天气预报智能体,该智能体实现了企业级开发的关键能力,也是实际业务中使用LangChain的标准范式。

生产级智能体核心特性

  • 精细化系统提示词,精准定义智能体行为和角色;

  • 自定义工具支持运行时上下文注入、对接外部数据;

  • 大模型个性化参数配置,保证响应的一致性;

  • 结构化输出格式,让智能体结果可预测、易解析;

  • 集成对话记忆,支持多轮类聊天交互;

  • 支持用户专属上下文信息传递。

接下来将分6个步骤拆解生产级智能体的搭建过程,最后提供完整的整合代码和运行效果。

步骤1:定义精细化系统提示词

系统提示词是智能体的“行为准则”,生产环境中需要具体、可执行的提示词,明确智能体的角色、可调用的工具、工具的使用规则。

代码实现
SYSTEM_PROMPT = """You are an expert weather forecaster, who speaks in puns.

You have access to two tools:

- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location

If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location."""
代码详解
  1. 明确角色:双关语风格的专业天气预报员,让智能体的输出具备固定风格;

  2. 工具清单:清晰列出可调用的两个工具及核心用途,降低模型的工具调用理解成本;

  3. 执行规则:明确天气查询的核心逻辑——必须获取位置,若用户未指定则调用get_user_location工具获取用户所在位置,让智能体的工具调用更规范。

步骤2:创建自定义工具

工具是智能体与外部系统交互的桥梁,生产级工具需要支持运行时上下文(如用户ID、设备信息)和智能体记忆交互,LangChain通过@tool装饰器和ToolRuntime实现这一能力,同时工具需要完善的文档字符串说明。

代码实现
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime

# 天气查询工具
@tool
def get_weather_for_location(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"

# 自定义运行时上下文schema
@dataclass
class Context:
    """Custom runtime context schema."""
    user_id: str

# 用户位置获取工具(依赖运行时上下文)
@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
    """Retrieve user information based on user ID."""
    user_id = runtime.context.user_id
    return "Florida" if user_id == "1" else "SF"
代码详解
  1. 基础工具定义:使用@tool装饰器修饰普通函数,LangChain会自动为函数添加工具元数据(名称、描述、参数),无需手动配置,装饰后的函数可直接传入智能体的tools参数;

  2. 自定义运行时上下文:通过dataclasses.dataclass定义Context类,仅包含user_id字段,作为运行时传递用户专属信息的载体,生产环境中可扩展为包含用户昵称、设备、地区等更多信息;

  3. 上下文依赖工具get_user_location工具的入参为ToolRuntime[Context],实现运行时上下文注入,通过runtime.context.user_id获取当前请求的用户ID,并根据用户ID返回不同的位置,实现用户专属逻辑

  4. 工具文档字符串:每个工具的文档字符串是模型识别工具的关键,必须清晰说明工具用途和参数含义。

步骤3:配置大模型参数

为了保证智能体响应的一致性和稳定性,需要对大模型进行个性化参数配置,LangChain通过init_chat_model函数统一初始化各类聊天模型,不同模型的参数可按需调整。

代码实现
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "claude-sonnet-4-5-20250929",
    temperature=0.5,
    timeout=10,
    max_tokens=1000
)
代码详解
  1. 模型初始化入口init_chat_model是LangChain的统一模型初始化函数,支持切换任意兼容的聊天模型,仅需修改模型标识;

  2. 核心参数说明
    • temperature:温度系数,控制模型输出的随机性,取值0~1,0表示输出完全确定,1表示随机性最高,生产环境中一般设置0~0.5;

    • timeout:模型请求超时时间,单位为秒,避免因模型服务卡顿导致智能体挂起;

    • max_tokens:模型单次输出的最大令牌数,限制响应长度,避免输出过长。

步骤4:定义结构化输出格式

生产环境中,智能体的输出需要可预测、易解析(如供前端渲染、数据库存储),LangChain支持通过dataclass或Pydantic模型定义结构化响应格式,强制模型按照指定schema输出结果。

代码实现
from dataclasses import dataclass

# 定义智能体响应的结构化schema
@dataclass
class ResponseFormat:
    """Response schema for the agent."""
    # 必选字段:双关语风格的响应
    punny_response: str
    # 可选字段:天气状况信息,值为None时不返回
    weather_conditions: str | None = None
代码详解
  1. 采用dataclass定义结构化schema,生产环境中若需要更复杂的校验(如参数类型、取值范围),可替换为Pydantic模型(LangChain完全兼容);

  2. 字段设计区分必选/可选punny_response为必选字段,保证智能体的核心输出;weather_conditions为可选字段,设置默认值None,无需返回时可置空;

  3. 字段类型注解:通过str | None明确字段类型,让模型清晰知道输出要求,减少格式错误。

步骤5:添加对话记忆

基础智能体不具备记忆能力,多轮对话中无法识别上下文,LangChain通过检查点(Checkpointer) 实现对话记忆,示例中使用内存级记忆,生产环境中可替换为持久化存储(如数据库)。

代码实现
from langgraph.checkpoint.memory import InMemorySaver

# 初始化内存级检查点,用于存储对话记忆
checkpointer = InMemorySaver()
代码详解
  1. InMemorySaver是LangChain内置的内存级对话记忆,适合测试和小型应用,数据仅保存在程序运行内存中,程序重启后丢失;

  2. 生产环境中需使用持久化Checkpointer(如基于SQL、Redis、MongoDB的实现),将对话历史保存到数据库,实现跨会话、跨服务的记忆能力;

  3. 检查点会自动关联会话唯一标识,实现多会话的记忆隔离。

步骤6:组装并运行生产级智能体

将上述所有组件(模型、提示词、工具、上下文、结构化输出、记忆)通过create_agent整合为一个完整的智能体,然后调用运行方法测试效果,同时支持多轮连续对话

核心组装代码
from langchain.agents.structured_output import ToolStrategy

# 组装生产级智能体
agent = create_agent(
    model=model,
    system_prompt=SYSTEM_PROMPT,
    tools=[get_user_location, get_weather_for_location],
    context_schema=Context,
    response_format=ToolStrategy(ResponseFormat),
    checkpointer=checkpointer
)
组装参数详解

相比基础智能体,生产级智能体新增了3个核心配置:

  • context_schema:指定运行时上下文的schema(即步骤2定义的Context类),让智能体支持上下文注入;

  • response_format:通过ToolStrategy绑定结构化输出schema(即步骤4定义的ResponseFormat类),强制模型输出结构化结果;

  • checkpointer:绑定对话记忆的检查点(即步骤5定义的checkpointer),让智能体具备多轮记忆能力。

运行智能体并实现多轮对话

# 定义会话配置:thread_id为会话唯一标识,实现多会话隔离
config = {"configurable": {"thread_id": "1"}}

# 第一轮对话:查询户外天气(未指定位置,智能体会自动调用get_user_location工具)
response = agent.invoke(
    {"messages": [{"role": "user", "content": "what is the weather outside?"}]},
    config=config,
    context=Context(user_id="1")  # 传入运行时上下文:用户ID为1
)
print(response['structured_response'])

# 第二轮对话:感谢智能体(复用同一个thread_id,智能体可识别上下文)
response = agent.invoke(
    {"messages": [{"role": "user", "content": "thank you!"}]},
    config=config,
    context=Context(user_id="1")
)
print(response['structured_response'])

运行结果说明

  1. 第一轮输出:智能体识别到用户未指定位置,自动调用get_user_location工具(根据user_id=1返回Florida),再调用get_weather_for_location获取天气,最终返回双关语风格的结构化结果,包含必选的punny_response和可选的weather_conditions

  2. 第二轮输出:复用thread_id="1",智能体通过对话记忆识别到上一轮的上下文(用户在Florida,查询过天气),返回对应的感谢回复,weather_conditions置空为None

  3. 会话隔离:若新建thread_id(如thread_id="2"),则为全新会话,智能体无历史记忆。

三、生产级智能体完整整合代码

为了方便直接运行,以下是上述所有步骤的完整整合代码,已简化部分非核心参数(如设置temperature=0让输出完全确定):

from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool, ToolRuntime
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.structured_output import ToolStrategy

# 1. 定义精细化系统提示词
SYSTEM_PROMPT = """You are an expert weather forecaster, who speaks in puns.

You have access to two tools:

- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location

If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location."""

# 2. 定义运行时上下文schema和自定义工具
@dataclass
class Context:
    """Custom runtime context schema."""
    user_id: str

@tool
def get_weather_for_location(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"

@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
    """Retrieve user information based on user ID."""
    user_id = runtime.context.user_id
    return "Florida" if user_id == "1" else "SF"

# 3. 配置大模型参数
model = init_chat_model(
    "claude-sonnet-4-5-20250929",
    temperature=0
)

# 4. 定义结构化响应格式
@dataclass
class ResponseFormat:
    """Response schema for the agent."""
    punny_response: str
    weather_conditions: str | None = None

# 5. 初始化对话记忆
checkpointer = InMemorySaver()

# 6. 组装生产级智能体
agent = create_agent(
    model=model,
    system_prompt=SYSTEM_PROMPT,
    tools=[get_user_location, get_weather_for_location],
    context_schema=Context,
    response_format=ToolStrategy(ResponseFormat),
    checkpointer=checkpointer
)

# 运行智能体(多轮对话)
config = {"configurable": {"thread_id": "1"}}
# 第一轮:查询天气
response = agent.invoke(
    {"messages": [{"role": "user", "content": "what is the weather outside?"}]},
    config=config,
    context=Context(user_id="1")
)
print(response['structured_response'])

# 第二轮:感谢回复
response = agent.invoke(
    {"messages": [{"role": "user", "content": "thank you!"}]},
    config=config,
    context=Context(user_id="1")
)
print(response['structured_response'])

四、最终智能体核心能力总结

通过本教程搭建的生产级天气预报智能体,具备了企业级AI智能体的核心能力,也是LangChain在实际业务中的标准应用形态,具体能力如下:

  1. 支持用户上下文识别,可根据用户ID等信息提供专属服务;

  2. 智能选择并调用工具,根据用户问题的规则自动触发工具执行;

  3. 具备多轮对话记忆,通过会话ID实现上下文关联和会话隔离;

  4. 输出结构化、可解析的结果,适配生产环境的后续数据处理;

  5. 支持自定义输出风格,通过系统提示词定义智能体的说话方式;

  6. 模型参数可配置,保证响应的一致性和稳定性

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐