Class LangChain4jLlmProvider

java.lang.Object
com.vaadin.flow.component.ai.provider.LangChain4jLlmProvider
All Implemented Interfaces:
LlmProvider

public class LangChain4jLlmProvider extends Object implements LlmProvider
LangChain4j implementation of LlmProvider, built on a LangChain4j AI service.

Supports both streaming and non-streaming LangChain4j models. Tool calling is supported through LangChain4j's Tool annotation.

Customizing the AI service: the provider runs each turn through an AI service that LangChain4j's AiServices builds. The constructors that take a customizer hand you that builder before the service is built, so you can add what LangChain4j offers there with its own API: retrieval augmentation (RAG), tool providers such as MCP, tool objects, input and output guardrails, listeners, and so on. A moderation model set in the customizer is not used, since LangChain4j applies it only to service methods annotated with @Moderate; use an input guardrail to check the user message instead.

 var provider = new LangChain4jLlmProvider(streamingChatModel,
         service -> service.contentRetriever(retriever)
                 .toolProvider(mcpToolProvider)
                 .inputGuardrails(new PromptInjectionGuardrail()));
 

The provider keeps doing what the orchestrator needs from it, whatever the customizer configured: it supplies the tools of each turn next to the tools of the customizer, adds the session context and the attachments to the user message, and reports the response metadata. Give the tools you add in the customizer names that the tools of the turn do not use: LangChain4j rejects two tools of the same name, and every turn that has both then fails. Once a turn is cancelled, the provider calls the model no more and does not pass a model response that arrives later on to the service, so no tool runs for it, whether the provider or the customizer supplied it. Before the customizer runs, the provider sets defaults that the customizer may replace: its own chat memory, and a result that tells the model when it called a tool that does not exist. The model is the one given to the constructor, so a model set in the customizer is not used. Errors of the tools added in the customizer are handled by LangChain4j, with the tool error handlers set in the customizer or with LangChain4j's defaults; see the LangChain4j documentation on how to handle them safely. Unless the customizer sets both handlers, LangChain4j logs a notice that asks for them, once, also when the customizer adds no tools. The notice does not concern the tools of the orchestrator, whose errors never reach these handlers. Setting both handlers in the customizer chooses the behavior for the tools you add, and LangChain4j then logs no notice.

System prompt: you can set a system prompt in the customizer with systemMessage(...). LangChain4j renders it as a prompt template: a {{name}} placeholder needs a value, and {{current_date}}, {{current_time}} and {{current_date_time}} are replaced, so the prompt must not use double braces for any other purpose. When the orchestrator also sends a system prompt, the orchestrator's prompt is used instead of the one set in the customizer, and it is sent as it is, without template rendering. The text of a user message is never rendered as a template.

Retrieval augmentation: a content retriever or retrieval augmentor set in the customizer works on the text of the user message, which ends with the session context of the turn. The attachments of the turn are added to the augmented message, and input guardrails check that message, so they also receive the retrieved content and a message part for each image, text, PDF, audio or video attachment. The provider's chat memory keeps the attachments with the user message also when storeRetrievedContentInChatMemory(false) leaves the retrieved content out of it. Retrieval and input guardrails run on the thread that asks for the response, before the model is called, also with a StreamingChatModel. When you use retrieval or input guardrails with a streaming model, call setBackgroundExecution(true) so that they do not block the UI thread.

Output guardrails: the text of the response is the text the output guardrails set in the customizer returned. LangChain4j runs them on the final answer only, so with output guardrails the text a model sends next to its tool calls is not passed on. The provider's chat memory keeps the answer as the guardrails returned it, so later turns continue from what the user received. When a guardrail fails the turn, the answer it rejected stays in the chat memory, unless the guardrail asks LangChain4j to remove it with fatalWithMessageRemoval(...) or failureWithMessageRemoval(...). When a turn with a StreamingChatModel is cancelled while a guardrail has asked the model again, your guardrails check an answer without text once more: LangChain4j needs an answer to finish. The turn has ended by then, so what the guardrails return for that answer is not passed on.

Streaming vs. non-streaming: The mode is determined by the constructor used. Pass a StreamingChatModel to LangChain4jLlmProvider(StreamingChatModel) for streaming, or a ChatModel to LangChain4jLlmProvider(ChatModel) for non-streaming. Streaming mode pushes partial responses to the UI as they arrive, which requires automatic server push or polling to deliver them. Annotate your UI class or application shell with @Push, or enable polling with UI.setPollInterval(), before using a streaming model. A warning is logged at runtime when neither is active. With output guardrails configured in the customizer, the answer is not streamed: it arrives in one piece once the guardrails have checked it. Without streaming, text a model sends next to its tool calls arrives with the answer at the end of the turn.

