Provider-agnostic chat surface used by every ::ai::* consumer.

This module defines:

  • Provider enum and a model-name → provider mapping for routing.
  • Message and ChatReply types that normalize provider responses so downstream code never branches on the underlying SDK.
  • ChatOptions carrying the chat function reference, model name, optional system prompt, and (for tool-using flows) tools plus a max-iterations cap.
  • run-loop, the canonical agent loop that calls chat-fn, dispatches tool_use blocks via ::ai::tool/dispatch, and iterates until the model finishes or the iteration cap is hit.

Provider packages (e.g. ::anthropic::messages, ::openai::chat) each expose a chat-with-tools function matching the new chat-fn contract:

chat-fn(model: Str, messages: Vec<Message>, system: Str?, tools: Vec<Tool>?): ChatReply

The legacy (model, prompt, system) -> Str shape used by ::ai::rag is still supported as-is — only run-loop callers must adopt the new shape.

Per-call provider credentials. ChatOptions.provider-opts carries a provider's opts (api-key, base-url, ...) so one run can serve many tenants without touching ctx. It is handed to the chat-opts-fn and chat-stream-opts-fn slots, on ChatOptions or on a ProviderRegistration:

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

A plain chat-fn keeps working without provider-opts, but can't receive it, so setting provider-opts for one is a failure naming the provider. A null or blank credential is a failure too, as is a base-url without a credential: a tenant's call never falls back to the project's ctx key.

The run loop never puts provider-opts in chat history, step or delta stream records, skill context or failure payloads. It marks each credential in it with ::hot::ctx/mark-secret, so call records mask it, including inside strings like Bearer ${key}. A credential shorter than 8 bytes is masked only as a whole value.

Values

CHARS_PER_TOKEN_HEURISTIC

CHARS_PER_TOKEN_HEURISTIC: Int 4

DEFAULT_MAX_ITERATIONS

DEFAULT_MAX_ITERATIONS: Int 10

DEFAULT_WARN_CONTEXT_PCT

DEFAULT_WARN_CONTEXT_PCT: Dec 0.8

MODEL_PREFIXES

MODEL_PREFIXES: Vec [
  {
    prefix: "claude",
    provider: Provider.Anthropic
  },
  {
    prefix: "gpt",
    provider: Provider.OpenAi
  },
  {
    prefix: "o1",
    provider: Provider.OpenAi
  },
  {
    prefix: "o3",
    provider: Provider.OpenAi
  },
  {
    prefix: "o4",
    provider: Provider.OpenAi
  },
  {
    prefix: "grok",
    provider: Provider.Xai
  },
  {
    prefix: "gemini",
    provider: Provider.Gemini
  }
]

PER_MESSAGE_OVERHEAD_TOKENS

PER_MESSAGE_OVERHEAD_TOKENS: Int 4

PROVIDER_PLAIN_KEYS

PROVIDER_PLAIN_KEYS: Vec [
  "base-url",
  "management-base-url",
  "api-version",
  "region",
  "environment",
  "endpoint",
  "path-style",
  "transport"
]

PROVIDER_SETTING_KEYS

PROVIDER_SETTING_KEYS: Vec [
  "base-url",
  "management-base-url",
  "api-version",
  "region",
  "environment"
]

Functions

assistant-message

fn (text: Str?, tool-calls: Vec<::ai::tool/ToolCall>?): Message

Construct a Message representing an assistant turn. When tool-calls is non-null the message records a tool-use turn that must be paired with one or more tool-result-message entries on the next user turn.

Example

call ::ai::tool/ToolCall({id: "tu_1", name: "get-weather", input: {city: "Paris"}})
first(::ai::chat/assistant-message("Checking.", [call]).tool-calls).name  // "get-weather"
::ai::chat/assistant-message(null, null).content  // ""

builtin-providers

fn (): Vec<ProviderRegistration>

Built-in provider registry. Entries only carry variant, detect, and display-name, with chat-fn and chat-stream-fn left null, so this namespace doesn't pin a dependency on every provider package.

