Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Anthropics Anthropic sdk python Messages Create With Tools

From Leeroopedia
Knowledge Sources
Domains Tool_Use, LLM, Function_Calling
Last Updated 2026-02-15 00:00 GMT

Overview

This page documents the Messages.create() method from the tool-use perspective, focusing on the tools and tool_choice parameters that enable Claude to invoke functions during a conversation. This is the same Messages.create() API used for standard message generation, extended with tool definitions.

API Signature (Tool-Relevant Parameters)

def create(
    self,
    *,
    max_tokens: int,
    messages: Iterable[MessageParam],
    model: ModelParam,
    # ... other params ...
    tool_choice: ToolChoiceParam | Omit = omit,
    tools: Iterable[ToolUnionParam] | Omit = omit,
    # ... other params ...
) -> Message | Stream[RawMessageStreamEvent]

Source Location

File: src/anthropic/resources/messages/messages.py, lines 927-1003

Import

import anthropic

client = anthropic.Anthropic()
message = client.messages.create(...)

Key Parameters

tools: Iterable[ToolUnionParam]

An iterable of tool definition dicts. The ToolUnionParam type is defined in src/anthropic/types/tool_union_param.py as:

ToolUnionParam: TypeAlias = Union[
    ToolParam,                      # Custom user-defined tools
    ToolBash20250124Param,          # Built-in bash tool
    ToolTextEditor20250124Param,    # Built-in text editor (Jan 2025)
    ToolTextEditor20250429Param,    # Built-in text editor (Apr 2025)
    ToolTextEditor20250728Param,    # Built-in text editor (Jul 2025)
    WebSearchTool20250305Param,     # Built-in web search tool
]

For custom tools, each ToolParam dict must contain:

Field Type Required Description
name str Yes Unique name for the tool, used in tool_use blocks
input_schema InputSchema Yes JSON Schema defining the tool's parameters
description str No (but recommended) Natural language description of what the tool does
cache_control None No Cache control breakpoint
strict bool No When true, guarantees schema validation on tool names and inputs
eager_input_streaming None No Enable incremental input streaming for this tool
type None No Tool type discriminator

tool_choice: ToolChoiceParam

Controls when and how the model uses tools. Defined in src/anthropic/types/tool_choice_param.py as:

ToolChoiceParam: TypeAlias = Union[
    ToolChoiceAutoParam,   # {"type": "auto"}
    ToolChoiceAnyParam,    # {"type": "any"}
    ToolChoiceToolParam,   # {"type": "tool", "name": "..."}
    ToolChoiceNoneParam,   # {"type": "none"}
]

Strategy details:

Strategy TypedDict Fields Behavior
Auto ToolChoiceAutoParam type: "auto", disable_parallel_tool_use: bool (optional) Model decides whether to use tools
Any ToolChoiceAnyParam type: "any", disable_parallel_tool_use: bool (optional) Model must use at least one tool
Tool ToolChoiceToolParam type: "tool", name: str (required), disable_parallel_tool_use: bool (optional) Model must use the specified tool
None ToolChoiceNoneParam type: "none" Model cannot use any tools

Return Value

Returns a Message object. When the model decides to invoke tools, the response has:

  • stop_reason == "tool_use"
  • content array containing one or more ToolUseBlock objects (and optionally TextBlock objects)

When the model responds with text only:

  • stop_reason == "end_turn"
  • content array containing TextBlock objects

Usage Examples

Basic tool call:

from anthropic import beta_tool

@beta_tool
def get_weather(city: str, unit: str = "celsius") -> str:
    """Get the current weather for a city.

    Args:
        city: The city name
        unit: Temperature unit (celsius or fahrenheit)
    """
    return f"The weather in {city} is 22 degrees"

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[get_weather.to_dict()],
    messages=[{"role": "user", "content": "What's the weather in London?"}]
)

Force a specific tool:

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[get_weather.to_dict()],
    tool_choice={"type": "tool", "name": "get_weather"},
    messages=[{"role": "user", "content": "Tell me about London"}]
)

Disable parallel tool use:

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[get_weather.to_dict(), get_news.to_dict()],
    tool_choice={"type": "auto", "disable_parallel_tool_use": True},
    messages=[{"role": "user", "content": "What's the weather and news in London?"}]
)

Raw tool definition (without decorator):

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "The city name"}
            },
            "required": ["city"]
        }
    }],
    messages=[{"role": "user", "content": "What's the weather in London?"}]
)

Internal Behavior

The method (lines 972-1003):

  1. Applies model deprecation warnings if applicable
  2. Transforms parameters via maybe_transform() to the appropriate MessageCreateParams type
  3. Posts to /v1/messages
  4. Returns a Message (non-streaming) or Stream[RawMessageStreamEvent] (streaming)
  5. Automatically calculates a non-streaming timeout based on max_tokens if none is provided

Dependencies

  • httpx: Underlying HTTP client for API requests
  • pydantic: Model for Message response parsing

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment