Expand description
§xai-grok
A high-level async client for the xAI Grok API, built on top of the
stream-rs streaming toolkit.
xAI exposes an OpenAI-compatible REST API at https://api.x.ai/v1, so
this crate speaks the OpenAI chat-completions wire format while using
stream-rs for the part most clients get wrong: byte-accurate Server-Sent
Events parsing of the streamed response. Chunk boundaries, multi-line
data: fields, partial UTF-8, and interleaved tool-call deltas are all
handled correctly regardless of how the bytes arrive off the socket.
§Capabilities
- Chat —
GrokClient::chatfor a single buffered response. - Realtime streaming —
GrokClient::chat_streamyields afutures_core::Streamof parsedChatChunks; or useGrokClient::chat_stream_collectto fold deltas back into the final message with a live token callback. - Tool calling — declare
Tools and read backToolCalls. - Vision — multimodal
Content::Partswith image URLs /data:URIs. - Structured outputs —
ResponseFormat::json_schema.
Embeddings: xAI does not currently expose a public
/v1/embeddingsREST endpoint (embeddings exist only server-side inside the Collections API), so this crate intentionally does not provide an embeddings method rather than inventing one.
§Quick start
use xai_grok::{GrokClient, ChatRequest, Message};
let client = GrokClient::from_env()?; // reads XAI_API_KEY
let req = ChatRequest::new("grok-4.3", vec![
Message::system("You are a concise assistant."),
Message::user("Say hello in one word."),
]);
let resp = client.chat(req).await?;
println!("{}", resp.content().unwrap_or_default());Re-exports§
pub use types::ChatChunk;pub use types::ChatRequest;pub use types::ChatResponse;pub use types::Content;pub use types::ContentPart;pub use types::Delta;pub use types::FunctionCall;pub use types::FunctionDef;pub use types::ImageUrl;pub use types::Message;pub use types::ResponseFormat;pub use types::Role;pub use types::Tool;pub use types::ToolCall;pub use types::ToolChoice;pub use types::Usage;
Modules§
- types
- Wire types for the xAI Grok chat-completions API.
Structs§
- Chat
Stream - A stream of parsed Grok completion chunks.
- Grok
Client - A high-level async client for the xAI Grok API.
- Grok
Client Builder - Builder for
GrokClient. - Open
AiAccumulator - Accumulates
OpenAIchat-completion streaming deltas into final choices.
Enums§
- Error
- Errors that can occur while talking to the xAI Grok API.
Constants§
- DEFAULT_
BASE_ URL - The default xAI API base URL.
Type Aliases§
- Result
- Convenient result alias.