DEV Community

Said Olano
Said Olano

Posted on Edited on

Stop Writing Glue Code: AI in Java, the Clean Way

Most of the AI code I read in Java projects isn't about AI. It builds request payloads, sets headers, serializes JSON, parses responses, and maps everything back into something the rest of the application can use. That is glue code. It's tedious to write, easy to get subtly wrong, and it hides the one thing you care about: what you are asking the model to do.

The 02-ai-services project shows a much cleaner approach using LangChain4J. You declare a Java interface, annotate it, and LangChain4J generates the implementation that calls Claude. The whole example is one small class and one dependency.

In this article we'll walk through the project, look at every line that matters, and pull out some practices you can apply in your own code.

The Idea: Declare Behavior, Don't Implement It

If you've used Spring Data repositories or declarative HTTP clients, the pattern will feel familiar. You write an interface that describes what you want, and a framework supplies the how.

The README for the project summarizes it in one sentence:

Declare a Java interface, and LangChain4J generates the implementation that calls Claude.

The project demonstrates four things:

  • @SystemMessage sets the model's behavior.
  • @UserMessage marks the parameter that carries the question.
  • AiServices.create(Interface.class, model) builds the proxy.
  • Changing the text of @SystemMessage and running again shows how the answers change.

The README also notes that "this is the pattern used by most of the other LangChain4J examples." So if you learn only one abstraction from the library, this is a good one to start with.

Project Setup

The project is a plain Maven build targeting JDK 21. Here is the 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.mx.development.jose.said</groupId>
    <artifactId>02-ai-services</artifactId>
    <version>1.0.0</version>
    <name>02-ai-services</name>
    <description>AI Services: declare an interface and let LangChain4J implement it</description>

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

    <dependencies>
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-anthropic</artifactId>
            <version>1.24.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <mainClass>com.mx.development.jose.said.AiServicesExample</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Enter fullscreen mode Exit fullscreen mode

A few things are worth noticing.

There is a single dependency. langchain4j-anthropic at version 1.24.1 is the only library declared. The example imports both the Anthropic chat model and the AI Services classes (AiServices, SystemMessage, UserMessage), and the project compiles with just this one dependency.

The Java version is pinned with maven.compiler.release. Setting it to 21 makes the compiler target the Java 21 API, not just the bytecode level. The README lists JDK 21 as a requirement, and this property enforces it.

The exec-maven-plugin declares the main class. This is what lets you run the example with mvn -q compile exec:java without building a jar. It's a small convenience, but for a learning project it removes a lot of friction.

The Whole Example in One File

Here is the full source of AiServicesExample.java:

package com.mx.development.jose.said;

import dev.langchain4j.model.anthropic.AnthropicChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;

/**
 * Example 02 - AI Services.
 *
 * You write only an interface. LangChain4J generates the implementation,
 * which sends the system message and the user message to Claude.
 */
public class AiServicesExample {

    static final String MODEL_NAME = "claude-haiku-5-5";

    public interface JavaTutor {

        @SystemMessage("You are a patient Java tutor. Answer in English, in at most three sentences.")
        String ask(@UserMessage String question);
    }

