Skip to content

Clients Anthropic client

github-actions[bot] edited this page Dec 2, 2026 · 1 revision

title: Anthropic client summary: Claude models, backend selection, request capabilities and refusal behavior.

Anthropic client

Purpose

Use AnthropicClient for Claude calls through the direct Anthropic API, Amazon Bedrock, or a Claude-on-AWS workspace. The client accepts ClaudeModel values or model-id strings, including ClaudeModel.FABLE_5_2 / "claude-fable-5-2".

It normalizes requests for the Anthropic API version used by the SDK, routes beta-only requests to the beta Messages endpoint, and makes a provider refusal observable rather than silently returning an empty response.

Public API

  • AnthropicClient — asynchronous Claude client with ask, ask_stream, invoke, and batch_ask.
  • ClaudeModel — supported Claude model enum, including FABLE_5_2.
  • ResponseRefusedError — typed InvokeError raised when a call promised parsed or invoked output and the provider refuses it.

Configuration & Parameters

Backend selection

backend Credentials and required parameters Notes
"direct" (default) api_key or ANTHROPIC_API_KEY Calls api.anthropic.com. This is the only backend supporting server-side refusal fallbacks.
"bedrock" Standard AWS credentials; aws_region or BEDROCK_AWS_REGION; optional region_prefix Uses Bedrock. When configured, region_prefix translates the model to a cross-region inference-profile id.
"aws" AWS credentials, aws_region, workspace_id or ANTHROPIC_AWS_WORKSPACE_ID, and an AWS workspace key (api_key or ANTHROPIC_AWS_API_KEY) Uses a Claude-on-AWS workspace. A direct API key is not the normal credential for this backend.

The existing defaults remain unchanged: the default and capacity fallback model are both claude-sonnet-4-5, and the lightweight invoke model is claude-haiku-4-5-20251001. This feature does not change either default.

Request capability normalization

The API version used by the SDK does not accept temperature, top_p, or top_k; the client removes them before every Messages request and the API defaults apply. Do not rely on those values being sent.

For Fable 5/5.1/5.2, Mythos 5, Opus 5.5, and Sonnet 5.5, an explicit thinking={"type": "disabled"} is removed because those models require the parameter to be omitted. For Fable/Mythos 5, Opus 5 and 4.7/4.8, Sonnet 5, and Haiku 5 models, enabled thinking with a fixed budget_tokens is rewritten to adaptive thinking. The rewrite preserves display when supplied:

# Sent by the caller
thinking = {"type": "enabled", "budget_tokens": 8_000, "display": "summary"}

# Sent by AnthropicClient for a budget-rejecting model
thinking = {"type": "adaptive", "display": "summary"}

Refusal fallbacks

refusal_fallbacks is keyword-only and disabled by default (None). It accepts:

Value Request behavior
None Do not request a server-side fallback. Existing direct calls continue to use the stable endpoint.
"default" Let Anthropic choose an eligible fallback according to the refusal category.
Sequence of str or ClaudeModel Request those fallback models in order.

The option is applied only for eligible direct requests (Fable 5, Mythos 5, Opus 5, and Sonnet 5.5). It adds the server-side-fallback-2026-07-01 beta flag and therefore uses the beta Messages endpoint. On bedrock and aws, the option is ignored and the client logs one warning at construction. It is never applied to Message Batches.

Usage Examples

Direct, Bedrock, and AWS workspace calls

Credentials are read from environment variables when corresponding constructor values are omitted. Do not put keys in source code.

import asyncio

from parrot.clients.anthropic import AnthropicClient, ClaudeModel


async def main() -> None:
    direct = AnthropicClient(backend="direct")  # ANTHROPIC_API_KEY
    bedrock = AnthropicClient(backend="bedrock", aws_region="us-east-1")
    workspace = AnthropicClient(
        backend="aws",
        aws_region="us-east-1",
        workspace_id="workspace-from-environment-or-config",
    )

    async with direct:
        answer = await direct.ask("Summarize this report.", model=ClaudeModel.FABLE_5_2)
        print(answer.output)

    async with bedrock:
        answer = await bedrock.ask("Summarize this report.", model=ClaudeModel.FABLE_5_2)
        print(answer.output)

    async with workspace:
        answer = await workspace.ask("Summarize this report.", model=ClaudeModel.FABLE_5_2)
        print(answer.output)


asyncio.run(main())

Handle a plain refusal

A non-structured ask() returns an AIMessage when the provider stops with "refusal". Check the terminal reason and the refusal metadata rather than treating its content as a normal answer.

from parrot.clients.anthropic import AnthropicClient


