xai

xAI API bindings for Hot.

Installation

Add this to the deps in your hot.hot file:

"hot.dev/xai": "1.3.1"

Configuration

Context VariableDescription
xai.api.keyxAI API key, used by every module except Collections management
xai.management.api.keyxAI Management API key, required by the Collections management functions

Set them from the environment in a ctx file:

::myapp::ctx ns

::hot::ctx/set(filter-vals({
    "xai.api.key": ::hot::env/get("XAI_API_KEY", ""),
    "xai.management.api.key": ::hot::env/get("XAI_MANAGEMENT_API_KEY", "")
}, (v) { not(is-empty(v)) }))

Per-call credentials

Every typed function takes a trailing opts Map that wins over ctx for that call, so one run can serve many tenants. Nothing is written to ctx.

opts keyctx keyNotes
api-keyxai.api.keySent as Authorization: Bearer ...
base-urlxai.base.urlFor proxies and gateways. In opts it needs api-key in opts too: the ctx key is never sent to a per-call URL
management-api-keyxai.management.api.keyUsed by the ::xai::collections management calls
management-base-urlxai.management.base.urlSame, for the Management API. In opts it needs management-api-key in opts too
answer ::xai::responses/chat("grok-3", "Hello!", {api-key: tenant-key})
models ::xai::models/list({api-key: tenant-key})

A blank or null key in opts is an error, never a fallback to ctx, so a tenant with a missing key can't run on your project's key. Leave the key out of opts to use ctx.

A per-call credential is masked in the run's call records, including inside strings like Bearer ${key}. A secret shorter than 8 bytes is masked only as a whole value. Records of your own calls that finished before this one may already be written, so mark a credential your code fetches with ::hot::ctx/mark-secret as soon as you have it.

Usage

Simple Chat

::responses ::xai::responses

answer ::responses/chat("grok-3", "What is the capital of France?")
println(answer)

With System Instructions

::responses ::xai::responses

poem ::responses/chat(
    "grok-3",
    "Write a haiku about programming",
    "You are a creative poet who loves technology."
)
println(poem)

Full Request Control

::responses ::xai::responses

request ::responses/CreateResponseRequest({
    model: "grok-3",
    input: [
        ::responses/user-message("Hello!"),
        ::responses/assistant-message("Hi there! How can I help you?"),
        ::responses/user-message("Tell me a joke")
    ],
    max_output_tokens: 1024,
    temperature: 0.8
})

response ::responses/create(request)
println(::responses/extract-response-text(response))

Streaming Responses

::responses ::xai::responses

response ::responses/create-stream(::responses/CreateResponseRequest({
    model: "grok-3",
    input: "Write a short story about a robot"
}))

for-each(response.body, (event) {
    text ::responses/extract-delta-text(event)
    cond {
        gt(length(text), 0) => { print(text) }
        ::responses/is-stream-done(event) => { println("\n---Done!---") }
        => { null }
    }
})

Continuing Conversations

The Responses API supports stateful conversations. Previous responses are stored server-side for 30 days.

::responses ::xai::responses

first-response ::responses/create(::responses/CreateResponseRequest({
    model: "grok-3",
    input: "My name is Alice"
}))

second-response ::responses/create(::responses/CreateResponseRequest({
    model: "grok-3",
    input: "What is my name?",
    previous_response_id: first-response.id
}))

Disable Server-Side Storage

::responses ::xai::responses

response ::responses/create(::responses/CreateResponseRequest({
    model: "grok-3",
    input: "This conversation won't be stored",
    store: false
}))

Tool calling with hot-ai

::xai::ai satisfies the ::ai::chat chat contract, so a Grok model can run under ::ai::chat/run-loop and run-loop-stream with tools. It sends xAI's OpenAI-compatible Chat Completions API through hot.dev/openai's chat-tools adapter. hot-ai's built-in registry leaves every provider's chat-fn null, so wire it on ChatOptions:

get-weather fn (city: Str): Str { `${city}: 18C` }

