Home

Spring AI vs LangChain4j

Spring AI and LangChain4j are the two main frameworks for adding LLMs to Java applications. This page compares them the way you would when picking one for a production system. Every example implements the same use case in both: an assistant that answers questions about orders by reading internal data.

Reference versions: Spring AI 2.0.x, LangChain4j 1.2x. Last updated November 2026. The examples only show what matters for the comparison, so check the documentation for the version you use.

Summary

Spring AILangChain4j
Maintained by The Spring team, as part of the Spring ecosystem. Independent open source project, with contributions from Red Hat (Quarkus) and Microsoft.
Framework coupling Built for Spring Boot: auto-configuration, starters, properties. Plain Java library. Integrations for Spring Boot, Quarkus, Helidon, Micronaut.
API style Fluent ChatClient, behavior added through advisors. Declarative AI Services (annotated interfaces) plus a low-level API.
Model selection From configuration (application.yml), code depends on the abstraction. Builder in code, or properties when using the Spring or Quarkus starter.
Tool calling @Tool and @ToolParam on Spring bean methods. @Tool and @P on methods of any object.
Conversation memory ChatMemory plus MessageChatMemoryAdvisor, conversation id passed as a parameter. ChatMemoryProvider plus @MemoryId on the AI Service method.
Structured output .call().entity(MyRecord.class) The AI Service method returns the type directly.
Streaming Flux<String> (Reactor). TokenStream with callbacks, or Flux with the Reactor module.
RAG VectorStore, retrieval advisors, ETL pipeline for documents. EmbeddingStore, ContentRetriever, RetrievalAugmentor, "Easy RAG" module.
Observability Built-in Micrometer: observations for model calls, tools and vector stores. ChatModelListener. Tracing and metrics come from the framework integration (e.g. Quarkus with OpenTelemetry).
MCP Client and server with Boot starters. @McpTool, @McpResource, @McpPrompt annotations in core since 2.0. Client (langchain4j-mcp module, still beta). For servers: community module, MCP Java SDK or Quarkus MCP Server.

1. Simple call

Spring AILangChain4j
# application.yml
spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4o-mini
@RestController
class HelloController {

    private final ChatClient chatClient;

    HelloController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/hello")
    String hello(@RequestParam String q) {
        return chatClient.prompt()
                .user(q)
                .call()
                .content();
    }
}
ChatModel model = OpenAiChatModel.builder()
        .apiKey(System.getenv("OPENAI_API_KEY"))
        .modelName("gpt-4o-mini")
        .build();

String answer = model.chat("Hello!");

Spring AI starts from configuration and gives you a ready-made bean. LangChain4j starts from code: you build the model yourself with no container involved, and the configuration is yours to manage unless you hand it to the framework starter.

2. Assistant with tools and memory

Spring AILangChain4j
@Component
class OrderTools {

    private final OrderRepository orders;

    OrderTools(OrderRepository orders) {
        this.orders = orders;
    }

    @Tool(description = "Returns the status of an order")
    String orderStatus(
            @ToolParam(description = "Order id") String orderId) {
        return orders.findStatus(orderId);
    }
}
@RestController
class AssistantController {

    private final ChatClient chatClient;

    AssistantController(ChatClient.Builder builder,
                        OrderTools tools,
                        ChatMemory memory) {
        this.chatClient = builder
                .defaultSystem("You are an order support assistant.")
                .defaultTools(tools)
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(memory).build())
                .build();
    }

    @PostMapping("/chat/{userId}")
    String chat(@PathVariable String userId,
                @RequestBody String message) {
        return chatClient.prompt()
                .user(message)
                .advisors(a -> a.param(
                        ChatMemory.CONVERSATION_ID, userId))
                .call()
                .content();
    }
}
class OrderTools {

    private final OrderRepository orders;

    OrderTools(OrderRepository orders) {
        this.orders = orders;
    }

    @Tool("Returns the status of an order")
    String orderStatus(@P("Order id") String orderId) {
        return orders.findStatus(orderId);
    }
}
interface Assistant {

    @SystemMessage("You are an order support assistant.")
    String chat(@MemoryId String userId,
                @UserMessage String message);
}
Assistant assistant = AiServices.builder(Assistant.class)
        .chatModel(model)
        .tools(new OrderTools(orderRepository))
        .chatMemoryProvider(id ->
                MessageWindowChatMemory.withMaxMessages(20))
        .build();

String reply = assistant.chat("user-42", "Where is my order 1234?");

In LangChain4j the contract is a Java interface. System prompt, memory and return type sit in the method signature, and the rest of the code only knows about Assistant. Spring AI builds the same behavior on the ChatClient with defaults and advisors, much like you would configure a RestClient or WebClient.

