xai_grpc_client/lib.rs
1//! # xai-grpc-client
2//!
3//! Unofficial Rust client for xAI's Grok API with gRPC support.
4//!
5//! ## Features
6//!
7//! - **Async/await API** - Built on tokio and tonic
8//! - **Type-safe requests** - Strongly typed request builders
9//! - **Streaming support** - Real-time response streaming
10//! - **Tool calling** - Function calling with 7 tool types
11//! - **Multimodal** - Text and image inputs
12//! - **Advanced features** - Log probabilities, reasoning traces, deferred completions
13//! - **Secure by default** - Uses `secrecy` crate for API keys
14//!
15//! ## Quick Start
16//!
17//! ```no_run
18//! use xai_grpc_client::{GrokClient, ChatRequest};
19//!
20//! #[tokio::main]
21//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
22//! // Initialize client from GROK_API_KEY environment variable
23//! let mut client = GrokClient::from_env().await?;
24//!
25//! // Create a simple chat request
26//! let request = ChatRequest::new()
27//! .user_message("What is the meaning of life?")
28//! .with_model("grok-2-1212")
29//! .with_max_tokens(100);
30//!
31//! // Get response
32//! let response = client.complete_chat(request).await?;
33//! println!("{}", response.content);
34//!
35//! Ok(())
36//! }
37//! ```
38//!
39//! ## Streaming Example
40//!
41//! ```no_run
42//! use xai_grpc_client::{GrokClient, ChatRequest};
43//! use tokio_stream::StreamExt;
44//!
45//! #[tokio::main]
46//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
47//! let mut client = GrokClient::from_env().await?;
48//!
49//! let request = ChatRequest::new()
50//! .user_message("Write a short poem");
51//!
52//! let mut stream = client.stream_chat(request).await?;
53//!
54//! while let Some(chunk) = stream.next().await {
55//! let chunk = chunk?;
56//! print!("{}", chunk.delta);
57//! }
58//!
59//! Ok(())
60//! }
61//! ```
62//!
63//! ## Tool Calling Example
64//!
65//! ```no_run
66//! use xai_grpc_client::{GrokClient, ChatRequest, FunctionTool, Tool, ToolChoice};
67//! use serde_json::json;
68//!
69//! #[tokio::main]
70//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
71//! let mut client = GrokClient::from_env().await?;
72//!
73//! let get_weather = FunctionTool::new(
74//! "get_weather",
75//! "Get the current weather in a location"
76//! )
77//! .with_parameters(json!({
78//! "type": "object",
79//! "properties": {
80//! "location": {
81//! "type": "string",
82//! "description": "City name"
83//! }
84//! },
85//! "required": ["location"]
86//! }));
87//!
88//! let request = ChatRequest::new()
89//! .user_message("What's the weather in Tokyo?")
90//! .add_tool(Tool::Function(get_weather))
91//! .with_tool_choice(ToolChoice::Auto);
92//!
93//! let response = client.complete_chat(request).await?;
94//!
95//! if !response.tool_calls.is_empty() {
96//! println!("Tool called: {:?}", response.tool_calls[0]);
97//! }
98//!
99//! Ok(())
100//! }
101//! ```
102
103// Include generated protobuf code once at module level
104#[path = "generated/xai_api.rs"]
105#[allow(warnings, missing_docs)]
106pub(crate) mod proto;
107
108#[allow(missing_docs)]
109mod auth;
110
111/// Client implementation for connecting to the xAI Grok API.
112pub mod client;
113
114/// Error types for the client.
115mod error;
116
117/// Request types and builders for chat completions.
118pub mod request;
119
120/// Response types for chat completions.
121pub mod response;
122
123/// Tool calling support (function calling, web search, etc.).
124pub mod tools;
125
126/// Model listing and information API.
127pub mod models;
128
129/// Embedding API for vector representations.
130pub mod embedding;
131
132/// Tokenization API for counting tokens.
133pub mod tokenize;
134
135/// API key information and status.
136pub mod api_key;
137
138/// Sample API for raw text sampling.
139pub mod sample;
140
141/// Image generation API.
142pub mod image;
143
144/// Documents search API for RAG.
145pub mod documents;
146
147// Re-exports for convenient access
148pub use api_key::ApiKeyInfo;
149pub use client::{GrokClient, GrokConfig};
150pub use documents::{DocumentSearchRequest, DocumentSearchResponse, RankingMetric, SearchMatch};
151pub use embedding::{
152 EmbedEncodingFormat, EmbedInput, EmbedRequest, EmbedResponse, Embedding, EmbeddingUsage,
153};
154pub use error::{GrokError, Result};
155pub use image::{GeneratedImage, ImageFormat, ImageGenerationRequest, ImageGenerationResponse};
156pub use models::{EmbeddingModel, ImageGenerationModel, LanguageModel, Modality};
157pub use proto::IncludeOption;
158pub use request::{
159 ChatRequest, CompletionOptions, ContentPart, ImageDetail, Message, MessageContent,
160 ReasoningEffort, ResponseFormat, SearchConfig, SearchMode, SearchSource,
161};
162pub use response::{
163 ChatChunk, ChatResponse, FinishReason, LogProb, LogProbs, TokenUsage, TopLogProb,
164};
165pub use sample::{SampleChoice, SampleRequest, SampleResponse};
166pub use tokenize::{Token, TokenizeRequest, TokenizeResponse};
167pub use tools::{
168 CollectionsSearchTool, DocumentSearchTool, FunctionCall, FunctionTool, McpTool, Tool, ToolCall,
169 ToolCallKind, ToolCallStatusKind, ToolChoice, WebSearchTool, XSearchTool,
170};
171
172// Re-export tonic types for users who need custom channel configuration
173// This allows users to configure TLS, timeouts, and other transport options
174// without adding tonic as a direct dependency
175pub use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint};
176
177/// Prelude module for convenient imports
178pub mod prelude {
179 pub use crate::{
180 ChatRequest, ChatResponse, GrokClient, GrokConfig, Message, MessageContent,
181 Result as GrokResult, Tool, ToolChoice,
182 };
183}