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 Models Resource

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, API_Resources
Last Updated 2026-02-15 12:00 GMT

Overview

Models API resource classes (Models and AsyncModels) for retrieving metadata about specific models and listing all available Claude models with cursor-based pagination.

Description

The Models (sync) and AsyncModels (async) classes extend SyncAPIResource and AsyncAPIResource respectively, providing two methods: retrieve(model_id) for fetching information about a specific model, and list() for enumerating all available models with pagination support.

The retrieve() method sends a GET request to /v1/models/{model_id} and returns a ModelInfo object. It validates that the model_id is non-empty, raising a ValueError otherwise. This method is useful for resolving model aliases to canonical model IDs or retrieving model-specific metadata.

The list() method sends a GET request to /v1/models and returns a paginated SyncPage[ModelInfo] (or AsyncPaginator[ModelInfo, AsyncPage[ModelInfo]] for async). It supports cursor-based pagination via after_id, before_id, and limit parameters, with a default page size of 20 and a maximum of 1000 items per page. More recently released models are listed first. Both methods also expose with_raw_response and with_streaming_response wrapper properties.

Usage

Use this resource to discover which models are available in the API, resolve model aliases to canonical IDs, or retrieve metadata about specific models. Access via client.models.retrieve() and client.models.list().

Code Reference

Source Location

Classes

Class Parent Description
Models SyncAPIResource Synchronous models resource
AsyncModels AsyncAPIResource Asynchronous models resource
ModelsWithRawResponse -- Wrapper returning raw httpx.Response objects
AsyncModelsWithRawResponse -- Async wrapper returning raw responses
ModelsWithStreamingResponse -- Wrapper for lazily streamed response bodies
AsyncModelsWithStreamingResponse -- Async wrapper for lazily streamed response bodies

Signature

class Models(SyncAPIResource):
    def retrieve(
        self,
        model_id: str,
        *,
        betas: List[AnthropicBetaParam] | Omit = omit,
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> ModelInfo: ...

    def list(
        self,
        *,
        after_id: str | Omit = omit,
        before_id: str | Omit = omit,
        limit: int | Omit = omit,
        betas: List[AnthropicBetaParam] | Omit = omit,
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> SyncPage[ModelInfo]: ...

class AsyncModels(AsyncAPIResource):
    async def retrieve(...) -> ModelInfo: ...
    def list(...) -> AsyncPaginator[ModelInfo, AsyncPage[ModelInfo]]: ...

Import

from anthropic import Anthropic, AsyncAnthropic

# Access via client instance
client = Anthropic()
client.models.retrieve(...)
client.models.list(...)

I/O Contract

retrieve() Parameters

Parameter Type Required Description
model_id str Yes Model identifier or alias (e.g., "claude-sonnet-4-20250514")
betas Omit No Beta feature flags sent via anthropic-beta header

list() Parameters

Parameter Type Required Description
after_id Omit No Cursor: return results immediately after this object ID
before_id Omit No Cursor: return results immediately before this object ID
limit Omit No Items per page (default 20, range 1-1000)
betas Omit No Beta feature flags sent via anthropic-beta header

Output

Method Return Type (Sync) Return Type (Async) Description
retrieve() ModelInfo ModelInfo Single model metadata object
list() SyncPage[ModelInfo] AsyncPaginator[ModelInfo, AsyncPage[ModelInfo]] Paginated list of model metadata objects

API Endpoints

Method HTTP Method Path
retrieve() GET /v1/models/{model_id}
list() GET /v1/models

Usage Examples

import anthropic

client = anthropic.Anthropic()

# Retrieve a specific model by ID
model_info = client.models.retrieve("claude-sonnet-4-20250514")
print(f"Model: {model_info.id}")
print(f"Display name: {model_info.display_name}")

# Resolve a model alias
model_info = client.models.retrieve("claude-sonnet-4-latest")
print(f"Resolved ID: {model_info.id}")

# List all available models (first page)
page = client.models.list()
for model in page.data:
    print(f"  {model.id}")

# List with pagination
page = client.models.list(limit=10)
for model in page.data:
    print(model.id)

# Iterate through all models using auto-pagination
for model in client.models.list():
    print(model.id)

# Async usage
import asyncio

async def main():
    async_client = anthropic.AsyncAnthropic()
    model = await async_client.models.retrieve("claude-sonnet-4-20250514")
    print(model.id)

    async for model in async_client.models.list():
        print(model.id)

asyncio.run(main())

# Access raw response
raw = client.models.with_raw_response.retrieve("claude-sonnet-4-20250514")
print(raw.headers)
model_info = raw.parse()

Implementation Details

Input Validation

The retrieve() method validates that model_id is non-empty:

if not model_id:
    raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}")

Beta Header Handling

Both methods convert beta flags into a comma-separated anthropic-beta header using the same pattern as other resources:

extra_headers = {
    **strip_not_given({
        "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given
    }),
    **(extra_headers or {}),
}

Related Pages

Implements Principle

Requires Environment

Uses Implementation

Page Connections

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