Skip to main content
Alpha 版本提示: 本文档涵盖的是 v1-alpha 版本。内容尚不完整,且可能随时变更。如需查阅最新稳定版本,请参阅 v0 版本的 LangChain Python 文档LangChain JavaScript 文档
欢迎使用 LangChain!本快速入门指南将在几分钟内带你从零开始构建一个功能完备的 AI 智能体。我们将从最简单的例子入手,逐步构建更复杂的功能。

极速上手

我们先从最基础的内容开始——创建一个能够回答问题并使用工具的简单智能体:
from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """获取指定城市的天气。"""
    return f"{city}总是阳光明媚!"

agent = create_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[get_weather],
    prompt="你是一个乐于助人的助手",
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "旧金山的天气怎么样?"}]}
)
刚才发生了什么? 我们创建了一个包含以下要素的智能体:
  • 一个语言模型(Claude 3.7 Sonnet)
  • 一个简单工具(天气函数)
  • 一个基础提示词
  • 通过消息调用的能力

构建一个贴近现实的智能体

现在我们来构建一个更实用的智能体。我们将创建一个天气预报智能体,展示你在生产环境中会用到的关键概念:
  1. 详细的系统提示词,以优化智能体行为
  2. 真实世界的工具,可与外部数据集成
  3. 模型配置,确保响应一致性
  4. 结构化输出,实现可预测的结果
  5. 对话记忆,支持类聊天交互
让我们逐步完成每个步骤:
1

定义系统提示词

系统提示词定义了智能体的“人格”和指令。请确保提示词具体且可操作:
system_prompt = """你是一位擅长双关语的天气预报专家。

你可以使用以下两个工具:

- get_weather_for_location:用于获取特定位置的天气
- get_user_location:用于获取用户所在位置

如果用户向你询问天气,请确保你已明确位置。如果从问题中可以判断用户指的是他们当前所在位置,请使用 get_user_location 工具获取其位置。"""
2

创建工具

工具 是智能体可以调用的函数,应有良好的文档说明。通常,工具需要连接外部系统,并依赖运行时配置来实现。注意下面 get_user_location 工具正是这样实现的:
from langchain_core.tools import tool

def get_weather_for_location(city: str) -> str:  # (1)!
    """获取指定城市的天气。"""
    return f"{city}总是阳光明媚!"

from langchain_core.runnables import RunnableConfig

USER_LOCATION = {
    "1": "佛罗里达",
    "2": "旧金山"
}

@tool
def get_user_location(config: RunnableConfig) -> str:
    """根据用户 ID 获取用户信息。"""
    user_id = config["context"].get("user_id")
    return USER_LOCATION[user_id]
3

配置模型

根据你的使用场景设置合适的语言模型参数:
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "anthropic:claude-3-7-sonnet-latest",
    temperature=0
)
4

定义响应格式

结构化输出可确保智能体以可预测的格式返回数据。这里我们使用 Python 的 DataClass
from dataclasses import dataclass

@dataclass
class WeatherResponse:
    conditions: str
    punny_response: str
5

添加记忆

让智能体能够记住对话历史:
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()
6

整合所有组件

现在,将所有组件组装成完整的智能体:
agent = create_agent(
    model=model,
    prompt=system_prompt,
    tools=[get_user_location, get_weather_for_location],
    response_format=WeatherResponse,
    checkpointer=checkpointer
)

config = {"configurable": {"thread_id": "1"}}
context = {"user_id": "1"}
response = agent.invoke(
    {"messages": [{"role": "user", "content": "外面天气怎么样?"}]},
    config=config,
    context=context
)

response['structured_response']

response = agent.invoke(
    {"messages": [{"role": "user", "content": "谢谢!"}]},
    config=config,
    context=context
)

response['structured_response']

你已构建的内容

恭喜!你现在拥有一个功能强大的 AI 智能体,它能够:
  • 理解上下文并记住对话历史
  • 智能使用多种工具
  • 以一致的格式提供结构化响应
  • 通过上下文处理用户特定信息
  • 在多次交互中保持对话状态