本快速入门指南将在几分钟内带您从简单设置到功能齐全的 AI 智能体。

构建基本智能体

首先创建一个可以回答问题和调用工具的简单智能体。该智能体将使用 Claude Sonnet 4.5 作为其语言模型,使用基本的天气函数作为工具,并使用简单的提示来指导其行为。
对于此示例,您需要设置一个 Claude (Anthropic) 账户并获取 API 密钥。然后,在终端中设置 ANTHROPIC_API_KEY 环境变量。
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",
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
要了解如何使用 LangSmith 跟踪您的智能体,请参阅 LangSmith 文档

构建真实世界的智能体

接下来,构建一个实用的天气预报智能体,演示关键的生产概念:
  1. 详细的系统提示,实现更好的智能体行为
  2. 创建工具,与外部数据集成
  3. 模型配置,实现一致的响应
  4. 结构化输出,获得可预测的结果
  5. 对话记忆,实现类似聊天的交互
  6. 创建并运行智能体,创建功能齐全的智能体
让我们逐步介绍每一步:
1

定义系统提示

系统提示定义您的智能体的角色和行为。保持具体和可操作:
SYSTEM_PROMPT = """您是一位专业的天气预报员,说话时使用双关语。

您可以访问两个工具:

- get_weather_for_location:使用此工具获取特定位置的天气
- get_user_location:使用此工具获取用户的位置

如果用户询问天气,请确保您知道位置。如果您能从问题中看出他们指的是他们所在的位置,请使用 get_user_location 工具来查找他们的位置。"""
2

创建工具

工具让模型通过调用您定义的函数与外部系统交互。 工具可以依赖运行时上下文,也可以与智能体内存交互。请注意下面 get_user_location 工具如何使用运行时上下文:
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}!"

@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"
工具应该有良好的文档:它们的名称、描述和参数名称成为模型提示的一部分。 LangChain 的 @tool 装饰器 添加元数据并通过 ToolRuntime 参数启用运行时注入。
3

配置您的模型

使用适合您用例的参数设置您的语言模型
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
)
4

定义响应格式

可选地,如果您需要智能体响应匹配特定模式,请定义结构化响应格式。
from dataclasses import dataclass

# We use a dataclass here, but Pydantic models are also supported.
@dataclass
class ResponseFormat:
    """Response schema for the agent."""
    # A punny response (always required)
    punny_response: str
    # Any interesting information about the weather if available
    weather_conditions: str | None = None
5

添加内存

向您的智能体添加内存以在交互之间维护状态。这允许智能体记住以前的对话和上下文。
from langgraph.checkpoint.memory import InMemorySaver

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=ResponseFormat,
    checkpointer=checkpointer
)

# `thread_id` is a unique identifier for a given conversation.
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'])
# ResponseFormat(
#     punny_response="Florida is still having a 'sun-derful' day! The sunshine is playing 'ray-dio' hits all day long! I'd say it's the perfect weather for some 'solar-bration'! If you were hoping for rain, I'm afraid that idea is all 'washed up' - the forecast remains 'clear-ly' brilliant!",
#     weather_conditions="It's always sunny in Florida!"
# )


# Note that we can continue the conversation using the same `thread_id`.
response = agent.invoke(
    {"messages": [{"role": "user", "content": "thank you!"}]},
    config=config,
    context=Context(user_id="1")
)

print(response['structured_response'])
# ResponseFormat(
#     punny_response="You're 'thund-erfully' welcome! It's always a 'breeze' to help you stay 'current' with the weather. I'm just 'cloud'-ing around waiting to 'shower' you with more forecasts whenever you need them. Have a 'sun-sational' day in the Florida sunshine!",
#     weather_conditions=None
# )
要了解如何使用 LangSmith 跟踪您的智能体,请参阅 LangSmith 文档
恭喜!您现在拥有一个可以:
  • 理解上下文并记住对话
  • 智能使用多个工具
  • 提供结构化响应,格式一致
  • 通过上下文处理用户特定信息
  • 在交互之间维护对话状态的 AI 智能体

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.