New Course: Agentic AI with Python
LangChain4jLLM APIs in Plain Java

First Java Project with the OpenAI SDK

Create a Maven project in VS Code, add the OpenAI Java SDK, load the API key from a .env file through launch.json, and send your first request to a model with the Responses API.

You have an API key from the OpenAI setup and a local model from the Ollama setup. Now we need a Java project that can use them.

This page builds that project and gets one answer back from a hosted model. The code is short. Most of the time goes into something every beginner runs into: getting the API key from a file into the running program.

Source code: the finished project for this lesson is in the folder LC4JCode_Le_Java_Project_with_OpenAI_in_VS_Code of the course repository.

What we are building

First_Request_Flow

A class with a main method that creates a client, builds a request, sends it and prints what comes back. No LangChain4j yet. Only the official OpenAI SDK.

Step 1: Create a Maven project

You can use any IDE. The course uses VS Code with the Extension Pack for Java.

In the lecture, an empty Maven project is generated by asking a coding assistant for "a simple Maven project". You can do the same, create one with your IDE's project wizard, or copy the starting point from the course repository.

The project is named lc4j and has this shape:

lc4j/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── com/
                └── telusko/
                    └── App.java

Run the generated App.java once before you change anything. It prints a greeting such as Hello Maven. Now you know that Java, Maven and the IDE work, and any later error comes from what you add.

Step 2: Add the OpenAI SDK

Open pom.xml and add the dependency from the OpenAI libraries page inside <dependencies>:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.telusko</groupId>
    <artifactId>lc4j</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.13.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.openai</groupId>
            <artifactId>openai-java</artifactId>
            <version>4.91.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.5.3</version>
            </plugin>
        </plugins>
    </build>
</project>

Save the file and let Maven download the library. In VS Code you can confirm it under Java Projects, Maven Dependencies, where openai-java should now be listed.

The release number

maven.compiler.release is 25 because the lecturer's machine runs JDK 25. If you have an older JDK installed, change this number to your version. The OpenAI SDK itself needs only Java 8 or later.

Step 3: Write the first request

Replace the content of App.java with the sample from the OpenAI documentation and add one line that prints the result:

App.java
package com.telusko;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public class App {

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ResponseCreateParams params = ResponseCreateParams.builder()
            .input("Say this is a test")
            .model(ChatModel.GPT_5_2)
            .build();

        Response response = client.responses().create(params);

        System.out.println(response.output());
    }
}

Read it from top to bottom:

LineWhat it does
OpenAIOkHttpClient.fromEnv()Creates the client, the object that knows how to reach the server. fromEnv tells it to read its settings, above all the API key, from environment variables
ResponseCreateParams.builder()Starts building one request
.input("Say this is a test")The text you send. This is what a user would type
.model(...)Which model should answer
.build()Finishes the request object
client.responses().create(params)Sends the request to the Responses API and waits for the answer
response.output()The list of things the model produced

"Say this is a test" is the usual first prompt. The model should simply answer with "This is a test."

Step 4: Run it and meet the first error

Click Run above the main method.

Exception in thread "main" java.lang.IllegalStateException: At least one credential source must be specified: credential (apiKey), workloadIdentity, or adminApiKey
	at com.openai.core.ClientOptions$Builder.effectiveCredential(ClientOptions.kt:753)
	at com.openai.core.ClientOptions$Builder.build(ClientOptions.kt:912)
	at com.openai.client.okhttp.OpenAIOkHttpClient$Builder.build(OpenAIOkHttpClient.kt:528)
	at com.openai.client.okhttp.OpenAIOkHttpClient$Companion.fromEnv(OpenAIOkHttpClient.kt:48)
	at com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv(OpenAIOkHttpClient.kt)
	at com.telusko.App.main(App.java:14)

The message is clear once you know what fromEnv() does. It looked for an API key in the environment and found none.

Why did the generated "Hello Maven" program run without any key? Because adding a dependency does nothing by itself. The key is needed only at the moment a client is created.

Step 5: Put the key in a .env file

The SDK documentation shows a way to pass the key in code, with .apiKey("...") on a builder. Do not use it for a real key. A key written in source code ends up in Git sooner or later.

Create a file named .env in the root of the project, next to pom.xml:

.env
OPENAI_API_KEY=your_api_key_here

Replace the placeholder with your real key. There are no quotes and no spaces around the = sign.

Then make sure Git ignores this file:

.gitignore
.env
target/

Check .gitignore before your first commit

Run git status after creating .env. If the file is listed, it is not ignored yet. A key that has been pushed to a public repository must be deleted in the OpenAI dashboard and replaced, even if you remove the file afterwards.

Step 6: Run again, and the same error

Run the program a second time. The error is exactly the same.

This is the step that confuses people. The file exists, the name is right, the key is correct, and the program still cannot see it.