async def request_text() -> None:
    client = AnthropicClient()
    async with client:
        message = await client.ask("Request that may be refused")

    if message.stop_reason == "refusal":
        refusal = message.metadata["refusal"]
        print(refusal["category"], refusal["explanation"])
        return

    print(message.output)

Handle typed structured and invoke errors

ask(..., structured_output=...) and invoke() promise parsed or invoked output. They raise ResponseRefusedError instead of sending a refusal into a parser. The error exposes the optional category, explanation, and model attributes.

The helper methods follow the same rule. ask_to_image(..., structured_output=...), analyze_sentiment(..., use_structured=True) and analyze_product_review raise; plain ask_to_image, summarize_text, translate_text, extract_key_points, analyze_sentiment, resume and batch_ask results carry metadata["refusal"]. detect_objects logs the failure and returns an empty list.

from pydantic import BaseModel

from parrot.clients.anthropic import AnthropicClient
from parrot.exceptions import ResponseRefusedError


class Answer(BaseModel):
    summary: str


async def request_structured() -> None:
    client = AnthropicClient()
    try:
        async with client:
            message = await client.ask("Classify this request", structured_output=Answer)
            # `message` is reached only when the provider did not refuse.
            print(message.output)
    except ResponseRefusedError as error:
        print(error.category, error.explanation, error.model)

Consume a terminal streamed refusal

ask_stream() yields text chunks followed by one terminal AIMessage. A refused stream yields that terminal message with metadata["refusal"] and does not take the max-token retry path.

from parrot.clients.anthropic import AnthropicClient
from parrot.models.responses import AIMessage


async def request_stream() -> None:
    client = AnthropicClient()
    async with client:
        async for item in client.ask_stream("Request that may be refused"):
            if isinstance(item, AIMessage):
                if item.stop_reason == "refusal":
                    print(item.metadata["refusal"])
                else:
                    print(item.output)
            else:
                print(item, end="")

Opt into server-side refusal fallbacks

Use "default" to let Anthropic select a fallback, or provide a list to control the order. When Anthropic serves a fallback, the returned AIMessage.model is the serving model and metadata["refusal_fallback"] records the last transition. When the requested model never ran, the response has no fallback block; the client then reads the fallback_message entry in usage.iterations and reports the requested model as from. invoke() returns no metadata, but its result's model is the serving model.

from parrot.clients.anthropic import AnthropicClient, ClaudeModel


async def request_with_fallbacks() -> None:
    client = AnthropicClient(
        refusal_fallbacks=[ClaudeModel.SONNET_5_5, "claude-opus-5"],
    )
    async with client:
        message = await client.ask("Answer safely", model=ClaudeModel.FABLE_5_2)

    served_by = message.metadata.get("refusal_fallback")
    if served_by:
        print(f"{served_by['from']} -> {served_by['to']}; served by {message.model}")

Gotchas

  • A model-list fallback is a provider request, not client-side retry logic. The client does not validate the list. In particular, a Sonnet 5.5 array-form fallback may name only claude-sonnet-5; an invalid pairing surfaces as the provider's normal 400 error.
  • Fallbacks work only on the direct backend, never on Bedrock, AWS workspaces, or Message Batches. betas and fallbacks route direct requests to client.beta.messages; if the SDK client has no beta namespace, those beta-only keys are dropped with a warning and the stable endpoint is used.
  • batch_ask reads results through the SDK's messages.batches.results(), in the order the API returns them, which may differ from request order. Match each AIMessage to its request by metadata["custom_id"]. Errored, canceled and expired requests come back as the dumped MessageBatchIndividualResponse dict, and each one logs a warning.
  • SDK fallback blocks use from_ in ordinary model dumps and from when dumped by alias. The client accepts both forms and records model-id strings in metadata["refusal_fallback"].
  • Fable 5.2 thinking blocks must be replayed unchanged in a continuing conversation. The client preserves content blocks when it continues a tool loop; callers should preserve them too.
  • context_1m=True sends the legacy context-1m-2025-08-07 beta flag through the beta endpoint. Current eligible Claude models already have a 1M context window, so the flag is retained for compatibility rather than enabling a new window. The 1M model prefixes make context budgeting five times larger for Fable, Mythos, Opus 4.6+/5, Sonnet 4.6+/5, and Haiku 5; compaction starts later and long conversations can send more input tokens. Explicit ContextBudget values, context_budget=False, and PARROT_COMPACTION_DISABLED=1 are unchanged. Bedrock-shaped model ids are not resolved to a 1M window by this mapping.
  • ask() and invoke() keep the non-streaming max_tokens ceiling of 21,333. Use ask_stream() for long generations.
  • Fable 5.2 requires 30-day data retention. A zero-data-retention organization receives 400 invalid_request_error, which propagates through the normal error path.

Related

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally