from langchain_anthropic import ChatAnthropicfrom typing_extensions import Annotatedmodel = ChatAnthropic(model="claude-haiku-4-5-20251001")def get_weather( location: Annotated[str, ..., "Location as city and state."]) -> str: """Get the weather at a location.""" return "It's sunny."model_with_tools = model.bind_tools([get_weather])response = model_with_tools.invoke("Which city is hotter today: LA or NY?")response.content
[{'text': "I'll help you compare the temperatures of Los Angeles and New York by checking their current weather. I'll retrieve the weather for both cities.", 'type': 'text'}, {'id': 'toolu_01CkMaXrgmsNjTso7so94RJq', 'input': {'location': 'Los Angeles, CA'}, 'name': 'get_weather', 'type': 'tool_use'}, {'id': 'toolu_01SKaTBk9wHjsBTw5mrPVSQf', 'input': {'location': 'New York, NY'}, 'name': 'get_weather', 'type': 'tool_use'}]
from pydantic import BaseModel, Fieldclass GetWeather(BaseModel): '''Get the current weather in a given location''' location: str = Field(description="The city and state, e.g. San Francisco, CA")class GetPopulation(BaseModel): '''Get the current population in a given location''' location: str = Field(description="The city and state, e.g. San Francisco, CA")model_with_tools = model.bind_tools([GetWeather, GetPopulation])ai_msg = model_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")ai_msg.tool_calls
from langchain_anthropic import ChatAnthropicmodel = ChatAnthropic(model="claude-sonnet-4-6")def get_weather(location: str) -> str: """Get the weather at a location.""" return "It's sunny."model_with_tools = model.bind_tools([get_weather], strict=True)
示例:类型安全的预订系统
考虑一个 passengers 必须是整数的预订系统:
from langchain_anthropic import ChatAnthropicfrom typing import Literalmodel = ChatAnthropic(model="claude-sonnet-4-6")def book_flight( destination: str, departure_date: str, passengers: int, cabin_class: Literal["economy", "business", "first"]) -> str: """Book a flight to a destination. Args: destination: The destination city departure_date: Date in YYYY-MM-DD format passengers: Number of passengers (must be an integer) cabin_class: The cabin class for the flight """ return f"Booked {passengers} passengers to {destination}"model_with_tools = model.bind_tools( [book_flight], strict=True, tool_choice="any",)response = model_with_tools.invoke("Book 2 passengers to Tokyo, business class, 2025-01-15")# 使用 strict=True 时,passengers 保证是 int,而不是 "2" 或 "two"print(response.tool_calls[0]["args"]["passengers"])
2
严格工具使用有一些需要注意的 JSON 模式限制。有关详细信息,请参阅 Claude 文档。如果你的工具模式使用了不支持的功能,你将收到 400 错误。在这些情况下,请简化模式或使用标准(非严格)工具调用。
对于复杂的工具,你可以提供使用示例来帮助 Claude 正确理解如何使用它们。这是通过设置工具的 extras 参数中的 input_examples 来实现的。
from langchain_anthropic import ChatAnthropicfrom langchain.tools import tool@tool( extras={ "input_examples": [ { "query": "weather report", "location": "San Francisco", "format": "detailed" }, { "query": "temperature", "location": "New York", "format": "brief" } ] })def search_weather_data(query: str, location: str, format: str = "brief") -> str: """Search weather database with specific query and format preferences. Args: query: The type of weather information to retrieve location: City or region to search format: Output format, either 'brief' or 'detailed' """ return f"{format.title()} {query} for {location}: Data found"model = ChatAnthropic(model="claude-sonnet-4-6")model_with_tools = model.bind_tools([search_weather_data])response = model_with_tools.invoke( "Get me a detailed weather report for Seattle")