Skip to main content

Crate openai_rust_sdk

Crate openai_rust_sdk 

Source
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 enables testing and yara.

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
OpenAI API 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 ApiClient trait for a struct that contains an HttpClient
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 HashMap fields
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.

Derive Macros§

De
Derive macro available if serde is built with features = ["derive"].
Ser
Derive macro available if serde is built with features = ["derive"].