Polski

Article · AI in Java · RAG

AI in Java: the official SDK, Spring AI and LangChain4j in practice

A map of the AI ecosystem on the JVM – when the official Anthropic SDK is enough, when Spring AI and when LangChain4j – plus streaming, structured responses in records, tools, RAG with pgvector and tests with a fake model.

By · · 18 min read

Most systems that handle orders, payments and warehouses run on the JVM – and that is where an AI feature usually lands, not in a separate Python service. The Java ecosystem has grown up to the job: there is the official Anthropic SDK, Spring AI with Spring Boot integration and LangChain4j with declarative "AI services". This guide shows the same tasks in all three approaches and helps you decide when to use which.

3
paths on the JVM – official SDK, Spring AI, LangChain4j
1
Java record – describes the shape of the model's answer and becomes a JSON Schema
2.1
Spring AI version – GA in November 2026, on Spring Boot 4

The problem: RestTemplate and hand-built JSON

The ordering platform of Halina's Pierogi is a Spring Boot monolith. The team wrote the first AI feature – summarizing complaints – on RestTemplate: the request JSON was assembled from strings, the response parsed by ObjectMapper into a Map<String, Object>, and the result pulled out of the text with a regular expression. A month later:

  • a change in the model's answer format broke the parser once a week,
  • every call blocked a server thread for over ten seconds, so Tomcat's thread pool ran dry at peak hours,
  • nobody knew how many tokens each feature used, because there were no metrics or usage logs,
  • integration tests needed an API key, so they were switched off in CI.

Each of these problems has a ready-made solution in the Java ecosystem – provided you pick the right layer.

Ecosystem map

LayerLibrariesWhat for
Provider SDKscom.anthropic:anthropic-java, com.openai:openai-javathe full API: streaming, structured outputs, tool runner, caching, batch, files
Spring integrationSpring AI (spring-ai-starter-model-anthropic, spring-ai-client-chat)ChatClient, @Tool, advisors, auto-configuration, Micrometer
Framework-independentLangChain4j (langchain4j, langchain4j-anthropic), Quarkus LangChain4jAiServices, memory, tools, RAG, agents
Vector storespgvector, Qdrant, Elasticsearch, Redis – via VectorStore (Spring AI) or EmbeddingStore (LangChain4j)semantic search – see embeddings and vector databases
Local embeddingsspring-ai-transformers, langchain4j-embeddings-* (ONNX)embeddings inside the JVM process, without sending data out
Local modelsOllama (Spring AI and LangChain4j modules)open models on your own hardware – see local LLMs
ProtocolMCP Java SDK, the Spring AI MCP starterMCP servers and clients
Observability and testsMicrometer, OpenTelemetry, JUnit, Testcontainerstoken metrics, tracing, tests with a fake model

maven: org.springframework.ai:spring-ai-client-chat

maven: dev.langchain4j:langchain4j

Diagram: Which layer to choose? Start with the simplest one that fits your stack

How the JVM ecosystem matured

As recently as 2023, Java developers wrote model integrations by hand or ported ideas from Python's LangChain. Today all three paths have stable versions, and Spring AI's Anthropic module uses the official SDK under the hood – so new API features reach Spring faster than they used to.

The code in this article is compiled against the versions current in November 2026: anthropic-java 3.14, Spring AI 2.1 on Spring Boot 4.2 and LangChain4j 1.24. Older tutorials often use API names that changed in the move to versions 1.x and 2.x.

  1. 2023 LangChain4j – first releases of a library inspired by LangChain but designed from scratch for Java.
  2. 2023 Spring AI – the project starts in the Spring ecosystem.
  3. 2025 Stable APIs – March: anthropic-java 1.0; May: LangChain4j 1.0 and Spring AI 1.0 GA.
  4. 2026 Spring AI 2.0 – June: a new major version on Spring Framework 7.
  5. 2026 anthropic-java 3.0 – October: a new major SDK version together with a new API version.
  6. 2026 Spring AI 2.1 – November: among others, human confirmation of tool calls.

The official SDK: streaming and an answer in a record

The Anthropic SDK for Java has builders for every request and one thread-safe client – you create it once, for example as a bean. For structured responses, pass a record class to outputConfig(...): the SDK generates a JSON Schema from it and returns the answer as a ready-made object.

Streaming and extracting an order into a record

StreamAnswer.java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.OutputConfig;
import com.anthropic.models.messages.RawMessageStreamEvent;

public class StreamAnswer {
    public static void main(String[] args) {
        // Reads ANTHROPIC_API_KEY from the environment; the client is thread-safe - create it once.
        AnthropicClient client = AnthropicOkHttpClient.fromEnv();

        MessageCreateParams params = MessageCreateParams.builder()
                .model("claude-opus-5-5")
                .maxTokens(64000L)
                .outputConfig(OutputConfig.builder().effort(OutputConfig.Effort.LOW).build())
                .system("You are the support assistant of Halina's Pierogi. Answer briefly.")
                .addUserMessage("How long do you cook frozen pierogi?")
                .build();

        // try-with-resources closes the HTTP stream even if the consumer stops early.
        try (StreamResponse<RawMessageStreamEvent> stream = client.messages().createStreaming(params)) {
            stream.stream()
                    .flatMap(event -> event.contentBlockDelta().stream())
                    .flatMap(delta -> delta.delta().text().stream())
                    .forEach(text -> System.out.print(text.text()));
        }
    }
}
ExtractOrder.java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.StructuredMessageCreateParams;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.List;

public class ExtractOrder {
    enum Dish { RUSKIE, CABBAGE, MEAT, SPINACH }

    record OrderLine(Dish dish, int quantity) {}

    record OrderDraft(
            List<OrderLine> lines,
            @JsonPropertyDescription("HH:MM, or null when not given") String pickupTime,
            String notes) {}

    public static void main(String[] args) {
        AnthropicClient client = AnthropicOkHttpClient.fromEnv();

        // outputConfig(Class) derives the JSON schema from the record and returns a typed builder.
        StructuredMessageCreateParams<OrderDraft> params = MessageCreateParams.builder()
                .model("claude-opus-5-5")
                .maxTokens(16000L)
                .system("Turn the customer's message into an order draft. Do not invent dishes.")
                .outputConfig(OrderDraft.class)
                .addUserMessage("2x ruskie and one cabbage for 18:30, no onion please")
                .build();

        client.messages().create(params).content().stream()
                .flatMap(block -> block.text().stream())
                .forEach(typed -> {
                    OrderDraft draft = typed.text(); // already deserialized
                    draft.lines().forEach(l -> System.out.println(l.quantity() + "x " + l.dish()));
                    System.out.println("pickup: " + draft.pickupTime());
                });
    }
}

What to watch for:

  • The stream must be closed. StreamResponse holds an open HTTP connection; try-with-resources guarantees it is closed even when you stop reading halfway.
  • effort instead of temperature. Current Claude models do not accept sampling parameters; you set reasoning depth in OutputConfig. Details in LLM fundamentals.
  • Jackson annotations are documentation for the model. @JsonPropertyDescription goes into the schema and tells the model the field format (for example HH:MM).

Tools: the tool runner on classes

In the Java SDK the tool use loop is run by the tool runner (in beta). Each tool is a class implementing Supplier<String>: public fields become the argument schema, Jackson annotations become descriptions, and the get() method runs the tool. The runner returns the model's messages one by one until it is done.

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Spring AI: ChatClient, @Tool and RAG with pgvector
  • LangChain4j: declarative AI services
  • Testing and observability
  • SDK, Spring AI or LangChain4j?
  • Checklist
  • Test yourself
  • What's next

Create a free account · Sign in