Anthropic Python SDK Type Definitions: TypedDicts and Pydantic Models Explained

The Anthropic Python SDK uses TypedDicts for request parameters and Pydantic BaseModels for API responses, all located in the src/anthropic/types/ directory.

The anthropics/anthropic-sdk-python repository provides comprehensive type definitions that ensure type safety when interacting with the Anthropic API. These Anthropic Python SDK type definitions separate request specifications from response objects, offering developers precise autocomplete support and runtime validation while maintaining parity with the OpenAPI specification.

TypedDict Request Definitions

The SDK represents all request parameters using TypedDicts with the naming convention <resource>_<action>_params. These files reside in src/anthropic/types/ and use total=False with typing_extensions.Required to mark optional versus required fields.

Core Request Types

Web Search and Tool Result Types

The SDK includes specific TypedDicts for web search functionality:

Cache Control and Caller Types

Pydantic BaseModel Response Definitions

Every object returned by the API is represented as a Pydantic BaseModel subclass. These models inherit from the SDK-specific BaseModel defined in src/anthropic/_models.py#L97, which adds helpers like to_dict(), to_json(), and request-ID handling.

Core Response Models

Tool and Block Models

Error and Beta Models

Specialized Feature Models

Practical Usage Examples

Building Requests with TypedDicts

When constructing API requests, import the appropriate TypedDict definitions to ensure type safety:

from anthropic import Anthropic
from anthropic.types.message_create_params import MessageCreateParams
from anthropic.types.tool_param import ToolParam

# Define tool using TypedDict

search_tool: ToolParam = {
    "name": "web_search",
    "description": "Search the web for a query",
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {"type": "string"}
        }
    },
}

# Build request parameters

params: MessageCreateParams = {
    "model": "claude-3-5-sonnet-20240620",
    "max_tokens": 1024,
    "messages": [
        {"role": "user", "content": "Find the latest news about AI safety."}
    ],
    "tools": [search_tool],
}

client = Anthropic()
response = client.messages.create(**params)

The MessageCreateParams TypedDict is defined in src/anthropic/types/message_create_params.py, while ToolParam lives in src/anthropic/types/tool_param.py.

Handling Web Search Tool Results

For web search tool results, use the specific TypedDicts designed for this feature:

from anthropic.types.web_search_tool_result_block_param import (
    WebSearchToolResultBlockParam,
    Caller,
)

result_block: WebSearchToolResultBlockParam = {
    "type": "web_search_tool_result",
    "tool_use_id": "toolu_01ABC",
    "content": {
        "type": "text",
        "text": "The most recent AI safety paper discusses..."
    },
    "cache_control": {"type": "ephemeral"},
}

This structure is defined in src/anthropic/types/web_search_tool_result_block_param.py at line 19.

Accessing Response Data with BaseModels

Responses from the API are Pydantic models with convenient accessor methods:

import anthropic

# Assume msg is the Message returned from client.messages.create()

msg = client.messages.create(...)

# Access usage statistics

print(f"Input tokens: {msg.usage.input_tokens}")
print(f"Output tokens: {msg.usage.output_tokens}")

# Iterate over content blocks

for block in msg.content:
    if isinstance(block, anthropic.types.tool_use_block.ToolUseBlock):
        print(f"Tool call: {block.name} with input {block.input}")
    elif isinstance(block, anthropic.types.text_block.TextBlock):
        print(f"Text: {block.text}")

# Convert to dictionary or JSON

dict_data = msg.to_dict()
json_str = msg.to_json()

The Message model is defined in src/anthropic/types/message.py, while ToolUseBlock and TextBlock are in src/anthropic/types/tool_use_block.py and src/anthropic/types/text_block.py respectively. All inherit from the custom BaseModel in src/anthropic/_models.py.

Summary

  • TypedDicts in src/anthropic/types/*_param.py files define request parameter structures with total=False and Required markers for OpenAPI compliance.
  • Pydantic BaseModels in src/anthropic/types/*.py (non-param files) represent API responses, inheriting from the custom BaseModel defined in src/anthropic/_models.py.
  • Web search tools have dedicated TypedDicts like WebSearchToolResultBlockParam located in src/anthropic/types/web_search_tool_result_block_param.py.
  • Beta features maintain separate type definitions in src/anthropic/types/beta/ to isolate experimental APIs.
  • All type definitions are auto-generated from the OpenAPI specification, ensuring request and response shapes remain synchronized.

Frequently Asked Questions

What is the difference between TypedDicts and Pydantic models in the Anthropic SDK?

TypedDicts are used exclusively for request parameters (files ending in _param.py), allowing you to pass plain dictionaries to methods like client.messages.create() while maintaining type safety. Pydantic BaseModels are used for all API responses, providing runtime validation, serialization methods like .to_dict() and .to_json(), and attribute access. The separation mirrors the OpenAPI specification's distinction between input schemas and output objects.

Where are the type definitions located in the repository?

All type definitions reside in the src/anthropic/types/ directory. Request parameter TypedDicts follow the pattern src/anthropic/types/<resource>_<action>_params.py (e.g., message_create_params.py), while response Pydantic models use src/anthropic/types/<model_name>.py (e.g., message.py, tool_use_block.py). Beta-specific types are isolated in src/anthropic/types/beta/.

How do I import and use specific type definitions like MessageCreateParams?

Import TypedDicts directly from their respective modules under anthropic.types:

from anthropic.types.message_create_params import MessageCreateParams
from anthropic.types.tool_param import ToolParam

params: MessageCreateParams = {
    "model": "claude-3-5-sonnet-20240620",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello"}]
}

For response models, import from the main types module:

from anthropic.types import Message, ToolUseBlock

Are beta features typed differently in the SDK?

Yes, beta features maintain separate type definitions to prevent breaking changes in stable code. Beta TypedDicts and Pydantic models are located in src/anthropic/types/beta/ and typically include Beta prefixes in their class names (e.g., BetaMessageBatchSucceededResult in src/anthropic/types/beta/messages/beta_message_batch_succeeded_result.py). These follow the same TypedDict/BaseModel separation as stable types but may change without notice as the beta APIs evolve.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →