📦openai / openai-java
← 返回首页
The official Java library for the OpenAI API
⚖️ Apache-2.0📅 创建于 2024-10-31🔄 更新于 2026-10-29
🔗 GitHub Kotlin

📄 仓库 README

在 GitHub 查看 ↗
来自 GitHub 仓库自述文件 · 版权归原作者所有

OpenAI Java API Library

Maven Central javadoc

The OpenAI Java SDK provides convenient access to the OpenAI REST API from applications written in Java.

The REST API documentation can be found on platform.openai.com. Javadocs are available on javadoc.io.

Installation

Gradle

implementation("com.openai:openai-java:4.94.0")

Maven

<dependency>
  <groupId>com.openai</groupId>
  <artifactId>openai-java</artifactId>
  <version>4.94.0</version>
</dependency>

Requirements

The framework-neutral SDK artifacts require Java 8 or later. Runtime floors and lifecycle states are declared per artifact in the Java version support policy.

Local development

Before building the repository, check that the local environment uses the development JDK declared by build.jdk in gradle/version-support.properties, then run lint:

./scripts/check-env
./scripts/lint

See CONTRIBUTING.md for the complete development workflow.

Usage

[!TIP] See the openai-java-example directory for complete and runnable examples!

The primary API for interacting with OpenAI models is the Responses API. You can generate text from the model with the code below.

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` environment variables
OpenAIClient client = OpenAIOkHttpClient.fromEnv();

ResponseCreateParams params = ResponseCreateParams.builder()
        .input("Say this is a test")
        .model(ChatModel.GPT_5_2)
        .build();
Response response = client.responses().create(params);

The previous standard (supported indefinitely) for generating text is the Chat Completions API. You can use that API to generate text from the model with the code below.

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

// Configures using the `openai.apiKey`, `openai.adminKey`, `openai.orgId`, `openai.projectId`, `openai.webhookSecret` and `openai.baseUrl` system properties
// Or configures using the `OPENAI_API_KEY`, `OPENAI_ADMIN_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
OpenAIClient client = OpenAIOkHttpClient.fromEnv();

ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
    .addUserMessage("Say this is a test")
    .model(ChatModel.GPT_5_2)
    .build();
ChatCompletion chatCompletion = client.chat().completions().create(params);

Amazon Bedrock

Use the optional openai-java-bedrock artifact to call OpenAI-compatible APIs on Amazon Bedrock with normal AWS credentials:

implementation("com.openai:openai-java-bedrock:4.94.0")
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.BedrockOpenAIOkHttpClient;

// Uses the standard AWS credential chain, including environment credentials,
// ~/.aws/credentials, AWS_PROFILE, workload roles, and instance metadata.
OpenAIClient client = BedrockOpenAIOkHttpClient.builder()
        .awsRegion("us-east-1")
        .build();

Requests are signed with fresh AWS credentials on every attempt. Existing AWS_BEARER_TOKEN_BEDROCK bearer credentials remain supported as a compatibility fallback. See the Amazon Bedrock guide for named profiles, temporary credentials, custom credential providers, async streaming, precedence rules, and security guidance.

Client configuration

Configure the client using system properties or environment variables:

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

// Configures using the `openai.apiKey`, `openai.adminKey`, `openai.orgId`, `openai.projectId`, `openai.webhookSecret` and `openai.baseUrl` system properties
// Or configures using the `OPENAI_API_KEY`, `OPENAI_ADMIN_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
OpenAIClient client = OpenAIOkHttpClient.fromEnv();

Or manually:

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

OpenAIClient client = OpenAIOkHttpClient.builder()
    .apiKey("My API Key")
    .adminApiKey("My Admin API Key")
    .build();

Or using a combination of the two approaches:

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

OpenAIClient client = OpenAIOkHttpClient.builder()
    // Configures using the `openai.apiKey`, `openai.adminKey`, `openai.orgId`, `openai.projectId`, `openai.webhookSecret` and `openai.baseUrl` system properties
    // Or configures using the `OPENAI_API_KEY`, `OPENAI_ADMIN_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
    .fromEnv()
    .apiKey("My API Key")
    .build();

