Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

simple-openai

> AI 编程
Open source

A Java library to use the OpenAI Api in the simplest possible way.

380 stars0 likes1 views
WebsiteGitHub

About

A Java library to use the OpenAI Api in the simplest possible way.

Simple-OpenAI

A Java library to use the OpenAI Api in the simplest possible way.

Table of Contents

  • Description
  • Supported Services
  • Installation
  • How to Use
    • Creating a SimpleOpenAI Object
    • Using HttpClient or OkHttp
    • Using Realtime Feature
    • Audio Example
    • Image Example
    • Chat Completion Example
    • Chat Completion with Streaming Example
    • Chat Completion with Functions Example
    • Chat Completion with Vision Example
    • Chat Completion with Audio Example
    • Chat Completion with Structured Outputs
    • Chat Completion Conversation Example
    • Assistant v2 Conversation Example
    • Response Conversation Example
    • Realtime Conversation Example
  • Exception Handling
  • Retrying Requests
  • Instructions for Android
  • Support for OpenAI-compatible API Providers
    • Gemini Vertex API
    • Gemini Google API
    • Deepseek API
    • Mistral API
    • Azure OpenAI
    • Anyscale
  • Run Examples
  • Contributing
  • License
  • Who is Using Simple-OpenAI?
  • Show Us Your Love

Description

Simple-OpenAI is a Java http client library for sending requests to and receiving responses from the OpenAI API. It exposes a consistent interface across all the services, yet as simple as you can find in other languages like Python or NodeJs. It's an unofficial library.

Simple-OpenAI uses the CleverClient library for http communication, Jackson for Json parsing, and Lombok to minimize boilerplate code, among others libraries.

✅ Supported Services

Simple-OpenAI seeks to stay up to date with the most recent changes in OpenAI. Currently, it supports most of the existing features and will continue to update with future changes.

Full support for most of the OpenAI services:

  • Audio (Speech, Transcription, Translation)
  • Batch (Batches of Chat Completion)
  • [ UPDATED] Chat Completion (Text Generation, Streaming, Function Calling, Vision, Structured Outputs, Audio, Web Search)
  • Completion (Legacy Text Generation)
  • Embedding (Vectoring Text)
  • Files (Upload Files)
  • Fine Tuning (Customize Models)
  • Image (Generate, Edit, Variation)
  • Models (List)
  • Moderation (Check Harmful Text)
  • [ UPDATED] Realtime (Speech-to-Speech Conversation, Multimodality, Function Calling)
  • [ UPDATED] Response (Text Generation, Streaming, Function Calling, Vision, Structured Outputs, Reasoning, Computer Use, File Search, Web Search, Remote MCP, Image Generation, Code Interpreter, Reusable Prompts). See examples of this service in ResponseDemo.java
  • [ UPDATED] Session Token (Create Ephemeral Tokens, Create Transcription Ephemeral Tokens)
  • Upload (Upload Large Files in Parts)
  • Assistants Beta v2 (Assistants, Threads, Messages, Runs, Steps, Vector Stores, Streaming, Function Calling, Vision, Structured Outputs)

Installation

You can install Simple-OpenAI by adding the following dependencies to your Maven project:

xml

    io.github.sashirestela
    simple-openai
    [simple-openai_latest_version]

    com.squareup.okhttp3
    okhttp
    [okhttp_latest_version]

Or alternatively using Gradle:

groovy
dependencies {
    implementation 'io.github.sashirestela:simple-openai:[simple-openai_latest_version]'
    /* OkHttp dependency is optional if you decide to use it with simple-openai */
    implementation 'com.squareup.okhttp3:okhttp:[okhttp_latest_version]'
}

Take in account that you need to use Java 11 or greater.

How to Use

Creating a SimpleOpenAI Object

This is the first step you need to do before to use the services. You must provide at least your OpenAI Api Key (See here for more details). In the following example we are getting the Api Key from an environment variable called OPENAI_API_KEY which we have created to keep it:

java
var openAI = SimpleOpenAI.builder()
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .build();

Optionally you could pass your OpenAI Organization Id in case you have multiple organizations and you want to identify usage by organization and/or you could pass your OpenAI Project Id in case you want to provides access to a single project. In the following example we are using environment variable for those Ids:

java
var openAI = SimpleOpenAI.builder()
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .organizationId(System.getenv("OPENAI_ORGANIZATION_ID"))
    .projectId(System.getenv("OPENAI_PROJECT_ID"))
    .build();

After you have created a SimpleOpenAI object, you are ready to call its services in order to communicate to OpenAI API.

Using HttpClient or OkHttp

