{"id":19436066,"url":"https://github.com/ralscha/openai4j","last_synced_at":"2025-10-18T01:17:37.787Z","repository":{"id":206521667,"uuid":"716111581","full_name":"ralscha/openai4j","owner":"ralscha","description":"Unofficial, community-maintained Java implementation of the OpenAI API","archived":false,"fork":false,"pushed_at":"2024-04-07T05:59:29.000Z","size":403,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-04-07T06:24:22.320Z","etag":null,"topics":["java","openai","openai-api"],"latest_commit_sha":null,"homepage":"https://github.com/ralscha/openai4j","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/ralscha.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}},"created_at":"2023-11-08T13:19:37.000Z","updated_at":"2024-04-07T06:24:41.291Z","dependencies_parsed_at":"2024-04-07T06:24:27.468Z","dependency_job_id":"ebe7f1a1-932c-4f4d-a9bb-60793f31dd91","html_url":"https://github.com/ralscha/openai4j","commit_stats":null,"previous_names":["ralscha/openai4j"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fopenai4j","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fopenai4j/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fopenai4j/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fopenai4j/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ralscha","download_url":"https://codeload.github.com/ralscha/openai4j/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240619430,"owners_count":19830204,"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":["java","openai","openai-api"],"created_at":"2024-11-10T15:09:23.668Z","updated_at":"2025-10-18T01:17:32.750Z","avatar_url":"https://github.com/ralscha.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# OpenAI now provides an official Java SDK: https://github.com/openai/openai-java\n\n\n# openai4j\n\nUnofficial, community-maintained Java implementation of the OpenAI API:\n\nhttps://platform.openai.com/docs/api-reference\n\nopenai4j is a Java library that implements most [documented endpoints](https://platform.openai.com/docs/api-reference) as of 16. April 2024, \nincluding the endpoints that are only available in beta.  \nLegacy, deprecated and streaming endpoints are not implemented.\n\n## Installation\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ech.rasc\u003c/groupId\u003e\n  \u003cartifactId\u003eopenai4j\u003c/artifactId\u003e\n  \u003cversion\u003e1.3.6\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n\n## Usage\n\n### Chat completions\n```java\n  String apiKey = ... // read OpenAI api key from environment variable\n  var client = OpenAIClient.create(c -\u003e c.apiKey(apiKey));\n\n  var response = client.chatCompletions.create(r -\u003e r\n\t\t.addMessages(SystemMessage.of(\"You are a helpful assistant\"),\n\t\t\t\tUserMessage.of(\"What is the capital of Spain?\"))\n\t\t.model(\"gpt-4o\"));\n  String response = response.choices().get(0).message().content();\n```\n\n### Function calling with Java code\n\n```java\npublic class ChatCompletionsFunctionExample {\n\tprivate final static ObjectMapper om = new ObjectMapper();\n\n\tstatic class Location {\n\t\t@JsonProperty(required = true)\n\t\t@JsonPropertyDescription(\"Latitude of the location. Geographical WGS84 coordinates\")\n\t\tpublic float latitude;\n\n\t\t@JsonProperty(required = true)\n\t\t@JsonPropertyDescription(\"Longitude of the location. Geographical WGS84 coordinates\")\n\t\tpublic float longitude;\n\t}\n\n\tstatic class TemperatureFetcher {\n\n\t\tpublic Float fetchTemperature(Location location) {\n\t\t\tSystem.out.println(\"calling fetchTemperature\");\n\t\t\ttry (var client = HttpClient.newHttpClient()) {\n\t\t\t\tvar request = HttpRequest.newBuilder()\n\t\t\t\t\t\t.uri(URI.create(\"https://api.open-meteo.com/v1/metno?latitude=\"\n\t\t\t\t\t\t\t\t+ location.latitude + \"\u0026longitude=\" + location.longitude\n\t\t\t\t\t\t\t\t+ \"\u0026current=temperature_2m\"))\n\t\t\t\t\t\t.build();\n\t\t\t\tvar response = client.send(request,\n\t\t\t\t\t\tjava.net.http.HttpResponse.BodyHandlers.ofString());\n\n\t\t\t\tvar body = response.body();\n\t\t\t\tSystem.out.println(body);\n\t\t\t\tvar jsonNode = om.readTree(body);\n\t\t\t\tvar current = jsonNode.get(\"current\");\n\t\t\t\tvar temperature = current.get(\"temperature_2m\");\n\t\t\t\treturn temperature.floatValue();\n\t\t\t}\n\t\t\tcatch (IOException | InterruptedException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tpublic static void main(String[] args) throws JsonProcessingException {\n\n\t\tString apiKey = ... // read OpenAI api key from environment variable\n\t\tvar client = OpenAIClient.create(c -\u003e c.apiKey(apiKey));\n\n\t\tTemperatureFetcher fetcher = new TemperatureFetcher();\n\t\tString functionName = \"get_temperature\";\n\t\tJavaFunction\u003cLocation, Float\u003e getWeather = JavaFunction.of(functionName,\n\t\t\t\t\"Get the current temperature of a location\", Location.class,\n\t\t\t\tfetcher::fetchTemperature);\n\n\t\tvar service = new ChatCompletionsService(client.chatCompletions, om);\n\n\t\tvar response = service.createJavaFunctions(r -\u003e r.addMessages(UserMessage.of(\n\t\t\t\t\"What are the current temperatures in Oslo, Norway and Helsinki, Finland?\"))\n\t\t\t\t.model(\"gpt-4o\").javaFunctions(List.of(getWeather)));\n\t\tvar choice = response.choices().get(0);\n\t\tSystem.out.println(choice.message().content());\n\n\t}\n}\n```\n\n\n### Asisstant\n\n```java\n  String apiKey = ... // read OpenAI api key from environment variable\n  var client = OpenAIClient.create(c -\u003e c.apiKey(apiKey));\n\n  Assistant assistant = client.assistants.create(c -\u003e c.name(\"Math Tutor\").instructions(\n      \"You are a personal math tutor. Write and run code to answer math questions.\")\n      .addTools(CodeTool.of()).model(\"gpt-4o\"));\n  }\n\n  var thread = client.threads.create();\n\n  var message = client.threadsMessages.create(thread.id(), c -\u003e c.content(\n        \"I need to solve the equation `3x + 11 = 14`. Can you help me?\"));\n\n  var run = client.threadsRuns.create(thread.id(),\n      c -\u003e c.assistantId(assistant.id()).instructions(\n          \"Please address the user as Jane Doe. The user has a premium account.\"));\n\n  client.threadsRuns.waitForProcessing(run, 30, TimeUnit.SECONDS, 2, TimeUnit.MINUTES);\n\n  var messages = client.threadsMessages.list(thread.id(), p -\u003e p.before(message.id()));\n  for (var msg : messages.data()) {\n     var content = msg.content().get(0);\n     if (content instanceof MessageContentText text) {\n       System.out.println(text.text().value());\n     }\n  }\n```\n\n### Azure\n\n```java\n  String apiKey = ... // read OpenAI api key from environment variable\n  String azureEndpoint = ... // \"https://myresource.openai.azure.com/\"\n  var azureClient = OpenAIClient\n     .create(Configuration.builder()\n     .apiVersion(\"2024-02-01\")\n     .apiKey(apiKey)\n     .azureDeployment(\"gpt-35-turbo\")\n     .azureEndpoint(azureEndpoint)\n     .build());\n```     \n\nCheck out the [openai4j-examples](https://github.com/ralscha/openai4j-examples) repository for more examples.\n\n## Changelog\n\n### 1.3.6 - December 3, 2024\n  * Add support for Predicted Outputs\n  * Support for gpt-4o-audio-preview model for chat completions, which supports both audio inputs and outputs.\n\n### 1.3.5 - October 2, 2024\n  * Add audioTokens and cachedTokens to the usage object of ChatCompletionResponse\n  * Add store and metadata field to ChatCompletionRequest\n\n### 1.3.4 - September 14, 2024\n  * Add completion_tokens_details and reasoning_tokens to usage\n  * Including file search results used by the file search tool, and customizing ranking behavior.\n \n### 1.3.3 - August 14, 2024\n  * Added support for Structured Outputs\n\n### 1.3.2 - July 20, 2024\n  * Added support for Uploads API\n\n### 1.3.1 - June 12, 2024\n  * Parallel function calling can be disabled in Chat Completions and the Assistants API by passing parallel_tool_calls=false.\n  * Added support for file search customizations.\n\n### 1.3.0 - May 13, 2024\n  * Support for Assistants API v2\n\n### 1.2.0 - April 16, 2024\n  * Added support for the Batch API\n  * Added support for seed in the fine-tuning API\n  * Added support for checkpoints in the fine-tuning API\n  * Added support for adding Messages when creating a Run in the Assistants API\n\n### 1.1.4 - April 7, 2024\n  * Added support for temperature and assistant message creation in the Assistants API\n\n### 1.1.3 - February 10, 2024\n  * Added timestamp_granularities parameter to the Audio API\n\n### 1.1.2 - January 26, 2024\n  * Added dimensions parameter to the Embeddings API\n\n### 1.1.1 - January 3, 2024\n  * Added additional_instructions parameter to run creation in the Assistants API\n  * Added logprobs and top_logprobs parameters to the Chat Completions API\n  * Changed function parameters argument on a tool call to be optional.\n\n### 1.1.0 - November 30, 2023\n  * Refactor all the builders\n  * Add ChatCompletionsService for calling Java functions and returning Java models\n\n### 1.0.4 - November 14, 2023\n  * More JavaDoc\n\n### 1.0.3 - November 13, 2023\n  * Add `name` property to Chat Completions SystemMessage and UserMessage\n  * More JavaDoc\n  * Replace arrays with List\n  \n### 1.0.2 - November 12, 2023\n  * Bugfix: SubmitToolOutputs not properly JSON decoded\n  * Bugfix: waitForProcessing in ThreadsRuns must return the last ThreadRun object\n\n### 1.0.1 - November 12, 2023\n  * Bugfix: ChatCompletions UserMessage for GPT Vision\n\n### 1.0.0 - November 11, 2023\n  * Initial release\n\n\n\n## License\nCode released under [the Apache license](http://www.apache.org/licenses/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fralscha%2Fopenai4j","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fralscha%2Fopenai4j","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fralscha%2Fopenai4j/lists"}