Blocking the request thread: a ChatModel call blocks the thread that subscribes to the response, which is the UI thread for a prompt triggered from the browser. A turn with a StreamingChatModel blocks that thread until the model call starts, which includes the retrieval and the input guardrails configured in the customizer. Call setBackgroundExecution(true) to run the turn on a background thread instead, so the request completes and the user's message renders while the LLM works.

Tool call limits: a model that keeps requesting tool calls instead of answering would never end its turn, and each round costs another model call. LangChain4j runs the tool-calling loop and bounds it with its maxToolCallingRoundTrips setting. Past that limit it stops the loop with an exception of its own, which you receive as the error of the turn. The provider keeps LangChain4j's default for that setting and adds no limit of its own. To change it, call maxToolCallingRoundTrips(...) in the customizer. The conversation stays usable after such a turn: it leaves only its prompt in the provider's chat memory, and the next prompt continues from there.

Each provider instance maintains its own chat memory. To share conversation history across components, reuse the same provider instance. The memory holds the user messages and the assistant's final answer of each turn; tool calls and their results are sent to the model only within the turn they belong to and are not replayed on later turns. A final answer without text, which a model may give once a tool call has done what was asked, is not stored either, so that the turn leaves only its user message in the memory. A chat memory you configure in the customizer replaces the provider's own, and LangChain4j fills it as it does for any AI service: it also receives the tool calls and their results, including those of a turn that failed or was cancelled, with storeRetrievedContentInChatMemory(false) a user message without its attachments, and with output guardrails the answer as the model gave it, not as the guardrails returned it. You own that memory: setHistory(List, Map) restores a saved conversation into the provider's own chat memory and does nothing when the customizer set one, so load the conversation into your memory yourself. Restoring a conversation through AiOrchestrator.Builder.withHistory(List, Map) still matters then: the message list the user sees and the orchestrator's own conversation history are restored by the orchestrator, not by the provider.

Note: LangChain4jLlmProvider is not serializable. If your application uses session persistence, you will need to create a new provider instance after session restore.

