get_num_tokens_from_messages(
self,
messages: list[BaseMessage],
tools: Sequence[dict[strCount tokens in a sequence of input messages.
This uses Anthropic's official token counting API.
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
model = ChatAnthropic(model="claude-sonnet-4-5-20250929")
messages = [
SystemMessage(content="You are a scientist"),
HumanMessage(content="Hello, Claude"),
]
model.get_num_tokens_from_messages(messages)
14from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
model = ChatAnthropic(model="claude-sonnet-4-5-20250929")
@tool(parse_docstring=True)
def get_weather(location: str) -> str:
"""Get the current weather in a given location
Args:
location: The city and state, e.g. San Francisco, CA
"""
return "Sunny"
messages = [
HumanMessage(content="What's the weather like in San Francisco?"),
]
model.get_num_tokens_from_messages(messages, tools=[get_weather])
403If provided, sequence of dict, BaseModel, function, or BaseTool
objects to be converted to tool schemas.
Additional keyword arguments are passed to the Anthropic
messages.count_tokens method.