除客户端外必须自行添加一个 Ktor 引擎依赖,否则无法发请求;Maven 项目不支持 BOM,且多平台支持需用 Gradle;调用真实 API 需自备 API key,测试中开启 live 测试会产生计费流量
openai-kotlin
aallamMIT活跃维护Kotlin 编写的 OpenAI API 客户端,支持多平台和协程,方便在 Kotlin 项目中调用 GPT、DALL·E、Whisper 等模型接口。
OpenAI API client for Kotlin with multiplatform and coroutines capabilities.
implementation "com.aallam.openai:openai-client:4.2.0"
// 另需添加一个 Ktor 引擎,例如:
runtimeOnly 'io.ktor:ktor-client-okhttp'README 未说明,纯客户端库,无显存或 GPU 要求
Kotlin 多平台 OpenAI API 客户端,用协程调用 OpenAI 各类接口
Kotlin 编写的 OpenAI API 客户端,支持多平台和协程,方便在 Kotlin 项目中调用 GPT、DALL·E、Whisper 等模型接口。
核心能力
- 基于 Ktor 引擎发起 HTTP 请求,可自选引擎
- 支持 Kotlin Multiplatform,依赖放 commonMain 按目标选引擎
- 协程化调用 Chat、Embeddings、Images、Audio 等接口
- 覆盖 Files、Batch、Fine-tuning、Vector Stores 等能力
- 内置 ProGuard/R8 规则,随 Jar 自动生效
容易踩的坑
- 4.2.0最新正式版2026-10-31 · 2026-10-31 17:11 UTC
See the migration guide.
Added
- responses/conversations: expanded request controls, tools and typed items; compaction, token counting, resumable SSE, WebSockets and persisted conversation management.
- chat: current tool, audio/file, cache and usage controls, plus stored-completion and message access.
- images: current GPT Image generation, editing, multi-image inputs, response metadata and incremental events.
- moderations/embeddings: multimodal omni-moderation, token-ID embedding inputs and encoded embedding results.
- files/retrieval: expiry and pagination controls, multipart uploads, vector search, file attributes/content and batch output expiry.
- audio: modern transcription options and result metadata, diarization, custom voice references, and transcription/speech streaming.
- realtime/live: scoped audio/tool WebSockets, credentials, translation, WebRTC/SIP signaling, Live sessions, sidebands, stored forks and recordings.
- decisions: typed predicate, choice and score questions, multimodal evidence, conversation history, caching and usage.
- resources: Containers, Skills and immutable versions, plus prompt/sample voice creation and consent management.
- administration: separate
OpenAIAdminclient for organization/project administration, governance, usage/cost reporting and spend controls. - webhooks/safety: project webhook management and HMAC verification, safety alerts/cases and content-provenance checks.
- fine-tuning: pause/resume, checkpoint access and checkpoint-model permissions for eligible existing workflows.
- http: response metadata observers exposing request IDs, rate-limit information and response headers without changing endpoint return types.
Fixed
- streaming: preserve coroutine context across Ktor dispatchers and close connections correctly on cancellation or interrupted collection.
- authentication: retain configured credentials after unauthorized responses and prevent authentication retries from replaying one-shot requests.
- resource uploads: preserve binary bytes, disable automatic replay, and close sources on failure or cancellation for Containers, Skills, voices and provenance.
- serialization/errors: correct Responses JSON-schema and nested Chat citation shapes, and retain API errors when response bodies or content-type headers are invalid.
Deprecated
- Retired Assistants, Threads, Messages, Runs, Edits, Fine-tunes and DALL-E-only entry points now emit warning-level deprecations; existing declarations remain available.
- Legacy Completions methods emit migration warnings. Independent Vector Store support and fine-tuned model deletion remain available.
- 4.1.02026-02-07 · 2026-02-07 21:05 UTC
查看更新说明
Added
- batch: make
OpenAIinterface extendBatchinterface (#433). - responses: add Responses API support (
create,retrieve,cancel,delete, andinput_itemslisting). - chat: add
web_search_optionsrequest support. - chat: expose
annotationsandreasoning_contentin chat message payloads. - chat: support
requiredtool choice mode (#429).
Fixed
- chat: make
ChatCompletionRequestBuilder.reasoningEffort,store, andmaxCompletionTokensconfigurable. - chat: improve
ChatResponseFormatcompatibility by supporting both primitive and object variants. - chat: always encode
JsonSchema.strict, including its defaulttruevalue (#430). - chat: set explicit JSON class discriminator for polymorphic
ContentPartserialization. - images: stabilize image edit uploads for live API compatibility (#459).
- tests: remove flaky external image URL dependency from chat vision live tests.
- tests: stabilize vector store live tests with current API behavior (#459).
Changed
- tests: make
openai-clientlive API tests opt-in viaOPENAI_LIVE_TESTS=1. - ci: split billable live tests into a small JVM smoke job and a separate full-live workflow.
- docs: fix RetrievalTool usage in Getting Started guide (#427).
- batch: make
- 4.0.12025-02-02 · 2025-02-02 13:13 UTC
查看更新说明
Added
- chat: add reasoning effort, max completion tokens, store options for reasoning model support (#415) (thanks @Taewan-P)
- 4.0.02025-02-02 · 2025-02-02 12:25 UTC
查看更新说明
Added
- WasmJs target (#387)
- assistants: add structured response (#391) (thanks @ahmedmirza994)
- chat: Add support for structured outputs (#397)
- chat: make ChatCompletionRequest a data class (#399) (thanks @yunmanger1)
- assistant: add streaming (#400) (thanks @Daltomon)
Fixed
- runs: support for file search tool calls (#405) (thanks @averyaube)
Changed
- Upgrade to Kotlin 2.0 (#387)
- Update Ktor to 3.0 (#387)
Breaking Changes
- Replace okio by kotlinx.io (#387)
- 4.0.0-beta01pre-release2024-10-28 · 2024-10-28 09:22 UTC
查看更新说明
Added
- WasmJs target (#387)
- feat(assistants): add structured response (#391) (thanks @ahmedmirza994)
Changed
- Upgrade to Kotlin 2.0 (#387)
- Update Ktor to 3.0 (#387)
Breaking Changes
- Replace okio by kotlinx.io (#387)
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
OpenAI API client for Kotlin
Kotlin client for OpenAI's API with multiplatform and coroutines capabilities.
📦 Setup
- Install OpenAI API Kotlin client by adding the following dependency to your
build.gradlefile:
repositories {
mavenCentral()
}
dependencies {
implementation "com.aallam.openai:openai-client:4.2.0"
}
- Choose and add to your dependencies one of Ktor's engines.
BOM
Alternatively, you can use openai-client-bom by adding the following dependency to your build.gradle file
dependencies {
// import Kotlin API client BOM
implementation platform('com.aallam.openai:openai-client-bom:4.2.0')
// define dependencies without versions
implementation 'com.aallam.openai:openai-client'
runtimeOnly 'io.ktor:ktor-client-okhttp'
}
Multiplatform
In multiplatform projects, add openai client dependency to commonMain, and choose
an engine for each target.
Maven
Gradle is required for multiplatform support, but there's nothing stopping you from using the jvm client in a Maven project. You still need to add to your dependencies one of Ktor's engines.
<dependencies>
<dependency>
<groupId>com.aallam.openai</groupId>
<artifactId>openai-client-jvm</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-client-okhttp-jvm</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
The BOM is not supported for Maven projects.
⚡️ Getting Started
[!NOTE] OpenAI encourages using environment variables for the API key. Read more.
Create an instance of OpenAI client:
val openai = OpenAI(
token = "your-api-key",
timeout = Timeout(socket = 60.seconds),
// additional configurations...
)
Or you can create an instance of OpenAI using a pre-configured OpenAIConfig:
val config = OpenAIConfig(
token = apiKey,
timeout = Timeout(socket = 60.seconds),
// additional configurations...
)
val openAI = OpenAI(config)
Use your OpenAI instance to make API requests. Learn more.
Supported features
- Responses
- Decisions
- Conversations
- Models
- Chat
- Images
- Embeddings
- Files
- Multipart uploads
- Fine-tuning
- Moderations
- Audio
- Realtime
- Batch
- Vector Stores
- Webhooks
- Organization usage and costs
- OrganizationAdministration
- Organization governance
- Containers
- Skills
- Voice management
- Live
- Spend controls
- Safety and content provenance
- Fine-tuning operations
Retired upstream APIs
The following interfaces remain available for existing consumers, but their OpenAI endpoints have shut down. See the migration guide.
Vector Stores remain independent of the retired Assistants endpoints.
Legacy
- Completions is a legacy API; model availability is separate from endpoint support.
Looking for a tokenizer? Try ktoken, a Kotlin library for tokenizing text.
📚 Guides
Get started and understand more about how to use OpenAI API client for Kotlin with these guides:
ℹ️ Sample apps
Sample apps are available under sample, please check the README for running instructions.
🔒 ProGuard / R8
The specific rules are already bundled into the Jar which can be interpreted by R8 automatically.
📸 Snapshots
To import snapshot versions into your project, add the following code snippet to your gradle file:
repositories {
//...
maven { url 'https://central.sonatype.com/repository/maven-snapshots/' }
}
🛠️ Troubleshooting
For common issues and their solutions, check the Troubleshooting Guide.
🧪 Testing
openai-client tests are live integration tests and can generate billable API traffic.
- Default (non-billable): live tests are disabled.
- Opt-in live tests: set
OPENAI_LIVE_TESTS=1andOPENAI_API_KEY.
The JVM live suite excludes mocked offline fixtures. CI runs those once in Offline Checks, then runs the live suite plus the separate Live and Content Provenance tasks. Containers live tests remain opt-in for eligible projects.
Examples:
# Free/offline checks
./gradlew :openai-core:jvmTest :openai-core:jsTest :openai-core:wasmJsTest :openai-core:apiCheck :openai-client:apiCheck
# Mocked HTTP client tests (no credentials or API traffic)
./gradlew :openai-client:offlineJvmTest
# Live smoke (billable)
OPENAI_LIVE_TESTS=1 OPENAI_API_KEY=... ./gradlew :openai-client:jvmTest --tests "*.TestModels"
⭐️ Support
Appreciate the project? Here's how you can help:
- Star: Give it a star at the top right. It means a lot!
- Contribute: Found an issue or have a feature idea? Submit a PR.
- Feedback: Have suggestions? Open an issue or start a discussion.
📄 License
OpenAI Kotlin API Client is an open-sourced software licensed under the MIT license. This is an unofficial library, it is not affiliated with nor endorsed by OpenAI. Contributions are welcome.