    public static void main(String[] args) {
        String apiKey = System.getenv("ANTHROPIC_API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalStateException("Set the ANTHROPIC_API_KEY environment variable first.");
        }

        AnthropicChatModel model = AnthropicChatModel.builder()
                .apiKey(apiKey)
                .modelName(MODEL_NAME)
                .maxTokens(512)
                .build();

        // The implementation of JavaTutor is generated here.
        JavaTutor tutor = AiServices.create(JavaTutor.class, model);

        System.out.println("Answer: " + tutor.ask("What is the difference between a record and a class?"));
        System.out.println("Answer: " + tutor.ask("When should I use Optional?"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's take it apart piece by piece.

The Interface Is the Contract

The center of the example is this nested interface:

public interface JavaTutor {

    @SystemMessage("You are a patient Java tutor. Answer in English, in at most three sentences.")
    String ask(@UserMessage String question);
}
Enter fullscreen mode Exit fullscreen mode

There is no class implementing JavaTutor anywhere in the project. Yet the code later calls tutor.ask(...) and gets a String back. Three things make that work.

@SystemMessage: who the model is

The text in @SystemMessage sets the model's behavior. In this example it does three jobs in one sentence:

  • It defines a role: a patient Java tutor.
  • It sets a language: answer in English.
  • It sets a length constraint: at most three sentences.

This is where the prompt lives, and it's now declared next to the method it affects. You don't have to hunt through string concatenation in some service class to find out what the model is being told. When you want to change the tutor's tone, you change the annotation text.

@UserMessage: what the caller is asking

The @UserMessage annotation marks the parameter that carries the question:

String ask(@UserMessage String question);
Enter fullscreen mode Exit fullscreen mode

Whatever string the caller passes to ask becomes the user message sent to the model. The method signature reads like ordinary Java: you give it a String question and get a String answer back.

The return type

ask returns a String, so the model's text reply is handed back directly. For an introductory example that's exactly what you want: no wrapper objects, no response parsing.

Building the Model

An AI Service needs a model to talk to. The example builds an AnthropicChatModel:

AnthropicChatModel model = AnthropicChatModel.builder()
        .apiKey(apiKey)
        .modelName(MODEL_NAME)
        .maxTokens(512)
        .build();
Enter fullscreen mode Exit fullscreen mode

The builder takes three settings:

  • apiKey: read from the environment (more on that below).
  • modelName: taken from the MODEL_NAME constant, which the example defines as "claude-haiku-5-5".
  • maxTokens: set to 512, which caps the length of the model's response.

The maxTokens(512) setting pairs naturally with the system message. The system message asks for at most three sentences, and the token cap is a hard ceiling in case the model is more verbose than requested. The instruction expresses the intent and the cap enforces a limit.

Notice also that the model name lives in a static final String constant rather than being inlined in the builder call. That makes it easy to find and change when you want to try a different model.

Generating the Implementation

This is the line the whole example is built around:

// The implementation of JavaTutor is generated here.
JavaTutor tutor = AiServices.create(JavaTutor.class, model);
Enter fullscreen mode Exit fullscreen mode

AiServices.create(Interface.class, model) builds the proxy, as the README puts it. You pass in the interface type and the chat model, and you get back an object that implements JavaTutor. When you call ask, that generated implementation sends the system message and the user message to Claude, as the class Javadoc says.

From this point on, the rest of your application only knows about JavaTutor. It doesn't need to know about the Anthropic builder, the model name, or how requests are made.

Calling the Service

Using the service is just calling a method:

System.out.println("Answer: " + tutor.ask("What is the difference between a record and a class?"));
System.out.println("Answer: " + tutor.ask("When should I use Optional?"));
Enter fullscreen mode Exit fullscreen mode

Two different questions go through the same service, and both are answered under the same system message. This shows the separation that makes the pattern useful: the system message is fixed per method, while the user message changes per call. The persona and rules are written once, and each call supplies only the question.

Failing Fast on a Missing API Key

One part of the example is easy to skim past but worth highlighting:

String apiKey = System.getenv("ANTHROPIC_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
    throw new IllegalStateException("Set the ANTHROPIC_API_KEY environment variable first.");
}
Enter fullscreen mode Exit fullscreen mode

The program reads the key from the ANTHROPIC_API_KEY environment variable and checks it before doing anything else. If the variable is missing or blank, it throws an IllegalStateException with a message that tells you exactly what to do.

This is good practice for two reasons:

  1. The key never appears in source code. Nothing sensitive gets committed to the repository.
  2. The failure is early and readable. Without the check, you'd hit an authentication problem later, in the middle of a model call, with a message that may be harder to connect to the real cause.

Best Practices You Can Take From This Project

The example is small, but it embodies several habits worth copying.

1. Treat the interface as your AI boundary

Application code depends on JavaTutor, not on the Anthropic model class. In the example, only main knows about AnthropicChatModel; everything after AiServices.create(...) uses the interface. If you keep that boundary in a larger application, then the rest of your code never has to change when you adjust how the model is configured.

2. Keep prompts close to the method they govern

Having the @SystemMessage text on the interface method means the prompt and the method signature are reviewed together. When someone reads ask, they see the instructions that shape its behavior. That's easier to maintain than a prompt buried in a distant utility class.

3. Give the system message concrete constraints

The example's system message isn't vague. It states a role ("patient Java tutor"), a language ("English"), and a limit ("at most three sentences"). Specific instructions are easier to verify: you can read an answer and immediately see whether it followed the rules.

4. Back up instructions with hard limits

maxTokens(512) complements the "three sentences" instruction. The prompt says what you want, and the setting limits the worst case. Using both is a cheap way to keep responses and costs predictable.

5. Keep secrets in the environment

The API key comes from ANTHROPIC_API_KEY, never from a literal in the code. Combined with the explicit check, you get both safety and clear errors.

6. Name constants for things you'll tweak

MODEL_NAME is a constant, so experimenting with a different model is a one-line change in an obvious place.

7. Start with the smallest working example

The project does one thing: one interface, one model, one proxy, two calls. It's easier to understand a pattern when it isn't tangled up with other features. The README says this is the pattern used by most of the other LangChain4J examples, so a solid grasp of it pays off as you move on.

8. Experiment by editing the system message

The README gives a direct suggestion: try changing the text of @SystemMessage and running again to see how the answers change. It's the fastest way to build an intuition for how much influence the system message has. Some variations to try:

  • Change "at most three sentences" to a different length limit.
  • Change the role from "patient Java tutor" to something stricter or more casual.
  • Change the language instruction.

Run the program after each change and compare the answers to the same two questions.

Why This Beats Hand-Written Glue

Consider what this approach does for the shape of your code.

Intent is visible. The interface tells you what the AI-backed component does, and the annotation tells you how the model is instructed. There's nothing else to read.

The surface area is small. The example has one interface method, one builder call, and one factory call. Each does one job.

It's ordinary Java. JavaTutor is a plain interface with a method that takes a String and returns a String. Because it's an interface, you can stand in for it when you need to, for instance by writing a simple implementation of JavaTutor that returns canned text for code that depends on it. That is a general property of interfaces rather than a feature of this project, but it's one of the practical benefits of exposing AI behavior through one.

The framework owns the plumbing. The class Javadoc states it plainly: "You write only an interface. LangChain4J generates the implementation, which sends the system message and the user message to Claude." The repetitive work is no longer your code.

How to Run the Project

Requirements

  • JDK 21
  • Maven 3.9 or later
  • An Anthropic API key

Steps

  1. Clone the repository:
   git clone https://github.com/josesaid/02-ai-services.git
   cd 02-ai-services
Enter fullscreen mode Exit fullscreen mode
  1. Set your API key and run the example:
   export ANTHROPIC_API_KEY=your-key-here
   mvn -q compile exec:java
Enter fullscreen mode Exit fullscreen mode

The compile goal builds the project, and exec:java runs the main class configured in the pom.xml, com.mx.development.jose.said.AiServicesExample. The -q flag keeps Maven quiet so the program's output is easy to read.

When it runs, the program asks the tutor the two questions from the source and prints each reply on a line starting with Answer:. The exact wording will come from the model, so it may differ from run to run.

If you forget to set the variable, the program stops immediately with Set the ANTHROPIC_API_KEY environment variable first., which is the IllegalStateException from the code above.

Things to try after the first run

  • Edit the @SystemMessage text and run again. Compare the new answers with the old ones.
  • Replace the two questions in main with your own.
  • Change maxTokens and see how it affects the length of the replies.
  • Change the value of MODEL_NAME.

Where to Go from Here

This project is example 02 in a series, and the README says its pattern is the one most of the other LangChain4J examples use. Once you're comfortable declaring an interface, annotating it, and creating it with AiServices.create, you have the base that the remaining examples build on.

The takeaway is simple. Describe the behavior you want in an interface, give the model clear instructions in @SystemMessage, mark the input with @UserMessage, and let the library handle the rest. Your code ends up shorter, easier to read, and focused on what the application actually needs from the model.

Source Code and Documentation

Clone it, set your key, change the system message, and see how the answers change. That small loop teaches more about AI Services than any amount of reading.

Top comments (0)