Anthropic¶
AnthropicProvider talks to the Anthropic Messages API
(POST /v1/messages). It takes the same messages, tools and
RuntimeConfig as OpenAIProvider, so a node can switch providers
without changing how it builds a call. This page covers what differs.
The 30-second version¶
import asyncio
import os
from pydantic import SecretStr
from openarmature.llm import AnthropicProvider, RuntimeConfig, SystemMessage, TextBlock, UserMessage
async def main() -> None:
provider = AnthropicProvider(
model="claude-opus-5-5",
api_key=SecretStr(os.environ.get("ANTHROPIC_API_KEY", "")),
)
messages = [
SystemMessage(content="You are a lunar geology tutor."),
UserMessage(content="Why are the lunar maria darker than the highlands?"),
]
config = RuntimeConfig(max_tokens=512) # required on every call
# await provider.ready() # pre-flight; needs a live endpoint
# response = await provider.complete(messages, config=config)
# answer = "".join(b.text for b in response.message.content if isinstance(b, TextBlock))
_ = (messages, config) # used once the calls above are uncommented
await provider.aclose()
asyncio.run(main())
The key is a pydantic SecretStr, so its repr is masked. It travels in
the x-api-key header, set on each request rather than stored in the
client's headers. Once the call ends, the header is overwritten on the
httpx request and on the redirect copy a 3xx response holds, so the
request an error or response exposes no longer shows the key. httpx's
transport layer keeps its own copy of the headers, though, which a
traceback's local variables can reach, so an error tracker that records
locals may still capture the key. A key with surrounding whitespace, a
control character or a non-ASCII character raises ValueError when the
provider is created, since it cannot be sent in a header. base_url
defaults to https://api.anthropic.com; pass the host root of a
gateway to route through one, without a /v1 suffix.
What differs from OpenAIProvider¶
max_tokens is required. The Messages API has no default, and the
provider does not pick one for you. A call without
RuntimeConfig.max_tokens raises ProviderInvalidRequest before
anything is sent.
Some settings are rejected. The Messages API has no seed,
frequency_penalty or presence_penalty. Setting any of them raises
ProviderInvalidRequest rather than being dropped quietly.
temperature, top_p and stop_sequences map directly, but most
current Claude models reject temperature and top_p; the API's 400
then surfaces as ProviderInvalidRequest. The provider sends API
version 2023-06-01 by default. Pass api_version= to send another.
A reply's content is always a list of blocks, even a plain text reply, because Anthropic returns content that way and a reply may hold reasoning blocks beside its text. Read the text by walking the blocks:
from openarmature.llm import Response, TextBlock
def reply_text(response: Response) -> str:
content = response.message.content
if isinstance(content, str):
return content # "" on a reply cut short with nothing left
return "".join(block.text for block in content if isinstance(block, TextBlock))
A reply cut short with nothing to show, such as a refusal
(finish_reason="content_filter"), has "" as its content instead.
Don't append that reply to a conversation you will send again: the next
complete() rejects an assistant message with no content and no tool
calls.
System messages go to the request's top-level system field, and
tool results travel as tool_result blocks inside a user message.
You build the conversation the same way as for any provider; the
mapping happens on the wire.
tool_choice="required" becomes Anthropic's {"type": "any"}.
The other modes and ForceTool map directly. Several current models,
Claude Opus 5.5 and Claude Sonnet 5.5 among them, reject forced tool use
("required" or ForceTool) with a 400, which surfaces as
ProviderInvalidRequest; use "auto" and name the tool in the prompt
instead. The same applies to the "tool_coercion" structured-output
path below, which forces a tool.
Images go out as url or base64 sources. The detail hint has
no Anthropic form and is dropped.
Extended thinking¶
Current Claude models think by default. Their replies hold
ThinkingBlock (and sometimes RedactedThinkingBlock) entries before
the text, and each carries a signature Anthropic checks on the next
turn, so append the assistant message exactly as you received it. By
default the reasoning text is left out and the block arrives empty with
only its signature; it is still a valid block and goes back the same
way.
The request's thinking and output_config parameters have no
RuntimeConfig field, so pass them through extras. For example, to
get readable summaries of the reasoning and set the effort level:
from openarmature.llm import RuntimeConfig
config = RuntimeConfig(
max_tokens=16000,
extras={
"thinking": {"type": "adaptive", "display": "summarized"},
"output_config": {"effort": "high"},
},
)
Anthropic signs no text blocks. A TextBlock signature in your history
came from another provider, so AnthropicProvider sends the text
without it, and leaves out a block that only carried a signature.
Anthropic does sign every thinking block, so a ThinkingBlock without
a signature came from another provider too, and is left out. A reply
holding a thinking block without a signature raises
ProviderInvalidResponse. An assistant message left with nothing to
send raises ProviderInvalidRequest.
The same extras route works for any other Messages API parameter
without a RuntimeConfig field, such as top_k or metadata. The
keys the provider builds itself are reserved: model, messages,
system, tools, tool_choice and stream, plus temperature,
top_p and max_tokens when RuntimeConfig sets them. An extras
value for a reserved key raises ProviderInvalidRequest, unless it
matches what the provider sends, in which case it is ignored. A
stop_sequences extra is merged with RuntimeConfig.stop_sequences.
How an output_config extra combines with structured output is covered
in the next section.
Structured output¶
complete(response_schema=...) works as it does on every provider:
Response.parsed holds the validated value, and a reply that does not
parse or validate raises StructuredOutputInvalid. See
Structured output for the two schema
forms.
from pydantic import BaseModel, ConfigDict
from openarmature.llm import AnthropicProvider, RuntimeConfig, UserMessage
class Crater(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
diameter_km: float
async def describe_crater(provider: AnthropicProvider) -> Crater:
response = await provider.complete(
[UserMessage(content="Name one large crater on the Moon and its diameter.")],
config=RuntimeConfig(max_tokens=1024),
response_schema=Crater,
)
assert isinstance(response.parsed, Crater)
return response.parsed
The provider sends your schema unchanged, and Anthropic accepts only
some schemas. It requires every object to set
additionalProperties: false, which a Pydantic model does with
extra="forbid", so give that to each model in the schema, nested ones
included. A schema Anthropic does not accept raises
ProviderInvalidRequest with Anthropic's reason.
The provider asks for structured output in one of three ways, set by
the structured_output constructor argument:
"native", the default, sends the schema as the request'soutput_config.format. Anthropic constrains the reply to the schema. Use it on any current Claude model."tool_coercion"is for older models withoutoutput_config.format. The request carries one tool, namedstructured_output, whose input schema is your schema, and forces the model to call it.Response.parsedcomes from that tool's input alone, and a reply that does not call the tool raisesStructuredOutputInvalid. The reply reports the tool's input as its text, as JSON, so the message has no tool call and the reply can go back into the conversation without a tool result. A reply that ends normally hasfinish_reason"stop". A call that passes a non-emptytoolslist or anytool_choicetakes"prompt_augmentation"instead, so your tools are never replaced. Anthropic does not allow a forced tool together with extended thinking, so the API rejects a call on this path that turnsthinkingon throughextras."prompt_augmentation"adds a directive holding the schema to thesystemprompt, and asks for nothing on the wire. Your message list is not changed.
The structured_output property returns the configured value. Each
call reports the one it took as structured_output_path on its typed
LLM event and as openarmature.llm.structured_output.path on its span.
Even on the native path a reply can miss the schema. A refusal
(finish_reason "content_filter"), a reply cut off at max_tokens
("length"), and a string enum value in the wrong case ("stop")
usually fail to parse or validate, and then raise
StructuredOutputInvalid, with the reply's text on output_content
and its finish_reason beside it. The provider never repairs such a
reply. The check is the schema, not the finish reason: on the native
and prompt-augmentation paths a cut-off or refused reply whose text
still validates is returned, with its finish_reason on the
Response. On "tool_coercion" a refused or cut-off reply
raises without being validated, since a tool call cut off at
max_tokens comes back with an empty input that a lenient schema would
accept. A native-path reply that ends normally but is not
a JSON object at all also logs the
openarmature.structured_output.schema_not_honored warning, as on
OpenAI's strict path. A reask, set with LlmRetryConfig(reask=...),
works on all three paths; on "tool_coercion" the failed tool input
goes back as the assistant's text.
On the native path the provider builds output_config.format, but
output_config has other members, such as effort. An
output_config extra merges its other members into the one the
provider sends:
from openarmature.llm import RuntimeConfig
config = RuntimeConfig(max_tokens=1024, extras={"output_config": {"effort": "low"}})
An extra that sets format to anything other than what the provider
builds raises ProviderInvalidRequest. On a call without a
response_schema, or on the other two paths, an output_config extra
is sent as written.
Not supported yet¶
- Streaming. Calls are atomic.
disable_parallel_tool_useandis_error. The first belongs inside the request'stool_choice, which is reserved, and the second on atool_resultblock, whichToolMessagehas no field for, so neither can be sent yet.
ready()¶
ready() fetches the bound model's record
(GET /v1/models/{model}), which checks the key and that the model
exists without billing any tokens. A missing model raises
ProviderInvalidModel; a rejected key raises ProviderAuthentication.
A reply that is not a model record, as a misconfigured gateway might
send, raises ProviderInvalidResponse.
Errors¶
Anthropic's errors map onto the same categories as every provider's.
Two are worth knowing: a 402 billing error raises
ProviderAuthentication, since the account cannot be used until it is
fixed, and a 529 overloaded error raises ProviderUnavailable, which
the default retry classifier treats as transient. A 429 carries its
retry-after delay on ProviderRateLimit.retry_after.
Observability¶
Spans and typed events name the provider anthropic. Pass
genai_system= to the constructor to report something else, such as a
gateway's name.
Example¶
The landing-site review example
runs a tool-calling review on AnthropicProvider with extended thinking,
printing summaries of the reasoning and keeping the thinking blocks in
the history across tool turns.