DEV Community

Said Olano
Said Olano

Posted on

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

Every Java team that starts working with large language models hits the same wall. The first demo is easy: build a JSON body, send an HTTP request, parse the response, print the text. Then the requirements arrive. The model must return a typed object. The prompt must be reused in six places. The same request must be retried on rate limits. Suddenly the codebase is full of string concatenation, manual JSON mapping and fragile parsing code. That code has a name: glue code.

This article shows a cleaner approach. With LangChain4j, you declare a plain Java interface, annotate its methods with the prompt, and the library generates the implementation that calls Claude for you. You write the contract, not the plumbing.

The full working example is in the repository 02 - AI Services, and the project page is at josesaid.github.io/02-ai-services.

The problem with hand-written glue

Consider a simple task: classify a support ticket. A first attempt usually looks like this:

String prompt = "Classify this ticket as BILLING, TECHNICAL or OTHER. Ticket: " + ticket;
String body = """
    {"model":"claude-haiku-5-5","max_tokens":50,
     "messages":[{"role":"user","content":"%s"}]}
    """.formatted(prompt.replace("\"", "\\\""));
HttpRequest request = HttpRequest.newBuilder(URI.create(API_URL))
    .header("x-api-key", apiKey)
    .header("anthropic-version", "2023-06-01")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// now parse the JSON, find the text block, trim it, check it is a valid label...
Enter fullscreen mode Exit fullscreen mode

Every line here is about transport and parsing. None of it describes the business rule, which is "classify this ticket into one of three labels". The escaping is fragile, the prompt is buried in a string, and the response validation is an afterthought. When the prompt changes, you change Java string literals. When the model returns something unexpected, you find out at runtime, in production.

The idea: describe the contract, let the library implement it

LangChain4j introduces AiServices. You describe what you want as an interface, and the framework creates a dynamic proxy that handles the prompt rendering, the model call and the conversion of the response into your return type.

Here is the same classification task with an interface:

interface TicketClassifier {

    @SystemMessage("You classify customer support tickets. Answer with one label only.")
    @UserMessage("Classify this ticket as BILLING, TECHNICAL or OTHER. Ticket: {{ticket}}")
    String classify(@V("ticket") String ticket);
}
Enter fullscreen mode Exit fullscreen mode

The prompt lives next to the method it belongs to. Placeholders are explicit. There is no escaping, no JSON, no parsing code. The business intent reads directly from the interface.

Wiring it to Claude

The model is configured once, and the service is created from the interface:

AnthropicChatModel model = AnthropicChatModel.builder()
        .apiKey(System.getenv("ANTHROPIC_API_KEY"))
        .modelName("claude-haiku-5-5")
        .build();

TicketClassifier classifier = AiServices.create(TicketClassifier.class, model);

String label = classifier.classify("I was charged twice for my subscription this month.");
System.out.println(label); // BILLING
Enter fullscreen mode Exit fullscreen mode

The dependency is the Anthropic integration for LangChain4j. In Maven it looks like this:

<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-anthropic</artifactId>
    <version>1.24.1</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

The project targets Java 21. Nothing else is needed to run it: set ANTHROPIC_API_KEY, run the class, and the classification is printed.

Why this is cleaner

There are four practical benefits.

The prompt is a first-class artifact. A prompt change is a one-line annotation change in a file that is easy to review. Teammates can see the intent without reading HTTP code.

The contract is typed. The method returns a String here, but the same mechanism can return records, enums, lists or other Java types. LangChain4j asks the model for a structure that maps to the return type and converts the answer for you. Your business code receives objects, not text to parse.

Testing becomes simpler. Because the service is an interface, you can replace the implementation with a fake in unit tests. Your business logic is tested without calling the network, and only a small number of integration tests need a real key.

The model is swappable. The interface does not mention Claude. Changing the model means changing the builder, not the code that uses the classifier. That matters when you want to compare models or move to a cheaper one for simple tasks.

