async-openai

Library Featured

Rust library for OpenAI

Checked · Sources

Downloads
1,302,033
Dependents
275
Stars
2,031
Forks
407
Contributors
109
Commits
405
Latest release
0.43.0 ·

About

From the project README ·

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
WhatAPIsCrate Feature Flags
Responses APIResponses, Conversations, Streaming events, Websocket Eventsresponses
WebhooksWebhook Eventswebhook
Platform APIsAudio, Audio Streaming, Videos, Images, Image Streaming, Embeddings, Evals, Fine-tuning, Graders, Batch, Files, Uploads, Models, Moderations, Decisions, Safety Alerts and Cases, Content Provenance Checksaudio, video, image, embedding, evals, finetuning, grader, batch, file, upload, model, moderation, decisions, safety, content-provenance-checks
Vector storesVector stores, Vector store files, Vector store file batchesvectorstore
ChatKit (Beta)ChatKitchatkit
ContainersContainers, Container Filescontainer
SkillsSkillsskill
RealtimeRealtime Calls, Client secrets, Client events, Server eventsrealtime
Chat CompletionsChat Completions, Streamingchat-completion
AdministrationAdmin API Keys, Audit Logs, Certificates, Data Retention, External Keys, External Storage, Groups, Invites, Projects, Roles, Spend Alerts, Spend Limits, Usage, Users; And their nested APIsadministration
LegacyCompletionscompletions

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

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(())
}

Image Image

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

FeatureTLS implementationCrypto providerNotes
rustls (default)rustls + rustls-platform-verifier rootsaws-lc-rs bundledWorks out of the box.
rustls-no-providerrustls + rustls-platform-verifier rootsNone — install your ownUse 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-tlsSystem TLSn/aOpenSSL on Linux, Secure Transport on macOS, SChannel on Windows.
native-tls-vendoredSystem TLS, vendored OpenSSLn/aStatically 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

License

This project is licensed under MIT license.

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.

async-openai beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
async-openai This page Featured

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 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
blazr App Listed

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 days
  • dormancy: last activity 2026-11-01, 8 days ago, E = 560: active
  • featured: featured: active_users 112.67, new_adopters 86, former_glory 1
Crates2 crates

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
Adoption113 active dependents, 86 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents112.6667crates.io database dumpYes
New dependents (365 days)86crates.io database dumpYes
Peak active dependents112.1667crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 8 days ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-11-01GitHub repositoryYes
Latest release2026-11-01crates.io database dumpYes
First release2022-12-02crates.io database dumpYes
Latest version0.43.0crates.io database dumpYes
Days the oldest outside issue waits for a reply163GitHub repositoryYes
Maintainer replies over 365 days81GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution126 releases, 1,302,033 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases126crates.io database dumpYes
Downloads over 30 days1302033crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository2,031 stars, 407 forks, 109 contributors, 405 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars2031GitHub repositoryYes — one part of the repository route
GitHub forks407GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account109GitHub contributorsYes — one part of the repository route
Commits on the default branch405GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly275crates.io database dumpNo

Corrections and review history

Report a correction

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.