Anthropic adapter that satisfies the ::ai::chat/run-loop contract:

chat-with-tools(
    model: Str,
    messages: Vec<::ai::chat/Message>,
    system: Str?,
    tools: Vec<::ai::tool/Tool>?
): ::ai::chat/ChatReply

The function translates ::ai::chat/Message records into Anthropic's content-block shape, calls ::anthropic::messages/post, and normalizes the response into a ::ai::chat/ChatReply so that run-loop does not need to know about Anthropic's wire format.

Per-call credentials. Each entry point also takes a trailing opts: Map (api-key, base-url, api-version, see ::anthropic::api/resolve). chat-with-tools and chat-with-tools-stream with opts match the chat-opts-fn and chat-stream-opts-fn slots of ::ai::chat/ChatOptions, which hand them ChatOptions.provider-opts:

opts ::ai::chat/ChatOptions({
    chat-opts-fn: ::anthropic::chat-tools/chat-with-tools,
    model: "claude-sonnet-4-5",
    provider-opts: {api-key: tenant-key}
})
answer ::ai::chat/run-loop(opts, "What is 17 + 25?")

Values

DEFAULT_MAX_TOKENS

DEFAULT_MAX_TOKENS: Int 1024

EMPTY_STATE

EMPTY_STATE: Map {
  text-blocks: {},
  tool-blocks: {},
  block-order: [],
  stop-reason: null,
  usage-input: 0,
  usage-cache-read: 0,
  usage-cache-write: 0,
  usage-output: 0
}

Functions

apply-request-options

fn (request: Map, options: ChatRequestOptions): Map

Apply output, effort and cache controls to an Anthropic request map.

Example

options ::anthropic::chat-tools/ChatRequestOptions({max-tokens: 4096, effort: "high", cache-control: {type: "ephemeral"}})
request ::anthropic::chat-tools/apply-request-options({model: "claude-sonnet-4-5", system: "Be brief."}, options)
request.max_tokens  // 4096
request.output_config  // {effort: "high"}
first(request.system).cache_control  // {type: "ephemeral"}

block-text

fn (b: Map): Str

Text from a single content block, or empty string.

Example

::anthropic::chat-tools/block-text({type: "text", text: "Hello"})  // "Hello"
::anthropic::chat-tools/block-text({type: "tool_use", id: "toolu_1", name: "search"})  // ""

block-tool-call

fn (b: Map): ::ai::tool/ToolCall?

Convert a tool_use content block into a ::ai::tool/ToolCall, or null otherwise.

Example

::anthropic::chat-tools/block-tool-call({type: "tool_use", id: "toolu_1", name: "search", input: {q: "hot"}}).name  // "search"
::anthropic::chat-tools/block-tool-call({type: "text", text: "Hello"})  // null

chat-with-tools

fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?): ::ai::chat/ChatReply
fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, opts: Map): ::ai::chat/ChatReply

Tools-aware chat function compatible with ::ai::chat/run-loop.

Parameters

  • model — Anthropic model id (e.g. "claude-sonnet-4-5").
  • messages — conversation history as Vec<::ai::chat/Message>.
  • system — optional system prompt.
  • tools — optional Vec<::ai::tool/Tool>. When non-null, tools are advertised to the model and tool_use responses become ChatReply.tool-calls.

Returns a normalized ::ai::chat/ChatReply regardless of the underlying response shape.

Example

::tool ::ai::tool

add fn (x: Int, y: Int): Int { add(x, y) }

opts ::ai::chat/ChatOptions({
    chat-fn: ::anthropic::chat-tools/chat-with-tools,
    model: "claude-sonnet-4-5",
    tools: [::tool/from-fn(add)]
})

answer ::ai::chat/run-loop(opts, "What is 17 + 25?")

chat-with-tools-options

fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, options: ChatRequestOptions): ::ai::chat/ChatReply
fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, options: ChatRequestOptions, opts: Map): ::ai::chat/ChatReply

chat-with-tools with an explicit output ceiling and Anthropic effort. Bind this function in a closure when a session needs model-specific controls while retaining the normalized four-argument chat contract. A trailing opts carries per-call credentials and settings.

Example

options ::anthropic::chat-tools/ChatRequestOptions({max-tokens: 4096, effort: "high"})

reply ::anthropic::chat-tools/chat-with-tools-options(
  "claude-sonnet-4-5",
  [::ai::chat/user-message("Summarize the release notes.")],
  "Be brief.",
  null,
  options
)
reply.text
reply.usage.output-tokens

chat-with-tools-stream

fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, on-delta: Fn): ::ai::chat/ChatReply
fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, on-delta: Fn, opts: Map): ::ai::chat/ChatReply

Streaming counterpart to chat-with-tools, compatible with ::ai::chat/run-loop-stream. Translates Anthropic SSE events into provider-agnostic ::ai::chat/ReplyDelta events delivered via on-delta, and returns a fully-aggregated ChatReply once the stream terminates.

Parameters

  • model — Anthropic model id.
  • messages — conversation history as Vec<::ai::chat/Message>.
  • system — optional system prompt.
  • tools — optional Vec<::ai::tool/Tool>.
  • on-delta — callback (delta: ReplyDelta): Null invoked for every event during streaming. Use ::ai::chat/noop-on-delta if you only care about the final ChatReply.

Example

on-text (delta) {
    match delta {
        ::ai::chat/ReplyDelta.TextDelta => { print(delta.text) }
        => { null }
    }
}

reply ::anthropic::chat-tools/chat-with-tools-stream(
    "claude-sonnet-4-5",
    [::ai::chat/user-message("Hi")],
    null,
    null,
    on-text
)