Wire a provider's adapter in setup code: set ChatOptions.chat-fn (or chat-opts-fn, chat-stream-fn, chat-stream-opts-fn) to it, or register it with with-providers and pass the registry as ChatOptions.providers. The adapters are ::anthropic::chat-tools/chat-with-tools, ::openai::chat-tools/chat-with-tools, ::gemini::chat-tools/chat-with-tools, ::xai::ai/chat-with-tools and ::aws::bedrock::chat-tools/chat-with-tools, each with a -stream counterpart. OpenAI-compatible servers (Groq, OpenRouter, Ollama, ...) and Qwen register through hot.dev/openai-compatible and hot.dev/qwen.

opts ::ai::chat/ChatOptions({
    chat-fn: ::gemini::chat-tools/chat-with-tools,
    chat-stream-fn: ::gemini::chat-tools/chat-with-tools-stream,
    model: "gemini-3.8-flash",
})

Example

map(::ai::chat/builtin-providers(), %.display-name)
// ["Anthropic", "OpenAI", "xAI", "Google Gemini"]

check-provider-opts

fn (provider-opts: Map?): Null

Fail when a credential in provider-opts is null or blank: a tenant with a missing key must never fall back to the provider's ctx key. Any key other than the settings in PROVIDER_SETTING_KEYS counts as a credential. Leave a key out to use ctx.

Also fail when management-base-url comes without management-api-key, or base-url without a credential, so a ctx key is never sent to a per-call URL. Provider names for the credential differ (api-key, token, ...), so for base-url any credential other than management-api-key passes here, and the provider's own resolver checks the exact key. Failures name keys, never values.

Example

// Passes: the credential has a value
::ai::chat/check-provider-opts({api-key: ::hot::ctx/get("tenant.acme.api.key")})

// Fails: a blank credential never falls back to the ctx key
::ai::chat/check-provider-opts({api-key: ""})

complete-prompt

fn (opts: ChatOptions, prompt: Str, system: Str?): Any

One prompt in, one Str out, for helpers such as ::ai::rag that don't run a tool loop. With opts.chat-opts-fn, sends the prompt as a single user message along with opts.provider-opts. Otherwise calls the legacy chat-fn contract, (model, prompt, system) -> Str.

Example

::chat ::ai::chat
prompt-fn (model, prompt, system) { `${model}: ${prompt}` }
opts ::chat/ChatOptions({chat-fn: prompt-fn, model: "gpt-4o"})
::chat/complete-prompt(opts, "Summarize this.", null)  // "gpt-4o: Summarize this."

count-tokens-heuristic

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

Provider-agnostic char/4 token estimator. Use as a fallback for ChatOptions.count-tokens-fn when a provider lacks a precise counter (e.g. OpenAI without tiktoken). Tracks BPE tokenizers to within ~10% on English prose; code/JSON/non-Latin will skew higher.

Contract matches the count-tokens-fn slot:

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

Example

::ai::chat/count-tokens-heuristic([::ai::chat/user-message("Hello there")], "gpt-4o")  // 8

detect-provider

fn (model: Str): Provider

Map a model name to its Provider variant. Walks builtin-providers() first, then falls back to the legacy MODEL_PREFIXES table for backward compatibility. Returns Err for unrecognized models. Use detect-provider-from when you have a custom registry.

Example

::ai::chat/detect-provider("claude-sonnet-4-5")  // Provider.Anthropic
::ai::chat/detect-provider("gpt-4o")             // Provider.OpenAi

detect-provider-from

fn (registry: Vec<ProviderRegistration>, model: Str): ProviderRegistration?

Find the registry entry whose detect returns true for model. Walks registry from the end first so user-supplied overrides win over built-ins. Returns null when nothing matches.

Example

registry ::ai::chat/builtin-providers()
::ai::chat/detect-provider-from(registry, "GPT-4o").display-name  // "OpenAI"
::ai::chat/detect-provider-from(registry, "llama3")  // null

dispatch-chat

fn (opts: ChatOptions, messages: Any, tools: Any): Any

Dispatch a chat call using opts. Resolution order:

  1. If opts.chat-opts-fn is set, call it with opts.provider-opts ({} when unset).
  2. If opts.chat-fn is set, call it directly.
  3. Otherwise resolve a ProviderRegistration via opts.providers (or built-ins) and call its chat-opts-fn with opts.provider-opts, or else its chat-fn.
  4. Otherwise fail with a clear message.

Use this helper in any code that wants to honor ChatOptions.providers without bypassing chat-fn's explicit-override semantics.

