Skip to main content
本快速入门将引导您在几分钟内从简单设置到构建功能完整的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="anthropic:claude-sonnet-4-5",
    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"}]}
)
对于此示例,您需要设置一个Claude (Anthropic)账户并获取API密钥。然后,在终端中设置ANTHROPIC_API_KEY环境变量。

构建真实场景智能体

接下来构建一个实用的天气预报智能体,展示关键的生产概念:
  1. 详细的系统提示以改善智能体行为
  2. 创建工具与外部数据集成
  3. 模型配置以获得一致的响应
  4. 结构化输出以获得可预测的结果
  5. 对话记忆用于类似聊天的交互
  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."""
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(
    "anthropic:claude-sonnet-4-5",
    temperature=0.5,
    timeout=10,
    max_tokens=1000
)
4

定义响应格式

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

# 我们在这里使用dataclass,但也支持Pydantic模型。
@dataclass
class ResponseFormat:
    """智能体的响应模式。"""
    # 一个包含双关语的响应(始终必需)
    punny_response: str
    # 可用的天气相关信息(如果存在)
    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`是给定对话的唯一标识符。
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!"
# )


# 注意,我们可以使用相同的`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
# )
恭喜!您现在拥有了一个能够:
  • 理解上下文并记住对话
  • 智能使用多个工具
  • 以一致格式提供结构化响应
  • 通过上下文处理用户特定信息
  • 在交互间维护对话状态的AI智能体

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