Keeping the boundary honest

An interface is not magic. A few habits keep the code healthy.

Put one responsibility behind each interface. A TicketClassifier should classify tickets. Do not add a method that also summarizes, translates and drafts a reply. Small interfaces are easier to test and easier to change.

Validate what matters outside the model. If your business only accepts three labels, check the returned value against that set, or use an enum as the return type so unexpected values fail early. A language model is a powerful component, but its output is still input from an external system.

Keep secrets out of the code. The API key comes from the environment. Never commit it, and never print it in logs.

Log the decisions, not the prompts. For debugging, log the label and the request identifier. Log full prompts only when you have a clear privacy policy, because tickets often contain personal data.

Where this fits in a real system

In a larger application, the interface becomes a port in your architecture. The rest of the system depends on TicketClassifier, not on Anthropic or LangChain4j. That is the same dependency-inversion idea that keeps database access behind repositories. The AI provider becomes an adapter, which you can replace, configure per environment or mock during tests.

This also helps teams that already use Spring. The same interface can be wired as a bean, configured with properties for the model name and timeouts, and injected into services like any other dependency. The LangChain4j integration for Spring Boot follows this model, so the AI feature feels like the rest of the codebase.

Running the example

Clone the repository, set your key, and run the example class:

git clone https://github.com/josesaid/02-ai-services.git
cd 02-ai-services
export ANTHROPIC_API_KEY="your-key"
mvn compile exec:java
Enter fullscreen mode Exit fullscreen mode

The project uses the exec-maven-plugin, so you do not need to build a jar to see the result. The output shows the label returned for the sample ticket. Change the prompt, run it again, and observe how the behavior changes without touching the plumbing.

Returning structured data instead of text

A classifier that returns a free-form sentence is hard to use in code. You end up searching for words in the answer, and a small change in wording breaks the logic. The better approach is to ask for a type the compiler understands. An enum is the simplest case:

enum TicketCategory { BILLING, TECHNICAL, OTHER }

interface TicketClassifier {

    @SystemMessage("You classify customer support tickets.")
    @UserMessage("Classify this ticket. Ticket: {{ticket}}")
    TicketCategory classify(@V("ticket") String ticket);
}
Enter fullscreen mode Exit fullscreen mode

Now the calling code reads like ordinary Java:

TicketCategory category = classifier.classify(ticket.body());
switch (category) {
    case BILLING -> billingQueue.add(ticket);
    case TECHNICAL -> engineeringQueue.add(ticket);
    case OTHER -> generalQueue.add(ticket);
}
Enter fullscreen mode Exit fullscreen mode

There is no string comparison and no parsing step in your business code. The framework asks the model for an answer that maps to the enum and converts it for you. If you need richer results, the same idea works with a record. For example, a method that returns a TicketAnalysis record with a category, a priority and a short summary gives you three typed fields from one model call. The principle stays the same: the contract is in the type, and the library handles the conversion.

Testing without calling the network

One of the most useful consequences of the interface approach is testability. Your business code depends on TicketClassifier, so a unit test can provide a fake implementation:

class FakeClassifier implements TicketClassifier {
    @Override
    public TicketCategory classify(String ticket) {
        return ticket.toLowerCase().contains("charged")
                ? TicketCategory.BILLING
                : TicketCategory.OTHER;
    }
}
Enter fullscreen mode Exit fullscreen mode

With this fake, the routing logic is tested in milliseconds, without an API key, without network access and without cost. The test checks what your system does with each category, which is the part you own. A separate, small group of integration tests calls the real model, to confirm that the prompt still produces the labels you expect. Those tests can be run less often, for example before a release or when a prompt changes.

This split matters for AI features in particular. Model output is not deterministic in the same way as a pure function, so you want as much of the surrounding logic as possible to be deterministic and well covered. Keep the model call behind the interface, and keep the decisions in ordinary, tested code.

Choosing a model

