Skip to main content

Anthropic

Implemented against the Messages API.

EndpointPOST https://api.anthropic.com/v1/messages
Authx-api-key: <key>
Extra headeranthropic-version: 2023-06-01
Key variableANTHROPIC_API_KEY
Default modelclaude-opus-5
Sourcesrc/dialect/anthropic/
let client = Client::from_env(EndpointPreset::Anthropic)?;
let agent = Agent::new(client);

Verified against the live endpoint: a full tool round trip completes, prompt to tool call to result to answer. See Verification status for what that does and does not cover.

Capability support​

CapabilitySupportedNotes
Text generationyes
Images in user turnsyesURLs and data: URIs both handled
System and developer turnsyesHoisted into the top level system field
max_tokensyesRequired by the API, defaulted when unset
temperature, top_pyesForwarded, but rejected by newer models, see below
reasoning_effortyesMapped onto output_config.effort, except None which disables thinking
response_formatpartlySchema only, JsonObject rejected
Tool declarationsyesparameters becomes input_schema
tool_choiceyesRequired becomes {"type": "any"}
Tool round tripyesNested in messages, not flat
previous_response_idnoRejected with UnsupportedCapability
metadatayesForwarded unchanged
Usage reportingyesTotal computed, cache reads and writes reported apart
Prompt cachingyescache_control sent on every request, turned off with prompt_cache(false)
RefusalspartlySurfaced as ResponseStatus::Other("refusal")
Streamingyesstream: true, decoded from message_start / content_block_* / message_delta. Dialect verified live for text, against a compatible endpoint

The one place Freyja invents a value​

Anthropic is the only supported provider that requires max_tokens on every request. OpenAI and Gemini both treat it as optional, so Freyja's usual rule of never inventing a default cannot hold here.

When max_tokens is unset, Freyja sends 16000. It is a cap and not a target, so the model still stops when it is finished, but it is a real number chosen by the library rather than by you or by the vendor. Set it explicitly on any request where the ceiling matters:

let agent = Agent::new(client).max_tokens(1024);
let run = agent.ask("Hello").await?;

The header is declared by Dialect::required_headers in src/dialect/mod.rs.

Anthropic nests, the others do not​

This is the structural difference that matters most when reading the code.

OpenAI puts messages, tool calls, and tool results side by side in one flat input list. Gemini does the same with a flat step_list. Anthropic instead nests everything inside a message: a tool call is a tool_use block inside an assistant turn, and a tool result is a tool_result block inside a user turn.

So the OpenAI and Gemini mappings both have a flush helper that emits accumulated text before each tool item, to keep transcript order intact across a flat list. The Anthropic mapping has no such helper, because order is already preserved by the nesting.

There are also only two roles on the wire, user and assistant. Everything else is either hoisted or collapsed, see Roles.

Sampling parameters may be rejected by the model​

temperature, top_p, and top_k were removed on Claude Opus 5, Claude Fable 5, Claude Opus 4.8, and Claude Opus 4.7. Sending any of them to those models returns HTTP 400. Older models such as Claude Sonnet 4.5 still accept them.

This is a per model restriction rather than a per API one, and Freyja does not track which model supports what. So temperature and top_p are forwarded unchanged and the provider decides. If you get a 400 mentioning one of them, remove the field rather than changing the model.

Anthropic returned HTTP 400: {"type":"error","error":{"type":"invalid_request_error", ...}}

Reasoning effort maps onto two different fields​

NeutralWire
ReasoningEffort::None"thinking": {"type": "disabled"}
Low, Medium, High, Xhigh, Max"output_config": {"effort": "..."}

None is the one case that is not an effort level at all, it is an instruction to turn thinking off, so it lands on a different field. Every other level maps straight across.

Note that disabling thinking has its own hazards on Claude Opus 5: the model occasionally writes a tool call into its visible text instead of emitting a tool_use block, which means the call silently never runs. Prefer Low over None unless you have a specific reason.

Response format is schema only​

