{"slug": "stop-writing-glue-code-ai-in-java-the-clean-way", "title": "Stop Writing Glue Code: AI in Java, the Clean Way", "summary": "A developer published a working example showing how Java teams can replace hand-written HTTP and JSON glue code for LLM calls with LangChain4j's AiServices, declaring a plain Java interface annotated with @SystemMessage and @UserMessage and letting the library generate the implementation that calls Anthropic's Claude. The example, built on Java 21 with the langchain4j-anthropic 1.24.1 dependency, classifies support tickets into BILLING, TECHNICAL or OTHER and returns typed results without manual escaping or response parsing.", "body_md": "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.\n\nThis 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.\n\nThe full working example is in the repository [02 - AI Services](https://github.com/josesaid/02-ai-services), and the project page is at [josesaid.github.io/02-ai-services](https://josesaid.github.io/02-ai-services/).\n\nConsider a simple task: classify a support ticket. A first attempt usually looks like this:\n\n```\nString prompt = \"Classify this ticket as BILLING, TECHNICAL or OTHER. Ticket: \" + ticket;\nString body = \"\"\"\n    {\"model\":\"claude-haiku-5-5\",\"max_tokens\":50,\n     \"messages\":[{\"role\":\"user\",\"content\":\"%s\"}]}\n    \"\"\".formatted(prompt.replace(\"\\\"\", \"\\\\\\\"\"));\nHttpRequest request = HttpRequest.newBuilder(URI.create(API_URL))\n    .header(\"x-api-key\", apiKey)\n    .header(\"anthropic-version\", \"2023-06-01\")\n    .POST(HttpRequest.BodyPublishers.ofString(body))\n    .build();\nHttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());\n// now parse the JSON, find the text block, trim it, check it is a valid label...\n```\n\nEvery 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.\n\nLangChain4j 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.\n\nHere is the same classification task with an interface:\n\n```\ninterface TicketClassifier {\n\n    @SystemMessage(\"You classify customer support tickets. Answer with one label only.\")\n    @UserMessage(\"Classify this ticket as BILLING, TECHNICAL or OTHER. Ticket: {{ticket}}\")\n    String classify(@V(\"ticket\") String ticket);\n}\n```\n\nThe 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.\n\nThe model is configured once, and the service is created from the interface:\n\n```\nAnthropicChatModel model = AnthropicChatModel.builder()\n        .apiKey(System.getenv(\"ANTHROPIC_API_KEY\"))\n        .modelName(\"claude-haiku-5-5\")\n        .build();\n\nTicketClassifier classifier = AiServices.create(TicketClassifier.class, model);\n\nString label = classifier.classify(\"I was charged twice for my subscription this month.\");\nSystem.out.println(label); // BILLING\n```\n\nThe dependency is the Anthropic integration for LangChain4j. In Maven it looks like this:\n\n```\n<dependency>\n    <groupId>dev.langchain4j</groupId>\n    <artifactId>langchain4j-anthropic</artifactId>\n    <version>1.24.1</version>\n</dependency>\n```\n\nThe project targets Java 21. Nothing else is needed to run it: set `ANTHROPIC_API_KEY`, run the class, and the classification is printed.\n\nThere are four practical benefits.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\nAn interface is not magic. A few habits keep the code healthy.\n\nPut 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.\n\nValidate 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.\n\nKeep secrets out of the code. The API key comes from the environment. Never commit it, and never print it in logs.\n\nLog 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.\n\nIn 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.\n\nThis 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.\n\nClone the repository, set your key, and run the example class:\n\n```\ngit clone https://github.com/josesaid/02-ai-services.git\ncd 02-ai-services\nexport ANTHROPIC_API_KEY=\"your-key\"\nmvn compile exec:java\n```\n\nThe 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.\n\nA 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:\n\n```\nenum TicketCategory { BILLING, TECHNICAL, OTHER }\n\ninterface TicketClassifier {\n\n    @SystemMessage(\"You classify customer support tickets.\")\n    @UserMessage(\"Classify this ticket. Ticket: {{ticket}}\")\n    TicketCategory classify(@V(\"ticket\") String ticket);\n}\n```\n\nNow the calling code reads like ordinary Java:\n\n```\nTicketCategory category = classifier.classify(ticket.body());\nswitch (category) {\n    case BILLING -> billingQueue.add(ticket);\n    case TECHNICAL -> engineeringQueue.add(ticket);\n    case OTHER -> generalQueue.add(ticket);\n}\n```\n\nThere 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.\n\nOne 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:\n\n```\nclass FakeClassifier implements TicketClassifier {\n    @Override\n    public TicketCategory classify(String ticket) {\n        return ticket.toLowerCase().contains(\"charged\")\n                ? TicketCategory.BILLING\n                : TicketCategory.OTHER;\n    }\n}\n```\n\nWith 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.\n\nThis 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.\n\nThe 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:\n\n```\nAnthropicChatModel fastModel = AnthropicChatModel.builder()\n        .apiKey(System.getenv(\"ANTHROPIC_API_KEY\"))\n        .modelName(\"claude-haiku-5-5\")\n        .build();\n```\n\nBecause 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.\n\nA 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.\n\nSome mistakes appear again and again when teams adopt this style.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\nA 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.\n\nDecide 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.\n\nDecide 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.\n\nFinally, 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.\n\nThe 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.\n\nGlue 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.\n\nIf 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.\n\nThe complete example is available at [github.com/josesaid/02-ai-services](https://github.com/josesaid/02-ai-services). The project page is at [josesaid.github.io/02-ai-services](https://josesaid.github.io/02-ai-services/).\n\nIf you have questions or a different approach, I would like to hear it in the comments.", "url": "https://wpnews.pro/news/stop-writing-glue-code-ai-in-java-the-clean-way", "canonical_source": "https://dev.to/said_olano/stop-writing-glue-code-ai-in-java-the-clean-way-3cm3", "published_at": "2026-11-28 02:42:13+00:00", "updated_at": "2026-11-28 02:43:24.758972+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-tools", "developer-tools", "generative-ai"], "entities": ["LangChain4j", "Anthropic", "Claude", "Java", "Maven", "josesaid"], "also_reported_by": [], "takeaway": "Declaring an annotated Java interface with LangChain4j's AiServices.create generates the prompt rendering, Claude call and response conversion, eliminating manual JSON escaping and parsing for typed LLM calls.", "recommendation": {"advice": "Replace hand-built HTTP and JSON glue for LLM calls with LangChain4j AiServices interfaces annotated with @SystemMessage and @UserMessage, so prompts and typed return contracts live in reviewable code.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/stop-writing-glue-code-ai-in-java-the-clean-way", "markdown": "https://wpnews.pro/news/stop-writing-glue-code-ai-in-java-the-clean-way.md", "text": "https://wpnews.pro/news/stop-writing-glue-code-ai-in-java-the-clean-way.txt", "jsonld": "https://wpnews.pro/news/stop-writing-glue-code-ai-in-java-the-clean-way.jsonld"}}