LLM Providers
An AI framework — such as Spring AI or LangChain4j — is a Java library that handles the protocol details of talking to LLM services like OpenAI or Anthropic. The orchestrator plugs into your chosen framework through the LlmProvider interface. Create a provider by instantiating the appropriate implementation directly. Two implementations are provided: one for Spring AI and one for LangChain4j.
|
Important
|
Memory Window Limit
Both built-in providers maintain a 30-message memory window of their own. The exceptions are a SpringAiLlmProvider whose ChatClient has a chat memory advisor or can’t be inspected, and a LangChain4jLlmProvider whose customizer sets a chat memory. There, the application owns the memory. Older messages are evicted from the provider’s working memory. The orchestrator’s getHistory() retains the full conversation, but the LLM only sees the most recent 30 messages.
|
Spring AI
SpringAiLlmProvider supports both streaming and synchronous Spring AI models.
Source code
Java
// From ChatModel - use an implementation of Spring AI ChatModel
ChatModel chatModel = OpenAiChatModel.builder()
.openAiClient(...).options(...).build();
SpringAiLlmProvider provider = new SpringAiLlmProvider(chatModel);
// From ChatClient - use a Spring AI ChatClient
ChatClient chatClient = ChatClient.builder(...)
.defaultAdvisors(...).build();
SpringAiLlmProvider provider = new SpringAiLlmProvider(chatClient);The provider manages its own conversation memory using a 30-message window. A provider created from a ChatClient does so too, unless the client already has a chat memory advisor, such as Spring AI’s MessageChatMemoryAdvisor. The application then owns the client’s memory. The provider also leaves the memory to the application when a custom ChatClient implementation doesn’t create its requests with a client built by ChatClient.builder(), because it can’t inspect that client’s configuration.
Streaming is enabled by default. To disable it, call setStreaming(false):
Source code
Java
provider.setStreaming(false);In synchronous mode, the whole exchange runs in the request that triggered it and blocks the UI until the response is complete. See Background Execution for keeping the UI responsive during long prompts.
|
Note
|
History Restoration with an Application-Owned Memory
A provider with its own memory restores the conversation into it, so withHistory() and reconnect() need no extra work. When the application owns the client’s memory, the provider can’t do that, and its setHistory() does nothing. It logs a warning when the client’s memory advisor has no default conversation id. Without one, the advisor has no conversation to read, and every prompt fails. Load the conversation into the client’s own ChatMemory before passing the client to the provider, or leave the memory advisor out and let the provider handle it. The orchestrator’s own conversation history and the Message List are restored either way.
|
LangChain4j
LangChain4jLlmProvider supports both streaming and synchronous LangChain4j models. The mode is determined by the model type passed to the constructor:
Source code
Java
// Streaming mode - use an implementation of LangChain4j StreamingChatModel
StreamingChatModel streamingChatModel = OpenAiStreamingChatModel.builder()
.apiKey(...).modelName(...).build();
LangChain4jLlmProvider provider = new LangChain4jLlmProvider(streamingChatModel);
// Synchronous mode - use an implementation of LangChain4j ChatModel
ChatModel chatModel = OpenAiChatModel.builder()
.apiKey(...).modelName(...).build();
LangChain4jLlmProvider provider = new LangChain4jLlmProvider(chatModel);The provider manages its own conversation memory using a 30-message window, unless a customizer replaces it.
Synchronous mode blocks the UI for the duration of each exchange; see Background Execution.
AI Service Customizer
The provider runs each turn through a LangChain4j AI service, which it builds with AiServices. Both constructors also accept a customizer as a second argument. The customizer receives the AiServices builder before the provider builds the service. Use it to add LangChain4j features with LangChain4j’s own API, such as retrieval-augmented generation, MCP tool providers, tool objects, guardrails, and listeners:
Source code
Java
LangChain4jLlmProvider provider = new LangChain4jLlmProvider(
streamingChatModel,
service -> service
// Retrieval from the application's embedding store
.contentRetriever(contentRetriever)
.inputGuardrails(promptInjectionGuardrail));Whatever the customizer configures, the provider keeps doing what the orchestrator needs from it:
-
It supplies the tools of each turn next to the customizer’s tools.
-
It adds the session context and the attachments to the user message.
-
It reports the response metadata.
-
It calls the model passed to the constructor, so a model set in the customizer isn’t used.
-
It sends the system prompt of the orchestrator in place of a
systemMessage()set in the customizer, unless that prompt isnullor blank.
The provider sets the following on the builder before the customizer runs, so the customizer can replace each of them:
| Builder method | Set by the provider |
|---|---|
| The provider’s own conversation memory. |
| A tool result that tells the model that the tool it called doesn’t exist. |
The following applies to what the customizer configures:
-
Chat memory: A memory set with
chatMemory()orchatMemoryProvider()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 output guardrails, it keeps the answer as the model gave it, not as the guardrails returned it. The application owns that memory. The provider skips it duringwithHistory()andreconnect(), so load the saved conversation into it before the next prompt. -
Retrieval and input guardrails: Retrieval works on the text of the user message, which ends with the session context of the turn. Input guardrails check the message after retrieval, so they also see the retrieved content and the attachments. Both run before the model is called, on the thread that sends the prompt, also with a streaming model. Enable background execution so that they don’t block the UI.
-
Output guardrails: The response is the text that the output guardrails returned. LangChain4j runs them on the final answer only, so text that the model sends next to its tool calls isn’t passed on. With a streaming model, the answer arrives in one piece once the guardrails have checked it. The provider’s own 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()orfailureWithMessageRemoval(). -
Moderation: A moderation model set in the customizer isn’t used, because LangChain4j applies it only to service methods annotated with
@Moderate. Use an input guardrail to check the user message instead. -
Tool names: Give the tools you add in the customizer names that no
withTools()tool or controller uses. LangChain4j rejects two tools of the same name, and every turn that has both then fails. -
Tool errors: LangChain4j handles the errors of tools added in the customizer, with the tool error handlers set there or with its defaults. Unless the customizer sets both
toolArgumentsErrorHandler()andtoolExecutionErrorHandler(), LangChain4j logs a notice that asks for them, once, also when the customizer adds no tools. The notice doesn’t concern the tools of the orchestrator, whose errors never reach these handlers. Setting both handlers chooses how the tools you add fail, and LangChain4j then logs no notice.
Framework Features
An LLM provider is a thin adapter: it hands each prompt to the framework and streams back what the framework produces. Everything else the model needs is set up in the framework, with the framework’s own API. The orchestrator works with whatever has been configured there and adds no framework features of its own.
Where the setup goes depends on the framework. With Spring AI, configure a ChatClient and wrap it in a provider. With LangChain4j, set the model’s own options on the model, and configure the AI service in a customizer.
Model Context Protocol (MCP) servers are the most common example. Neither the orchestrator nor the provider is an MCP client. Configure the framework’s MCP client: its transport, its credentials, and which of the server’s tools the model may see. Then hand its tools to the provider. With Spring AI, register the tool callbacks on a ChatClient:
Source code
Java
ChatClient chatClient = ChatClient.builder(chatModel)
// Tool callbacks from Spring AI's MCP client
.defaultTools(mcpToolCallbacks)
.build();
SpringAiLlmProvider provider = new SpringAiLlmProvider(chatClient);With LangChain4j, add a McpToolProvider in the customizer:
Source code
Java
// Tool provider for LangChain4j's MCP client
McpToolProvider mcpToolProvider = McpToolProvider.builder()
.mcpClients(mcpClient)
.build();
LangChain4jLlmProvider provider = new LangChain4jLlmProvider(chatModel,
service -> service.toolProvider(mcpToolProvider));The MCP tools then reach the model on every turn, next to any tools registered on the orchestrator through withTools() or a controller. The model calls all of them the same way, so tool names have to be unique across every source and match ^[a-zA-Z0-9_-]{1,64}$ — validated when a controller is registered, but not for names that come from an MCP server.
Other framework features work the same way: configure them in the framework, then create the provider. This covers the following:
-
Retrieval-augmented generation against a vector store
-
Guardrails, including content moderation
-
Observability
-
Model options such as temperature and token limits
-
Structured output with schema validation
-
Limits on the tool-calling loop of a turn
The framework’s own reference documentation is where to look for the details:
|
Tip
|
System Prompt Precedence
Pass a system prompt to AiOrchestrator.builder() to override the framework default on every turn. If the prompt is null or blank, the provider uses any defaultSystem() text on the Spring AI client or systemMessage() set in the LangChain4j customizer.
|
Background Execution
A synchronous provider produces the response on the thread that asks for it. For a prompt sent from the browser, that is the request thread: the request does not return until the model has produced the complete response, including any tool calls along the way. The interface freezes for the whole wait, and since the request holds the session lock, other views in the same session wait too.
Background execution moves the exchange to a background thread instead. Enable it on either built-in provider:
Source code
Java
provider.setBackgroundExecution(true);The user’s message then appears immediately and the Message List shows a typing indicator while the model works, the UI stays responsive, and the response replaces the indicator when the model finishes. The setting is off by default. It’s read for each prompt, so it can be changed at any time; the next prompt uses the new mode.
With a streaming model, the response already arrives on the LLM client’s own threads, so the setting has no effect on a SpringAiLlmProvider in streaming mode. A LangChain4jLlmProvider with a streaming model still starts each turn on the thread that sends the prompt. The retrieval and the input guardrails of a customizer run there, before the model is called. Background execution moves that start to a background thread as well.
The response is now produced outside any request, so it reaches the browser through server push or polling. Enable push by annotating the application shell with @Push (see Server Push), or enable polling with UI.setPollInterval(). Without either, the response only shows up with the next request the browser happens to make — the page looks stuck even though the turn completed on the server. The provider logs a warning, once per provider instance, when neither is active; the same warning applies in streaming mode, whose response also arrives outside a request. Manual push mode is not enough on its own, because nothing in the framework calls ui.push() for the application.
Everything that the orchestrator does before it hands the prompt to the provider still runs in the request thread:
-
Adding the user’s message to the Message List and showing the typing indicator
-
AiController.onRequest() -
The request listener
-
The session context supplier
The model calls, every tool execution, and the ResponseListener run on a background thread, as do the retrieval and the input guardrails of a LangChain4j customizer. There, UI.getCurrent() and other Vaadin thread locals return null and components must not be touched directly. Thread-bound framework state, such as Spring Security’s SecurityContext, is absent there for the same reason.
Wrap component access in ui.access(), or capture what a tool needs in AiController.onRequest() while the request thread is still current — see Tool Calling & Programmatic Prompts and Controllers. The built-in controllers already handle this. AiController.onResponse() is the exception: the orchestrator calls it through ui.access(), so it can update components directly.
|
Note
|
One Prompt at a Time
The orchestrator processes one prompt at a time. In the default synchronous mode, a message submitted while a turn is running waits for the session lock and is processed when the turn ends. With background execution the lock is free, so the same message is rejected and dropped with a server-side warning — and the Message Input has already cleared its text.
|
If the user closes or reloads the browser tab while a turn is running, the turn still completes on the server: the response is recorded in the conversation history and the ResponseListener fires as usual. Only the UI updates are skipped, along with AiController.onResponse(), which needs an attached UI. The setting itself lives on the provider and is not serialized with the session — apply it again to the recreated provider after a session restore, before passing it to reconnect(). See Conversation History & Session Persistence.
Custom LLM Providers
Implement the LlmProvider interface to connect to any LLM framework:
Source code
Java
public class MyLlmProvider implements LlmProvider {
@Override
public Flux<String> stream(LlmRequest request) {
// Return a reactive stream of response tokens
// request.userMessage() -- the user's prompt
// request.attachments() -- any file attachments
// request.systemPrompt() -- the system prompt
// request.tools() -- tool objects registered via withTools()
// request.explicitTools() -- ToolSpec tools contributed by the controller
// request.sessionContext() -- per-turn session context, or null
// request.metadataSink() -- consumer for response metadata
}
@Override
public void setHistory(List<ChatMessage> history,
Map<String, List<AiAttachment>> attachmentsByMessageId) {
// Restore conversation context
}
}A provider is responsible for its own conversation memory, for the tool-calling loop over both the vendor-annotated tool objects and the framework-agnostic ToolSpec tools (see Controllers), and for appending the session context to the user message when one is given.
The response stream carries text only. The provider can also publish the finish reason and token usage of the turn through the metadataSink() consumer on the request. Each call carries everything observed so far and replaces the value of any earlier call, so publish whenever the provider learns more — a turn that fails midway has then still reported what was observed. Pass null for any value the framework doesn’t report; a provider that observes no metadata never calls the consumer. See Response Metadata for how applications read it.
The orchestrator calls stream() on the thread that triggers the prompt and subscribes to the returned stream on that same thread — whether a turn runs in the background is decided entirely by the implementation. An implementation whose LLM call blocks should schedule that call itself; otherwise it occupies the request thread and holds the session lock for the whole turn. See Background Execution for how the built-in providers expose this as a setting.