See this table for the available options:

Setter System property Environment variable Required Default value
apiKey openai.apiKey OPENAI_API_KEY false -
adminApiKey openai.adminKey OPENAI_ADMIN_KEY false -
organization openai.orgId OPENAI_ORG_ID false -
project openai.projectId OPENAI_PROJECT_ID false -
webhookSecret openai.webhookSecret OPENAI_WEBHOOK_SECRET false -
baseUrl openai.baseUrl OPENAI_BASE_URL true "https://api.openai.com/v1"

System properties take precedence over environment variables.

[!TIP] Don't create more than one client in the same application. Each client has a connection pool and thread pools, which are more efficient to share between requests.

Modifying configuration

To temporarily use a modified client configuration, while reusing the same connection and thread pools, call withOptions() on any client or service:

import com.openai.client.OpenAIClient;

OpenAIClient clientWithOptions = client.withOptions(optionsBuilder -> {
    optionsBuilder.baseUrl("https://example.com");
    optionsBuilder.maxRetries(42);
});

The withOptions() method does not affect the original client or service.

Workload identity authentication

Workload identity authentication allows applications running in cloud environments (Kubernetes, Azure, GCP) to authenticate using short-lived tokens issued by the cloud provider, instead of long-lived API keys.

Basic setup

import com.openai.auth.*;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

SubjectTokenProvider provider = K8sServiceAccountTokenProvider.builder().build();

WorkloadIdentity workloadIdentity = WorkloadIdentity.builder()
    .identityProviderId("your-identity-provider-id")
    .serviceAccountId("your-service-account-id")
    .provider(provider)
    .build();

OpenAIClient client = OpenAIOkHttpClient.builder()
    .workloadIdentity(workloadIdentity)
    .build();

X.509 client certificate authentication

Applications with a client certificate can exchange that certificate directly for short-lived OpenAI access tokens without providing a JWT or implementing SubjectTokenProvider:

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.client.okhttp.X509Transport;
import com.openai.client.okhttp.X509WorkloadIdentity;
import java.time.Duration;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509TrustManager;

X509ExtendedKeyManager keyManager = /* load your PKCS#12 key manager */;
X509TrustManager trustManager = /* load your trusted server roots */;

X509Transport transport = X509Transport.builder()
    .keyManager(keyManager)
    .certificateAlias("client-certificate")
    .trustManager(trustManager)
    .build();

X509WorkloadIdentity identity = X509WorkloadIdentity.builder()
    .identityProviderId("your-identity-provider-id")
    .serviceAccountId("your-service-account-id")
    .transport(transport)
    .refreshBuffer(Duration.ofMinutes(10)) // Optional; defaults to 20 minutes.
    .build();

OpenAIClient client = OpenAIOkHttpClient.builder()
    .x509WorkloadIdentity(identity)
    .build();

OpenAIOkHttpClientAsync.builder() supports the same x509WorkloadIdentity option. Tokens are obtained lazily, cached, and refreshed before expiration. Both the token exchange and API requests use the configured fixed certificate alias, isolated direct mutual-TLS connections, and native hostname verification; redirects and custom transport settings are not supported. Close the SDK client to release both connection pools. For a complete compilable PKCS#12 setup, see X509WorkloadIdentityExample.

Kubernetes service account token provider

// Use default token path (/var/run/secrets/kubernetes.io/serviceaccount/token)
SubjectTokenProvider provider = K8sServiceAccountTokenProvider.builder().build();

```java // Or specify a custom token path SubjectTokenProvider provider = K8sServiceAc

📈 近 7 天 Star 趋势

每日新增 Star(柱)与累计 Star(线)· 数据来自 GitHub

🏆 排名变化趋势

在各榜单中的排名历史(数字越小越靠前)

📋 历史上榜记录

每次快照的详细数据
日期 榜单 排名 周期新增 总 STAR