The interface hides the model, but the choice still matters. For classification, a small and fast model is usually enough. It is cheaper, responds quicker and is easier to run at volume. For summarization of long documents or multi-step reasoning, a larger model may be worth the cost. The model name is a single line in the builder:

AnthropicChatModel fastModel = AnthropicChatModel.builder()
        .apiKey(System.getenv("ANTHROPIC_API_KEY"))
        .modelName("claude-haiku-5-5")
        .build();
Enter fullscreen mode Exit fullscreen mode

Because the rest of the code only sees the interface, you can create two services from the same interface, one with a fast model and one with a larger model, and compare their answers on a set of real tickets. Measure first, then decide. Do not assume that the biggest model is always the right one for a narrow task.

A practical habit is to keep a small set of labeled examples for each interface. Run them whenever you change a prompt or a model. The examples work as a regression suite. They tell you whether a change improved the behavior or only changed the wording.

Common pitfalls

Some mistakes appear again and again when teams adopt this style.

Prompts that are too vague. If the prompt says "classify this ticket" without listing the labels, the model may invent new ones. State the allowed values in the system message, and use an enum as the return type so invalid answers cannot reach the rest of the system.

Mixing responsibilities in one interface. An interface that classifies, summarizes, translates and drafts a reply is hard to test and hard to change. Split it. Each method should have one clear purpose and one clear return type.

Ignoring failures. Network calls can fail, and rate limits happen. Decide what your system does when the model is unavailable. For a support queue, the safe fallback may be to route the ticket to a human queue. Make that decision explicit in code, not in an exception that nobody handles.

Logging too much. Prompts often contain personal data. Log the decision, the category and a request identifier. Keep full prompts out of logs unless your privacy policy clearly allows it and access is restricted.

Forgetting cost. Every call costs money and time. Cache results when the same input appears often, and avoid calling the model for cases that simple rules can handle, such as an empty ticket or a message that matches a known template.

Moving from a sample to a team project

A single example class is a good starting point, but a team project needs a few more decisions. Decide where the interfaces live. A common layout keeps them in the domain or application layer, with the LangChain4j implementations in an infrastructure module. That way the business rules depend only on the interface, and the choice of provider is isolated in one place.

Decide who owns the prompts. Prompts are product behavior, so they deserve the same review as code. Store them next to the interface, write a short comment about the intent, and include the labeled examples in the test suite. When a product owner asks why the model made a decision, you can point to the prompt, the examples and the tests.

Decide how you will observe the behavior in production. Track the distribution of categories over time. A sudden shift can mean that the incoming tickets changed, or that a model update changed the behavior. Either way, you want to see it on a dashboard before a customer complains. Record the model name and the prompt version with each decision, so you can explain past results.

Finally, plan for change. Models improve and prices move. Because the model is isolated behind an interface and a builder, switching to a newer model is a configuration change followed by the regression suite. That is the real benefit of the clean approach: the parts that change most often are the easiest to change.

Security and configuration

The API key belongs in the environment or in a secrets manager, never in source code. In a Spring application, read the key and the model name from configuration properties, so each environment can use its own values without a code change. Keep timeouts explicit, so a slow response does not hold a thread indefinitely. Treat the model output as external input: validate it, limit its length when that matters, and never execute it as code or as a database command.

The takeaway

Glue code is not a sign of a serious AI project. It is a sign of a project that has not yet chosen the right abstraction. With LangChain4j's AI Services, the abstraction is an interface: a clear statement of what the application needs from the model. The implementation details of HTTP, JSON and retries stay in the library, where they can be tested and improved once for everyone.

If your team writes Java and is starting with Claude, begin with one interface. Describe one task, give it a precise prompt, and let the framework do the rest. You will spend your time on the business problem instead of on string manipulation.

The complete example is available at github.com/josesaid/02-ai-services. The project page is at josesaid.github.io/02-ai-services.

If you have questions or a different approach, I would like to hear it in the comments.

java #ai #langchain4j #anthropic

Top comments (0)