Skip to main content

Crate openai_core

Crate openai_core 

Source
Expand description

§openai-core

openai-core is an async Rust SDK for the OpenAI-compatible ecosystem.

It is a community-maintained, unofficial library. The crate tracks the main capability surface exposed by openai-node, then adapts it into Rust-native builders, typed models, async streams, and provider abstractions.

§Start Here

§Installation

[dependencies]
openai-core = "0.1"

Enable extra features only when you need them:

[dependencies]
openai-core = { version = "0.1", features = ["structured-output", "tool-runner", "realtime", "responses-ws"] }

§Feature Flags

FeatureDefaultPurpose
streamYesSSE and streaming response support
multipartYesFile uploads and multipart requests
webhooksYesWebhook HMAC verification
rustls-tlsYesrustls-based TLS for reqwest and WebSockets
structured-outputNoparse::<T>(), JSON Schema helpers, typed structured outputs
tool-runnerNoTool registration, tool execution loops, and runner traces
realtimeNoRealtime WebSocket support
responses-wsNoResponses WebSocket support

docs.rs for this crate is built with all features enabled, so feature-gated items are visible in the generated API pages and marked with doc(cfg(...)).

§Quick Start

use openai_core::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::builder()
        .api_key(std::env::var("OPENAI_API_KEY")?)
        .build()?;

    let response = client
        .responses()
        .create()
        .model("gpt-5.4")
        .input_text("Are semicolons optional in JavaScript?")
        .send()
        .await?;

    println!("{:?}", response.output_text());
    Ok(())
}

§Common Workflows

§Responses API

Use Client with .responses() for the primary documented API path. Key types include Response, ResponseOutputItem, ResponseOutputContentPart, and ResponseUsage.

§Chat Completions API

Use .chat().completions() when you want the compatibility path that maps more directly to classic chat completion workflows. Key types include ChatCompletion, ChatCompletionChunk, and ChatCompletionMessage.

§Streaming

For SSE and event-driven flows, start from .responses().stream() or .chat().completions().stream(). The stream runtime is documented under stream, with high-level types such as ResponseStream, ChatCompletionStream, AssistantStream, and RawSseStream.

§Uploads and Multipart

Use to_file, UploadSource, and FileLike to normalize byte buffers, local files, readers, and HTTP responses into multipart uploads.

§Webhooks

Use WebhookVerifier to validate signatures and WebhookEvent to deserialize incoming webhook payloads.

§Pagination

Use Page, CursorPage, and PageStream when iterating across paginated list endpoints.

§Realtime and Responses WebSocket

Realtime and WebSocket APIs are available behind the realtime and responses-ws features. The generated API docs include the exported socket and event types when those features are enabled.

§API Map

§Guides and Examples

openai-core 提供了一个围绕 OpenAI 兼容接口构建的异步 Rust SDK。 它支持多 Provider、分页、SSE 流、Multipart 上传、Webhook 校验以及工具调用辅助能力。

Re-exports§