Example

::chat ::ai::chat
reply-fn (model, messages, system, tools) {
    ::chat/ChatReply({text: `${model} says hi`, stop-reason: "end_turn"})
}
opts ::chat/ChatOptions({chat-fn: reply-fn, model: "claude-sonnet-4-5"})
::chat/dispatch-chat(opts, [::chat/user-message("Hello")], null).text  // "claude-sonnet-4-5 says hi"

dispatch-chat-stream

fn (opts: ChatOptions, messages: Any, tools: Any, on-delta: Fn): Any

Streaming counterpart to dispatch-chat. Honors explicit opts.chat-stream-opts-fn and opts.chat-stream-fn first, then the same two slots on opts.providers[*]. chat-stream-opts-fn receives opts.provider-opts ({} when unset).

Example

::chat ::ai::chat
stream-fn (model, messages, system, tools, on-delta) {
    on-delta(::chat/ReplyDelta.TextDelta({text: "hi"}))
    ::chat/ChatReply({text: "hi", stop-reason: "end_turn"})
}
opts ::chat/ChatOptions({chat-stream-fn: stream-fn, model: "claude-sonnet-4-5"})
::chat/dispatch-chat-stream(opts, [::chat/user-message("Hello")], null, ::chat/noop-on-delta).text  // "hi"

flatten-parts

fn (parts: Vec<MessagePart>?): Str

Collapse a Vec<MessagePart> into a single string for adapters that don't yet support multi-part input. Text parts are concatenated with \\n\\n separators; image/audio/file parts become bracketed placeholders so the model knows something was attached even when the bytes can't be sent.

Returns the empty string for empty input.

Example

::chat ::ai::chat
::chat/flatten-parts([::chat/text-part("Caption"), ::chat/image-part("https://example.com/cat.png")])
// "Caption\n\n[image:image (https://example.com/cat.png)]"

image-part

fn (url: Str): MessagePart
fn (data: Str, mime: Str): MessagePart

Convenience: build an image MessagePart. Either data (base64) or url should be set; mime should describe the encoding when data is set.

Example

::ai::chat/image-part("https://example.com/cat.png").url  // "https://example.com/cat.png"
::ai::chat/image-part("iVBORw0KGgo=", "image/png").mime  // "image/png"

make-usage

fn (raw: Map?, provider-name: Str?, model: Str?): ChatUsage

Build a ChatUsage from a provider-native usage map. Accepts Anthropic-style (input_tokens/output_tokens), OpenAI-style (prompt_tokens/completion_tokens), Gemini-style (promptTokenCount/candidatesTokenCount/thoughtsTokenCount) and the normalized kebab-case keys; missing fields stay null.

Anthropic counts cached input tokens apart from input_tokens, so its cache_read_input_tokens and cache_creation_input_tokens are added into input-tokens. Gemini counts thinking apart from candidatesTokenCount, so its thoughtsTokenCount is added into output-tokens, as the other providers already count it. total-tokens is the reported total when there is one, otherwise input + output.

usage ::ai::chat/make-usage({
    prompt_tokens: 120,
    completion_tokens: 84,
    latency_ms: 1280,
}, "OpenAI", "gpt-4o")
usage.total-tokens  // 204

gemini ::ai::chat/make-usage({
    promptTokenCount: 100,
    candidatesTokenCount: 20,
    thoughtsTokenCount: 30,
    cachedContentTokenCount: 80,
    totalTokenCount: 150,
}, "Google Gemini", "gemini-2.5-flash")
gemini.output-tokens  // 50
gemini.cache-read-tokens  // 80

message-text

fn (msg: Message): Str

Extract the textual content of a Message, regardless of whether it's stored in content or in parts. Adapters that haven't moved to multi-part input use this to keep working with multi-part-aware callers.

Example

::chat ::ai::chat
::chat/message-text(::chat/user-message("Hello"))  // "Hello"
::chat/message-text(::chat/Message({role: "user", content: "", parts: [::chat/text-part("Hi there")]}))  // "Hi there"

noop-on-delta

fn (delta: ReplyDelta): Null

Default on-delta callback used when a streaming caller does not supply one. Discards every event.

Example

::ai::chat/noop-on-delta(::ai::chat/ReplyDelta.TextDelta({text: "hi"}))  // null

