async-openai
Library Featured
Rust library for OpenAI
- Downloads
- 1,302,033
- Dependents
- 275
- Stars
- 2,031
- Forks
- 407
- Contributors
- 109
- Commits
- 405
- Latest release
- 0.43.0 ·
About
Async Rust library for OpenAI
Overview
async-openai is an unofficial Rust library for OpenAI, based on OpenAI OpenAPI spec.
- Requests are retried with exponential backoff when rate limited.
- Ergonomic builder pattern for all request objects.
- SSE streaming.
- Granular feature flags to enable any types or apis.
- WASM.
- Middleware support with tower ecosystem.
+ OpenAI compatible providers
- Bring your own custom types for Request or Response objects.
- Customize path, query and headers per request or for all requests.
- Microsoft Azure OpenAI Service.
Feature Flags
Read the full README
| What | APIs | Crate Feature Flags |
|---|---|---|
| Responses API | Responses, Conversations, Streaming events, Websocket Events | responses |
| Webhooks | Webhook Events | webhook |
| Platform APIs | Audio, Audio Streaming, Videos, Images, Image Streaming, Embeddings, Evals, Fine-tuning, Graders, Batch, Files, Uploads, Models, Moderations, Decisions, Safety Alerts and Cases, Content Provenance Checks | audio, video, image, embedding, evals, finetuning, grader, batch, file, upload, model, moderation, decisions, safety, content-provenance-checks |
| Vector stores | Vector stores, Vector store files, Vector store file batches | vectorstore |
| ChatKit (Beta) | ChatKit | chatkit |
| Containers | Containers, Container Files | container |
| Skills | Skills | skill |
| Realtime | Realtime Calls, Client secrets, Client events, Server events | realtime |
| Chat Completions | Chat Completions, Streaming | chat-completion |
| Administration | Admin API Keys, Audit Logs, Certificates, Data Retention, External Keys, External Storage, Groups, Invites, Projects, Roles, Spend Alerts, Spend Limits, Usage, Users; And their nested APIs | administration |
| Legacy | Completions | completions |
Usage
The library reads API key from the environment variable OPENAI_API_KEY.
# On macOS/Linux
export OPENAI_API_KEY='sk-...'
# On Windows Powershell
$Env:OPENAI_API_KEY='sk-...'
Other official environment variables supported are: OPENAI_ADMIN_KEY, OPENAI_BASE_URL, OPENAI_ORG_ID, OPENAI_PROJECT_ID
- Visit examples directory on how to use
async-openai. - Visit docs.rs/async-openai for docs.
Image Generation Example
use async_openai::{
types::images::{CreateImageRequestArgs, ImageModel, ImageSize},
Client,
};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// create client, reads OPENAI_API_KEY environment variable for API key.
let client = Client::new();
let request = CreateImageRequestArgs::default()
.model(ImageModel::GptImage2)
.prompt("cats on sofa and carpet in living room")
.n(2)
.size(ImageSize::Auto)
.user("async-openai")
.build()?;
let response = client.images().generate(request).await?;
// Concurrently save each image in its own Tokio task.
// Create directory if it doesn't exist.
let paths = response.save("./data").await?;
paths
.iter()
.for_each(|path| println!("Image file path: {}", path.display()));
Ok(())
}
OpenAI Compatible Providers
Even though the scope of the crate is official OpenAI APIs, it is very configurable to work with compatible providers.
Bring Your Own Types
Enable methods whose input and outputs are generics with byot feature. It creates a new method with same name and _byot suffix.
For example, to use serde_json::Value as request and response type:
let response: Value = client
.chat()
.create_byot(json!({
"messages": [
{
"role": "developer",
"content": "You are a helpful assistant"
},
{
"role": "user",
"content": "What do you think about life?"
}
],
"model": "gpt-4o",
"store": false
}))
.await?;
This can be useful in many scenarios:
- When shape of request/response in OpenAI-compatible APIs don't exactly match OpenAI.
- Extend existing types in this crate with new fields like
extra_body(with serde flatten) - To avoid typing verbose types.
- To escape deserialization errors on expected type and actual response mismatch.
*_byot methods require same trait bounds as regular methods.
Visit examples/bring-your-own-type directory to learn more.
References: Borrow Instead of Move
With byot use reference to request types
let response: Response = client
.responses()
.create_byot(&request).await?
Visit examples/borrow-instead-of-move to learn more.
Configurable Requests
Configure path, headers, and query parameters for a HTTP request.
Request Options
Use path(), .query(), .header(), .headers() on the API group. Path overrides the default path but all other methods are additive - adds to existing query or headers.
For demonstration:
client
.chat()
// override default path
.path("/v1/messages")
// query can be a struct or a map too - additive
.query(&[("limit", "10")])?
// header for unique id for this API request - additive
.header("x-request-id", "id123")?
.list()
.await?
Modifying all Requests
Use Config, OpenAIConfig etc. for configuring url, headers or query parameters globally for all requests.
Dynamic Dispatch
This allows you to use same code (say a fn) to call APIs on different OpenAI-compatible providers.
Create a client with Box or Arc wrapped configuration.
For example:
use async_openai::{Client, config::{Config, OpenAIConfig}};
// Use `Box` or `std::sync::Arc` to wrap the config
let config = Box::new(OpenAIConfig::default()) as Box<dyn Config>;
// create client
let client: Client<Box<dyn Config>> = Client::with_config(config);
// A function can now accept a `&Client<Box<dyn Config>>` parameter
// which can invoke any openai compatible api
fn chat_completion(client: &Client<Box<dyn Config>>) {
todo!()
}
Rust Types
To only use Rust types from the crate - disable default features and use feature flag types.
There are granular feature flags like response-types, chat-completion-types, etc.
These granular types are enabled when the corresponding API feature is enabled - for example responses will enable response-types.
TLS backends
The crate exposes the underlying reqwest TLS options as Cargo features. Pick exactly one; disable default features when choosing anything other than rustls.
TLS Feature Flags
| Feature | TLS implementation | Crypto provider | Notes |
|---|---|---|---|
rustls (default) | rustls + rustls-platform-verifier roots | aws-lc-rs bundled | Works out of the box. |
rustls-no-provider | rustls + rustls-platform-verifier roots | None — install your own | Use this to pick ring (or share a provider across your tree). Call e.g. rustls::crypto::ring::default_provider().install_default().unwrap(); at the start of main. |
native-tls | System TLS | n/a | OpenSSL on Linux, Secure Transport on macOS, SChannel on Windows. |
native-tls-vendored | System TLS, vendored OpenSSL | n/a | Statically links a bundled OpenSSL build. |
Webhooks
Support for webhook includes event types, signature verification, and building webhook events from payloads.
Middleware
Middleware is supported via Tower ecosystem, which can be enabled with middleware feature. See middleware for more detail.
OpenAPI
The openapi feature provides utoipa schemas
for Chat Completions and Completions types. Enable the corresponding type features
(chat-completion-types and/or completion-types). Other API families are not yet
covered. See the OpenAPI example.
Contributing
🎉 Thank you for taking the time to contribute and improve the project. I'd be happy to have you!
Please see contributing guide!
Complimentary Crates
- async-openai-wasm provides WASM support.
- openai-func-enums macros for working with function/tool calls.
License
This project is licensed under MIT license.
Compatibility
- Runs on
- GPU support unknown
What shows it
- no dependency or feature matches a backend row
- Native code
- None found
- No native code found
- Python bindings
- No Python binding crate found
- License
- MIT
Compare with similar projects
Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.
| Project | Downloads | Dependents | Stars | Latest release | Runs on (GPU) | Native code | License |
|---|---|---|---|---|---|---|---|
|
Rust library for OpenAI |
1,302,033 downloads over 30 days | 275 | 2,031 | 0.43.0 | GPU support unknown | No native code found | MIT |
|
rust-genai Featured
Multi-AI Providers Library for Rust. (OpenAI, Gemini, Anthropic, DeepSeek, Ollama, OMLX, AWS Bedrock, Vertex, Xai, Groq, Kimi, GLM and many more) |
118,643 downloads over 30 days | 81 | 938 | 0.7.3 | GPU support unknown | No native code found | Apache-2.0 OR MIT |
|
ollama-rs Featured
A Rust library for interacting with the Ollama API |
45,579 downloads over 30 days | 68 | 1,061 | 0.3.6 | GPU support unknown | No native code found | MIT |
|
openai-api-rs Listed
OpenAI API client library for Rust (unofficial) |
46,400 downloads over 30 days | 33 | 485 | 10.0.2 | GPU support unknown | No native code found | MIT |
|
aisdk Listed
An open-source Rust library for building AI-powered applications, inspired by the Vercel AI SDK. It provides a robust, type-safe, and easy-to-use interface for interacting with various Large Language Models (LLMs). |
36,877 downloads over 30 days | 4 | 263 | 0.6.1 | GPU support unknown | No native code found | MIT |
|
openai Listed
An unofficial Rust library for the OpenAI API. |
10,846 downloads over 30 days | 13 | 128 | 1.1.1 | GPU support unknown | No native code found | MIT |
|
Inference server for LLMs, speech and embeddings: OpenAI-compatible routes with streaming, plus speech synthesis (TTS) and transcription (ASR). Serves Llama, Mistral, Qwen, Mamba2, MLA+MoE and hybrid models from SafeTensors, AWQ, GPTQ and GGUF. |
8 binary downloads per release | Not applicable | 7 | 0.7.1 | CUDA, WebGPU | Binds native code: ring (feature distributed) | Apache-2.0 |
Why FeaturedIt passes every Featured gate.
What it meets
- It has 113 active dependents and 86 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days.
- Active dependents are at 100% of their peak. Featured needs at least 50%.
- Docs are present. The release commit or a manifest ties the crate to the repository.
- No vulnerability advisory stays unpatched past the grace window. At least one version is neither a prerelease nor 0.0.x.
- The last activity is on 1 Nov 2026, 8 days ago. The rules expect an update within 560 days. Dormancy rule
Exact rules: Featured library. The check on applied thresholds version 9.
Every rule outcome, as the check records it
expected-interval: version 0.43.0 base 140, doubled for 1302033 downloads per month, doubled for 112.67 active users: E = 560 daysdormancy: last activity 2026-11-01, 8 days ago, E = 560: activefeatured: featured: active_users 112.67, new_adopters 86, former_glory 1
Crates2 crates
- async-openai Primary
- async-openai-macros
Measurements and sources
Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.
Sources6 sources
- Description: the crates.io description
- crates.io database dump, fetched
- RustSec advisory database, fetched
- GitHub repository, fetched
- crates.io package, fetched
- GitHub contributors, fetched
Adoption113 active dependents, 86 new dependents in 365 days1 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Active dependents | 112.6667 | crates.io database dump | Yes | |
| New dependents (365 days) | 86 | crates.io database dump | Yes | |
| Peak active dependents | 112.1667 | crates.io database dump | Yes | |
| Active dependents as a share of the peak | 1 | crates.io database dump | Yes | |
| Binary downloads per release | Not measured | Yes |
MaintenanceLatest human commit: 8 days ago3 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Latest human commit | 2026-11-01 | GitHub repository | Yes | |
| Latest release | 2026-11-01 | crates.io database dump | Yes | |
| First release | 2022-12-02 | crates.io database dump | Yes | |
| Latest version | 0.43.0 | crates.io database dump | Yes | |
| Days the oldest outside issue waits for a reply | 163 | GitHub repository | Yes | |
| Maintainer replies over 365 days | 81 | GitHub repository | Yes | |
| Repository archived | false | GitHub repository | Yes | |
| Repository gone | false | GitHub repository | Yes | |
| Release commit or manifest in the repo | true | crates.io package | Yes | |
| Published docs | true | crates.io database dump | Yes | |
| Latest release fails cargo check | Not measured | Yes | ||
| Build check date | Not measured | Yes | ||
| Build check toolchain | Not measured | Yes |
SecurityUnpatched vulnerabilities: none
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Unpatched vulnerabilities past the grace window | none | RustSec advisory database | Yes | |
| RustSec unmaintained advisory | none | RustSec advisory database | Yes | |
| Deprecation notice | none | crates.io database dump | Yes | |
| Deprecated requirement | none | crates.io database dump | Yes |
Distribution126 releases, 1,302,033 downloads over 30 days5 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Releases | 126 | crates.io database dump | Yes | |
| Downloads over 30 days | 1302033 | crates.io database dump | Yes | |
| Binary downloads over the last 3 releases | Not measured | Yes | ||
| Homebrew installs on request over 365 days | Not measured | Yes | ||
| Repology repository families | Not measured | Yes | ||
| Docker pull growth over 90 days | Not measured | Yes | ||
| Docker pulls at the growth baseline | Not measured | Yes | ||
| Every version a prerelease | false | crates.io database dump | Yes | |
| Every version 0.0.x | false | crates.io database dump | Yes | |
| Every version yanked | false | crates.io database dump | Yes | |
| Crate deleted from crates.io | false | crates.io database dump | Yes |
Repository2,031 stars, 407 forks, 109 contributors, 405 commits. Stars alone never qualify a project.
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| GitHub stars | 2031 | GitHub repository | Yes — one part of the repository route | |
| GitHub forks | 407 | GitHub repository | Yes — one part of the repository route | |
| Contributors with a GitHub account | 109 | GitHub contributors | Yes — one part of the repository route | |
| Commits on the default branch | 405 | GitHub repository | No | |
| Repository's main crate left out of the entry | none | crates.io database dump | Yes |
Facts that never count
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| License | MIT | crates.io database dump | No | |
| Runs on, from listed crates and their direct dependencies | GPU support unknown | crates.io database dump | No | |
| What shows each backend | no dependency or feature matches a backend row | crates.io database dump | No | |
| Native code, from listed crates and their dependencies | No native code found | crates.io database dump | No | |
| Python bindings, from direct dependencies of listed crates | No Python binding crate found | crates.io database dump | No | |
| Crates that depend on a listed crate directly | 275 | crates.io database dump | No |
Corrections and review history
No correction applies to this entry.
Judgments
A judgment enters only through an approved issue and a merged pull request.
No judgment applies to this entry.