pub use audio_helpers::AudioPlaybackInput;
pub use audio_helpers::RecordAudioOptions;
pub use audio_helpers::play_audio;
pub use audio_helpers::record_audio;
pub use auth::ApiKeySource;
pub use client::Client;
pub use client::ClientBuilder;
pub use config::ClientOptions;
pub use config::LogLevel;
pub use config::LogRecord;
pub use config::Logger;
pub use config::LoggerHandle;
pub use config::RequestOptions;
pub use error::ApiError;
pub use error::ApiErrorKind;
pub use error::ConnectionError;
pub use error::ContentFilterFinishReasonError;
pub use error::Error;
pub use error::LengthFinishReasonError;
pub use error::ProviderCompatibilityError;
pub use error::Result;
pub use error::SerializationError;
pub use error::StreamError;
pub use error::WebSocketError;
pub use error::WebSocketErrorKind;
pub use error::WebhookVerificationError;
pub use files::FileLike;
pub use files::MultipartField;
pub use files::ToFileInput;
pub use files::UploadSource;
pub use files::to_file;
pub use helpers::ParsedChatCompletion;structured-output
pub use helpers::ParsedResponse;structured-output
pub use helpers::json_schema_for;structured-output
pub use helpers::parse_json_payload;structured-output
pub use helpers::ToolDefinition;tool-runner
pub use helpers::ToolHandler;tool-runner
pub use helpers::ToolRegistry;tool-runner
pub use pagination::CursorPage;
pub use pagination::ListEnvelope;
pub use pagination::Page;
pub use pagination::PageStream;
pub use providers::AuthScheme;
pub use providers::AzureAuthMode;
pub use providers::AzureOptions;
pub use providers::CapabilitySet;
pub use providers::CompatibilityMode;
pub use providers::Provider;
pub use providers::ProviderKind;
pub use providers::ProviderProfile;
pub use resources::AudioSpeechCreateParams;
pub use resources::AudioTranscription;
pub use resources::AudioTranscriptionSegment;
pub use resources::AudioTranscriptionSegmentId;
pub use resources::AudioTranscriptionWord;
pub use resources::AudioTranslation;
pub use resources::Batch;
pub use resources::BatchCreateParams;
pub use resources::BatchError;
pub use resources::BatchErrors;
pub use resources::BatchRequestCounts;
pub use resources::BatchUsage;
pub use resources::BatchUsageInputTokensDetails;
pub use resources::BatchUsageOutputTokensDetails;
pub use resources::BetaAssistant;
pub use resources::BetaAssistantTool;
pub use resources::BetaRealtimeSession;
pub use resources::BetaRealtimeTranscriptionSession;
pub use resources::BetaThread;
pub use resources::BetaThreadMessage;
pub use resources::BetaThreadMessageContent;
pub use resources::BetaThreadRun;
pub use resources::BetaThreadRunIncompleteDetails;
pub use resources::BetaThreadRunLastError;
pub use resources::BetaThreadRunRequiredAction;
pub use resources::BetaThreadRunRequiredActionFunction;
pub use resources::BetaThreadRunRequiredActionFunctionToolCall;
pub use resources::BetaThreadRunRequiredActionSubmitToolOutputs;
pub use resources::BetaThreadRunStep;
pub use resources::BetaThreadRunStepDetails;
pub use resources::BetaThreadRunTool;
pub use resources::BetaThreadRunUsage;
pub use resources::BetaThreadToolResources;
pub use resources::ChatCompletion;
pub use resources::ChatCompletionChoiceLogprobs;
pub use resources::ChatCompletionChunk;
pub use resources::ChatCompletionMessage;
pub use resources::ChatCompletionStoreContentPart;
pub use resources::ChatCompletionStoreMessage;
pub use resources::ChatCompletionTokenLogprob;
pub use resources::ChatCompletionTokenTopLogprob;
pub use resources::ChatCompletionToolCall;
pub use resources::ChatContentDeltaEvent;
pub use resources::ChatKitConfiguration;
pub use resources::ChatKitRateLimits;
pub use resources::ChatKitSession;
pub use resources::ChatKitThread;
pub use resources::ChatKitThreadContent;
pub use resources::ChatKitThreadItem;
pub use resources::ChatKitThreadStatus;
pub use resources::ChatKitWorkflow;
pub use resources::ChatLogProbsDeltaEvent;
pub use resources::ChatReasoningDetail;
pub use resources::ChatRefusalDeltaEvent;
pub use resources::ChatToolArgumentsDeltaEvent;
pub use resources::ChatToolChoice;
pub use resources::ChatToolChoiceMode;
pub use resources::Completion;
pub use resources::CompletionChoice;
pub use resources::CompletionLogProbs;
pub use resources::CompletionUsage;
pub use resources::CompletionUsageCompletionTokensDetails;
pub use resources::CompletionUsagePromptTokensDetails;
pub use resources::Container;
pub use resources::ContainerCreateParams;
pub use resources::ContainerExpiresAfter;
pub use resources::ContainerFile;
pub use resources::ContainerFileCreateParams;
pub use resources::Conversation;
pub use resources::ConversationContentPart;
pub use resources::ConversationCreateParams;
pub use resources::ConversationInputItem;
pub use resources::ConversationItem;
pub use resources::ConversationItemCreateParams;
pub use resources::ConversationUpdateParams;
pub use resources::DeleteResponse;
pub use resources::EmbeddingData;
pub use resources::EmbeddingResponse;
pub use resources::EmbeddingUsage;
pub use resources::Eval;
pub use resources::EvalCreateParams;
pub use resources::EvalDataSourceConfig;
pub use resources::EvalOutput;
pub use resources::EvalOutputItem;
pub use resources::EvalRun;
pub use resources::EvalRunCreateParams;
pub use resources::EvalRunInput;
pub use resources::EvalTestingCriterion;
pub use resources::EvalUpdateParams;
pub use resources::FileObject;
pub use resources::FineTuningCheckpoint;
pub use resources::FineTuningCheckpointPermission;
pub use resources::FineTuningHyperparameterValue;
pub use resources::FineTuningJob;
pub use resources::FineTuningJobCreateParams;
pub use resources::FineTuningJobError;
pub use resources::FineTuningJobEvent;
pub use resources::FineTuningJobHyperparameters;
pub use resources::FineTuningJobIntegration;
pub use resources::FineTuningMetrics;
pub use resources::FineTuningWandbIntegration;
pub use resources::GraderModel;
pub use resources::GraderModelCatalog;
pub use resources::GraderRunErrors;
pub use resources::GraderRunMetadata;
pub use resources::GraderRunResponse;
pub use resources::GraderValidateResponse;
pub use resources::ImageData;
pub use resources::ImageGenerateParams;
pub use resources::ImageGenerationResponse;
pub use resources::InputTokenCount;
pub use resources::KnownResponseOutputTextAnnotation;
pub use resources::Model;
pub use resources::ModerationCreateResponse;
pub use resources::ModerationResult;
pub use resources::RealtimeClientSecretCreateResponse;
pub use resources::RealtimeSessionClientSecret;
pub use resources::RealtimeSessionPayload;
pub use resources::Response;
pub use resources::ResponseError;
pub use resources::ResponseFunctionToolCall;
pub use resources::ResponseIncompleteDetails;
pub use resources::ResponseInputItemPayload;
pub use resources::ResponseInputPayload;
pub use resources::ResponseInputTokensDetails;
pub use resources::ResponseOutputContentPart;
pub use resources::ResponseOutputContentPartRaw;
pub use resources::ResponseOutputItem;
pub use resources::ResponseOutputItemRaw;
pub use resources::ResponseOutputMessage;
pub use resources::ResponseOutputRefusal;
pub use resources::ResponseOutputText;
pub use resources::ResponseOutputTextAnnotation;
pub use resources::ResponseOutputTextAnnotationUnknown;
pub use resources::ResponseOutputTextContainerFileCitation;
pub use resources::ResponseOutputTextFileCitation;
pub use resources::ResponseOutputTextFilePath;
pub use resources::ResponseOutputTextLogprob;
pub use resources::ResponseOutputTextTopLogprob;
pub use resources::ResponseOutputTextUrlCitation;
pub use resources::ResponseOutputTokensDetails;
pub use resources::ResponseUsage;
pub use resources::Skill;
pub use resources::SkillCreateParams;
pub use resources::SkillUpdateParams;
pub use resources::SkillVersion;
pub use resources::SkillVersionContent;
pub use resources::SkillVersionCreateParams;
pub use resources::UploadObject;
pub use resources::UploadPart;
pub use resources::VectorStore;
pub use resources::VectorStoreAttributeValue;
pub use resources::VectorStoreAttributes;
pub use resources::VectorStoreExpiresAfter;
pub use resources::VectorStoreFile;
pub use resources::VectorStoreFileBatch;
pub use resources::VectorStoreFileChunkingStrategy;
pub use resources::VectorStoreFileContent;
pub use resources::VectorStoreFileCounts;
pub use resources::VectorStoreFileLastError;
pub use resources::VectorStoreMetadata;
pub use resources::VectorStoreSearchContent;
pub use resources::VectorStoreSearchResponse;
pub use resources::VectorStoreSearchResult;
pub use resources::VectorStoreStaticFileChunkingStrategy;
pub use resources::Video;
pub use resources::VideoCharacter;
pub use resources::VideoCharacterCreateParams;
pub use resources::VideoCreateParams;
pub use resources::ChatCompletionRunner;tool-runner
pub use resources::ChatCompletionStreamingRunner;tool-runner
pub use resources::ChatCompletionToolResult;tool-runner
pub use stream::AssistantEventStream;
pub use stream::AssistantImageFileDoneEvent;
pub use stream::AssistantMessageCreatedEvent;
pub use stream::AssistantMessageDeltaEvent;
pub use stream::AssistantMessageDoneEvent;
pub use stream::AssistantRunStepCreatedEvent;
pub use stream::AssistantRunStepDeltaEvent;
pub use stream::AssistantRunStepDoneEvent;
pub use stream::AssistantRuntimeEvent;
pub use stream::AssistantStream;
pub use stream::AssistantStreamEvent;
pub use stream::AssistantStreamSnapshot;
pub use stream::AssistantTextCreatedEvent;
pub use stream::AssistantTextDeltaEvent;
pub use stream::AssistantTextDoneEvent;
pub use stream::AssistantToolCallCreatedEvent;
pub use stream::AssistantToolCallDeltaEvent;
pub use stream::AssistantToolCallDoneEvent;
pub use stream::ChatCompletionEventStream;
pub use stream::ChatCompletionRuntimeEvent;
pub use stream::ChatCompletionStream;
pub use stream::ChatContentDoneEvent;
pub use stream::ChatContentSnapshotEvent;
pub use stream::ChatLogProbsDoneEvent;
pub use stream::ChatLogProbsSnapshotEvent;
pub use stream::ChatRefusalDoneEvent;
pub use stream::ChatRefusalSnapshotEvent;
pub use stream::ChatToolArgumentsDoneEvent;
pub use stream::ChatToolArgumentsSnapshotEvent;
pub use stream::LineDecoder;
pub use stream::RawSseStream;
pub use stream::ResponseEventStream;
pub use stream::ResponseFunctionCallArgumentsEvent;
pub use stream::ResponseOutputTextEvent;
pub use stream::ResponseRuntimeEvent;
pub use stream::ResponseStream;
pub use stream::SseEvent;
pub use stream::SseStream;
pub use webhooks::HeaderLookup;
pub use webhooks::WebhookEvent;
pub use webhooks::WebhookVerifier;
pub use websocket::OpenAIResponsesWebSocket;responses-ws
pub use websocket::OpenAIRealtimeWS;realtime
pub use websocket::OpenAIRealtimeWebSocket;realtime
pub use websocket::RealtimeServerEvent;realtime
pub use websocket::RealtimeSocket;realtime
pub use websocket::RealtimeStreamMessage;realtime
pub use websocket::ResponsesServerEvent;responses-ws
pub use websocket::ResponsesSocket;responses-ws
pub use websocket::ResponsesStreamMessage;responses-ws
pub use websocket::SocketCloseOptions;realtime or responses-ws
pub use websocket::SocketStreamMessage;realtime or responses-ws
pub use websocket::WebSocketServerEvent;realtime or responses-ws

Modules§

audio_helpers
本地音频播放与录制辅助能力。
auth
认证相关的通用抽象。
client
客户端入口与构建器。
config
客户端与请求级配置。
error
SDK 错误类型定义。
files
文件上传相关抽象。
helpersstructured-output
Structured output 与工具调用辅助能力。
pagination
分页相关类型。
providers
Provider 兼容层。
resources
资源命名空间、公开类型与请求构建器。
stream
Streaming runtime split into protocol, chat, responses, and assistant layers.
webhooks
Webhook 校验。
websocketrealtime or responses-ws
WebSocket protocol models and transport implementation.

Structs§

ApiResponse
表示带有元信息的响应对象。
JsonPayload
通用的原始 JSON 载荷包装器。
ResponseMeta
表示一次响应携带的元信息。