首先创建一个能够回答问题并调用工具的简单智能体。该智能体将使用 Claude Sonnet 4.6 作为其语言模型,一个基础的天气函数作为工具,以及一个简单的提示词来指导其行为。
from langchain.agents import create_agentdef get_weather(city: str) -> str: """获取指定城市的天气。""" 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",)# 运行智能体agent.invoke( {"messages": [{"role": "user", "content": "what is the weather in sf"}]})
from langchain.agents.structured_output import ToolStrategyagent = 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!"# )# 注意,我们可以使用相同的 `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# )
Show 完整示例代码
from dataclasses import dataclassfrom langchain.agents import create_agentfrom langchain.chat_models import init_chat_modelfrom langchain.tools import tool, ToolRuntimefrom langgraph.checkpoint.memory import InMemorySaverfrom langchain.agents.structured_output import ToolStrategy# 定义系统提示词SYSTEM_PROMPT = """你是一位擅长说双关语的天气预报专家。你可以使用两种工具:- get_weather_for_location:用于获取特定地点的天气- get_user_location:用于获取用户的位置如果用户询问天气,请确保你知道地点。如果你能从问题中判断他们指的是他们所在的位置,请使用 get_user_location 工具来查找他们的位置。"""# 定义上下文模式@dataclassclass Context: """自定义运行时上下文模式。""" user_id: str# 定义工具@tooldef get_weather_for_location(city: str) -> str: """获取指定城市的天气。""" return f"It's always sunny in {city}!"@tooldef get_user_location(runtime: ToolRuntime[Context]) -> str: """根据用户 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)# 定义响应格式@dataclassclass ResponseFormat: """智能体的响应模式。""" # 一个双关语回复(始终必需) 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!"# )# 注意,我们可以使用相同的 `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# )