prefix-detector

fn (prefix: Str): Fn

Build a detect function that matches when the model starts with prefix (case-insensitive).

Example

detect ::ai::chat/prefix-detector("mistral")
detect("Mistral-Large")  // true
detect("gpt-4o")  // false

provider-name

fn (provider: Provider): Str

Human-readable name for a Provider. Falls back to the variant's short name for any provider enrolled by a third-party package via Source -> Provider.Variant arrows. The _ default arm is required because Provider is an open enum.

Example

::ai::chat/provider-name(::ai::chat/Provider.OpenAi)  // "OpenAI"

resolve-registration

fn (opts: ChatOptions): Any

Pick the ProviderRegistration whose detect matches opts.model, using opts.providers first if set, otherwise the built-in registry.

Returns the whole registration value rather than its chat-fn. This is intentional — Hot reliably round-trips struct values across function boundaries, but extracting a typed fn field and returning it as a value does not preserve the fn ref. Call reg.chat-fn(...) directly on the returned registration to dispatch.

::chat ::ai::chat

local-chat (model, messages, system, tools) {
    ::chat/ChatReply({text: "Hello from llama3", stop-reason: "end_turn"})
}

registry ::chat/with-providers([
    ::chat/ProviderRegistration({
        variant: ::chat/Provider.OpenAi,
        detect: ::chat/prefix-detector("ollama/"),
        display-name: "Ollama",
        chat-fn: local-chat,
        chat-stream-fn: null,
        embed-fn: null,
    })
])

opts ::chat/ChatOptions({model: "ollama/llama3", providers: registry})
reg ::chat/resolve-registration(opts)
reply reg.chat-fn(opts.model, [::chat/user-message("Hi")], opts.system, null)
reply.text  // "Hello from llama3"

run-loop

fn (opts: ChatOptions, user-msg: Str): Str

Drive a chat conversation through any number of tool-use turns, stopping when the model says end_turn or when max-iterations is reached.

opts.chat-fn must match the tools-aware contract:

(model: Str, messages: Vec<Message>, system: Str?, tools: Vec<Tool>?) -> ChatReply

On each iteration:

  1. Call chat-fn with the running message list.
  2. If the reply has no tool calls, return its text. When on-final-reply is set and returns a Str, send that as a user turn and loop instead.
  3. Otherwise, dispatch every tool call via ::ai::tool/dispatch. If a tool marked ends-run succeeded, return its output. Else append the assistant turn and one tool-result turn per call, and loop.

Errors from individual tool calls are surfaced back to the model as tool-result-message entries with the failure text — the model is allowed to recover. With fail-on-tool-error (or a tool's fail-on-error), a failed call ends the loop with an Err holding a ToolFailure instead. Hitting max-iterations raises a fail.

Example

sum 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: [::ai::tool/from-fn(sum)],
    max-iterations: 5
})

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

run-loop-messages

fn (opts: ChatOptions, messages: Vec<Message>): Str

Variant of run-loop that takes an explicit Vec<Message> as starting history. Useful for resuming an existing conversation.

Example

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

history [
    ::ai::chat/user-message("Hi"),
    ::ai::chat/assistant-message("Hello!", null),
    ::ai::chat/user-message("How are you?")
]
::ai::chat/run-loop-messages(opts, history)

run-loop-stream

fn (opts: ChatOptions, user-msg: Str): Str
fn (opts: ChatOptions, user-msg: Str, on-delta: Fn?): Str

Streaming counterpart to run-loop. Drives a tools-aware conversation through any number of turns, invoking on-delta(delta: ReplyDelta) for every event the underlying chat-stream-fn emits across all turns.

opts.chat-stream-fn must match the streaming contract:

(model: Str, messages: Vec<Message>, system: Str?,
 tools: Vec<Tool>?, on-delta: Fn) -> ChatReply

On each iteration the function:

  1. Calls chat-stream-fn with the running message list and a merged on-delta that also forwards to ::hot::stream/data when opts.emit-stream-deltas is on.
  2. Collects the final ChatReply. If no tool calls, returns the accumulated text.
  3. Otherwise dispatches every tool call via ::ai::tool/dispatch, appends the assistant turn + tool-result turns, and loops.

Errors and max-iterations behavior match run-loop.

Example

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

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

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

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