NeutralWire
ResponseFormat::Textomitted, this is the API default
ResponseFormat::JsonObjectrejected with UnsupportedCapability
ResponseFormat::JsonSchema"output_config": {"format": {"type": "json_schema", "schema": ...}}

Anthropic has no schema-less JSON mode, so JsonObject is refused rather than silently downgraded to free text.

The name and strict fields on JsonSchema are dropped, because Anthropic's structured outputs take neither. The name is a label with no effect on behaviour, and schema enforcement is inherent to the feature rather than opt in. Tool level strict is a separate thing and is forwarded.

Thinking blocks must be replayed​

A response from a reasoning model contains thinking blocks carrying an opaque signature, and redacted_thinking blocks carrying an opaque data field. When you continue the conversation on the same model, those blocks have to come back unchanged and in position. Editing or reconstructing one is rejected.

This is the same requirement Gemini has with thought signatures, and Freyja solves it the same way. Any block it does not model becomes OutputContent::Reasoning, and GenerateResponse::to_message() carries it into the next request untouched:

request = request
.message(response.to_message()) // carries thinking blocks
.extend_messages(tool_results);

Replaying a Claude thinking block to a different model is safe, the server drops it from the prompt rather than erroring, and you are not billed for it. So a provider swap mid conversation degrades quietly rather than failing.

Prompt caching​

Anthropic caches a prompt only when asked, so Freyja asks on every request with a top-level cache_control. Each turn of a conversation then reads the transcript the turn before wrote, and pays a tenth of the input price for it. Two identical requests of 10,525 prompt tokens cost $0.066 and $0.005.

"cache_control": { "type": "ephemeral" }

A cache write costs a quarter more than plain input, and a cache lasts five minutes unused. A single request never repeated pays that quarter for nothing, and so does an endpoint that speaks this dialect without caching. Turn it off for either:

let config = EndpointPreset::Anthropic.config().prompt_cache(false);

A prompt shorter than the model's minimum, about a thousand tokens, is not cached and costs nothing extra. OpenAI and Gemini cache on their own, with no field to send, and Freyja reads their cache counts the same way.

Usage has no total, and hides cached tokens​

Anthropic reports four usage fields and no total:

"usage": {
"input_tokens": 10,
"output_tokens": 5,
"cache_creation_input_tokens": 100,
"cache_read_input_tokens": 1000
}

input_tokens is the uncached remainder only, not the whole prompt. A long running agent whose prompt is cached reports a small input_tokens while actually having sent a large prompt.

Freyja normalizes this by summing all three prompt fields:

NeutralComputed as
Usage::input_tokensinput_tokens + cache_creation_input_tokens + cache_read_input_tokens
Usage::output_tokensoutput_tokens
Usage::total_tokensthe sum of the two above
Usage::cached_input_tokenscache_read_input_tokens
Usage::cache_write_tokenscache_creation_input_tokens

Cost prices the cached parts at their own rates.

Field mapping​

Outbound​

NeutralWire
modelmodel, defaulting to claude-opus-5
max_tokensmax_tokens, defaulting to 16000
system and developer turnssystem, joined with a blank line
other turnsmessages
temperaturetemperature
top_ptop_p
reasoning_effortoutput_config.effort or thinking
response_formatoutput_config.format
toolstools, with parameters renamed to input_schema
tool_choicetool_choice
metadatametadata

Inbound​

WireNeutral
idid
modelmodel
stop_reasonstatus
content[].textOutputContent::Text
content[].tool_useOutputContent::ToolCall
every other blockOutputContent::Reasoning
usageUsage, summed as described above
everything elseprovider_metadata

Roles​

Neutral roleWire role
Useruser
Assistantassistant
Tooluser
System, Developerhoisted, no turn emitted

Tool results ride on a user turn, the same convention Gemini uses. Consecutive same role turns are legal here and the API merges them, so a tool result immediately after a user message needs no special handling.

A turn that produces no content blocks is dropped rather than sent, because the API rejects an empty content array.

Tool arguments are parsed​

The neutral model carries arguments as a string, but Anthropic expects a structured object in tool_use.input. Freyja parses it on the way out.