Since:
25.3
Author:
Vaadin Ltd
  • Constructor Details

    • LangChain4jLlmProvider

      public LangChain4jLlmProvider(dev.langchain4j.model.chat.StreamingChatModel chatModel)
      Constructor with a streaming chat model.
      Parameters:
      chatModel - the streaming chat model, not null
      Throws:
      NullPointerException - if chatModel is null
    • LangChain4jLlmProvider

      public LangChain4jLlmProvider(dev.langchain4j.model.chat.ChatModel chatModel)
      Constructor with a non-streaming chat model.
      Parameters:
      chatModel - the non-streaming chat model, not null
      Throws:
      NullPointerException - if chatModel is null
    • LangChain4jLlmProvider

      public LangChain4jLlmProvider(dev.langchain4j.model.chat.StreamingChatModel chatModel, Consumer<dev.langchain4j.service.AiServices<?>> customizer)
      Constructor with a streaming chat model and a customizer of the AI service the provider is built on. The customizer receives LangChain4j's AiServices builder before the service is built and can configure retrieval augmentation, tool providers such as MCP, guardrails and the other features of the builder. See the class documentation for what the provider adds to the service and which of its defaults the customizer can replace.
       new LangChain4jLlmProvider(streamingChatModel, service -> service
               .contentRetriever(retriever).toolProvider(mcpToolProvider));
       
      Parameters:
      chatModel - the streaming chat model, not null
      customizer - the customizer of the AI service builder, not null
      Throws:
      NullPointerException - if chatModel or customizer is null
      Since:
      25.4
    • LangChain4jLlmProvider

      public LangChain4jLlmProvider(dev.langchain4j.model.chat.ChatModel chatModel, Consumer<dev.langchain4j.service.AiServices<?>> customizer)
      Constructor with a non-streaming chat model and a customizer of the AI service the provider is built on. The customizer receives LangChain4j's AiServices builder before the service is built and can configure retrieval augmentation, tool providers such as MCP, guardrails and the other features of the builder. See the class documentation for what the provider adds to the service and which of its defaults the customizer can replace.
       new LangChain4jLlmProvider(chatModel, service -> service
               .contentRetriever(retriever).toolProvider(mcpToolProvider));
       
      Parameters:
      chatModel - the non-streaming chat model, not null
      customizer - the customizer of the AI service builder, not null
      Throws:
      NullPointerException - if chatModel or customizer is null
      Since:
      25.4
  • Method Details

    • stream

      public reactor.core.publisher.Flux<String> stream(LlmProvider.LlmRequest request)
      Description copied from interface: LlmProvider
      Streams a response from the LLM based on the provided request. This method returns a reactive stream that emits response tokens as they become available from the LLM. The provider manages conversation history internally, so each call to this method adds to the ongoing conversation context.

      Threading: this method is called on the thread that triggers the prompt, and the returned stream is subscribed to on that same thread. An implementation whose LLM call blocks must therefore schedule that call itself — for example with subscribeOn(Schedulers.boundedElastic()) — otherwise it occupies the UI thread and holds the session lock for the whole turn, and nothing the turn produces reaches the browser until it ends. The built-in providers expose this as a setBackgroundExecution(boolean) setting, since running the turn on the request thread is the simpler default when a turn is short.

      Callers only consume the stream and do not schedule it, so whether a turn runs in the background is decided entirely by the implementation.

      Specified by:
      stream in interface LlmProvider
      Parameters:
      request - the LLM request containing user message, system prompt, attachments, and tools, not null
      Returns:
      a Flux stream that emits response tokens as strings, never null
    • isBackgroundExecution

      public boolean isBackgroundExecution()
      Gets whether the LLM call runs on a background thread.
      Returns:
      true if the call runs on a background thread, false if it runs on the thread that asks for the response
    • setBackgroundExecution

      public void setBackgroundExecution(boolean backgroundExecution)
      Sets whether to run the LLM call on a background thread. The default is false, which runs it on the thread that asks for the response — the UI thread, for a prompt triggered from the browser.

      With a StreamingChatModel, the response arrives on the LLM client's own threads either way, but the turn starts on the thread that asks for it: the retrieval augmentation and the input guardrails configured in the customizer run there before the model is called. Retrieval from an embedding store or a web search can take seconds, so enable this setting when you use retrieval or input guardrails with a streaming model. The start of the turn then runs on a background thread as well.

      A ChatModel call blocks for the whole turn, every tool call included. On the UI thread that means holding the session lock until the turn ends, so nothing the turn produces reaches the browser and the application appears frozen. Set this to true to run the call on a background thread instead: the request completes immediately, the user's message and the typing indicator render, and the response is added when it arrives.

      This requires the following from the application:

      • A way to deliver the response. Annotate the application shell or UI class with @Push, or enable polling with UI.setPollInterval(int). Manual push mode is not enough on its own, because nothing calls ui.push() for you. A warning is logged when neither is active.
      • Thread-safe tools. On a background thread Vaadin thread locals such as UI.getCurrent() and framework contexts such as Spring Security's SecurityContext are not bound, and UI components must not be accessed directly. Wrap component access in ui.access(), or capture what you need in AiController.onRequest(com.vaadin.flow.component.ai.orchestrator.RequestListener.RequestEvent), which still runs on the UI thread. This is the same requirement a StreamingChatModel already has. With a streaming model, the setting extends it to the retrieval and the input guardrails.

      The orchestrator processes one prompt at a time. Without background execution, a message submitted while a turn is running waits for the session lock and is processed when the turn ends; with it, the submit is rejected and dropped with a warning — and a connected input has already cleared its text.

      Like the streaming mode, the setting is not preserved when the session is serialized: an application that restores sessions must re-apply it when it recreates the provider.

      Parameters:
      backgroundExecution - true to run the call on a background thread, false to run it on the thread that asks for the response
    • setHistory

      public void setHistory(List<ChatMessage> history, Map<String,List<AiAttachment>> attachmentsByMessageId)
      Description copied from interface: LlmProvider
      Restores the provider's conversation memory from a list of chat messages with their associated attachments. Any existing memory is cleared before the new history is applied.

      Providers that support setting chat history should override this method.

      This method must not be called while a streaming response is in progress.

      Specified by:
      setHistory in interface LlmProvider
      Parameters:
      history - the list of chat messages to restore, not null
      attachmentsByMessageId - a map from ChatMessage.messageId() to the list of attachments for that message, not null