The reason: a .env file is only a text file. Java does not read it. Many tools and frameworks load .env files for you, and that makes it feel like a standard feature of the language. It is not. fromEnv() reads real environment variables of the running process, and nobody has turned the lines of that file into environment variables yet.

Step 7: Let VS Code load the file with launch.json

VS Code can do exactly that for programs it starts. Create a folder named .vscode in the project root, and in it a file named launch.json:

.vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "App",
            "request": "launch",
            "mainClass": "com.telusko.App",
            "projectName": "lc4j",
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}
FieldMeaning
mainClassThe class with the main method to start
projectNameThe Maven project, the artifactId from pom.xml
envFileA file whose lines become environment variables of the program when VS Code launches it

The file is in the course repository, so you do not have to type it.

In the lecture, the coding assistant first writes a launch.json that contains a place to paste the key itself. The lecturer rejects that and asks for a version that uses the .env file. That is the right call. The key should live in one ignored file and nowhere else.

Run again from the Run link above main:

[ResponseOutputItem{message=ResponseOutputMessage{id=msg_0f4d72c6e92a9353006addfdc2eff487d19e5dd952e428ce0f, content=[Content{outputText=ResponseOutputText{annotations=[], text=This is a test., type=output_text, logprobs=[], additionalProperties={}}}], role=assistant, status=completed, type=message, phase=, additionalProperties={}}}]

It works. Somewhere inside that line is text=This is a test.

Running outside VS Code

launch.json only applies when VS Code starts the program. If you run from a terminal, for example with Maven, set the variable in that terminal first. In PowerShell: $env:OPENAI_API_KEY = "your_api_key_here". In bash or zsh: export OPENAI_API_KEY=your_api_key_here. In IntelliJ IDEA, add the variable in the run configuration.

Step 8: Use the model you chose

The sample from the documentation uses a constant, ChatModel.GPT_5_2. The SDK has such a constant for many models, but a constant can only exist for a model that was known when your SDK version was released.

A model id is just a string, so you can always write it directly. Change the request to the model from the previous lesson, and ask a real question:

App.java
ResponseCreateParams params = ResponseCreateParams.builder()
    .input("who is telusko")
    .model("gpt-6-sol")
    .build();

Run it. The output is much longer now. Shortened, it looks like this:

[ResponseOutputItem{reasoning=ResponseReasoningItem{id=rs_..., summary=[], type=reasoning, content=[], encryptedContent=gAAAAABq3f3o..., status=, additionalProperties={}}}, ResponseOutputItem{message=ResponseOutputMessage{id=msg_..., content=[Content{outputText=ResponseOutputText{annotations=[], text=Telusko is a programming education platform and YouTube channel founded by Navin Reddy. It offers tutorials on topics such as Java, Python, and software development., type=output_text, ...}}], role=assistant, status=completed, type=message, phase=final_answer, additionalProperties={}}}]

The answer is there, and it is right. Look at the structure around it:

Item in the output listWhat it is
First item, reasoning=...The model's thinking. It is returned in encrypted form, which is the long block of random-looking characters
Second item, message=...The actual answer, in the text field

With the first model there was only one item. With a reasoning model there are two, and the answer is the second one. Printing the whole list is fine for a first look, but it is not something you can show to a user. The next page fixes that.

Mistakes made in the lecture

1. Expecting an error too early. The lecturer expects the plain project to fail right after the dependency is added, because no key is set. It runs fine. The key is checked when fromEnv() is called, not when the library is on the classpath.

2. Red underlines on imports that are correct. After the dependency is added, VS Code underlines the com.openai imports in red and says they do not exist, although the program compiles and runs. This is the editor's Java support being out of date, not a problem in your code. If it bothers you, open the command palette and run Java: Clean Java Language Server Workspace, then let the project reload.

3. Believing that a .env file is read automatically. It is not, as Step 6 shows. Something has to load it: launch.json here, a framework or a library in other projects.

4. Leaving the sample's model in place. The first successful run still uses the model constant from the documentation. Always check which model a copied sample uses. It decides the quality of the answer and the cost of the request.

5. An unused import. After Step 8, import com.openai.models.ChatModel; is no longer used. It stays in the lecture's file and does no harm. You can delete it.

Try It Yourself

  1. Create the project, run the generated class and confirm that Java and Maven work.
  2. Add the dependency and the code from Step 3. Run it without a key and read the first line of the error.
  3. Create .env and run again without launch.json. Confirm that the error does not change.
  4. Add launch.json, run again and find the text= part in the output.
  5. Change the model id to the one you chose and ask a question about something you know well. Check whether the answer is correct.
  6. Count the items in the printed list. Is there a reasoning item? Try another model and compare.
  7. Run git status and make sure .env is not listed.

Official references


Written By: Shramik Masti

How is this guide?

Last updated on