DEV Community

Cover image for Building Your First AI Client in Java (Cerebras AI)
Deividas Strole
Deividas Strole

Posted on

Building Your First AI Client in Java (Cerebras AI)

In this tutorial, you'll learn how to build a very simple AI chat client in Java. Because of the free tier and the speed, we will be using Cerebras AI here. The same principles though apply to other AI providers like OpenAI (ChatGPT), Claude, or Gemini. If you decide to use other AI models — just adjust the API endpoint and model names.


Prefer video? You can watch the full tutorial on YouTube above.

What You'll Need

  • Java 11 or higher (we'll use the modern HttpClient API)
  • A Cerebras AI API key
  • Your favorite IDE or text editor

Step 1: Get Your Cerebras API Key

First, you'll need to get an API key from Cerebras:

  1. Visit Cerebras AI and sign up for an account
  2. Navigate to the API section or developer dashboard
  3. Generate a new API key
  4. Copy the key—you'll need it in the next step

... and of course - keep your API key secure and never commit it to version control!

Step 2: Set Up Your API Key as an Environment Variable

Instead of hardcoding your API key in your source code, store it as an environment variable. This keeps your key secure and makes your code more portable.

On Windows
Open Command Prompt or PowerShell and run:
SETX CEREBRAS_API_KEY "your-api-key-here"

Replace your-api-key-here with your actual API key. You'll need to restart your IDE or terminal for the changes to take effect.

On macOS/Linux
Add this line to your ~/.bashrc, ~/.zshrc, or ~/.bash_profile:
export CEREBRAS_API_KEY="your-api-key-here"

Then reload your configuration:
bashsource ~/.bashrc # or ~/.zshrc

Step 3: Create Your Java Project

Create a new Java file called AIChat.java and add the following code:

javaimport java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class AIChat {
    public static void main(String[] args) throws IOException, InterruptedException {
        String apiKey = System.getenv("CEREBRAS_API_KEY");

        String requestBody = """
        {
            "model": "llama3.1-8b",
            "messages": [
                {"role": "user", "content": "How to win a lotto?"}
            ],
            "temperature": 0.2
        }
        """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.cerebras.ai/v1/chat/completions"))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Code

Let's break down what this code does:

1. Reading the API Key
String apiKey = System.getenv("CEREBRAS_API_KEY");

This retrieves your API key from the environment variable you set earlier.

2. Building the Request Body

String requestBody = """
{
    "model": "llama3.1-8b",
    "messages": [
        {"role": "user", "content": "How to win a lotto?"}
    ],
    "temperature": 0.2
}
""";
Enter fullscreen mode Exit fullscreen mode

The request body is a JSON object containing:

  • model: The AI model to use (Cerebras offers various Llama models)
  • messages: An array of message objects with roles and content
  • temperature: Controls randomness (0.0 = deterministic, 1.0 = creative)

3. Creating the HTTP Request

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.cerebras.ai/v1/chat/completions"))
    .header("Content-Type", "application/json")
    .header("Authorization", "Bearer " + apiKey)
    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
    .build();
Enter fullscreen mode Exit fullscreen mode

This builds an HTTP POST request with:

  • The Cerebras API endpoint
  • JSON content type header
  • Authorization header with your API key
  • The request body we created

4. Sending the Request

HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
Enter fullscreen mode Exit fullscreen mode

This creates an HTTP client, sends the request, and prints the JSON response.

Step 4: Run Your Application
Compile and run your program:

javac AIChat.java
java AIChat
Enter fullscreen mode Exit fullscreen mode

You should see a JSON response containing the AI's answer!

Parsing the JSON Response

The raw JSON response isn't very user-friendly. Let's improve our code to extract just the AI's message. You can use a JSON library like Gson or Jackson, or parse it manually for simple cases:

// Add this method to extract the content
private static String extractContent(String jsonResponse) {
    int contentStart = jsonResponse.indexOf("\"content\":\"") + 11;
    int contentEnd = jsonResponse.indexOf("\"", contentStart);
    return jsonResponse.substring(contentStart, contentEnd)
        .replace("\\n", "\n");
}

// In main, replace the println with:
String aiResponse = extractContent(response.body());
System.out.println("AI Response: " + aiResponse);
Enter fullscreen mode Exit fullscreen mode

Adapting to Other AI Providers

Want to use a different AI provider? Here's what you need to change:

OpenAI (ChatGPT)

Anthropic (Claude)

  • Endpoint: https://api.anthropic.com/v1/messages
  • Model: claude-sonnet-4-5-20250929
  • Headers: Add "x-api-key" instead of "Authorization"
  • API Version: Add header "anthropic-version": "2023-06-01"

Google (Gemini)

Next Steps

Now that you have a working AI client, you can:

  • Add user input to make it interactive
  • Implement conversation history by maintaining a messages array
  • Add error handling for network issues and API errors
  • Parse JSON responses properly using Gson or Jackson
  • Create a command-line chat interface
  • Experiment with different models and temperature settings

Conclusion

Congratulations - you have successfully built your first AI client in Java! Yahoo! This simple example demonstrates the core concepts you'll use regardless of which AI provider you choose. The key takeaways are understanding HTTP requests, JSON formatting, and secure API key management.

Happy coding, and enjoy exploring the world of AI integration!

About the Author

Deividas Strole is a Full-Stack Developer based in California, specializing in Java, Spring Boot, React, and AI-driven development. He writes about software engineering, modern full-stack development, and digital marketing strategies.

Connect with me:

Top comments (0)