使用 AI 编程助手?
- 安装 LangChain 文档 MCP 服务器 让您的助手访问最新的 LangChain 文档和示例。
- 安装 LangChain Skills 以提高您的助手在 LangChain 生态系统任务中的表现。
前提条件
对于这些示例,您需要:- 安装 LangChain 包
- 配置一个 Claude (Anthropic) 账户并获取 API 密钥
- 在您的终端中设置
ANTHROPIC_API_KEY环境变量
构建一个简单智能体
首先创建一个能够回答问题并调用工具的简单智能体。该智能体以 Claude Sonnet 4.6 为其语言模型,以一个基本的天气函数为工具,并使用一个简单的提示词来指导其行为。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-6",
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 文档。
构建一个真实的智能体
接下来,构建一个真实的天气预报智能体,来具体阐述关键的概念:- 详细的系统提示词 以获得更好的智能体行为
- 创建工具 以集成外部数据
- 模型配置 以获得一致的响应
- 结构化输出 以获得可预测的结果
- 对话记忆 以获得类似聊天的交互体验
- 创建并运行代理 以测试功能完整的智能体
定义系统提示词
系统提示词定义了智能体的角色和行为。系统提示词要尽量具体和可操作:
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."""
新建工具
工具 允许模型通过调用您定义的函数与外部系统交互。
工具可以访问运行时上下文,也可以与智能体记忆交互。请注意下面
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"
配置您的模型
根据您的选择,配置正确参数来设置您的语言模型:根据所选的模型和提供商,初始化参数可能会有所不同;请参阅它们的参考页面了解详情。
from langchain.chat_models import init_chat_model
model = init_chat_model(
"claude-sonnet-4-6",
temperature=0.5,
timeout=10,
max_tokens=1000
)
定义响应格式
如果您需要智能体的应答符合特定模式结构,可选择定义结构化响应格式。
from dataclasses import dataclass
# 我们在这里使用 dataclass,但也支持 Pydantic 模型。
@dataclass
class ResponseFormat:
"""Response schema for the agent."""
# 一个双关语的回复(始终必需)
punny_response: str
# 如果有的话,关于天气状况的任何有趣信息
weather_conditions: str | None = None
创建并运行智能体
将所有组件组装到智能体,然后运行!
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
)
# `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!"
# )
# 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'])
# 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
# )
# )
Show 完整版代码
Show 完整版代码
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
# 定义系统提示词
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."""
# 定义上下文模式
@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"
# 配置模型
model = init_chat_model(
"claude-sonnet-4-6",
temperature=0
)
# 定义响应格式
@dataclass
class ResponseFormat:
"""Response schema for the agent."""
# 一个双关语的回复(始终必需)
punny_response: str
# 如果有的话,关于天气状况的任何有趣信息
weather_conditions: str | None = None
# 设置记忆
checkpointer = InMemorySaver()
# 创建代理
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
)
# 运行代理
# `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!"
# )
# 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'])
# 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 文档。
- 理解上下文 并记住对话
- 智能使用多个工具
- 以一致格式提供结构化响应
- 通过上下文处理用户特定信息
- 在交互之间保持对话状态

