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.
implementation("com.openai:openai-java:4.94.0")
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.94.0</version>
</dependency>
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.
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.
[!TIP] See the
openai-java-exampledirectory 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);
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.
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.
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 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.
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();
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.
// 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
| 日期 | 榜单 | 排名 | 周期新增 | 总 STAR |
|---|