Are you an LLM? You can read better optimized documentation at /api/@nhtio/adk/batteries/llm/anthropic_messages/adapter.md for this page in Markdown format
@nhtio/adk/batteries/llm/anthropic_messages/adapter
Cross-environment executor adapter for the Anthropic Messages API.
Remarks
Native Anthropic Messages adapter targeting client.messages.create from @anthropic-ai/sdk (a hard static dependency of this battery). Node-first: an Anthropic API key in a browser bundle is unacceptably exposed, so browser is deliberately not a target or gate for this adapter — dangerouslyAllowBrowser exists only for the caller who accepts that risk knowingly.
Structurally a sibling of the native Ollama and OpenAI Chat Completions adapters, with the Anthropic-wire divergences:
- Transport: the Anthropic SDK owns the HTTP call (
client.messages.create), not rawfetch. ADK owns retry (maxRetries: 0on the client) and timeout (requestTimeoutMsfences an internalAbortControllerlinked withctx.abortSignal; whenrequestTimeoutMsis0a large explicit sentinel is set on the SDK client so the SDK's own silent 10-minute default is never silently inherited). - Streaming:
Stream<RawMessageStreamEvent>— anAsyncIterablethe SDK already filterspingframes out of; a mid-stream provider error surfaces as a thrownAPIErrorfromfor awaititeration, not a discriminated event variant, so the consumption loop is wrapped in atry/catch. - Content-block state machine keyed by
index:content_block_startcarries the ONLY occurrence of atool_useblock'sid/nameand aredacted_thinkingblock'sdata;content_block_deltacarries five delta variants (text_delta,thinking_delta,signature_delta,input_json_delta,citations_delta— the last is out of scope for v1 and is a no-op);content_block_stopfinalizes only that index.message_stopis not trusted to arrive; finalization is reachable from stream EOF too. - Stop reasons: all seven (
end_turn,max_tokens,stop_sequence,tool_use,pause_turn,refusal,model_context_window_exceeded) are handled explicitly —refusalis a real terminal HTTP-200 outcome (never mistaken for an error),model_context_window_exceededmaps toE_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW. - Error translation: typed SDK error classes (
BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError,ConflictError,UnprocessableEntityError,RateLimitError,InternalServerError,APIConnectionTimeoutError,APIConnectionError,APIUserAbortError, genericAPIError) are narrowed and mapped to ADK exceptions. Context overflow arrives as a 400BadRequestErrorand is detected from body text (prompt is too long), not status. A real upstream 529overloaded_erroris retriable (E_ANTHROPIC_MESSAGES_HTTP_ERROR) — never routed into the fatal same-numbered adapter-side exceptions, which use 529 as their own unrelated status code. - Thinking persistence: signed
thinkingblocks persist as aThoughtcarrying a{variant:'thinking', thinking, signature, prefixFingerprint}payload;redacted_thinkingblocks carry{variant:'redacted_thinking', data, prefixFingerprint}. The fingerprint is computed via the exportedfingerprintAnthropicMessagesPrefixhelper — never reimplemented. - No request repair: a
tool_choicethat appears not to have been honored (forces a name the response never calls) only warns viahelpers.log.warn—AnthropicMessagesAdapterOptionshas nostrictToolChoiceescape hatch, consistent with the "warn loudly, send anyway" ethos.
Per-iteration flow (steps 1–9 of the plan):
- Merge constructor / executor / stash options and re-validate.
- Resolve helpers, falling back to bundled
default*for each unset field. - Artifact-reader tools: pre-forged onto
ctx.toolsby the DispatchRunner core; read as-is. - Pre-render every persisted tool-call result into an Anthropic tool-result content block.
- When
tokenEncoding !== null, sum the token weight of every persisted bucket and throw @nhtio/adk/batteries!E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW when the total exceedscontextWindow. - Build the request via
buildAnthropicMessagesHistory. - Call
client.messages.createwith retry/timeout ownership; classify and translate errors. - Streaming path: content-block state machine + usage latching + stop-reason handling.
- Non-streaming path: same persistence + tool-execution loop, from a single
Message.
Classes
| Class | Description |
|---|---|
| AnthropicMessagesAdapter | Opinionated cross-environment LLM adapter for the Anthropic Messages wire shape. |