{"id":15069082,"url":"https://github.com/jetkai/openai-for-java","last_synced_at":"2025-04-10T16:51:51.448Z","repository":{"id":97863278,"uuid":"608602162","full_name":"jetkai/openai-for-java","owner":"jetkai","description":"OpenAI/ChatGPT library for Java - Requires JDK 11 at minimum.","archived":false,"fork":false,"pushed_at":"2023-03-13T18:52:36.000Z","size":3990,"stargazers_count":48,"open_issues_count":1,"forks_count":5,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-03-24T14:44:29.003Z","etag":null,"topics":["ai-image","ai-image-generation","ai-transcription","ai-translator","chatgpt","chatgpt-api","gpt-3","gpt-3-text-generation","gpt-35-turbo","gpt3","gpt4","gptchat","gradle","java","java-11","java-library","jdk11","open-ai-api","openai","openai-api"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jetkai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-02T11:06:42.000Z","updated_at":"2025-03-01T15:08:26.000Z","dependencies_parsed_at":"2024-02-06T05:16:05.477Z","dependency_job_id":null,"html_url":"https://github.com/jetkai/openai-for-java","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetkai%2Fopenai-for-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetkai%2Fopenai-for-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetkai%2Fopenai-for-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetkai%2Fopenai-for-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jetkai","download_url":"https://codeload.github.com/jetkai/openai-for-java/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248256088,"owners_count":21073460,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-image","ai-image-generation","ai-transcription","ai-translator","chatgpt","chatgpt-api","gpt-3","gpt-3-text-generation","gpt-35-turbo","gpt3","gpt4","gptchat","gradle","java","java-11","java-library","jdk11","open-ai-api","openai","openai-api"],"created_at":"2024-09-25T01:40:23.665Z","updated_at":"2025-04-10T16:51:51.438Z","avatar_url":"https://github.com/jetkai.png","language":"Java","funding_links":[],"categories":["人工智能"],"sub_categories":["LLM客户端"],"readme":"# OpenAI For Java\n\n![GitHub last commit](https://img.shields.io/github/last-commit/jetkai/openai-for-java)\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/jetkai/openai-for-java/main.yml)\n![GitHub deployments](https://img.shields.io/github/deployments/jetkai/openai-for-java/openai-for-java?label=deployment)\n[![codecov](https://codecov.io/gh/jetkai/openai-for-java/branch/main/graph/badge.svg?token=2E96DBLLN0)](https://codecov.io/gh/jetkai/openai-for-java)\n![GitHub issues](https://img.shields.io/github/issues/jetkai/openai-for-java)\n![GitHub all releases](https://img.shields.io/github/downloads/jetkai/openai-for-java/total)\n\n\u003e Note, this project is under active development. If there are any suggestions you may have, feel free to let me know. 😊\n\u003e\n\u003e You can use this library as part of your project \u0026 integrate it into your app.\n\u003e\n\u003e OpenAI is **free-to-use**, but you will require an API key. You can get this for free by clicking [**here**](https://platform.openai.com/account/api-keys).\n\n```java\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(\"YOUR_API_KEY_HERE\") //Required\n                .setOrganization(\"YOUR_ORGANIZATION_HERE\") //Optional\n                .createChatCompletion(chatMessageHistoryHere) //Optional (ChatGPT)\n                .setTimeout(Duration.ofSeconds(10)) //Optional\n                .setProxy(proxy) //Optional\n                .build() //Creates our OpenAI class from our OpenAI.Builder\n                .sendRequest(); //Optional - Sends request to OpenAI\n```\n\n---\n\n## Minimum Requirements\n\n- Java 11 [JDK](https://developers.redhat.com/content-gateway/file/openjdk/11.0.18/java-11-openjdk-11.0.18.10-1.windows.redhat.x86_64.msi)\n- An OpenAI [API Key](https://platform.openai.com/account/api-keys)\n\n## Release `1.1.2`\n\n\u003e The dependencies I am using for this project are [`jackson-databind`](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind) for JSON parsing, [`junit-jupiter`](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api) for testing and [`jacoco`](https://mvnrepository.com/artifact/org.jacoco/jacoco-maven-plugin) for reporting.\n\n### Maven\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003eio.github.jetkai\u003c/groupId\u003e\n  \u003cartifactId\u003eopenai\u003c/artifactId\u003e\n  \u003cversion\u003e1.1.2\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### Gradle\n```kotlin\n//Groovy (build.gradle)\nimplementation group: 'io.github.jetkai', name: 'openai', version: '1.1.2'\n\n//Kotlin (build.gradle.kts)\nimplementation(\"io.github.jetkai:openai:1.1.2\")\n```\n\n### Download\n\n| Binary `(Recommended)`                                                                       \t| Binary `(Excluding Dependencies)`                                                                     \t| JavaDoc                                                                                              \t| Sources                                                                                              \t|\n|----------------------------------------------------------------------------------------------\t|-------------------------------------------------------------------------------------------------------\t|------------------------------------------------------------------------------------------------------\t|------------------------------------------------------------------------------------------------------\t|\n| \u003e [Download](https://github.com/jetkai/openai-for-java/releases/download/1.1.2/openai.jar) \u003c \t| \u003e [Download](https://github.com/jetkai/openai-for-java/releases/download/1.1.2/openai-excldeps.jar) \u003c \t| \u003e [Download](https://github.com/jetkai/openai-for-java/releases/download/1.1.2/openai-javadoc.jar) \u003c \t| \u003e [Download](https://github.com/jetkai/openai-for-java/releases/download/1.1.2/openai-sources.jar) \u003c \t|\n\n## Available API(s) `March 2023`\n\n✅ ChatGPT 3.5 (Latest) - `using CreateChatCompletion`\n\n✅ Spell Checking - `using CreateCompletion`\n\n✅ Transcriptions (From Audio File) - `using CreateTranscription`\n\n✅ Translations (From Text or Audio File) - `using CreateTranslation` / `CreateTranscriptionTranslation`\n\n✅ AI Image Creation / Editing - `using CreateImage` / `CreateImageEdit` / `CreateImageVariation`\n\n---\n\n###### [OpenAI API Reference](https://platform.openai.com/docs/api-reference/)\n\n- [ListModel](https://platform.openai.com/docs/api-reference/models/retrieve) -\u003e `https://api.openai.com/v1/models`\n- [ListModels](https://platform.openai.com/docs/api-reference/models/list) -\u003e `https://api.openai.com/v1/models/{model}`\n- [CreateCompletion](https://platform.openai.com/docs/api-reference/completions/create) -\u003e `https://api.openai.com/v1/completions`\n- [CreateChatCompletion](https://platform.openai.com/docs/api-reference/chat/create) -\u003e `https://api.openai.com/v1/chat/completions`\n- [CreateEdit](https://platform.openai.com/docs/api-reference/edits/create) -\u003e `https://api.openai.com/v1/edits`\n- [CreateImage](https://platform.openai.com/docs/api-reference/images/create) -\u003e `https://api.openai.com/v1/images/generations`\n- [CreateImageEdit](https://platform.openai.com/docs/api-reference/images/create-edit) -\u003e `https://api.openai.com/v1/images/edits`\n- [CreateImageVariation](https://platform.openai.com/docs/api-reference/images/create-variation) -\u003e `https://api.openai.com/v1/images/variations`\n- [CreateEmbeddings](https://platform.openai.com/docs/api-reference/embeddings/create) -\u003e `https://api.openai.com/v1/embeddings`\n- [CreateTranscription](https://platform.openai.com/docs/api-reference/audio/create) -\u003e `https://api.openai.com/v1/audio/transcriptions`\n- [CreateTranscriptionAndTranslation](https://platform.openai.com/docs/api-reference/audio/create) -\u003e `https://api.openai.com/v1/audio/translations`\n- [CreateTranslation](https://platform.openai.com/docs/api-reference/audio/create) -\u003e `https://api.openai.com/v1/completions`\n\n---\n\n# Source Code (Examples)\n\n## [ChatGPT-3.5 Turbo](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleChatGPT.java)\n\n    Scenario: Say \"Hello\" to the AI and ask the AI to respond back with the last thing I said.\n\n```java\n public static void main(String[] args) {\n        ExampleChatGPT gpt = new ExampleChatGPT();\n\n        //The first message that we want to send\n        String message1 = \"Hello ChatGPT!\";\n        //The second message that we want to send\n        String message2 = \"What was the first thing I said?\";\n\n        //Response 1 from ChatGPT\n        String response1 = gpt.exampleBuilders(message1);\n        System.out.println(\"Sent: \" + message1);\n        System.out.println(\"Response: \" + response1);\n\n        //Response 2 from ChatGPT\n        String response2 = gpt.exampleBuilders(message2);\n        System.out.println(\"Sent: \" + message2);\n        System.out.println(\"Response: \" + response2);\n    }\n\n    private String exampleBuilders(String message) {\n        //Create the Message Data object with the message we wish to send\n        ChatCompletionMessageData messageData = ChatCompletionMessageData.builder()\n                .setRole(\"user\")\n                .setContent(message)\n                .build();\n\n        //Store the message that we want to send, to the MessageHistory List\n        messageHistory.add(messageData);\n\n        //Build the data structure which contains the message history and model information\n        ChatCompletionData completionData = ChatCompletionData.builder()\n                .setModel(\"gpt-3.5-turbo\")\n                .setMessages(messageHistory)\n                .build();\n\n        //Sends the request to OpenAI's endpoint \u0026 parses the response data\n        //Instead of openAI.sendRequest(); you can initialize the request\n        //for the class manually - openAI.createChatCompletion().initialize();\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .createChatCompletion(completionData)\n                .build()\n                .sendRequest();\n\n        //Check to see if there is a valid response from OpenAI\n        //You can also call Optional\u003cCreateChatCompletion\u003e createChatCompletion = openAI.chatCompletion();\n        CreateChatCompletion createChatCompletion = openAI.getChatCompletion();\n\n        //Store chat response from AI, this allows the AI to see the full history of our chat\n        //Including both our messages and the AI's messages\n        messageHistory.addAll(createChatCompletion.asChatResponseDataList());\n\n        //Parse the response back as plain-text \u0026 replace \\n \u0026 ascii characters (Šťŕĭńġ -\u003e String)\n        return createChatCompletion.asNormalizedText();\n    }\n```\n\n## [AI Image Creation](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleImageCreation.java)\n\n    Scenario: Have an AI create a red panda with glasses, and have this drawn as a cartoon.\n\n```java\n    public static void main(String[] args) throws IOException {\n        //Initialize ExampleImageCreation class\n        ExampleImageCreation imageCreation = new ExampleImageCreation();\n\n        //A text description of the desired image(s). The maximum length is 1000 characters\n        String description = \"A picture of a red panda with glasses, drawn as a cartoon.\";\n\n        //The number of images to generate. Must be between 1 and 10.\n        int amount = 1;\n\n        //The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024\n        String size = \"1024x1024\";\n\n        URI[] imageLinks = imageCreation.communicate(description, amount, size);\n\n        for(URI imageLink : imageLinks) {\n            System.out.println(\"Opening URI [\"+imageLink+\"] in the web browser.\");\n            Desktop.getDesktop().browse(imageLink);\n        }\n    }\n\n    private URI[] communicate(String imageDescription, int numberOfImages, String size) {\n        //Alternatively can use ImageData.create(imageDescription, numberOfImages, size);\n        ImageData imageData = ImageData.builder()\n                //A text description of the desired image(s). The maximum length is 1000 characters\n                .setPrompt(imageDescription)\n                //The number of images to generate. Must be between 1 and 10.\n                .setN(numberOfImages)\n                //The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024\n                .setSize(size)\n                .build();\n\n        OpenAI openAI = OpenAI.builder()\n                //Set our OpenAI API key\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                //Specify the createImage API endpoint\n                .createImage(imageData)\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the CreateImage API from OpenAI \u0026 create instance\n        Optional\u003cCreateImage\u003e createImage = openAI.image();\n\n        //Gather the URI(s) from the API response\n        return createImage.map(CreateImage::asUriArray).orElse(null);\n    }\n```\n\n## [Spelling Correction](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleSpellingCorrection.java)\n\n    Scenario: Correct the spelling within the sentence \"Wha dai of the wek is it?\".\n\n```java\n    public static void main(String[] args) {\n        //Initialize ExampleSpellingCorrection class\n        ExampleSpellingCorrection spelling = new ExampleSpellingCorrection();\n\n        String spellingMistake = \"Wha dai of the wek is it?\";\n        String instruction = \"Fix the spelling mistakes\";\n\n        //Send request to API - response as string\n        String spellingCorrection = spelling.communicate(spellingMistake, instruction);\n\n        //Print out the mistake \u0026 correction\n        System.out.println(\"Mistake: \" + spellingMistake);\n        System.out.println(\"Correction: \" + spellingCorrection);\n    }\n\n    private String communicate(String spellingMistake, String instruction) {\n        //Call the ListModels API from OpenAI \u0026 create instance\n        //You can also specify the model and use the following:\n        //EditData.create(model, spellingMistake, instruction);\n        EditData editData = EditData.create(spellingMistake, instruction);\n\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .createEdit(editData)\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the CreateEdit API from OpenAI \u0026 create instance\n        Optional\u003cCreateEdit\u003e createEdit = openAI.edit();\n\n        //Return model as a JSON string\n        return createEdit.map(CreateEdit::asText).orElse(null);\n    }\n```\n\n## [Translate Language](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleTranslation.java)\n\n    Scenario: Translate \"Hello, how are you today?\" from English to French.\n\n```java\n    public static void main(String[] args) {\n        //Initialize ExampleTranslation class\n        ExampleTranslation translation = new ExampleTranslation();\n\n        //This is the language we want to translate our audio file to\n        String toLanguage = \"French\";\n\n        //Example audio file that we are going to upload to OpenAI to be translated\n        String message = \"Hello, how are you today?\";\n\n        //Response from OpenAI with the translated string\n        String response = translation.communicate(message, toLanguage);\n\n        //Print the translation to the console\n        System.out.println(response);\n    }\n\n    private String communicate(String message, String toLanguage) {\n        //TranslationData, ready to send to the OpenAI API\n        CompletionData translationData = CompletionData.translation(message, toLanguage);\n\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .createTranslation(translationData)\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the CreateTranslation API from OpenAI \u0026 create instance\n        Optional\u003cCreateTranslation\u003e createTranslation = openAI.translation();\n\n        //Return as text, do not replace \\n or ascii characters\n        return createTranslation.map(CreateCompletion::asText).orElse(null);\n    }\n```\n\n## [Audio Transcript](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleTranscriptionFromAudioFile.java)\n\n    Scenario: Create a transcript from an audio file.\n\n```java\n    public static void main(String[] args) throws URISyntaxException {\n        //Initialize ExampleTranslationFromAudioFile class\n        ExampleTranscriptionFromAudioFile transcriptAudioFile = new ExampleTranscriptionFromAudioFile();\n\n        //Example audio file that we are going to upload to OpenAI to be translated\n        URL audioUrl = ExampleTranscriptionFromAudioFile.class.getResource(\"what-can-i-do.mp3\");\n        Path filePath = null;\n        if (audioUrl != null) {\n            filePath = Path.of(audioUrl.toURI());\n        }\n\n        //Response from OpenAI with the translated string\n        String response = transcriptAudioFile.communicate(filePath);\n\n        //Print the translation to the console\n        System.out.println(response);\n    }\n\n    private String communicate(Path filePath) {\n        //AudioData, ready to send to the OpenAI API\n        AudioData transcriptionData = AudioData.create(filePath);\n\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .createTranscription(transcriptionData)\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the CreateTranscription API from OpenAI \u0026 create instance\n        Optional\u003cCreateTranscription\u003e createTranscription = openAI.transcription();\n\n        //Return as text, do not replace \\n or ascii characters\n        return createTranscription.map(CreateTranscription::asText).orElse(null);\n    }\n```\n\n## [Audio Transcript \u0026 Translate](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleTranslationFromAudioFile.java)\n\n    Scenario: Create a transcript from an audio file, then translate the transcript from English to French.\n\n```java\n    public static void main(String[] args) throws URISyntaxException {\n        //Initialize ExampleTranslationFromAudioFile class\n        ExampleTranslationFromAudioFile translateFromAudioFile = new ExampleTranslationFromAudioFile();\n\n        //This is the language we want to translate our audio file to\n        //Language parameter must be specified in ISO-639-1 format or Locale\n        //Example -\u003e \"French\" = \"fr\" | \"English UK\" = \"en_GB\"\n        //String language = \"fr\";\n        Locale language = Locale.FRENCH;\n\n        //Example audio file that we are going to upload to OpenAI to be translated\n        URL audioUrl = ExampleTranslationFromAudioFile.class.getResource(\"what-can-i-do.mp3\");\n        Path filePath = null;\n        if (audioUrl != null) {\n            filePath = Path.of(audioUrl.toURI());\n        }\n        if(filePath == null) {\n            System.err.println(\"File could not be found.\");\n            return;\n        }\n\n        //Response from OpenAI with the translated string\n        String response = translateFromAudioFile.communicate(filePath, language);\n\n        //Print the translation to the console\n        System.out.println(response);\n    }\n\n    private String communicate(Path filePath, Locale language) {\n        //Alternatively can use AudioData.create(audioPath, \"fr\");\n        AudioData audioTranslationData = AudioData.create(filePath, language);\n\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .createTranscriptionTranslation(audioTranslationData)\n                .build();\n\n        //Sends the request to OpenAI's endpoint \u0026 parses the response data\n        openAI.sendRequest();\n\n        //Call the CreateTranslation API from OpenAI \u0026 create instance\n        Optional\u003cCreateTranscriptionTranslation\u003e createTranslation = openAI.transcriptionTranslation();\n\n        //Return as text, do not replace \\n or ascii characters\n        return createTranslation.map(CreateTranscription::asText).orElse(null);\n    }\n```\n\n## [List Model Information](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleListModel.java)\n\n    Scenario: Get information about a specific model.\n\n```java\n   public static void main(String[] args) {\n        //Initialize ExampleListModel class\n        ExampleListModel getModel = new ExampleListModel();\n\n        //Send request to API - response as JSON string\n        String modelJson = getModel.communicate();\n\n        //Print out the model information in JSON\n        System.out.println(modelJson);\n    }\n\n    private String communicate() {\n\n        String modelName = \"davinci\";\n\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .listModel(modelName)\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the ListModels API from OpenAI \u0026 create instance\n        Optional\u003cListModel\u003e getModels = openAI.model();\n\n        //Return model as a JSON string\n        return getModels.map(ListModel::asJson).orElse(null);\n    }\n```\n\n## [List All Models](https://github.com/jetkai/openai-for-java/blob/main/src/main/java/examples/ExampleListModels.java)\n\n    Scenario: List all the models available from OpenAI.\n\n```java\n    public static void main(String[] args) {\n        //Initialize ExampleListModels class\n        ExampleListModels getModels = new ExampleListModels();\n\n        //Send request to API and deserialize response as List\u003cModalData\u003e\n        List\u003cModelData\u003e models = getModels.communicate();\n        for(ModelData model : models) {\n            Optional\u003cString\u003e id = model.id();\n            if(id.isEmpty()) {\n                continue;\n            }\n            //Print out the names of all the available models, to the console\n            System.out.println(id.get());\n        }\n        //models.stream().map(ModelData::id).forEach(System.out::println);\n    }\n\n    private List\u003cModelData\u003e communicate() {\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(System.getenv(\"OPEN_AI_API_KEY\"))\n                .listModels()\n                .build()\n                //Sends the request to OpenAI's endpoint \u0026 parses the response data\n                .sendRequest();\n\n        //Call the ListModels API from OpenAI \u0026 create instance\n        Optional\u003cListModels\u003e getModels = openAI.models();\n\n        //Return models as a data structure list, so that we can get the name from each model\n        return getModels.map(ListModels::asDataList).orElse(null);\n    }\n```\n\n## CreateCompletion\n\n```java\n    @Test\n    void createCompletionTest() {\n        //Grab OpenAI API key from system environment variables (gradle.properties)\n        String apiKey = System.getenv(\"OPEN_AI_API_KEY\");\n        String organization = System.getenv(\"OPEN_AI_ORGANIZATION\");\n        assertNotNull(apiKey);\n        assertNotNull(organization);\n\n        //CompletionData, ready to send to the OpenAI API\n        CompletionData completion = CompletionData.builder()\n                //ID of the model to use. You can use the List models API to see all of your available models,\n                //or see our Model overview for descriptions of them.\n                .setModel(\"text-davinci-003\")\n\n                //The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens,\n                //or array of token arrays.\n                //Note that \u003c|endoftext|\u003e is the document separator that the model sees during training, so if a prompt\n                //is not specified the model will generate as if from the beginning of a new document.\n                .setPrompt(\"Say this is a test\")\n\n                //The maximum number of tokens to generate in the completion.\n                //The token count of your prompt plus max_tokens cannot exceed the model's context length.\n                //Most models have a context length of 2048 tokens (except for the newest models, which support 4096).\n                .setMaxTokens(7)\n\n                //What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the\n                //output more random, while lower values like 0.2 will make it more focused and deterministic.\n                //We generally recommend altering this or top_p but not both.\n                .setTemperature(0)\n\n                //An alternative to sampling with temperature, called nucleus sampling, where the model considers\n                //the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the\n                //top 10% probability mass are considered.\n                //We generally recommend altering this or temperature but not both.\n                .setTopP(1)\n\n                //How many completions to generate for each prompt.\n                //Note: Because this parameter generates many completions, it can quickly consume your token quota.\n                //Use carefully and ensure that you have reasonable settings for max_tokens and stop.\n                .setN(1)\n\n                //Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent\n                //events as they become available, with the stream terminated by a data: [DONE] message.\n                .setStream(false)\n\n                //Include the log probabilities on the logprobs most likely tokens, as well the chosen tokens.\n                //For example, if logprobs is 5, the API will return a list of the 5 most likely tokens.\n                //The API will always return the logprob of the sampled token, so there may be up to logprobs+1\n                //elements in the response.\n                //The maximum value for logprobs is 5. If you need more than this, please contact us through our\n                //Help center and describe your use case.\n                //.setLogprobs()\n\n                //Up to 4 sequences where the API will stop generating further tokens.\n                //The returned text will not contain the stop sequence.\n                .setStop(\"\\n\")\n                .build();\n\n        //Create OpenAI instance using API key \u0026 organization\n        //Organization is optional\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(apiKey)\n                .setOrganization(organization)\n                .createCompletion(completion)\n                .build()\n                .sendRequest();\n\n        assertNotNull(openAI);\n\n        //Call the CreateCompletion API from OpenAI \u0026 create instance\n        Optional\u003cCreateCompletion\u003e optionalCreateCompletion = openAI.completion();\n        assertFalse(optionalCreateCompletion.isEmpty());\n\n        CreateCompletion createCompletion = optionalCreateCompletion.get();\n\n        //Data structure example\n        CompletionResponseData responseData = createCompletion.asData();\n        assertNotNull(responseData);\n\n        //Json example\n        String json = createCompletion.asJson();\n        assertNotNull(json);\n        assertFalse(json.isEmpty());\n    }\n```\n\n### CreateEdit\n\n```java\n@Test\n    void createEditTest() {\n        //Grab OpenAI API key from system environment variables (gradle.properties)\n        String apiKey = System.getenv(\"OPEN_AI_API_KEY\");\n        String organization = System.getenv(\"OPEN_AI_ORGANIZATION\");\n        assertNotNull(apiKey);\n        assertNotNull(organization);\n\n        //EditData, ready to send to the OpenAI Api\n        EditData edit = EditData.builder()\n                //ID of the model to use. You can use the text-davinci-edit-001 or\n                //code-davinci-edit-001 model with this endpoint.\n                .setModel(\"text-davinci-edit-001\")\n\n                //The input text to use as a starting point for the edit.\n                .setInput(\"What day of the wek is it?\")\n\n                //The instruction that tells the model how to edit the prompt.\n                .setInstruction(\"Fix the spelling mistakes\")\n                .build();\n\n        //Create OpenAI instance using API key \u0026 organization\n        //Organization is optional\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(apiKey)\n                .setOrganization(organization)\n                .createEdit(edit)\n                .build()\n                .sendRequest();\n\n        assertNotNull(openAI);\n\n        //Call the CreateEdit API from OpenAI \u0026 create instance\n        Optional\u003cCreateEdit\u003e optionalCreateEdit = openAI.edit(); //You can call \"data\" to see the response\n        assertFalse(optionalCreateEdit.isEmpty());\n\n        CreateEdit createEdit = optionalCreateEdit.get();\n\n        //Data structure example\n        CompletionResponseData responseData = createEdit.asData();\n        assertNotNull(responseData);\n\n        //StringArray example\n        String[] stringArray = createEdit.asStringArray();\n        assertNotNull(stringArray);\n\n        //Json example\n        String json = createEdit.asJson();\n        assertNotNull(json);\n        assertFalse(json.isEmpty());\n    }\n```\n\n### CreateImageVariation\n\n```java\n    @Test\n    void createImageVariationTest() {\n        //Grab OpenAI API key from system environment variables (gradle.properties)\n        String apiKey = System.getenv(\"OPEN_AI_API_KEY\");\n        String organization = System.getenv(\"OPEN_AI_ORGANIZATION\");\n        assertNotNull(apiKey);\n        assertNotNull(organization);\n\n        //Example image file that we are going to upload to OpenAI\n        URL imageUrl = CreateImageVariationTest.class.getResource(\"otter.png\");\n        Path imagePath = null;\n        try {\n            if (imageUrl != null) {\n                imagePath = Path.of(imageUrl.toURI());\n            }\n        } catch (URISyntaxException e) {\n            throw new RuntimeException(e);\n        }\n\n        assertNotNull(imagePath);\n\n        //ImageVariationData, ready to send to the OpenAI API\n        ImageVariationData imageVariationData = ImageVariationData.builder()\n                //Set the path for the image file\n                .setImage(imagePath)\n                //Set the number of images to generate. Must be between 1 and 10.\n                .setN(2)\n                //Set the size of the generated images. Must be one of 256x256, 512x512, or 1024x1024.\n                .setSize(\"256x256\")\n                .build();\n\n        //Create OpenAI instance using API key \u0026 organization\n        //Organization is optional\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(apiKey)\n                .setOrganization(organization)\n                .createImageVariation(imageVariationData)\n                .build()\n                //Finally, send our request to the API, this initiates the request (after .build())\n                .sendRequest();\n\n\n        //Call the CreateTranscription API from OpenAI \u0026 create instance\n        Optional\u003cCreateImageVariation\u003e optionalCreateImageVariation = openAI.imageVariation();\n        assertFalse(optionalCreateImageVariation.isEmpty());\n\n        CreateImageVariation createImageVariation = optionalCreateImageVariation.get();\n\n        //String List example (contains all the image urls)\n        List\u003cString\u003e stringList = createImageVariation.asStringList();\n        assertNotNull(stringList);\n        assertFalse(stringList.isEmpty());\n\n        //URI array example (contains all the image urls)\n        URI[] uriArray = createImageVariation.asUriArray();\n        assertNotNull(uriArray);\n        assertNotEquals(0, uriArray.length);\n\n        //Data structure example\n        ImageResponseData responseData = createImageVariation.asData();\n        assertNotNull(responseData);\n\n        //Json example\n        String json = createImageVariation.asJson();\n        assertNotNull(json);\n        assertFalse(json.isEmpty());\n    }\n```\n\n### CreateEmbedding\n\n```java\n    @Test\n    void createEmbeddingTest() {\n        //Grab OpenAI API key from system environment variables (gradle.properties)\n        String apiKey = System.getenv(\"OPEN_AI_API_KEY\");\n        String organization = System.getenv(\"OPEN_AI_ORGANIZATION\");\n        assertNotNull(apiKey);\n        assertNotNull(organization);\n\n        //EmbeddingData, ready to send to the OpenAI API\n        EmbeddingData embed = EmbeddingData.builder()\n                //ID of the model to use. You can use the List models API to see all of your available models,\n                //or see our Model overview for descriptions of them.\n                .setModel(\"text-embedding-ada-002\")\n                //Input text to get embeddings for, encoded as a string or array of tokens.\n                //To get embeddings for multiple inputs in a single request, pass an array of strings or array of token arrays.\n                //Each input must not exceed 8192 tokens in length.\n                .setInput(\"The food was delicious and the waiter...\")\n                .build();\n\n        //Call the CreateEmbedding API from OpenAI \u0026 create instance\n        OpenAI openAI = OpenAI.builder()\n                .setApiKey(apiKey)\n                .setOrganization(organization)\n                .createEmbedding(embed)\n                .build()\n                .sendRequest();\n\n        Optional\u003cCreateEmbedding\u003e optionalEmbedding = openAI.embedding();\n        assertFalse(optionalEmbedding.isEmpty());\n\n        CreateEmbedding createEmbedding = optionalEmbedding.get();\n\n        //Data structure example\n        EmbeddingResponseData embeddingBlock = createEmbedding.asData();\n        assertNotNull(embeddingBlock);\n\n        //Float List example\n        List\u003cFloat\u003e floatList = createEmbedding.asFloatList();\n        assertNotNull(floatList);\n        assertFalse(floatList.isEmpty());\n\n        //Json example\n        String json = createEmbedding.asJson();\n        assertNotNull(json);\n        assertFalse(json.isEmpty());\n    }\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetkai%2Fopenai-for-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjetkai%2Fopenai-for-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetkai%2Fopenai-for-java/lists"}