Unlike Gemini, which accepts a bare string as a tool result and so can fall back to sending one, Anthropic requires input to be an object. Anything else fails locally rather than at the API:

invalid request for Anthropic: tool call arguments must be a JSON object;
Anthropic rejects anything else, got '42'

An empty or whitespace-only string is treated as {}, for tools that take no arguments.

Coming back, input arrives as a JSON value and Freyja stringifies it, so OutputContent::ToolCall::arguments is a string on every dialect.

Status mapping​

Wire stop_reasonNeutral
end_turnResponseStatus::Completed
stop_sequenceResponseStatus::Completed
max_tokensResponseStatus::Incomplete
tool_useResponseStatus::RequiresAction
refusalResponseStatus::Other("refusal")
pause_turnResponseStatus::Other("pause_turn")
anything elseResponseStatus::Other(String)

Two of these deliberately stay as Other rather than being flattened.

A refusal is not a Failed, the request succeeded and the model chose not to answer, and content may be empty. Check status before reading content, or you will read an empty response and think the model returned nothing.

A pause_turn is not a RequiresAction either. RequiresAction in Freyja means the model is waiting on a tool result you supply. A paused turn is resumed by re-sending the transcript unchanged, with no tool result involved, so treating it as RequiresAction would send an agent loop looking for tool calls that are not there.

Unlike Gemini, has_tool_calls() and status agree here: a response with tool calls always carries stop_reason: "tool_use". has_tool_calls() is still the right loop condition, for consistency across providers.

Rejected before the network​

ConditionError
previous_response_id setUnsupportedCapability
response_format is JsonObjectUnsupportedCapability
Non text content in a system or developer turnUnsupportedCapability
An image on a non user turnUnsupportedCapability, unverified: no key has been available to test it
Tool arguments that are not a JSON objectInvalidRequest
A malformed image data URIInvalidRequest

previous_response_id is refused because Anthropic keeps no server side transcript at all. Every request carries the full history, so there is nothing to continue from. If you are porting from OpenAI and relying on it, you need to keep the transcript yourself.

Default model​

claude-opus-5 is used when model is unset. It is the preset's default_model in src/endpoint/presets.rs, not a property of the dialect. Set model on the request, or default_model on the config, for anything you need to stay stable.

Verification status​

This backend shipped unverified and was confirmed later, once a key was available. A full tool round trip now completes end to end:

tool call: add({"a":20,"b":22})
tool result: 42
assistant: 42
usage: 114 tokens

That single run covers more than it looks like. It exercises the nested message shape, the tool_use and tool_result block formats, tool_use_id correlation across turns, the invented max_tokens default, the summed usage mapping, and the x-api-key plus anthropic-version header pair.

What it does not cover, and what is therefore still only as good as the offline tests:

Status
Text generation and tool callingverified live
Streaming, textverified live, but against a compatible endpoint rather than Anthropic
Streaming, tool callsnot exercised live, on this or any dialect
Thinking block replaynot exercised, the run returned none
Images, both URL and data URInot exercised
response_format, reasoning_effort, tool_choicenot exercised
Refusal and pause_turn handlingnot exercised, and hard to trigger deliberately

A text turn has been streamed live through this dialect, but against a Claude-compatible endpoint rather than Anthropic's own service, so the wire format is covered and the vendor is not. Deltas arrived, usage landed on Done, and into_response rebuilt the same text.

Streamed tool calls have not been run anywhere. The message_start / content_block_* / message_delta event shapes come from Anthropic's documentation and are tested against recorded fixtures, with streamed_response_matches_generate asserting that a drained stream matches what generate builds from the same turn. That is an offline parity test, not evidence the endpoint sends what Freyja expects. See Streaming.

The thinking gap is the other one worth knowing about, since it is the failure mode that cost the most on Gemini. The replay path is shared with Gemini and covered by preserves_thinking_blocks_in_place, but a signed Anthropic block has never made a round trip.

To re-check after changes, run an agent with a tool against the endpoint, as Building an agent shows.