Simple-OpenAI uses one of the following available http client components: Java's HttpClient (by default) or Square's OkHttp (adding a dependency).You can use the clientAdapter attribute to indicate which to use. In the following example we are providing a custom Java HttpClient:

…

Using Realtime Feature

If you want to use the Realtime feature, you need to set the realtimeConfig attribute. For this feature you will set another http client (similar to clientAdapter) for WebSocket communication: Java's HttpClient (by default) or Square's OkHttp

…

Audio Example

Example to call the Audio service to transform text to audio. We are requesting to receive the audio in binary format (InputStream):

…

Example to call the Audio service to transcribe an audio to text. We are requesting to receive the transcription in plain text format (see the name of the method):

java
var audioRequest = TranscriptionRequest.builder()
        .file(Paths.get("hello_audio.mp3"))
        .model("whisper-1")
        .responseFormat(AudioResponseFormat.VERBOSE_JSON)
        .temperature(0.2)
        .timestampGranularity(TimestampGranularity.WORD)
        .timestampGranularity(TimestampGranularity.SEGMENT)
        .build();
var futureAudio = openAI.audios().transcribe(audioRequest);
var audioResponse = futureAudio.join();
System.out.println(audioResponse);

Image Example

Example to call the Image service to generate two images in response to our prompt. We are requesting to receive the images' urls and we are printing out them in the console:

…

Chat Completion Example

Example to call the Chat Completion service to ask a question and wait for a full answer. We are printing out it in the console:

java
var chatRequest = ChatRequest.builder()
        .model("gpt-4o-mini")
        .message(SystemMessage.of("You are an expert in AI."))
        .message(UserMessage.of("Write a technical article about ChatGPT, no more than 100 words."))
        .temperature(0.0)
        .maxCompletionTokens(300)
        .build();
var futureChat = openAI.chatCompletions().create(chatRequest);
var chatResponse = futureChat.join();
System.out.println(chatResponse.firstContent());

Chat Completion with Streaming Example

Example to call the Chat Completion service to ask a question and wait for an answer in partial message deltas. We are printing out it in the console as soon as each delta is arriving:

…

Chat Completion with Functions Example

This functionality empowers the Chat Completion service to solve specific problems to our context. In this example we are setting three functions and we are entering a prompt that will require to call one of them (the function product). For setting functions we are using additional classes which implements the interface Functional. Those classes define a field by each function argument, annotating them to describe them and each class must override the execute method with the function's logic. Note that we are using the FunctionExecutor utility class to enroll the functions and to execute the function selected by the openai.chatCompletions() calling:

…

Chat Completion with Vision Example

Example to call the Chat Completion service to allow the model to take in external images and answer questions about them:

…

Example to call the Chat Completion service to allow the model to take in local images and answer questions about them (check the Base64Util's code in this repository):

…

Chat Completion with Audio Example

Example to call the Chat Completion service to generate a spoken audio response to a prompt, and to use audio inputs to prompt the model (check the Base64Util's code in this repository):

…

Chat Completion with Structured Outputs

Example to call the Chat Completion service to ensure the model will always generate responses that adhere to a Json Schema defined through Java classes:

…

Chat Completion Conversation Example

This example simulates a conversation chat by the command console and demonstrates the usage of ChatCompletion with streaming and call functions.

You can see the full demo code as well as the results from running the demo code:

ConversationDemo.java

Demo Results

…

Assistant v2 Conversation Example

This example simulates a conversation chat by the command console and demonstrates the usage of the latest Assistants API v2 features:

  • Vector Stores to upload files and incorporate it as new knowledge base.
  • Function Tools to use internal bussiness services to answer questions.
  • File Search Tools to use vectorized files to do semantic search.
  • Thread Run Streaming to answer with chunks of tokens in real time.

You can see the full demo code as well as the results from running the demo code:

ConversationV2Demo.java

Demo Results

…

Response Conversation Example

This example simulates a conversation chat by the command console and demonstrates the usage of the Response API features:

  • Text Generation
  • Streaming
  • Function Calling
  • Vision
  • FileSearch
  • WebSearch

You can see the full demo code as well as the results from running the demo code:

ConversationV3Demo.java

Demo Results

…

Realtime Conversation Example

In this example you can see the code to establish a speech-to-speech conversation between you and the model using your microphone and your speaker. Here you can see in action the following events:

  • ClientEvent.SessionUpdate
  • ClientEvent.InputAudioBufferAppend
  • ClientEvent.ResponseCreate
  • ServerEvent.ResponseAudioDelta
  • ServerEvent.ResponseAudioDone
  • ServerEvent.ResponseAudioTranscriptDone
  • ServerEvent.ConversationItemAudioTransCompleted

You can see the full code on:

[RealtimeDemo.java](src/demo/java

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javaaiapiawesomeazure-openai

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.