一个 Java 库,可用最简单的方式使用 OpenAI Api。
A Java library to use the OpenAI Api in the simplest possible way.
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.
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:
You can install Simple-OpenAI by adding the following dependencies to your Maven project:
io.github.sashirestela
simple-openai
[simple-openai_latest_version]
com.squareup.okhttp3
okhttp
[okhttp_latest_version]
Or alternatively using Gradle:
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.
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:
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:
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.
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:
…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
…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):
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);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:
…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:
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());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:
…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:
…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):
…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):
…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:
…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:
Demo Results
…This example simulates a conversation chat by the command console and demonstrates the usage of the latest Assistants API v2 features:
You can see the full demo code as well as the results from running the demo code:
Demo Results
…This example simulates a conversation chat by the command console and demonstrates the usage of the Response API features:
You can see the full demo code as well as the results from running the demo code:
Demo Results
…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:
You can see the full code on:
[RealtimeDemo.java](src/demo/java
暂无开放 Issues,或尚未同步最近议题。