opts ::ai::chat/ChatOptions({
    chat-fn: ::xai::ai/chat-with-tools,
    chat-stream-fn: ::xai::ai/chat-with-tools-stream,
    model: "grok-4.3",
    tools: [::ai::tool/from-fn(get-weather)]
})

answer ::ai::chat/run-loop(opts, "What's the weather in Paris?")

Or register it, so grok-* and xai/<model> ids route to xAI:

opts ::ai::chat/ChatOptions({
    model: "grok-4.7",
    providers: ::ai::chat/with-providers([::xai::ai/provider()])
})

For a per-call key, use chat-opts-fn and chat-stream-opts-fn (or the registry) with provider-opts: {api-key: tenant-key}. For another output ceiling or reasoning-effort, bind chat-with-tools-options with an ::openai::chat-tools/ChatRequestOptions in a closure, or pass one to provider(...). A missing key and a refused call each come back as an Err you can check with is-err.

Image Generation

Generate images with grok-imagine-image (the default). File helpers return unified AIMedia.Image values from ::ai::media.

Simple Image URL

url ::xai::images/create-image("A futuristic city at sunset")
println(url)

Generate and Save to File

::images ::xai::images
AIMedia ::ai::media/AIMedia

result ::images/generate-to-file("uploads/city.png", "A futuristic city at sunset")

match result {
    AIMedia.Image => {
        println(result.media.file.path)
        println(result.revised_prompt)
    }
    _ => { println("Error generating image") }
}

cat ::images/generate-to-file("output/cat.png", ::images/CreateImageRequest({
    prompt: "A cat wearing a spacesuit",
    quality: "hd",
    style: "vivid"
}))

Generate Multiple Images

// Creates uploads/landscape-0.png, uploads/landscape-1.png, uploads/landscape-2.png
batch ::xai::images/generate-batch-to-files("uploads/landscape-{n}.png", "A beautiful mountain landscape", 3)

println(`Generated ${batch.succeeded} images`)
for-each(batch.items, (media) { println(media.media.file.path) })

Search the web and X with AI-powered responses.

::search ::xai::search

news ::search/search-web("grok-3", "What is the latest news about AI?")
posts ::search/search-x("grok-3", "What are people saying about the new iPhone?")
both ::search/search-all("grok-3", "What's happening with climate change today?")

Using Search Tools Directly

::responses ::xai::responses
::search ::xai::search

response ::responses/create(::responses/CreateResponseRequest({
    model: "grok-3",
    input: "Find recent discussions about Rust programming",
    tools: [::search/web-search-tool(), ::search/x-search-tool()]
}))

Collections (RAG)

Collections store documents with automatic embeddings for semantic, keyword or hybrid search. Creating and managing collections uses xai.management.api.key. search uses xai.api.key.

::collections ::xai::collections

results ::collections/search(::collections/SearchRequest({
    query: "What were the key revenue drivers?",
    collection_ids: ["col_abc123"],
    max_results: 10,
    retrieval_mode: ::collections/MODE_SEMANTIC
}))
first(results.results).content

List Available Models

all-models ::xai::models/list()
for-each(all-models.data, (model) { println(model.id) })

API Base URL

https://api.x.ai/v1 (Collections management: https://management-api.x.ai)

Available Models

Constants in ::xai::models:

  • Chat: grok-4-1-fast-reasoning, grok-4-1-fast-non-reasoning, grok-4-fast-reasoning, grok-4-fast-non-reasoning, grok-4-0709, grok-code-fast-1, grok-3, grok-3-mini
  • Vision: grok-2-vision-1212
  • Images: grok-imagine-image, grok-2-image-1212
  • Video: grok-imagine-video

Modules

ModuleDescription
::xai::responsesChat Responses API (main chat interface)
::xai::aihot-ai tool-calling adapter for run-loop
::xai::imagesImage generation
::xai::searchLive web and X search
::xai::collectionsCollections (document storage and search)
::xai::modelsModel listing and info
::xai::apiLow-level authenticated requests

Documentation

License

Apache-2.0 - see LICENSE