run-loop-stream-messages

fn (opts: ChatOptions, messages: Vec<Message>, on-delta: Fn?): Str

Variant of run-loop-stream that takes an explicit Vec<Message> as starting history. Useful for resuming an existing conversation while still streaming the next response.

Example

::chat ::ai::chat
stream-fn (model, messages, system, tools, on-delta) {
    on-delta(::chat/ReplyDelta.TextDelta({text: "Why did the tool cross the road?"}))
    ::chat/ChatReply({text: "Why did the tool cross the road?", stop-reason: "end_turn"})
}
opts ::chat/ChatOptions({chat-stream-fn: stream-fn, model: "claude-sonnet-4-5"})
history [::chat/user-message("Hi"), ::chat/assistant-message("Hello!", null), ::chat/user-message("Tell me a joke.")]
::chat/run-loop-stream-messages(opts, history, null)  // "Why did the tool cross the road?"

text-part

fn (text: Str): MessagePart

Convenience: build a MessagePart({kind: "text", text: …}).

Example

::ai::chat/text-part("Hello").kind  // "text"

tool-result-message

fn (result: ::ai::tool/ToolResult): Message

Construct a Message carrying a ::ai::tool/dispatch result back to the model. Echoes result.id as tool-call-id so providers can correlate it with the originating ToolCall, and sets is-error: true when the tool failed.

Example

result ::ai::tool/ToolResult({id: "tu_1", output: "18C and clear", is-error: false})
::ai::chat/tool-result-message(result).tool-call-id  // "tu_1"

user-message

fn (text: Str): Message

Construct a Message with role: "user" and the given text content.

Example

::ai::chat/user-message("Hello").role  // "user"

with-providers

fn (extras: Vec<ProviderRegistration>): Vec<ProviderRegistration>

Compose a registry from the built-in entries plus extras. Later entries take precedence over earlier ones when their detect matches the same model — this lets a third-party adapter override a built-in (e.g. routing all gpt-* calls through a self-hosted proxy).

::chat ::ai::chat

proxy ::chat/ProviderRegistration({
    variant: ::chat/Provider.OpenAi,
    detect: ::chat/prefix-detector("gpt"),
    display-name: "OpenAI Proxy",
    chat-fn: null,
    chat-stream-fn: null,
    embed-fn: null,
})

registry ::chat/with-providers([proxy])
::chat/detect-provider-from(registry, "gpt-4o").display-name  // "OpenAI Proxy"

Types

ChatOptions

ChatOptions type {
    chat-fn: Fn?,
    chat-stream-fn: Fn?,
    model: Str,
    system: Str?,
    tools: Vec<::ai::tool/Tool>?,
    skills: Vec<Any>?,
    skill-resolver: ::ai::skill/SkillResolver?,
    skill-context: Map?,
    providers: Vec<ProviderRegistration>?,
    max-iterations: Int?,
    max-context-tokens: Int?,
    max-output-tokens: Int?,
    warn-context-pct: Dec?,
    emit-steps: Bool?,
    step-data-type: Str?,
    emit-stream-deltas: Bool?,
    delta-data-type: Str?,
    count-tokens-fn: Fn?,
    model-context-window: Int?,
    chat-opts-fn: Fn?,
    chat-stream-opts-fn: Fn?,
    provider-opts: Map?,
    on-final-reply: Fn?,
    fail-on-tool-error: Bool?
}

Options bundle for chat-consuming functions.

Required

  • chat-fn — function reference used to call the underlying provider. Two contracts are recognized:

    • Legacy: (model: Str, prompt: Str, system: Str?) -> Str — used by ::ai::rag and other single-shot helpers.
    • Tools-aware: (model: Str, messages: Vec<Message>, system: Str?, tools: Vec<Tool>?) -> ChatReply — required by run-loop.
  • model — model identifier passed through to the provider.

  • chat-stream-fn — streaming counterpart used by run-loop-stream. Contract:

    (model: Str, messages: Vec<Message>, system: Str?,
     tools: Vec<Tool>?, on-delta: Fn) -> ChatReply
    

    The function invokes on-delta(delta: ReplyDelta) for each event in turn order and returns the same ChatReply shape as the non-streaming version.

  • chat-opts-fn — chat-fn (tools-aware contract) that also takes provider-opts as a fifth argument. Preferred over chat-fn.

  • chat-stream-opts-fn — chat-stream-fn that also takes provider-opts as a sixth argument. Preferred over chat-stream-fn.

