{"id":13643895,"url":"https://github.com/theokanning/openai-java","last_synced_at":"2026-01-14T02:24:26.655Z","repository":{"id":39694606,"uuid":"295598569","full_name":"TheoKanning/openai-java","owner":"TheoKanning","description":"OpenAI Api Client in Java","archived":true,"fork":false,"pushed_at":"2024-06-06T20:00:23.000Z","size":547,"stargazers_count":4779,"open_issues_count":130,"forks_count":1210,"subscribers_count":84,"default_branch":"main","last_synced_at":"2025-11-18T11:14:57.026Z","etag":null,"topics":["gpt3","java","openai"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TheoKanning.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","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":"2020-09-15T02:58:52.000Z","updated_at":"2025-11-11T09:38:56.000Z","dependencies_parsed_at":"2022-07-13T13:30:43.734Z","dependency_job_id":"26ada833-43c1-4203-8829-cc49614e7e88","html_url":"https://github.com/TheoKanning/openai-java","commit_stats":null,"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"purl":"pkg:github/TheoKanning/openai-java","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheoKanning%2Fopenai-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheoKanning%2Fopenai-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheoKanning%2Fopenai-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheoKanning%2Fopenai-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TheoKanning","download_url":"https://codeload.github.com/TheoKanning/openai-java/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheoKanning%2Fopenai-java/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28408711,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T01:52:23.358Z","status":"online","status_checked_at":"2026-01-14T02:00:06.678Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["gpt3","java","openai"],"created_at":"2024-08-02T01:01:54.402Z","updated_at":"2026-01-14T02:24:26.640Z","avatar_url":"https://github.com/TheoKanning.png","language":"Java","readme":"![Maven Central](https://img.shields.io/maven-central/v/com.theokanning.openai-gpt3-java/client?color=blue)\n\n\u003e ⚠️ Notice: This project is no longer maintained and has been archived as of June 6th, 2024.\nThank you to everyone who has contributed and supported this project. While the repository will remain available in its current state, no further updates or support will be provided. Please feel free to fork and modify the code as needed.\n\n\u003e ⚠️OpenAI has deprecated all Engine-based APIs. See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below for more info.\n\n# OpenAI-Java\nJava libraries for using OpenAI's GPT apis. Supports GPT-3, ChatGPT, and GPT-4.\n\nIncludes the following artifacts:\n- `api` : request/response POJOs for the GPT APIs.\n- `client` : a basic retrofit client for the GPT endpoints, includes the `api` module\n- `service` : A basic service class that creates and calls the client. This is the easiest way to get started.\n\nas well as an example project using the service.\n\n## Supported APIs\n- [Models](https://platform.openai.com/docs/api-reference/models)\n- [Completions](https://platform.openai.com/docs/api-reference/completions)\n- [Chat Completions](https://platform.openai.com/docs/api-reference/chat/create)\n- [Edits](https://platform.openai.com/docs/api-reference/edits)\n- [Embeddings](https://platform.openai.com/docs/api-reference/embeddings)\n- [Audio](https://platform.openai.com/docs/api-reference/audio)\n- [Files](https://platform.openai.com/docs/api-reference/files)\n- [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning)\n- [Images](https://platform.openai.com/docs/api-reference/images)\n- [Moderations](https://platform.openai.com/docs/api-reference/moderations)\n- [Assistants](https://platform.openai.com/docs/api-reference/assistants)\n\n#### Deprecated by OpenAI\n- [Engines](https://platform.openai.com/docs/api-reference/engines)\n- [Legacy Fine-Tunes](https://platform.openai.com/docs/guides/legacy-fine-tuning)\n\n## Importing\n\n### Gradle\n`implementation 'com.theokanning.openai-gpt3-java:\u003capi|client|service\u003e:\u003cversion\u003e'`\n\n### Maven\n```xml\n   \u003cdependency\u003e\n    \u003cgroupId\u003ecom.theokanning.openai-gpt3-java\u003c/groupId\u003e\n    \u003cartifactId\u003e{api|client|service}\u003c/artifactId\u003e\n    \u003cversion\u003eversion\u003c/version\u003e       \n   \u003c/dependency\u003e\n```\n\n## Usage\n### Data classes only\nIf you want to make your own client, just import the POJOs from the `api` module.\nYour client will need to use snake case to work with the OpenAI API.\n\n### Retrofit client\nIf you're using retrofit, you can import the `client` module and use the [OpenAiApi](client/src/main/java/com/theokanning/openai/OpenAiApi.java).  \nYou'll have to add your auth token as a header (see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java))\nand set your converter factory to use snake case and only include non-null fields.\n\n### OpenAiService\nIf you're looking for the fastest solution, import the `service` module and use [OpenAiService](service/src/main/java/com/theokanning/openai/service/OpenAiService.java).  \n\n\u003e ⚠️The OpenAiService in the client module is deprecated, please switch to the new version in the service module.\n```java\nOpenAiService service = new OpenAiService(\"your_token\");\nCompletionRequest completionRequest = CompletionRequest.builder()\n        .prompt(\"Somebody once told me the world is gonna roll me\")\n        .model(\"babbage-002\"\")\n        .echo(true)\n        .build();\nservice.createCompletion(completionRequest).getChoices().forEach(System.out::println);\n```\n\n### Customizing OpenAiService\nIf you need to customize OpenAiService, create your own Retrofit client and pass it in to the constructor.\nFor example, do the following to add request logging (after adding the logging gradle dependency):\n\n```java\nObjectMapper mapper = defaultObjectMapper();\nOkHttpClient client = defaultClient(token, timeout)\n        .newBuilder()\n        .interceptor(HttpLoggingInterceptor())\n        .build();\nRetrofit retrofit = defaultRetrofit(client, mapper);\n\nOpenAiApi api = retrofit.create(OpenAiApi.class);\nOpenAiService service = new OpenAiService(api);\n```\n\n### Adding a Proxy\nTo use a proxy, modify the OkHttp client as shown below:\n```java\nObjectMapper mapper = defaultObjectMapper();\nProxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));\nOkHttpClient client = defaultClient(token, timeout)\n        .newBuilder()\n        .proxy(proxy)\n        .build();\nRetrofit retrofit = defaultRetrofit(client, mapper);\nOpenAiApi api = retrofit.create(OpenAiApi.class);\nOpenAiService service = new OpenAiService(api);\n```\n\n### Functions\nYou can create your functions and define their executors easily using the ChatFunction class, along with any of your custom classes that will serve to define their available parameters. You can also process the functions with ease, with the help of an executor called FunctionExecutor.\n\nFirst we declare our function parameters:\n```java\npublic class Weather {\n    @JsonPropertyDescription(\"City and state, for example: León, Guanajuato\")\n    public String location;\n    @JsonPropertyDescription(\"The temperature unit, can be 'celsius' or 'fahrenheit'\")\n    @JsonProperty(required = true)\n    public WeatherUnit unit;\n}\npublic enum WeatherUnit {\n    CELSIUS, FAHRENHEIT;\n}\npublic static class WeatherResponse {\n    public String location;\n    public WeatherUnit unit;\n    public int temperature;\n    public String description;\n    \n    // constructor\n}\n```\n\nNext, we declare the function itself and associate it with an executor, in this example we will fake a response from some API:\n```java\nChatFunction.builder()\n        .name(\"get_weather\")\n        .description(\"Get the current weather of a location\")\n        .executor(Weather.class, w -\u003e new WeatherResponse(w.location, w.unit, new Random().nextInt(50), \"sunny\"))\n        .build()\n```\n\nThen, we employ the FunctionExecutor object from the 'service' module to assist with execution and transformation into an object that is ready for the conversation:\n```java\nList\u003cChatFunction\u003e functionList = // list with functions\nFunctionExecutor functionExecutor = new FunctionExecutor(functionList);\n\nList\u003cChatMessage\u003e messages = new ArrayList\u003c\u003e();\nChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), \"Tell me the weather in Barcelona.\");\nmessages.add(userMessage);\nChatCompletionRequest chatCompletionRequest = ChatCompletionRequest\n        .builder()\n        .model(\"gpt-3.5-turbo-0613\")\n        .messages(messages)\n        .functions(functionExecutor.getFunctions())\n        .functionCall(new ChatCompletionRequestFunctionCall(\"auto\"))\n        .maxTokens(256)\n        .build();\n\nChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();\nChatFunctionCall functionCall = responseMessage.getFunctionCall(); // might be null, but in this case it is certainly a call to our 'get_weather' function.\n\nChatMessage functionResponseMessage = functionExecutor.executeAndConvertToMessageHandlingExceptions(functionCall);\nmessages.add(response);\n```\n\u003e **Note:** The `FunctionExecutor` class is part of the 'service' module.\n\nYou can also create your own function executor. The return object of `ChatFunctionCall.getArguments()` is a JsonNode for simplicity and should be able to help you with that.\n\nFor a more in-depth look, refer to a conversational example that employs functions in: [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java).\nOr for an example using functions and stream: [OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java)\n\n### Streaming thread shutdown\nIf you want to shut down your process immediately after streaming responses, call `OpenAiService.shutdownExecutor()`.  \nThis is not necessary for non-streaming calls.\n\n## Running the example project\nAll the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your OpenAI api token\n```bash\nexport OPENAI_TOKEN=\"sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n```\nYou can try all the capabilities of this project using:\n```bash\n./gradlew runExampleOne\n```\nAnd you can also try the new capability of using functions:\n```bash\n./gradlew runExampleTwo\n```\nOr functions with 'stream' mode enabled:\n```bash\n./gradlew runExampleThree\n```\n\n## FAQ\n### Does this support GPT-4?\nYes! GPT-4 uses the ChatCompletion Api, and you can see the latest model options [here](https://platform.openai.com/docs/models/gpt-4).  \nGPT-4 is currently in a limited beta (as of 4/1/23), so make sure you have access before trying to use it.\n\n### Does this support functions?\nAbsolutely! It is very easy to use your own functions without worrying about doing the dirty work.\nAs mentioned above, you can refer to [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java) or \n[OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java) projects for an example. \n\n### Why am I getting connection timeouts?\nMake sure that OpenAI is available in your country.\n\n### Why doesn't OpenAiService support x configuration option?\nMany projects use OpenAiService, and in order to support them best I've kept it extremely simple.  \nYou can create your own OpenAiApi instance to customize headers, timeouts, base urls etc.  \nIf you want features like retry logic and async calls, you'll have to make an `OpenAiApi` instance and call it directly instead of using `OpenAiService`\n\n## Deprecated Endpoints\nOpenAI has deprecated engine-based endpoints in favor of model-based endpoints. \nFor example, instead of using `v1/engines/{engine_id}/completions`, switch to `v1/completions` and specify the model in the `CompletionRequest`.\nThe code includes upgrade instructions for all deprecated endpoints.\n\nI won't remove the old endpoints from this library until OpenAI shuts them down.\n\n## License\nPublished under the MIT License\n","funding_links":[],"categories":["CLIs"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheokanning%2Fopenai-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftheokanning%2Fopenai-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheokanning%2Fopenai-java/lists"}