Technology RadarTechnology Radar
Trial

The official OpenAI Java SDK is a first-party, idiomatic Java client for the OpenAI API — covering chat completions, streaming, structured outputs, embeddings, file uploads, and more, with native Java types and builder patterns.

Why It's in Trial

OpenAI released an official Java SDK in 2024 (previously community-maintained). It's now the recommended way to call OpenAI APIs directly from Java, when you don't want the overhead of Spring AI or LangChain4j's abstractions.

Use the raw SDK when: you need precise control over every API parameter, you're building a thin wrapper service, or you want to avoid framework dependencies.

Use Spring AI or LangChain4j instead when: you want multi-provider portability, built-in RAG, or agent patterns without writing them yourself.

Usage

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

Chat completions:

OpenAIClient client = OpenAIClient.builder()
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .build();

ChatCompletion completion = client.chat().completions().create(
    ChatCompletionCreateParams.builder()
        .model(ChatModel.GPT_4O)
        .addUserMessage("What is Spring AI?")
        .build()
);

System.out.println(completion.choices().get(0).message().content());

Structured output (response maps to a Java record):

record TechRadarEntry(String name, String ring, String rationale) {}

ParsedChatCompletion<TechRadarEntry> result = client.beta().chat()
    .completions().parsedCreate(
        ChatCompletionCreateParams.builder()
            .model(ChatModel.GPT_4O)
            .responseFormat(TechRadarEntry.class)
            .addUserMessage("Describe Spring AI as a tech radar entry.")
            .build(),
        TechRadarEntry.class
    );

TechRadarEntry entry = result.choices().get(0).message().parsed().get();

Streaming with virtual threads:

try (Stream<ChatCompletionChunk> stream = client.chat().completions()
        .createStreaming(params).stream()) {
    stream.forEach(chunk ->
        chunk.choices().stream()
             .flatMap(c -> c.delta().content().stream())
             .forEach(System.out::print)
    );
}

Key Characteristics

Property Value
Maintained by OpenAI (official)
Java version 11+
Supports Chat, streaming, structured output, embeddings, files, images
Async CompletableFuture-based async methods