Optional

  • provider-opts — per-call provider credentials and settings (api-key, base-url, ...), so one run can serve many tenants without touching ctx. Handed to chat-opts-fn and chat-stream-opts-fn as is, on ChatOptions or on the matching ProviderRegistration. Plain chat-fn and chat-stream-fn can't receive it, so setting it for them is a failure naming the provider. So is a null or blank credential, or a base-url without a credential: a tenant's call never falls back to the project's ctx key. Masked in the run's call records, and in nothing else the run loop stores or emits.
  • system — system prompt prepended to every call.
  • tools — tools the model is allowed to call from run-loop.
  • skills — vector of skill-meta'd functions to advertise to the model. run-loop wraps these in ::ai::skill/in-memory-resolver and exposes the list_skills/read_skill/apply_skill built-in tools automatically. Ignored when skill-resolver is set.
  • skill-resolver — explicit ::ai::skill/SkillResolver. Takes precedence over skills and lets callers plug in store-backed, embedding-ranked, or otherwise dynamic skill discovery while reusing the run-loop's index + built-in-tools machinery.
  • skill-context — per-turn map merged into every apply_skill invocation's ctx argument before the skill's body-fn runs. The harness's keys override anything the model passes for the same key — useful for threading inbound attachments, sender identity, transport, or session info into skill resolution without trusting the model to populate them. Ignored by static body skills (those are returned verbatim).
  • max-iterations — hard cap on run-loop turns (default 10).
  • max-context-tokens, max-output-tokens, warn-context-pct — reserved for Phase 1.5 token-budget enforcement; ignored today.
  • emit-steps — when true, run-loop publishes a per-turn observability record to the current run's stream via ::hot::stream/data. Defaults to false. Errors from missing stream context are swallowed so opting in is safe in any execution environment.
  • step-data-type — stream data-type label used when emit-steps is on. Defaults to "ai:chat:step".
  • emit-stream-deltas — when true, run-loop-stream mirrors every ReplyDelta to the current run's stream via ::hot::stream/data (in addition to invoking any caller on-delta). Defaults to false. Errors from missing stream context are swallowed.
  • delta-data-type — stream data-type label used when emit-stream-deltas is on. Defaults to "ai:chat:delta".
  • count-tokens-fn — provider's (messages, model) -> Int counter used by pre-call budget checks. When unset, falls back to count-tokens-heuristic. It doesn't receive provider-opts; bind per-call credentials in a closure.
  • model-context-window — explicit context-window size in tokens. When unset, the budget check uses max-context-tokens directly without computing a percentage.
  • on-final-reply — called when the model replies with no tool calls, as (reply: ChatReply, messages: Vec<Message>) -> Str?, where messages is the history the model answered. Return null or an empty Str to accept the reply. Return a Str to send it to the model as a user turn and ask again, for example "You haven't called submit_result yet." Each extra turn counts toward max-iterations. An Err it returns ends the loop with that Err.
  • fail-on-tool-error — when true, a failed tool call ends the loop with an Err holding a ToolFailure, instead of going back to the model as an error result. Use it when the failure should be retried by the platform, not explained by the model. A tool's own fail-on-error wins over this. A call to a tool that doesn't exist always goes back to the model.

Example

::tool ::ai::tool
::anth ::anthropic::messages

weather-tool ::tool/from-fn(get-weather)

opts ChatOptions({
    chat-fn: ::anth/chat-with-tools,
    model: "claude-sonnet-4-5",
    system: "You are a concise assistant.",
    tools: [weather-tool],
    max-iterations: 5
})

ChatReply

ChatReply type {
    text: Str?,
    tool-calls: Vec<::ai::tool/ToolCall>?,
    stop-reason: Str,
    usage: Any?,
    raw: Any?
}

Normalized provider response. Returned by the new chat-fn contract and consumed by run-loop.

