Gemini 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
It translates ::ai::chat/Message records into Gemini contents,
calls generateContent (or streamGenerateContent), and normalizes the
response into a ::ai::chat/ChatReply, so run-loop does not need to
know Gemini's wire format.
Wiring. ::ai::chat's built-in registry leaves chat-fn null for
every provider, so set the adapter on ChatOptions (or register it with
::ai::chat/with-providers):
opts ::ai::chat/ChatOptions({
chat-fn: ::gemini::chat-tools/chat-with-tools,
chat-stream-fn: ::gemini::chat-tools/chat-with-tools-stream,
model: "gemini-2.5-flash",
})
Per-call credentials. Each entry point also takes a trailing
opts: Map (api-key, base-url, see ::gemini::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.
Tool calls. A Gemini function call may come with no id, and a model
that thinks returns a thoughtSignature on the call that Gemini 3
requires back on the next turn. The adapter keeps both in
ToolCall.meta (gemini-id, thought-signature), which run-loop
carries into the next request untouched. A call with no Gemini id gets a
generated one.
Failures. A refused call, an error inside the stream, a stream that
ends before its finish reason and a reply with no text and no call all
come back as an Err: ::gemini::api/HttpError for the first two,
ReplyError for the last two.
Values
EMPTY_STATE
EMPTY_STATE: Map {
text: "",
calls: [],
finish-reason: null,
block-reason: null,
finish-message: null,
usage: null
}
PROVIDER_NAME
PROVIDER_NAME: Str "Google Gemini"
Functions
build-request
fn (messages: Vec<::ai::chat/Message>, system: Str?, tools: Vec<::ai::tool/Tool>?, options: ChatRequestOptions): Map
The generateContent request body for a conversation, pure. system
and any system messages become systemInstruction; tools become one
functionDeclarations set, left out when there are none. With
options.cached-content set, the system instruction, tools and tool
config are left out, since Gemini takes them from the cache.
Example
request ::gemini::chat-tools/build-request(
[::ai::chat/user-message("Hi")],
"Be brief.",
null,
::gemini::chat-tools/ChatRequestOptions({max-tokens: 256})
)
request.systemInstruction // {parts: [{text: "Be brief."}]}
request.generationConfig // {maxOutputTokens: 256}
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— Gemini model id (e.g."gemini-2.5-flash").messages— conversation history asVec<::ai::chat/Message>.system— optional system prompt.tools— optionalVec<::ai::tool/Tool>. When non-empty, tools are offered to the model andfunctionCallparts becomeChatReply.tool-calls.
Returns a normalized ::ai::chat/ChatReply. A refused call is an Err
carrying ::gemini::api/HttpError; a reply with no text and no call is
an Err carrying ReplyError.
Example
add fn (x: Int, y: Int): Int { add(x, y) }
opts ::ai::chat/ChatOptions({
chat-fn: ::gemini::chat-tools/chat-with-tools,
model: "gemini-2.5-flash",
tools: [::ai::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 explicit ChatRequestOptions (output ceiling,
thinking, cache, safety, response schema). Bind it in a closure to keep
the four-argument chat contract with model-specific controls. A trailing
opts carries per-call credentials and settings.
Example
options ::gemini::chat-tools/ChatRequestOptions({max-tokens: 4096, thinking-budget: 1024})
reply ::gemini::chat-tools/chat-with-tools-options(
"gemini-2.5-flash",
[::ai::chat/user-message("Summarize the release notes.")],
"Be brief.",
null,
options
)
reply.text
reply.usage.thought-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 Gemini SSE chunks into
::ai::chat/ReplyDelta events delivered via on-delta, and returns the
aggregated ChatReply once the stream ends.
Parameters
model— Gemini 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. Use::ai::chat/noop-on-deltaif you only want the reply.
A refused call or an error partway through is an Err carrying
::gemini::api/HttpError; a stream cut short or a reply with nothing
in it is an Err carrying ReplyError. on-delta gets no Stop then.
Example
on-text (delta) {
match delta {
::ai::chat/ReplyDelta.TextDelta => { print(delta.text) }
=> { null }
}
}
reply ::gemini::chat-tools/chat-with-tools-stream(
"gemini-2.5-flash",
[::ai::chat/user-message("Hi")],
null,
null,
on-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 ChatRequestOptions.
Example
options ::gemini::chat-tools/ChatRequestOptions({max-tokens: 4096, thinking-level: "low"})
reply ::gemini::chat-tools/chat-with-tools-stream-options(
"gemini-3-flash",
[::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 Gemini's countTokens endpoint. Compatible
with the count-tokens-fn slot on ::ai::chat/ChatOptions.
For a per-call key, bind the three-argument form in a closure:
(messages, model) { ::gemini::chat-tools/count-tokens(messages, model, {api-key: key}) }.
Example
messages [::ai::chat/user-message("How many tokens is this?")]
::gemini::chat-tools/count-tokens(messages, "gemini-4-hydrogen")
finalize-state
fn (state: Map): ::ai::chat/ChatReply
Convert the final stream state into a ChatReply. A stream that ended
with no finish reason was cut short and is an Err carrying an
incomplete-stream ReplyError; one with neither text nor a call is an
empty-reply Err.
Example
state {...::gemini::chat-tools/EMPTY_STATE, text: "Hi", finish-reason: "STOP"}
::gemini::chat-tools/finalize-state(state).text // "Hi"
cut ::gemini::chat-tools/finalize-state({...::gemini::chat-tools/EMPTY_STATE, text: "Hel"})
err-value(cut).kind // "incomplete-stream"
generation-config
fn (options: ChatRequestOptions): Map?
The generationConfig for options, or null when nothing is set.
Example
options ::gemini::chat-tools/ChatRequestOptions({max-tokens: 2048, thinking-budget: 512})
config ::gemini::chat-tools/generation-config(options)
config.maxOutputTokens // 2048
config.thinkingConfig.thinkingBudget // 512
::gemini::chat-tools/generation-config(::gemini::chat-tools/DEFAULT_REQUEST_OPTIONS) // null
handle-chunk
fn (state: Map, data: Map?, on-delta: Fn): Map
Fold one parsed stream chunk into the stream state, sending its
ReplyDelta events to on-delta. A chunk carrying error is an Err
holding ::gemini::api/HttpError (status 200, since the call itself
succeeded). usageMetadata is cumulative, so the latest replaces the
last.
Example
chunk {candidates: [{content: {role: "model", parts: [{text: "Hi"}]}, finishReason: "STOP"}]}
state ::gemini::chat-tools/handle-chunk(::gemini::chat-tools/EMPTY_STATE, chunk, ::ai::chat/noop-on-delta)
state.text // "Hi"
state.finish-reason // "STOP"
parse-response
fn (body: Map): ::ai::chat/ChatReply
Normalize a generateContent response body into a
::ai::chat/ChatReply. Thought parts are left out of the text, and
functionCall parts become tool-calls. A response with neither text
nor a call is an Err carrying ReplyError.
Example
reply ::gemini::chat-tools/parse-response({
candidates: [{content: {role: "model", parts: [{text: "Hello"}]}, finishReason: "STOP"}],
usageMetadata: {promptTokenCount: 5, candidatesTokenCount: 1, totalTokenCount: 6}
})
reply.text // "Hello"
reply.stop-reason // "end_turn"
reply.usage.total-tokens // 6
part-text
fn (part: Map): Str
The visible text of a response part. A thought part (thought: true)
is the model's reasoning, not its answer, so it reads as empty.
Example
::gemini::chat-tools/part-text({text: "Hello"}) // "Hello"
::gemini::chat-tools/part-text({text: "Let me think.", thought: true}) // ""
part-tool-call
fn (part: Map): ::ai::tool/ToolCall?
Convert a functionCall part into a ::ai::tool/ToolCall, or null for
any other part. A Gemini id and the part's thoughtSignature go in
meta (gemini-id, thought-signature); a call with no Gemini id gets
a generated one.
Example
call ::gemini::chat-tools/part-tool-call({functionCall: {id: "fc1", name: "search", args: {q: "hot"}}, thoughtSignature: "sig"})
call.id // "fc1"
call.meta // {gemini-id: "fc1", thought-signature: "sig"}
::gemini::chat-tools/part-tool-call({text: "Hello"}) // null
reply-from-response
fn (response: ::hot::http/HttpResponse): ::ai::chat/ChatReply
The ChatReply for a generateContent HTTP response. A refused call
(status 400 or more) is an Err carrying ::gemini::api/HttpError with
Gemini's decoded error body.
Example
refused ::hot::http/HttpResponse({status: 429, headers: {}, body: {error: {code: 429, status: "RESOURCE_EXHAUSTED"}}})
reply ::gemini::chat-tools/reply-from-response(refused)
err-value(reply).status // 429
err-value(reply).body.error.status // "RESOURCE_EXHAUSTED"
response-usage
fn (u: Any): Map?
Normalize Gemini's usageMetadata into {input-tokens, output-tokens, total-tokens, cache-read-tokens, thought-tokens}. input-tokens
includes the cached tokens, and output-tokens the thought tokens, as
for the other providers.
Example
::gemini::chat-tools/response-usage({promptTokenCount: 100, candidatesTokenCount: 20, thoughtsTokenCount: 30, cachedContentTokenCount: 80, totalTokenCount: 150})
// {input-tokens: 100, output-tokens: 50, total-tokens: 150, cache-read-tokens: 80, thought-tokens: 30}
::gemini::chat-tools/response-usage(null) // null
stop-reason
fn (finish-reason: Str?, has-calls: Bool): Str
Map a Gemini finishReason to ChatReply.stop-reason: "tool_use"
when the reply holds calls, "max_tokens" for MAX_TOKENS,
"end_turn" for STOP or null, and the lowercased reason otherwise
(for example "safety" or "recitation" on a partial reply).
Example
::gemini::chat-tools/stop-reason("STOP", true) // "tool_use"
::gemini::chat-tools/stop-reason("MAX_TOKENS", false) // "max_tokens"
::gemini::chat-tools/stop-reason("STOP", false) // "end_turn"
::gemini::chat-tools/stop-reason("SAFETY", false) // "safety"
to-contents
fn (messages: Vec<::ai::chat/Message>): Map
Convert a conversation into Gemini contents plus the text of any
system messages: {contents, system}. Assistant turns become model
turns, and the tool results that answer one model turn go in one user
turn.
Example
call ::ai::tool/ToolCall({id: "c1", name: "search", input: {q: "hot"}})
out ::gemini::chat-tools/to-contents([
::ai::chat/user-message("Find hot"),
::ai::chat/assistant-message("", [call]),
::ai::chat/tool-result-message(::ai::tool/ToolResult({id: "c1", output: "3 hits", is-error: false})),
])
map(out.contents, %.role) // ["user", "model", "user"]
out.contents[2].parts[0].functionResponse.name // "search"
to-function-call-part
fn (call: ::ai::tool/ToolCall): Map
Convert a ::ai::tool/ToolCall into a Gemini functionCall part. The
call's meta.gemini-id goes back as the call's id, and its
meta.thought-signature as the part's thoughtSignature.
Example
call ::ai::tool/ToolCall({id: "c1", name: "search", input: {q: "hot"}, meta: {thought-signature: "sig"}})
part ::gemini::chat-tools/to-function-call-part(call)
part.functionCall // {name: "search", args: {q: "hot"}}
part.thoughtSignature // "sig"
to-function-declaration
fn (t: ::ai::tool/Tool): Map
Convert a ::ai::tool/Tool into a Gemini function declaration. The
input schema goes in parametersJsonSchema, which takes standard JSON
Schema, and is left out for a tool that takes no arguments.
Example
tool ::ai::tool/Tool({
name: "search",
description: "Search the docs.",
input-schema: {type: "object", properties: {q: {type: "string"}}, required: ["q"]},
fn: (input) { [] }
})
decl ::gemini::chat-tools/to-function-declaration(tool)
decl.name // "search"
decl.parametersJsonSchema.required // ["q"]
to-function-response-part
fn (m: ::ai::chat/Message, calls: Map): Map
Convert a role: "tool" message into a Gemini functionResponse part.
calls maps a tool-call id to the ToolCall it answers, which gives
the part its name (and its Gemini id, when the call had one). A result
whose call is not in calls is named by its id.
Example
call ::ai::tool/ToolCall({id: "c1", name: "search", input: {q: "hot"}})
result ::ai::chat/tool-result-message(::ai::tool/ToolResult({id: "c1", output: "3 hits", is-error: false}))
part ::gemini::chat-tools/to-function-response-part(result, {c1: call})
part.functionResponse // {name: "search", response: {result: "3 hits"}}
Types
ChatRequestOptions
ChatRequestOptions type {
max-tokens: Int?,
temperature: Dec?,
thinking-level: Str?,
thinking-budget: Int?,
include-thoughts: Bool?,
cached-content: Str?,
safety-settings: Vec<Map>?,
response-mime-type: Str?,
response-schema: Map?,
tool-mode: Str?
}
Per-request controls for Gemini generateContent. Every field is
optional; a null field is left out of the request so the model's default
applies.
max-tokens—maxOutputTokens. Thinking counts against it.temperature— sampling temperature.thinking-level— Gemini 3 thinking level ("low","high").thinking-budget— Gemini 2.5 thinking budget in tokens (0turns thinking off,-1lets the model decide).include-thoughts— ask for thought summaries. They are kept out of the reply's text either way.cached-content— acachedContents/...name from::gemini::cachedcontents. With it set, the system prompt, tools and tool config are left out of the request: Gemini refuses them beside a cache, so they must be in the cache.safety-settings—[{category, threshold}], as Gemini takes them.response-mime-type— e.g."application/json".response-schema— a JSON Schema for the reply (responseJsonSchema). Sets the MIME type toapplication/jsonwhen that is not given.tool-mode—functionCallingConfig.mode:"AUTO","ANY","NONE"or"VALIDATED".
ReplyError
ReplyError type {
kind: Str,
finish-reason: Str?,
block-reason: Str?,
message: Str?
}
Why a call that Gemini answered produced no usable reply.
kind—"empty-reply"(no text and no call) or"incomplete-stream"(the stream ended before a finish reason).finish-reason— the candidate'sfinishReason, e.g."SAFETY","MALFORMED_FUNCTION_CALL", or"MAX_TOKENS"when thinking used the whole output budget.block-reason—promptFeedback.blockReasonwhen the prompt itself was blocked.message— the candidate'sfinishMessage, when Gemini gives one.
Example
reply ::gemini::chat-tools/parse-response({candidates: [{finishReason: "SAFETY"}]})
is-err(reply) // true
err-value(reply).finish-reason // "SAFETY"