Building Your First AI Client in Java (Cerebras AI)
Source: Dev.to

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 apply to other AI providers like OpenAI (ChatGPT), Claude, or Gemini—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
HttpClientAPI) - A Cerebras AI API key
- Your favorite IDE or text editor
Step 1: Get Your Cerebras API Key
- Visit the Cerebras AI website and sign up for an account.
- Navigate to the API section or developer dashboard.
- Generate a new API key.
- Copy the key—you’ll need it in the next step.
⚠️ Security tip: Keep your API key secret and never commit it to version control!
Step 2: Set Up Your API Key as an Environment Variable
Storing the key in an environment variable keeps it out of your source code and makes the program portable.
On Windows
SETX CEREBRAS_API_KEY "your-api-key-here"
Replace your-api-key-here with the actual key.
Restart your IDE or terminal for the change to take effect.
On macOS / Linux
Add the following line to ~/.bashrc, ~/.zshrc, or ~/.bash_profile:
export CEREBRAS_API_KEY="your-api-key-here"
Then reload the configuration:
source ~/.bashrc # or source ~/.zshrc
Step 3: Create Your Java Project
Create a new file named AIChat.java and paste the code below.
import 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 response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
Understanding the Code
1. Reading the API Key
String apiKey = System.getenv("CEREBRAS_API_KEY");
Retrieves the 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
}
""";
model– the AI model to use (Cerebras offers several Llama variants).messages– an array of message objects (roleandcontent).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();
Sets the endpoint, content‑type, authorization header, and the JSON payload.
4. Sending the Request
HttpClient client = HttpClient.newHttpClient();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
Creates an HTTP client, sends the request, and prints the raw JSON response.
Step 4: Run Your Application
javac AIChat.java
java AIChat
You should see a JSON response containing the AI’s answer.
Parsing the JSON Response
The raw JSON isn’t very user‑friendly. Below is a quick‑and‑dirty method to extract just the AI’s message. For production code, consider a proper JSON library such as Gson or Jackson.
// Add this method inside the AIChat class
private static String extractContent(String jsonResponse) {
int start = jsonResponse.indexOf("\"content\":\"") + 11;
int end = jsonResponse.indexOf("\"", start);
return jsonResponse.substring(start, end);
}
You could then replace the final System.out.println(response.body()); with:
String content = extractContent(response.body());
System.out.println("AI says: " + content);
🎉 That’s it!
You now have a minimal Java client that talks to Cerebras AI (or any compatible provider). Feel free to expand the program—add a loop for continuous chat, integrate a UI, or swap in a different model. Happy coding!
Adapting to Other AI Providers
Want to use a different AI provider? Here’s what you need to change:
OpenAI (ChatGPT)
- Endpoint:
https://api.openai.com/v1/chat/completions - Model:
gpt-4orgpt-3.5-turbo - API‑Key environment variable:
OPENAI_API_KEY
Anthropic (Claude)
- Endpoint:
https://api.anthropic.com/v1/messages - Model:
claude-sonnet-4-5-20250929 - Headers:
- Use
x-api-keyinstead ofAuthorization - Add
anthropic-version: 2023-06-01
- Use
Google (Gemini)
- Endpoint:
https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent - Note: Different request format – see Google’s documentation for details.
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
messagesarray. - 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! 🎉
This simple example demonstrates the core concepts you’ll use regardless of which AI provider you choose. The key takeaways are:
- Understanding HTTP requests.
- Formatting JSON payloads.
- Secure API‑key management.
Happy coding, and enjoy exploring the world of AI integration!
About the Author
Deividas Strole – 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:
- Personal website:
- LinkedIn:
- GitHub:
- YouTube:
- Academia:
- X (Twitter):