Fields

  • text — the assistant's text output for this turn (may be empty when the turn is purely tool-use).
  • tool-calls — parsed ToolCall records when the model requested tool use.
  • stop-reason — "end_turn", "tool_use", "max_tokens", "stop_sequence", or any other provider-specific reason.
  • usage — token accounting and cost. Adapters that have moved to structured usage populate this with a ChatUsage; legacy adapters still populate it with a raw Map and callers use make-usage to coerce. Phase 1.5 will normalize on ChatUsage.
  • raw — the raw provider response for adapter use; opaque to run-loop callers.

ChatUsage

ChatUsage type {
    input-tokens: Int?,
    output-tokens: Int?,
    total-tokens: Int?,
    cache-read-tokens: Int?,
    cache-write-tokens: Int?,
    thought-tokens: Int?,
    cost-usd: Dec?,
    latency-ms: Int?,
    provider: Str?,
    model: Str?
}

Provider-agnostic usage and cost shape. Returned alongside ChatReply.usage by adapters that have populated it. Construct via make-usage(map) to coerce a provider's native usage map (with fields like prompt_tokens, completion_tokens) into the normalized shape.

Fields

  • input-tokens — tokens consumed by the prompt + tool definitions, cached ones included.
  • output-tokens — tokens generated by the model, thinking included.
  • total-tokens — the provider's total when it reports one, otherwise input + output.
  • cache-read-tokens — the part of input-tokens served from a prompt cache.
  • cache-write-tokens — the part of input-tokens written to a prompt cache.
  • thought-tokens — the part of output-tokens spent on thinking.
  • cost-usd — provider-reported cost in USD when available.
  • latency-ms — wall-clock time the call took, when measured by the adapter.
  • provider — display-name of the provider that handled the call.
  • model — concrete model name (e.g. "claude-sonnet-4-5").

Message

Message type {
    role: Str,
    content: Any,
    parts: Vec<MessagePart>?,
    tool-calls: Vec<::ai::tool/ToolCall>?,
    tool-call-id: Str?,
    is-error: Bool?
}

One turn of a chat conversation in normalized form. Provider adapters translate this into their native message shape.

Fields

  • role — "user", "assistant", "system", or "tool".
  • content — usually a Str (plain text). For role: "tool" it is the result returned by ::ai::tool/dispatch. For role: "assistant" turns that called tools it may be empty. When parts is set, adapters that support multi-part input should prefer parts and treat content as a flattened fallback.
  • parts — optional multi-part body. Set this when the message mixes text with images, audio, or files. Adapters that don't support multi-part input call flatten-parts(parts) to get a string equivalent.
  • tool-calls — present on role: "assistant" turns that requested tool use; carries the parsed ToolCall records.
  • tool-call-id — present on role: "tool" results, echoing the id of the originating ToolCall.
  • is-error — true on a role: "tool" result whose tool failed, so an adapter can mark it in the provider's shape. Null otherwise.

Example

user-msg Message({role: "user", content: "What's the weather in Paris?"})

multimodal Message({
    role: "user",
    content: "What's in this image?",
    parts: [
        text-part("What's in this image?"),
        image-part(image-bytes, "image/png"),
    ],
})

assistant-call Message({
    role: "assistant",
    content: "",
    tool-calls: [::tool/ToolCall({id: "tu_1", name: "get-weather", input: {city: "Paris"}})]
})

tool-result Message({
    role: "tool",
    content: "18C and clear",
    tool-call-id: "tu_1"
})

MessagePart

MessagePart type {
    kind: Str,
    text: Str?,
    mime: Str?,
    data: Str?,
    url: Str?,
    name: Str?,
    meta: Map?
}

One element of a multi-part message. Used by adapters and agent code to pass mixed text + image + audio + file content into a single Message turn without falling back to provider-specific shapes.

Fields

  • kind — "text" | "image" | "audio" | "file" | "tool-result".
  • text — UTF-8 string content. Set for kind: "text" and as a caption fallback on other kinds.
  • mime — best-effort media type (e.g. "image/png", "audio/mp3").
  • data — base64-encoded bytes when the part is inlined.
  • url — addressable URL when the part is referenced rather than inlined.
  • name — display label (filename for files, alt text for images).
  • meta — open map for adapter-specific hints (Anthropic cache_control, OpenAI image.detail, etc.).

Adapters that don't yet support multi-part input MUST flatten parts via flatten-parts(parts) before sending — this collapses text parts into a single string and discards everything else with a placeholder note so the model sees something coherent.

Provider