Then reply.text holds the full assistant text, reply.tool-calls holds any parsed tool calls (with their input maps reconstructed from streamed JSON fragments), and reply.usage carries the provider-reported token totals.

A refused call, or an error event partway through the stream, returns an Err carrying ::anthropic::api/HttpError, whose body holds the API's reason. on-delta gets no Stop then.

chat-with-tools-stream-options

fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, on-delta: Fn, options: ChatRequestOptions): ::ai::chat/ChatReply
fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, on-delta: Fn, options: ChatRequestOptions, opts: Map): ::ai::chat/ChatReply

Streaming chat-with-tools with explicit output and effort controls.

Example

options ::anthropic::chat-tools/ChatRequestOptions({max-tokens: 4096, effort: "high"})

reply ::anthropic::chat-tools/chat-with-tools-stream-options(
  "claude-sonnet-4-5",
  [::ai::chat/user-message("Summarize the release notes.")],
  "Be brief.",
  null,
  ::ai::chat/noop-on-delta,
  options
)
reply.text

count-tokens

fn (messages: Vec<::ai::chat/Message>, model: Str): Int
fn (messages: Vec<::ai::chat/Message>, model: Str, opts: Map): Int

Count the input tokens a Vec<::ai::chat/Message> would consume against model, using Anthropic's stable /v1/messages/count_tokens endpoint. Returns the exact count Anthropic would charge.

Compatible with the count-tokens-fn slot on ::ai::chat/ChatOptions:

(messages: Vec<Message>, model: Str): Int

System prompt and tools are not currently included by this helper — pass them via a custom wrapper if you need to model their cost. The caller's pre-call budget check should add the model's reserved overhead separately.

Network calls cost nothing in API credits but they are not free in latency; cache the result when checking budget repeatedly against an unchanged history.

The count-tokens-fn slot has no credentials argument. For a per-call key, bind the three-argument form in a closure: (messages, model) { count-tokens(messages, model, {api-key: key}) }.

Example

messages [::ai::chat/user-message("How many tokens is this?")]
::anthropic::chat-tools/count-tokens(messages, "claude-sonnet-4-5")

// With a per-call key
::anthropic::chat-tools/count-tokens(messages, "claude-sonnet-4-5", {api-key: ::hot::ctx/get("tenant.anthropic-key")})

response-text

fn (blocks: Vec): Str

Concatenate text content blocks from an Anthropic response.

Example

::anthropic::chat-tools/response-text([{type: "text", text: "Hello "}, {type: "text", text: "world"}])  // "Hello world"

response-tool-calls

fn (blocks: Vec): Vec<::ai::tool/ToolCall>

Extract ::ai::tool/ToolCall entries from a list of Anthropic content blocks.

Example

blocks [{type: "text", text: "Searching."}, {type: "tool_use", id: "toolu_1", name: "search", input: {q: "hot"}}]
map(::anthropic::chat-tools/response-tool-calls(blocks), %.id)  // ["toolu_1"]

response-usage

fn (u: Any): Map?

Normalize Anthropic's usage shape into {input-tokens, output-tokens, cache-read-tokens, cache-write-tokens}.

Example

::anthropic::chat-tools/response-usage({input_tokens: 10, cache_read_input_tokens: 90, output_tokens: 5})
// {input-tokens: 100, output-tokens: 5, cache-read-tokens: 90, cache-write-tokens: 0}

::anthropic::chat-tools/response-usage(null)  // null

to-anthropic-message

fn (m: ::ai::chat/Message): Map

Convert a single normalized ::ai::chat/Message into Anthropic's InputMessage shape. Tool results are emitted as user turns with a tool_result content block (Anthropic's wire convention).

Example

::anthropic::chat-tools/to-anthropic-message(::ai::chat/user-message("Hi"))  // {role: "user", content: "Hi"}

result ::ai::chat/Message({role: "tool", content: {sum: 42}, tool-call-id: "toolu_1"})
first(::anthropic::chat-tools/to-anthropic-message(result).content).tool_use_id  // "toolu_1"

to-anthropic-tool

fn (t: ::ai::tool/Tool): Map

Convert a ::ai::tool/Tool into Anthropic's Tool shape (rename input-schema to input_schema, keep name and description).

Example

tool ::ai::tool/Tool({
  name: "search",
  description: "Search the docs.",
  input-schema: {type: "object", properties: {q: {type: "string"}}},
  fn: (input) { [] }
})
::anthropic::chat-tools/to-anthropic-tool(tool).name  // "search"
::anthropic::chat-tools/to-anthropic-tool(tool).input_schema.type  // "object"

to-tool-use-block

fn (call: ::ai::tool/ToolCall): Map

Convert a ::ai::tool/ToolCall into an Anthropic tool_use content block.

Example

call ::ai::tool/ToolCall({id: "toolu_1", name: "search", input: {q: "hot"}})
::anthropic::chat-tools/to-tool-use-block(call)  // {type: "tool_use", id: "toolu_1", name: "search", input: {q: "hot"}}

Types

ChatRequestOptions

ChatRequestOptions type {
    max-tokens: Int,
    effort: Str?,
    cache-control: Map?
}

Per-request output controls for Anthropic Messages.

Claude Opus 5 has thinking enabled by default and counts thinking plus visible text against max_tokens, so callers selecting it should use a materially larger ceiling than the legacy 1024-token adapter default.

cache-control turns on prompt caching, as Anthropic's own value: {type: "ephemeral"}, or {type: "ephemeral", ttl: "1h"}. It marks the system prompt, which caches the tools with it, and the conversation, whose mark moves forward each turn. A loop that sends its long skills and pack as the system prompt then reads them from the cache on every call. Keep what changes between calls out of the system prompt, since a change there misses the cache for everything after it.