3. Structured output

Spring AILangChain4j
record OrderSummary(String orderId,
                    String status,
                    List<String> issues) {}

OrderSummary summary = chatClient.prompt()
        .user("Summarize this ticket: " + ticket)
        .call()
        .entity(OrderSummary.class);
record OrderSummary(String orderId,
                    String status,
                    List<String> issues) {}

interface TicketAnalyzer {

    @UserMessage("Summarize this ticket: {{ticket}}")
    OrderSummary summarize(@V("ticket") String ticket);
}

4. Streaming

Spring AILangChain4j
@GetMapping(value = "/stream",
            produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String q) {
    return chatClient.prompt()
            .user(q)
            .stream()
            .content();
}
interface StreamingAssistant {
    TokenStream chat(String message);
}

StreamingAssistant assistant = AiServices
        .builder(StreamingAssistant.class)
        .streamingChatModel(streamingModel)
        .build();

assistant.chat("Hello!")
        .onPartialResponse(System.out::print)
        .onCompleteResponse(r -> System.out.println())
        .onError(Throwable::printStackTrace)
        .start();

5. MCP

Spring AI: exposing tools as an MCP server LangChain4j: consuming an MCP server as a client
// starter: spring-ai-starter-mcp-server-webmvc
@Component
class OrderMcpTools {

    @McpTool(name = "order_status",
             description = "Returns the status of an order")
    String orderStatus(
            @McpToolParam(description = "Order id",
                          required = true) String orderId) {
        return orders.findStatus(orderId);
    }
}
McpTransport transport = new StreamableHttpMcpTransport.Builder()
        .url("http://localhost:8080/mcp")
        .build();

McpClient mcpClient = new DefaultMcpClient.Builder()
        .transport(transport)
        .build();

ToolProvider toolProvider = McpToolProvider.builder()
        .mcpClients(mcpClient)
        .build();

Assistant assistant = AiServices.builder(Assistant.class)
        .chatModel(model)
        .toolProvider(toolProvider)
        .build();

MCP is where the two differ most. The Spring team contributed the official MCP Java SDK, and Spring AI supports both the server and the client side. LangChain4j works well as a client, but to write a server you are better off with the MCP Java SDK or Quarkus.

LangChain4j 1.19 removed the SSE transport (HttpMcpTransport), so use Streamable HTTP or stdio.

When to choose which

Spring AI if

LangChain4j if

Whichever you pick, keep the LLM behind an interface you own (a port, in hexagonal architecture terms). Then switching framework or model only touches the code behind that interface.

Production concerns

Does the provider abstraction hold up?

For the code, mostly yes. In both frameworks, switching from one provider to another is a dependency and a configuration change, and the tool and structured output code stays the same.

The behavior does not carry over as easily. Models differ in how reliably they pick the right tool, whether they call several tools in one turn, and whether they support a JSON schema natively or only follow format instructions in the prompt. Provider-specific options (such as OpenAiChatOptions in Spring AI) also leak the provider back into your code as soon as you use them. Treat a model change like a dependency upgrade: run the same test suite against the new model before switching.

How do you pass the user identity to a tool?

The rule that matters in both frameworks: the model must never decide who the user is. Do not expose a userId parameter that the LLM fills in. The tool reads the identity from context the server controls.

In Spring AI you pass that context with .toolContext(Map.of("userId", userId)) on the prompt, and the tool method receives it as a ToolContext parameter that is not shown to the model. In a blocking call the tool also runs on the request thread, so SecurityContextHolder works, but do not count on it with streaming. In LangChain4j a tool parameter annotated with @ToolMemoryId receives the same id passed with @MemoryId, which you can use as the user or session key.

For MCP servers the identity travels as an OAuth token, as defined by the MCP authorization spec. A Spring AI MCP server can be secured as an OAuth2 resource server with Spring Security. The client has to forward a token that represents the user, not a technical account with broader permissions.

Where do retries, fallbacks and circuit breakers go?

Both frameworks handle basic retries on the model call. Spring AI uses Spring Retry, configured through the spring.ai.retry.* properties. LangChain4j model builders have a maxRetries option.

Neither gives you a fallback to a different model out of the box. Put it in the adapter behind your own interface: with Resilience4j in Spring (a @CircuitBreaker whose fallback method calls a second ChatClient built on another model), or with the SmallRye Fault Tolerance annotations (@Timeout, @Retry, @Fallback) on Quarkus AI Services. Keeping this logic in the adapter means the rest of the application never knows which model actually answered.

How do you test it?

Split the tests by what is deterministic and what is not.

Sources

Home