Known AI chat completion providers. Declared enum open so third-party adapters can register their own provider identity via arrow enrollment without forking this enum:

Mistral type { name: Str }
Mistral -> Provider.Mistral

Match expressions on Provider MUST include a _ default arm (open-enum-match-missing-default otherwise).

ProviderRegistration

ProviderRegistration type {
    variant: Provider,
    detect: Any,
    display-name: Str,
    chat-fn: Any,
    chat-stream-fn: Any,
    embed-fn: Any,
    meta: Map?,
    chat-opts-fn: Any?,
    chat-stream-opts-fn: Any?
}

Open-registry entry describing a chat-completion provider. First-party providers (Anthropic, OpenAI, xAI, Gemini) populate the built-in registry; third-party packages register their own via with-providers.

Fields

  • variant — the Provider enum variant (open enum, third parties enroll via arrow: MyProviderTag -> Provider.MyProviderTag).
  • detect — (model: Str) -> Bool. Returns true when this entry should handle the given lowercased model name.
  • display-name — human-readable label used in logs and provider-name.
  • chat-fn — tools-aware chat function matching the (model, messages, system, tools) -> ChatReply contract.
  • chat-stream-fn — optional streaming variant.
  • chat-opts-fn — optional chat-fn that also takes ChatOptions.provider-opts as a fifth argument. Preferred over chat-fn when set.
  • chat-stream-opts-fn — optional chat-stream-fn that also takes provider-opts as a sixth argument. Preferred over chat-stream-fn when set.
  • embed-fn — optional embeddings function for RAG.
  • meta — open map for capability flags (vision, audio, tool-choice, etc.).

ReplyDelta

Provider-agnostic streaming event emitted by a chat-stream-fn. Each event is one of:

  • TextDelta — a text fragment (concatenate to rebuild the turn).
  • ToolUseStart — a new tool call has begun (id, name).
  • ToolUseInputDelta — partial JSON of a tool call's input.
  • ToolUseEnd — a tool call has finished streaming.
  • Stop — terminal event with stop-reason and optional usage.

Provider adapters translate native SSE/wire events into this enum so consumers (and run-loop-stream) never branch on the underlying SDK.

Declared enum open so provider adapters can introduce provider-specific delta kinds (e.g., ThinkingDelta, ReasoningDelta) via arrow enrollment without forking this type. Match expressions on ReplyDelta MUST include a _ default arm (open-enum-match-missing-default otherwise) — unknown deltas should be silently ignored or forwarded.

StreamStop

StreamStop type {
    reason: Str,
    usage: Map?
}

Final event of a streaming turn. reason mirrors ChatReply.stop-reason ("end_turn", "tool_use", "max_tokens", …). usage carries the normalized {input-tokens, output-tokens} map when the provider reports it on this terminal event.

TextDelta

TextDelta type {
    text: Str
}

Incremental text fragment from a streaming reply. text is the delta only — concatenate them in order to reconstruct the full assistant text for the turn.

ToolFailure

ToolFailure type {
    tool: Str,
    call-id: Str,
    input: Map,
    error: Any,
    iteration: Int
}

Why run-loop stopped on a failed tool call, when ChatOptions.fail-on-tool-error or the tool's fail-on-error is on. The loop returns it as an Err.

  • tool: the tool's name, as the model called it.
  • call-id: the call's id.
  • input: the input the model passed.
  • error: the tool's failure, as ToolResult.output holds it.
  • iteration: the turn it happened on, from 1.

Example

failure ::ai::chat/ToolFailure({tool: "charge", call-id: "c1", input: {}, error: "card declined", iteration: 2})
failure.error  // "card declined"

ToolUseEnd

ToolUseEnd type {
    id: Str
}

A tool_use block has finished streaming. The accumulated input JSON is now ready to parse and dispatch.

ToolUseInputDelta

ToolUseInputDelta type {
    id: Str,
    partial-input-json: Str
}

Partial JSON fragment of a tool call's input. Concatenate the partial-input-json strings for a given id, then from-json the result to reconstruct the call's input map.

ToolUseStart

ToolUseStart type {
    id: Str,
    name: Str
}

A new tool_use block has begun in a streaming reply. The model has chosen name for tool-call id; the input arguments stream as ToolUseInputDelta events until a matching ToolUseEnd.