Skip to main content

xai_grok/
lib.rs

1//! # xai-grok
2//!
3//! A high-level async client for the [xAI Grok API], built on top of the
4//! [`stream-rs`](stream_rs) streaming toolkit.
5//!
6//! xAI exposes an **OpenAI-compatible** REST API at `https://api.x.ai/v1`, so
7//! this crate speaks the `OpenAI` chat-completions wire format while using
8//! `stream-rs` for the part most clients get wrong: byte-accurate Server-Sent
9//! Events parsing of the streamed response. Chunk boundaries, multi-line
10//! `data:` fields, partial UTF-8, and interleaved tool-call deltas are all
11//! handled correctly regardless of how the bytes arrive off the socket.
12//!
13//! ## Capabilities
14//!
15//! * **Chat** — [`GrokClient::chat`] for a single buffered response.
16//! * **Realtime streaming** — [`GrokClient::chat_stream`] yields a
17//!   [`futures_core::Stream`] of parsed [`ChatChunk`]s; or use
18//!   [`GrokClient::chat_stream_collect`] to fold deltas back into the final
19//!   message with a live token callback.
20//! * **Tool calling** — declare [`Tool`]s and read back [`ToolCall`]s.
21//! * **Vision** — multimodal [`Content::Parts`] with image URLs / `data:` URIs.
22//! * **Structured outputs** — [`ResponseFormat::json_schema`].
23//!
24//! > **Embeddings:** xAI does **not** currently expose a public
25//! > `/v1/embeddings` REST endpoint (embeddings exist only server-side inside
26//! > the Collections API), so this crate intentionally does not provide an
27//! > embeddings method rather than inventing one.
28//!
29//! ## Quick start
30//!
31//! ```no_run
32//! use xai_grok::{GrokClient, ChatRequest, Message};
33//!
34//! # async fn run() -> xai_grok::Result<()> {
35//! let client = GrokClient::from_env()?; // reads XAI_API_KEY
36//! let req = ChatRequest::new("grok-4.3", vec![
37//!     Message::system("You are a concise assistant."),
38//!     Message::user("Say hello in one word."),
39//! ]);
40//! let resp = client.chat(req).await?;
41//! println!("{}", resp.content().unwrap_or_default());
42//! # Ok(())
43//! # }
44//! ```
45//!
46//! [xAI Grok API]: https://docs.x.ai
47
48#![warn(missing_docs)]
49
50mod client;
51mod error;
52pub mod types;
53
54pub use client::{ChatStream, GrokClient, GrokClientBuilder, DEFAULT_BASE_URL};
55pub use error::{Error, Result};
56
57// Re-export the most-used types at the crate root for ergonomics.
58pub use types::{
59    ChatChunk, ChatRequest, ChatResponse, Content, ContentPart, Delta, FunctionCall, FunctionDef,
60    ImageUrl, Message, ResponseFormat, Role, Tool, ToolCall, ToolChoice, Usage,
61};
62
63// Re-export the underlying accumulator so callers can fold streamed deltas
64// themselves if they don't use `chat_stream_collect`.
65pub use stream_rs::accumulators::openai::OpenAiAccumulator;