provider-xai
v1.4.0xAI Chat Completions provider worker; implements provider::xai::stream and provider::xai::refresh_models behind llm-router.
Install
iii trigger compose::add worker=provider-xaiRun in your project with the iii engine running. Exact versions are immutable and digest-pinned.
provider-xai
xAI Chat Completions provider worker behind llm-router.
Implements the provider protocol from
tech-specs/2026-06-agentic/llm-router.md: provider::xai::stream
(SSE chunks → AssistantMessageEvent frames into a router-owned channel) and
provider::xai::refresh_models (live GET /v1/models filtered to
chat/reasoning families ∪ curated capability snapshot →
router::models::reconcile).
provider::xai::count_tokens counts a prompt behind router::count_tokens:
the request is rendered from this worker's own wire rows and tool array
(schemas in Python json.dumps form), tokenized in one /tokenize-text
call, and xAI's measured overhead is added on top: the server-side preamble
per model family (~180 tokens on grok-build/4.20/4.3 and the older
grok-code-fast, grok-3 and grok-4 ids xAI now serves as those, ~1,240 on
grok-4.7), the tools header, image tokens from each PNG/JPEG's dimensions,
and the server-tool definitions on the Agent Tools path. The constants are
calibrated against billed prompt_tokens, not published by xAI.
A response_format schema, and the thinking_level that shifts grok-4.3's
preamble (6 to 8 tokens shorter with reasoning off or high), count when the
caller passes them to provider::xai::count_tokens directly.
router::count_tokens does not forward either yet (MOT-5568), so counts
through the router leave the schema out and assume the default effort.
Behavior
- Registration: self-declares via
router::provider::registerwith backoff until acked, and re-declares on everyrouter::on-readyevent (it observes that function at boot; the observer outlives router restarts). The declaration ships a static curatedmodelsslice (no cold-catalog hole) andcredential_env_var: XAI_API_KEY. - Identity binding: the router returns a
registration_tokenon first registration; it is persisted in state (scopeprovider-xai, keyregistration_token) and presented on every laterregister/resolve/reconcile. If that state is lost the router rejects re-registration — the operator must clear the binding on the router side. - Credentials: resolved per request via
router::provider::resolve(config slice →XAI_API_KEYenv on the router → none). Bothapi_keyandoauthcredential shapes are sent asAuthorization: Bearer; v1 performs no OAuth refresh. - Liveness:
pingat least every 30s of upstream silence; a failed channel write (caller gone /router::abort) drops the SSE receiver and aborts the in-flight HTTP request. - Errors: 401/403 →
auth_expired, 429 →rate_limited(exceptinsufficient_quota, a billing wall →permanent),context_length_exceeded→context_overflow, 5xx/network →transient, other 4xx →permanent. No transport retries here — the router owns retry policy. - Structured output: native. A
response_formatwith a schema maps to strictjson_schemamode; without one,json_objectmode (the caller must mention "JSON" in the prompt per xAI's rules). Every curated record declaressupports_structured_output: true. - Reasoning:
thinking_levelmaps toreasoning_effortper grok family (src/reasoning.rs, verified against api.x.ai):grok-4.3takes the full laddernone/low/medium/high/xhigh,grok-3-minitakeslow/high, and every other current model (grok-build, thegrok-4.20-*snapshots) rejects the param with a 400, so it is omitted. Reasoning models stream their chain of thought asreasoning_contentdeltas, which the worker surfaces asthinkingblocks on the channel (src/sse.rs);completion_tokens_details.reasoning_tokenslands onusage.reasoning. - Prompt caching: automatic on xAI's side — no request markers. On the
Responses (Agent Tools) path the body
prompt_cache_keyis a key derived from the router'scache_intent.surface_digest(the frozen agent-profile prefix, so independent sessions on one profile share it) when present, else a key derived from the session id; thex-grok-conv-idheader always stays the session.prompt_tokens_details.cached_tokenslands onusage.cache_read. - Curated snapshot:
src/curated.rscarries windows / output ceilings / capability flags / pricing (USD per MTok). Update it against models.dev when xAI ships new models — discovery only supplies bare ids.
Tests
cargo test # unit (pure modules + TCP stubs)
III_ENGINE_BIN=$(which iii) cargo test --test integration -- --test-threads=1The integration suite spawns a real engine, the real router (path dep), this provider, and a local stub upstream — no external API calls anywhere.
Running
The binary takes the standard worker CLI flags: --url (engine WebSocket,
default ws://127.0.0.1:49134, falls back to the III_WS_URL environment
variable), --manifest (print the registry manifest and exit), and
--config (accepted but ignored with a warning — provider config comes
from the llm-router configuration entry).