genai - Multi-AI Providers Library for Rust
Currently natively supports: OpenAI, Anthropic, Gemini, xAI, Ollama, Groq, DeepSeek, Cohere, Together, Fireworks, Nebius, Mimo, Zai (Zhipu AI), BigModel.
Also allows a custom URL with ServiceTargetResolver (see examples/c06-target-resolver.rs)
Provides a single, ergonomic API to many generative AI providers, such as Anthropic, OpenAI, Gemini, xAI, Ollama, Groq, and more.
NOTE: Big update with v0.5.0 - New adapters (BigModel, MIMO), Gemini Thinking support, Anthropic Reasoning Effort, and a more robust internal streaming engine.
v0.5.0 - (2026-01-09)
- What's new:
- New Adapters: BigModel.cn and MIMO model adapter (thanks to Akagi201).
- zai - change namespace strategy with (zai:: for default, and zai-codding:: for subscription, same Adapter)
- Gemini Thinking & Thought: Full support for Gemini Thought signatures (thanks to Himmelschmidt) and thinking levels.
- Reasoning Effort Control: Support for
ReasoningEffortfor Anthropic (Claude 3.7/4.5) and Gemini (Thinking levels), includingReasoningEffort::None. - Content & Binary Improvements: Enhanced binary/PDF API and size tracking.
- Internal Stream Refactor: Switched to a unified
EventSourceStreamandWebStreamfor better reliability and performance across all providers. - Dependency Upgrade: Now using
reqwest 0.13.
- What's still awesome:
- Normalized and ergonomic Chat API across all major providers.
- Native protocol support for Gemini and Anthropic protocols (Reasoning/Thinking controls).
- PDF, Image, and Embedding support.
- Custom Auth, Endpoint, and Header overrides.
See: - CHANGELOG
Big Thanks to
- v0.5.x
- BinaryMuse for #114 Anthropic ToolCalls streaming fix
- Himmelschmidt for #111 Gemini
responseJsonSchemasupport, #103 error body capture, and Gemini Thought signatures - malyavi-nochum for #109 Fireworks default streaming fix
- mengdehong for #108 Ollama reasoning streaming fix
- Akagi201 for #105 MIMO model adapter
- v0.1.x .. v0.4.x
- Vagmi Mudumbai for #96 openai audio_type
- Himmelschmidt for #98 openai service_tier
- Bart Carroll for #91 Fixed streaming tool calls for openai models
- Rui Andrada for #95 refactoring ZHIPU adapter to ZAI
- Adrien Extra headers in requests, seed for chat requests, and fixes (with Julien Chaumond for extra headers)
- Andrew Rademacher for PDF support, Anthropic streamer
- Jesus Santander Embedding support PR #83
- 4t145 for raw body capture PR #68
- Vagmi Mudumbai exec_chat bug fix PR #86
- Maximilian Goisser Fix OpenAI adapter to use ServiceTarget
- ClanceyLu for Tool Use Streaming support, web configuration support, and fixes
- @SilasMarvin for fixing content/tools issues with some Ollama models PR #55
- @una-spirito for Gemini
ReasoningEffort::Budgetsupport - @jBernavaPrah for adding tracing (it was long overdue). PR #45
- @GustavoWidman for the initial Gemini tool/function support! PR #41
- @AdamStrojek for initial image support PR #36
- @semtexzv for
stop_sequencesAnthropic support PR #34 - @omarshehab221 for de/serialize on structs PR #19
- @tusharmath for making webc::Error PR #12
- @giangndm for making stream Send PR #10
- @stargazing-dino for PR #2 - implement Groq completions
Usage examples
- Check out AIPACK, which wraps this genai library into an agentic runtime to run, build, and share AI Agent Packs. See
pro@coderfor a simple example of how I use AI PACK/genai for production coding.
Note: Feel free to send me a short description and a link to your application or library using genai.
Key Features
- Native Multi-AI Provider/Model: OpenAI, Anthropic, Gemini, Ollama, Groq, xAI, DeepSeek (Direct chat and stream) (see examples/c00-readme.rs)
- DeepSeekR1 support, with
reasoning_content(and stream support), plus DeepSeek Groq and Ollama support (andreasoning_contentnormalization) - Image Analysis (for OpenAI, Gemini flash-2, Anthropic) (see examples/c07-image.rs)
- Custom Auth/API Key (see examples/c02-auth.rs)
- Model aliases (see examples/c05-model-names.rs)
- Custom endpoint, auth, and model identifier (see examples/c06-target-resolver.rs)
Examples | Thanks | Library Focus | Changelog | Provider Mapping: ChatOptions | Usage
Examples
//! Base examples demonstrating the core capabilities of genai
use ;
use ;
use Client;
const MODEL_OPENAI: &str = "gpt-4o-mini"; // o1-mini, gpt-4o-mini
const MODEL_ANTHROPIC: &str = "claude-3-haiku-20240307";
// or namespaced with simple name "fireworks::qwen3-30b-a3b", or "fireworks::accounts/fireworks/models/qwen3-30b-a3b"
const MODEL_FIREWORKS: &str = "accounts/fireworks/models/qwen3-30b-a3b";
const MODEL_TOGETHER: &str = "together::openai/gpt-oss-20b";
const MODEL_GEMINI: &str = "gemini-2.0-flash";
const MODEL_GROQ: &str = "llama-3.1-8b-instant";
const MODEL_OLLAMA: &str = "gemma:2b"; // sh: `ollama pull gemma:2b`
const MODEL_XAI: &str = "grok-3-mini";
const MODEL_DEEPSEEK: &str = "deepseek-chat";
const MODEL_ZAI: &str = "glm-4-plus";
const MODEL_COHERE: &str = "command-r7b-12-2024";
// NOTE: These are the default environment keys for each AI Adapter Type.
// They can be customized; see `examples/c02-auth.rs`
const MODEL_AND_KEY_ENV_NAME_LIST: & = &;
// NOTE: Model to AdapterKind (AI Provider) type mapping rule
// - starts_with "gpt" -> OpenAI
// - starts_with "claude" -> Anthropic
// - starts_with "command" -> Cohere
// - starts_with "gemini" -> Gemini
// - model in Groq models -> Groq
// - starts_with "glm" -> ZAI
// - For anything else -> Ollama
//
// This can be customized; see `examples/c03-mapper.rs`
async
More Examples
- examples/c00-readme.rs - Quick overview code with multiple providers and streaming.
- examples/c01-conv.rs - Shows how to build a conversation flow.
- examples/c02-auth.rs - Demonstrates how to provide a custom
AuthResolverto provide auth data (i.e., for api_key) per adapter kind. - examples/c03-mapper.rs - Demonstrates how to provide a custom
AdapterKindResolverto customize the "model name" to "adapter kind" mapping. - examples/c04-chat-options.rs - Demonstrates how to set chat generation options such as
temperatureandmax_tokensat the client level (for all requests) and per-request level. - examples/c05-model-names.rs - Shows how to get model names per AdapterKind.
- examples/c06-target-resolver.rs - For custom auth, endpoint, and model.
- examples/c07-image.rs - Image analysis support
-
genai live coding, code design, & best practices
- Adding Gemini Structured Output (vid-0060)
- Adding OpenAI Structured Output (vid-0059)
- Splitting the json value extension trait to its own public crate value-ext value-ext
- (part 1/3) Module, Error, constructors/builders
- (part 2/3) Extension Traits, Project Files, Versioning
- (part 3/3) When to Async? Project Files, Versioning strategy
Library Focus:
-
Focuses on standardizing chat completion APIs across major AI services.
-
Native implementation, meaning no per-service SDKs.
- Reason: While there are some variations across the various APIs, they all follow the same pattern and high-level flow and constructs. Managing the differences at a lower layer is actually simpler and more cumulative across services than doing SDK gymnastics.
-
Prioritizes ergonomics and commonality, with depth being secondary. (If you require a complete client API, consider using async-openai and ollama-rs; they are both excellent and easy to use.)
-
Initially, this library will mostly focus on text chat APIs, with images and function calling coming later.
ChatOptions
- (1) - OpenAI-compatible notes
- Models: OpenAI, DeepSeek, Groq, Ollama, xAI, Mimo, Together, Fireworks, Nebius, Zai, Together, Fireworks, Nebius, Zai
| Property | OpenAI Compatibles (*1) | Anthropic | Gemini generationConfig. |
Cohere |
|---|---|---|---|---|
temperature |
temperature |
temperature |
temperature |
temperature |
max_tokens |
max_tokens |
max_tokens (default 1024) |
maxOutputTokens |
max_tokens |
top_p |
top_p |
top_p |
topP |
p |
Usage
| Property | OpenAI Compatibles (1) | Anthropic usage. |
Gemini usageMetadata. |
Cohere meta.tokens. |
|---|---|---|---|---|
prompt_tokens |
prompt_tokens |
input_tokens (added) |
promptTokenCount (2) |
input_tokens |
completion_tokens |
completion_tokens |
output_tokens (added) |
candidatesTokenCount (2) |
output_tokens |
total_tokens |
total_tokens |
(computed) | totalTokenCount (2) |
(computed) |
prompt_tokens_details |
prompt_tokens_details |
cached/cache_creation |
N/A for now | N/A for now |
completion_tokens_details |
completion_tokens_details |
N/A for now | N/A for now | N/A for now |
-
(1) - OpenAI-compatible notes
- Models: OpenAI, DeepSeek, Groq, Ollama, xAI, Mimo
- For Groq, the property
x_groq.usage. - At this point, Ollama does not emit input/output tokens when streaming due to the Ollama OpenAI compatibility layer limitation. (see ollama #4448 - Streaming Chat Completion via OpenAI API should support stream option to include Usage)
prompt_tokens_detailsandcompletion_tokens_detailswill have the value sent by the compatible provider (or None)
-
(2): Gemini tokens
- Right now, with the Gemini Stream API, it's not clear whether usage for each event is cumulative or must be summed. It appears to be cumulative, meaning the last message shows the total amount of input, output, and total tokens, so that is the current assumption. See possible tweet answer for more info.
Notes on Possible Direction
- Will add more data on ChatResponse and ChatStream, especially metadata about usage.
- Add vision/image support to chat messages and responses.
- Add function calling support to chat messages and responses.
- Add
embedandembed_batch. - Add the AWS Bedrock variants (e.g., Mistral and Anthropic). Most of the work will be on the "interesting" token signature scheme; trying to avoid bringing in large SDKs, this might be a lower-priority feature.
- Add the Google Vertex AI variants.
- May add the Azure OpenAI variant (not sure yet).
Links
- crates.io: crates.io/crates/genai
- GitHub: github.com/jeremychone/rust-genai
- Sponsored by BriteSnow (Jeremy Chone's consulting company)