Expand description
§OpenAI Rust SDK
openai_rust_sdk is an unofficial, async, type-safe Rust client for the OpenAI API. The
Responses API is the recommended starting point for new integrations;
the crate also covers conversations, streaming and tools, Batch, files, vector stores,
media, Realtime, fine-tuning, evals, and administration APIs.
This community-maintained crate is not affiliated with, endorsed by, or maintained by OpenAI. The API changes quickly, so consult the dated coverage matrix before depending on a particular endpoint in production.
§Quick start
Set OPENAI_API_KEY and choose OPENAI_MODEL explicitly (for example,
gpt-5.6-luna), then create a
response:
use openai_rust_sdk::{OpenAIError, from_env, models::CreateResponseRequest};
#[tokio::main]
async fn main() -> openai_rust_sdk::Result<()> {
let client = from_env()?;
let model = std::env::var("OPENAI_MODEL")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
.ok_or_else(|| {
OpenAIError::InvalidRequest(
"OPENAI_MODEL must be set to a non-empty model ID".to_owned(),
)
})?;
let request = CreateResponseRequest::new_text(
model,
"Explain Rust's ownership model in one concise sentence.",
);
let response = client.create_response_v2(&request).await?;
println!("{}", response.output_text());
Ok(())
}from_env also accepts the optional OPENAI_BASE_URL environment variable. A custom base URL
must be an API origin without /v1 or a trailing slash. The API key is sent as a bearer token
to that origin, so only configure endpoints you trust.
§API lifecycle
Responses and Conversations are the modern integration path. Assistants, Threads, and Runs remain available for migration, but OpenAI has deprecated the Assistants API and announced its shutdown for August 26, 2026. See OpenAI’s migration guide.
§Cargo features
default: the core OpenAI API client.yara: local validation and CLI tooling for the optional YARA-X Batch API example.testing: reserved compatibility feature; currently adds no dependencies.full: all optional capabilities; currently enablestestingandyara.
See the YARA-X Batch example for exact CLI commands and security considerations.
§Reliability
The shared HTTP client does not currently apply automatic retries or expose a global request timeout. Applications should add workload-appropriate timeouts, exponential backoff with jitter, and idempotency handling. More details are in the configuration guide.
Complete, runnable programs live in the repository’s
examples directory, starting
with quickstart.rs and responses_api.rs.
Re-exports§
pub use api::batch::BatchApi;pub use api::streaming::StreamingApi;pub use api::AdminApi;pub use api::AssistantsApi;pub use api::ConversationsApi;pub use api::CustomToolsApi;pub use api::EvalsApi;pub use api::FineTuningApi;pub use api::FunctionsApi;pub use api::RealtimeAudioApi;pub use api::ResponsesApi;pub use api::RunsApi;pub use api::SkillsApi;pub use api::ThreadsApi;pub use api::UploadsApi;pub use api::VectorStoresApi;pub use api::VideosApi;pub use builders::FunctionBuilder;pub use builders::ObjectSchemaBuilder;pub use client::ChatBuilder;pub use client::OpenAIClient;pub use client::from_env;pub use client::from_env_with_base_url;pub use error::OpenAIError;pub use error::Result;pub use models::responses_v2::CreateResponseRequest;pub use models::responses_v2::InputTokenCountResponse;pub use models::responses_v2::ResponseStreamEvent;pub use prompt_engineering::Example;pub use prompt_engineering::PromptBuilder;pub use prompt_engineering::PromptPatterns;pub use prompt_engineering::PromptTemplateBuilder;pub use prompt_engineering::XmlContentBuilder;pub use schema::EnhancedSchemaBuilder;pub use schema::JsonSchema;pub use schema::SchemaBuilder;pub use testing::batch_generator::BatchJobGenerator;pub use models::realtime::*;pub use models::assistants::*;pub use models::functions::*;pub use models::responses::*;
Modules§
- api
OpenAIAPI functionality- builders
- Function and schema builders
- client
- Client implementations and builders
- constants
- Constants used throughout the SDK Constants used throughout the OpenAI API SDK
- error
- Error types and handling
- helpers
- Helper utilities to reduce code duplication Helper modules for reducing code duplication
- macros
- Common macros for reducing code duplication Common macros for reducing code duplication across the codebase
- models
- Data models and types
- prompt_
engineering - Prompt engineering utilities and builders
- schema
- JSON Schema utilities JSON Schema builder for structured outputs
- testing
- Utilities for the optional YARA-X Batch API example
- webhooks
- Offline verification and parsing of OpenAI webhook deliveries. Verify webhook deliveries before parsing their exact raw request bodies.
Macros§
- file_
err - Convenience macro for FileError mapping with format string
- http_
delete - Macro to generate HTTP DELETE method wrappers
- http_
delete_ beta - Macro to generate HTTP DELETE method wrappers with beta headers
- http_
get - Macro to generate simple HTTP GET method wrappers
- http_
get_ beta - Macro to generate HTTP GET method wrappers with beta headers
- http_
post - Macro to generate HTTP POST method wrappers
- http_
post_ beta - Macro to generate HTTP POST method wrappers with beta headers
- impl_
api_ client - Macro to implement the
ApiClienttrait for a struct that contains anHttpClient - impl_
api_ test_ suite - Macro to generate comprehensive test suites for API clients and models
- impl_
audio_ format_ methods - Macro to generate common audio format methods for audio builders
- impl_
builder - Macro to implement the basic Builder trait
- impl_
builder_ build - Macro to generate standard builder
build()methods with field validation - impl_
builder_ methods - Macro for implementing common builder methods
- impl_
builder_ setters - Macro to implement standard builder pattern setter methods
- impl_
bytes_ to_ human_ readable - Macro to generate bytes to human readable formatting
- impl_
bytes_ usage - Generic macro to implement BytesUsage
- impl_
comprehensive_ test_ suite - Macro to generate comprehensive test suites that can replace entire test modules
- impl_
default_ object_ type - Macro to generate default object type functions
- impl_
delete_ response - Generic macro to implement DeleteResponse
- impl_
enum_ display - Macro to generate Display implementations for enums that serialize as lowercase strings
- impl_
file_ supported - Generic macro to implement FileSupported
- impl_
filterable_ list_ response - Generic macro to implement FilterableListResponse
- impl_
fine_ tuning_ params - Macro to generate fine-tuning job parameter types with pagination
- impl_
fluent_ setters - Macro to generate fluent setter methods for builders
- impl_
format_ methods - Macro to generate common format methods for builders
- impl_
image_ size_ methods - Macro to generate common size methods for image builders
- impl_
list_ params - Macro to generate list parameter structures with pagination support
- impl_
list_ params_ with_ builder - Macro to generate common list parameter types with builder pattern methods This eliminates massive duplication in vector stores, fine tuning, and similar modules
- impl_
list_ query_ params - Macro to implement ListQueryParams trait for pagination structures
- impl_
list_ response - Macro to generate list response structures
- impl_
list_ response_ methods - Macro to generate list response filtering methods for responses with data field
- impl_
map_ setters - Macro to generate builder methods for
HashMapfields - impl_
metadata_ builder - Generic macro to implement MetadataBuilder for any builder type
- impl_
option_ setters - Macro to generate builder methods for optional non-string fields
- impl_
pagination_ params - Generic macro to implement PaginationParams
- impl_
params_ test_ suite - Macro to generate parameter testing suites with pagination
- impl_
query_ params - Macro for implementing query parameter building with common fields
- impl_
response_ constructors - Macro to generate success/failure response constructors
- impl_
run_ builder_ methods - Macro to generate run builder methods that delegate to RunConfigurationBuilder trait
- impl_
run_ config_ builder - Macro to generate RunConfigurationBuilder trait implementations
- impl_
status_ enum - Generic macro to implement StatusEnum for snake_case serialized enums
- impl_
status_ filters - Macro to generate status filtering methods for list responses
- impl_
status_ methods - Macro to generate status checking methods for entities
- impl_
string_ setters - Macro to generate builder methods for optional string fields
- impl_
test_ helpers - Macro to generate common test helper functions for request/response testing
- impl_
transcription_ format_ methods - Macro to generate common transcription format methods
- impl_
usage_ methods - Macro to generate usage bytes methods for list responses
- impl_
validation - Macro to implement common validation methods
- impl_
vec_ setters - Macro to generate builder methods for vector fields
- impl_
with_ format - Macro to implement WithFormat trait
- impl_
with_ n - Macro to implement WithN trait
- impl_
with_ quality - Macro to implement WithQuality trait
- impl_
with_ size - Macro to implement WithSize trait
- impl_
with_ speed - Macro to implement WithSpeed trait
- impl_
with_ temperature - Macro to implement WithTemperature trait
- impl_
with_ user - Macro to implement WithUser trait
- invalid_
request_ err - Convenience macro for InvalidRequest mapping
- map_err
- Macro to simplify error mapping with format strings
Usage:
map_err!(FileError, "Failed to read file: {}") - network_
err - Convenience macro for Unknown error mapping (network errors)
- parse_
err - Convenience macro for ParseError mapping
- parsing_
err - Convenience macro for parsing errors that go to InvalidRequest
- request_
err - Convenience macro for RequestError mapping
- streaming_
err - Convenience macro for Streaming error mapping
- validation_
err - Convenience macro for validation errors (parsing errors that go to InvalidRequest)
Traits§
- De
- A data structure that can be deserialized from any data format supported by Serde.
- Ser
- A data structure that can be serialized into any data format supported by Serde.