OpenAI 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
Translates ::ai::chat/Message records into OpenAI's chat
completions wire format, calls ::openai::chat/complete, and
normalizes the response into a ::ai::chat/ChatReply so that
run-loop does not need to know about OpenAI's specifics.
chat-with-tools and chat-with-tools-stream also take a trailing
opts Map (see ::openai::api/resolve), which makes them fit the
chat-opts-fn and chat-stream-opts-fn slots, so
ChatOptions.provider-opts works through the run loop:
tenant-key ::hot::ctx/get("tenant.openai.key")
opts ::ai::chat/ChatOptions({
chat-opts-fn: ::openai::chat-tools/chat-with-tools,
model: "gpt-4o-mini",
provider-opts: {api-key: tenant-key}
})
answer ::ai::chat/run-loop(opts, "What is 17 + 25?")
Values
CHARS_PER_TOKEN_HEURISTIC
CHARS_PER_TOKEN_HEURISTIC: Int 4
DEFAULT_MAX_TOKENS
DEFAULT_MAX_TOKENS: Int 1024
EMPTY_STREAM_STATE
EMPTY_STREAM_STATE: Map {
text: "",
tool-blocks: {},
tool-order: [],
finish-reason: null,
usage-input: 0,
usage-output: 0
}
PER_MESSAGE_OVERHEAD_TOKENS
PER_MESSAGE_OVERHEAD_TOKENS: Int 4
Functions
apply-request-options
fn (request: Map, options: ChatRequestOptions): Map
Apply output and reasoning controls to an OpenAI request map: the
output ceiling (as max_completion_tokens, or max-tokens-param),
reasoning_effort when set, stream_options removal when
stream-usage is false, and extra-body merged last.
Example
options ::openai::chat-tools/ChatRequestOptions({max-completion-tokens: 256, max-tokens-param: "max_tokens"})
::openai::chat-tools/apply-request-options({model: "llama3.2"}, options) // {model: "llama3.2", max_tokens: 256}
build-chat-body
fn (model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, options: ChatRequestOptions, stream: Bool): Map
Build the Chat Completions request body for the normalized adapter:
an optional system message, the translated messages, tools when
the list is non-empty (servers reject tools: []), and options applied by apply-request-options. With
stream: true it also sets stream: true and
stream_options: {include_usage: true} (unless stream-usage is
false). Pure; exposed for testing.
Example
body ::openai::chat-tools/build-chat-body(
"gpt-4o-mini",
[::ai::chat/user-message("Hi")],
"Be terse.",
null,
::openai::chat-tools/DEFAULT_REQUEST_OPTIONS,
false
)
body.messages[0].role // => "system"
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— OpenAI model id (e.g."gpt-4o-mini").messages— conversation history asVec<::ai::chat/Message>.system— optional system prompt; prepended as asystem::ai::chat/Messageif provided.tools— optionalVec<::ai::tool/Tool>. When non-null, tools are advertised to the model and anytool_callsin the response becomeChatReply.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: ::openai::chat-tools/chat-with-tools,
model: "gpt-4o-mini",
tools: [::tool/from-fn(add)]
})
answer ::ai::chat/run-loop(opts, "What is 17 + 25?")
chat-with-tools-at
fn (ep: ::openai::api/Endpoint, model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, options: ChatRequestOptions): ::ai::chat/ChatReply
chat-with-tools-options against an explicit ::openai::api/Endpoint
(any OpenAI-compatible server). Reads no ctx, so keyless local servers
work. The request body is sent as a plain Map, so options.extra-body
can carry provider-specific fields, and the response is parsed
leniently.
Bind it in a closure to get a ::ai::chat/run-loop chat function, or
use ::openai::compatible/provider to get a ready-made
ProviderRegistration.
Example
ep ::openai::api/endpoint("http://localhost:11434/v1")
opts ::openai::chat-tools/ChatRequestOptions({
max-completion-tokens: 512,
max-tokens-param: "max_tokens"
})
reply ::openai::chat-tools/chat-with-tools-at(
ep, "llama3.2", [::ai::chat/user-message("Hi")], null, null, opts
)
reply.text
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 reasoning effort.
The original four-argument function remains the provider-agnostic
::ai::chat/run-loop contract; bind this function in a closure when a
session needs model-specific request controls.
Example
options ::openai::chat-tools/ChatRequestOptions({max-completion-tokens: 256, reasoning-effort: "none"})
reply ::openai::chat-tools/chat-with-tools-options("gpt-4o-mini", [::ai::chat/user-message("Hi")], "Be terse.", null, options)
reply.text
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 OpenAI SSE events into
provider-agnostic ::ai::chat/ReplyDelta events delivered via
on-delta, and returns a fully-aggregated ChatReply once
the stream terminates.
To get usage totals, OpenAI requires
stream_options: {include_usage: true} — this adapter sets that
automatically.
Parameters
model— OpenAI model id.messages— conversation history asVec<::ai::chat/Message>.system— optional system prompt.tools— optionalVec<::ai::tool/Tool>.on-delta— callback(delta: ReplyDelta): Nullinvoked for every event during streaming.
Example
reply ::openai::chat-tools/chat-with-tools-stream(
"gpt-4o-mini",
[::ai::chat/user-message("Hi")],
null,
null,
(delta) { print(delta) }
)
reply.text
chat-with-tools-stream-at
fn (ep: ::openai::api/Endpoint, model: Str, messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, on-delta: Fn, options: ChatRequestOptions): ::ai::chat/ChatReply
Streaming chat-with-tools-at: the run-loop-stream adapter against
an explicit ::openai::api/Endpoint. Emits ::ai::chat/ReplyDelta
events through on-delta and returns the aggregated ChatReply.
Set options.stream-usage to false for servers that reject
stream_options.
Example
ep ::openai::api/endpoint("http://localhost:11434/v1")
options ::openai::chat-tools/ChatRequestOptions({max-completion-tokens: 256, stream-usage: false})
reply ::openai::chat-tools/chat-with-tools-stream-at(
ep,
"llama3.2",
[::ai::chat/user-message("Hi")],
null,
null,
(delta) { print(delta) },
options
)
reply.text
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 reasoning controls.
Example
options ::openai::chat-tools/ChatRequestOptions({max-completion-tokens: 256, reasoning-effort: "none"})
reply ::openai::chat-tools/chat-with-tools-stream-options(
"gpt-4o-mini",
[::ai::chat/user-message("Hi")],
null,
null,
(delta) { print(delta) },
options
)
reply.usage
count-tokens
fn (messages: Vec<::ai::chat/Message>, model: Str): Int
Heuristic token counter for OpenAI chat models.
OpenAI does not expose a server-side counter, so this function
estimates using ceil(total_chars / 4) + per_message_overhead,
where 4 chars/token tracks the cl100k tokenizer to within ~10%
for English prose. Code, JSON, or non-Latin text will skew
further. For exact counts, embed tiktoken (e.g. via a
Python/JS Box) and pass the result via
ChatOptions.count-tokens-fn.
Compatible with the count-tokens-fn slot on
::ai::chat/ChatOptions:
(messages: Vec<Message>, model: Str): Int
Example
::openai::chat-tools/count-tokens([::ai::chat/user-message("Hello there")], "gpt-4o-mini") // 8
parse-chat-reply
fn (response: Map): ::ai::chat/ChatReply
Normalize a (decoded) Chat Completions response body into a
::ai::chat/ChatReply: first-choice text and tool calls, the finish
reason (default "stop"), and usage. Tolerates missing fields.
Example
reply ::openai::chat-tools/parse-chat-reply({
choices: [{message: {content: "Hello"}, finish_reason: "stop"}],
usage: {prompt_tokens: 12, completion_tokens: 5}
})
reply.text // "Hello"
reply.stop-reason // "stop"
parse-tool-call
fn (tc: Map): ::ai::tool/ToolCall
Convert one OpenAI tool_calls entry into a ::ai::tool/ToolCall.
OpenAI ships function arguments as a JSON string; we decode it
into a Map. A non-JSON or empty payload becomes {}.
Example
call ::openai::chat-tools/parse-tool-call({id: "call_1", function: {name: "add", arguments: "{\"x\":1}"}})
call.name // "add"
call.input // {x: 1}
response-text
fn (msg: Map): Str
Extract assistant text content from an OpenAI choice's message.
Example
::openai::chat-tools/response-text({content: "Hello"}) // "Hello"
::openai::chat-tools/response-text({}) // ""
response-tool-calls
fn (msg: Map): Vec<::ai::tool/ToolCall>
Extract ::ai::tool/ToolCall entries from an OpenAI choice's message.
Example
msg {tool_calls: [{id: "call_1", function: {name: "add", arguments: "{}"}}]}
::openai::chat-tools/response-tool-calls(msg)[0].id // "call_1"
response-usage
fn (u: Any): Map?
Normalize OpenAI's usage shape into {input-tokens, output-tokens}.
Example
::openai::chat-tools/response-usage({prompt_tokens: 12, completion_tokens: 5}) // {input-tokens: 12, output-tokens: 5}
to-openai-message
fn (m: ::ai::chat/Message): Map
Convert a single normalized ::ai::chat/Message into OpenAI's
chat completion Message. role: "tool" maps to OpenAI's tool
response shape and uses tool_call_id for correlation.
Example
::openai::chat-tools/to-openai-message(::ai::chat/user-message("Hi")) // {role: "user", content: "Hi"}
to-openai-tool
fn (t: ::ai::tool/Tool): Map
Convert a ::ai::tool/Tool into OpenAI's tool definition shape:
{type: "function", function: {name, description?, parameters}}.
Example
tool ::ai::tool/Tool({
name: "add",
description: "Add two numbers",
input-schema: {type: "object"},
fn: (input) { input }
})
::openai::chat-tools/to-openai-tool(tool).function.name // "add"
to-openai-tool-call
fn (call: ::ai::tool/ToolCall): Map
Convert a ::ai::tool/ToolCall into OpenAI's tool_calls entry.
Example
call ::ai::tool/ToolCall({id: "call_1", name: "add", input: {x: 1}})
::openai::chat-tools/to-openai-tool-call(call).function.arguments // "{\"x\":1}"
Types
ChatRequestOptions
ChatRequestOptions type {
max-completion-tokens: Int,
reasoning-effort: Str?,
max-tokens-param: Str?,
stream-usage: Bool?,
extra-body: Map?
}
Per-request controls for the normalized Chat Completions adapter.
reasoning-effort is passed as reasoning_effort. When using GPT-5.6
with function tools through Chat Completions, set it to "none"; use the
Responses API for reasoning-enabled tool loops.
The optional fields below exist for OpenAI-compatible servers and are all no-ops when unset:
max-tokens-param: the body field that carriesmax-completion-tokens. Default"max_completion_tokens"; set"max_tokens"for servers that only accept the older name (DeepSeek, Mistral, Ollama, DashScope, most gateways).stream-usage: whenfalse, streaming requests omitstream_options: {include_usage: true}for servers that reject it.extra-body: provider-specific fields merged into every request body (e.g. Qwen'senable_thinking, OpenRouter'sproviderrouting). They are merged last, so they can override defaults.