Using LLM4S with Jakarta EE and MicroProfile
Call a model from a Jakarta EE 10 application on Open Liberty: a CDI-produced JLlmClient configured with MicroProfile Config, a blocking and a streamed Jakarta REST endpoint, a MicroProfile Health check, and tests on the real server.
Table of contents
- Run the sample
- Dependencies
- Configuration
- The client as a CDI bean
- Blocking and streamed endpoints
- Health check
- Testing
- Pitfalls
- Where next
There is no Jakarta EE module for llm4s. This page wires the Java API into a Jakarta EE application with
CDI, Jakarta REST and MicroProfile. Every Java, XML and properties snippet is an excerpt of the runnable sample,
modules/samples/jakarta-ee-java,
which CI builds and tests on Open Liberty against the library on every pull request that touches it. The code uses
only Jakarta EE 10 Web Profile and MicroProfile Config and Health APIs, so the same WAR should deploy on another
server that has them, such as WildFly or Payara; only Open Liberty is tested.
Run the sample
You need JDK 21 or newer and Maven 3.9 or newer. The sample’s default provider is a local
Ollama server at http://localhost:11434, which needs no key.
mvn liberty:dev downloads Open Liberty, starts it with the application and redeploys on every change:
1
2
3
ollama pull llama3.2
cd modules/samples/jakarta-ee-java
mvn liberty:dev -Dllm4s.version=1.0.0
Then ask it something, once as a whole reply and once streamed, and read its readiness check:
1
2
3
curl -X POST -H 'Content-Type: text/plain' -d 'What is Jakarta EE, in one sentence?' http://localhost:9080/api/chat
curl -N -X POST -H 'Content-Type: text/plain' -d 'What is Jakarta EE?' http://localhost:9080/api/chat/stream
curl http://localhost:9080/health/ready
Without -Dllm4s.version the build uses 0.1.0-SNAPSHOT, the code of your checkout, which you first publish to
your local Maven repository with sbt publishM2 as the sample’s README shows. The tests need neither
Ollama nor a key: mvn verify runs the unit tests, and mvn verify -Pit also runs the integration tests on Open
Liberty.
Dependencies
llm4s is Scala 3 only, and the _3 suffix is part of every artifact name. llm4s-java-api brings llm4s-core,
llm4s-agent and the Scala library, but no provider: declare the provider modules you build clients for. Set
llm4s.version to 1.0.0 (or later). These are packaged in the WAR’s
WEB-INF/lib; the Jakarta EE and MicroProfile APIs are provided, by the server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.llm4s</groupId>
<artifactId>llm4s-java-api_3</artifactId>
<version>${llm4s.version}</version>
</dependency>
<dependency>
<groupId>org.llm4s</groupId>
<artifactId>llm4s-ollama_3</artifactId>
<version>${llm4s.version}</version>
</dependency>
<dependency>
<groupId>org.llm4s</groupId>
<artifactId>llm4s-openai-compatible_3</artifactId>
<version>${llm4s.version}</version>
</dependency>
The server needs only four features:
1
2
3
4
5
6
<featureManager>
<feature>restfulWS-3.1</feature>
<feature>cdi-4.0</feature>
<feature>mpConfig-3.1</feature>
<feature>mpHealth-4.0</feature>
</featureManager>
Configuration
The client is described by four MicroProfile Config keys, with defaults in
src/main/resources/META-INF/microprofile-config.properties:
1
2
3
4
llm4s.provider=ollama
llm4s.model=llama3.2
# llm4s.base-url=http://localhost:11434
# llm4s.api-key=
A system property or an environment variable overrides each key. MicroProfile Config maps . and - to _ and
upper-cases the name, so llm4s.base-url is LLM4S_BASE_URL and llm4s.api-key is LLM4S_API_KEY. Keep a real
key in the environment or a secret, never in the properties file. Llm4sSettings reads the keys and chooses the
builder:
1
2
3
4
5
6
7
static Llm4sSettings from(Config config) {
return new Llm4sSettings(
config.getOptionalValue("llm4s.provider", String.class).orElse("ollama"),
config.getValue("llm4s.model", String.class),
config.getOptionalValue("llm4s.base-url", String.class).orElse(null),
config.getOptionalValue("llm4s.api-key", String.class).orElse(null));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
LlmResult<JLlmClient> build() {
return switch (provider) {
case "ollama" -> {
var builder = Llm4s.ollama().model(model);
yield (baseUrl == null ? builder : builder.baseUrl(baseUrl)).build();
}
case "openai-compatible" -> {
var builder = Llm4s.openAiCompatible().model(model).baseUrl(baseUrl);
yield (apiKey == null ? builder : builder.apiKey(apiKey)).build();
}
default -> throw new IllegalStateException(
"Unknown llm4s.provider '" + provider + "': use ollama or openai-compatible");
};
}
The client as a CDI bean
One JLlmClient serves the whole application: many threads can use it at once
(Sharing one client), and close() releases its
provider client and executor. A producer builds it from the settings, and a disposer closes it when the application
stops:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// JLlmClient is a final class, so CDI cannot proxy it, and a normal scope such as @ApplicationScoped needs a
// proxy. @Singleton is a pseudo-scope without one: still one client for the whole application.
@Produces
@Singleton
JLlmClient client(Llm4sSettings settings) {
LlmResult<JLlmClient> client = settings.build();
if (client.isFailure()) {
throw new IllegalStateException(
"Cannot build the llm4s client: " + client.getError().getMessage(), client.getError());
}
return client.get();
}
// Called when the application stops: closes the client's connections and threads.
void close(@Disposes JLlmClient client) {
client.close();
}
// Builds the client as the application starts, so a misconfiguration fails the deployment, not the first request.
void buildAtStartup(@Observes Startup event, JLlmClient client) {
}
With an unknown llm4s.provider, Open Liberty refuses to start the application and logs the
IllegalStateException, rather than answering the first request with an error.
Blocking and streamed endpoints
A @RequestScoped Jakarta REST resource gets the client injected. POST /api/chat returns the whole reply; the
model’s failure is a gateway error, with a rate limit and a timeout kept visible:
1
2
3
4
5
6
7
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response chat(String question) {
Reply reply = answer(question);
return Response.status(reply.status()).entity(reply.body()).build();
}
1
2
3
4
5
6
7
8
9
10
11
Reply answer(String question) {
if (question == null || question.isBlank()) {
return new Reply(400, "Send a question as the request body");
}
LlmResult<String> answer = client.complete(conversation(question).build());
if (answer.isSuccess()) {
return new Reply(200, answer.get());
}
LlmException error = answer.getError();
return new Reply(statusOf(error), error.getKind() + ": " + error.getMessage());
}
POST /api/chat/stream sends each piece of the reply as a server-sent event, from the stream’s own thread. Each send
waits for its write, so the events stay in order, and a client that has gone makes the listener throw, which stops
the call rather than paying for the rest of the reply. The request’s thread waits for the whole reply, then closes
the stream and the sink, which ends the response. A failure ends the stream with an error event, so it is not
mistaken for an empty answer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void stream(String question, @Context SseEventSink sink, @Context Sse sse) {
if (question == null || question.isBlank()) {
throw new BadRequestException("Send a question as the request body");
}
try (sink) {
LlmResult<CompletionStream> started = client.stream(conversation(question).build(),
piece -> sink.send(sse.newEvent(piece)).toCompletableFuture().join());
if (started.isFailure()) {
sendError(sink, sse, started.getError());
return;
}
try (CompletionStream stream = started.get()) {
LlmResult<JCompletion> reply = stream.await();
if (reply.isFailure()) {
sendError(sink, sse, reply.getError());
}
}
}
}
Both endpoints block a server thread while the model answers, and Open Liberty’s thread pool grows to cover it.
client.completeAsync returns a CompletableFuture instead, which a Jakarta REST method can return as a
CompletionStage (Java threading and cancellation). The sample does not do this,
and two things change if you do: a failure completes the future with an LlmException, which is a 500 unless you
map it (handle(...) or an ExceptionMapper), and a client that disconnects does not cancel the call.
Health check
A MicroProfile Health readiness check at /health/ready reports the provider and model. It does not call the model,
so a probe costs no tokens and does not fail when the provider is slow:
1
2
3
4
5
6
7
8
@Override
public HealthCheckResponse call() {
return HealthCheckResponse.named("llm4s")
.up()
.withData("provider", settings.provider())
.withData("model", settings.model())
.build();
}
Testing
Neither kind of test needs a model or a key. mvn verify runs the unit tests, and mvn verify -Pit the
integration tests as well; CI runs both.
The unit tests use FakeLlmClient from llm4s-java-api (Testing your code), a real
JLlmClient that answers from a script, and call the resource’s answer method directly:
1
2
3
4
5
6
FakeLlmClient fake = FakeLlmClient.builder()
.reply("Jakarta EE is a set of Java specifications.")
.failWith(LlmErrorKind.TIMEOUT, "too slow")
.failWith(LlmErrorKind.RATE_LIMIT, "slow down")
.build();
ChatResource resource = new ChatResource(fake.client());
The integration tests run on Open Liberty, in the it profile. The liberty-maven-plugin downloads the server,
installs its features, deploys the application and starts it before the tests, and stops it after. Its JVM options
point the client at a stub Ollama server the tests start, so the real client calls it over HTTP inside the
application server. They are in a profile so that they never reach mvn liberty:dev:
1
2
3
4
<jvmOptions>
<param>-Dllm4s.base-url=http://127.0.0.1:${stub.port}</param>
<param>-Dllm4s.model=stub-model</param>
</jvmOptions>
ChatIT then calls /api/chat, /api/chat/stream and /health/ready and checks the stub’s reply, the 502 of a
provider failure, the event stream and its error event, the 400 of an empty question and the readiness data.
Pitfalls
- A final class cannot be a normal-scoped bean.
JLlmClientis final, so a producer annotated@ApplicationScopedfails the deployment (Open Liberty’s CDI reportsWELD-001410, non-proxyable dependencies): CDI needs a proxy for a normal scope. Use@Singleton, as above, or wrap the client in a class of your own. - Class loading. Everything llm4s needs is in
WEB-INF/lib: the Scala 3 and 2.13 libraries, cats, upickle and Typesafe Config; llm4s has no Jackson dependency. Open Liberty does not expose its own copies of third-party libraries to an application, so they do not clash, and no class-loader setting is needed. On a server that does expose them, give the application’s own classes precedence (parent-last) if two versions conflict. The WAR is about 34 MB, most of it the Scala libraries; with several applications on one server, a shared library holds one copy. - Logging. Open Liberty logs through
java.util.loggingand llm4s through SLF4J. Without an SLF4J binding llm4s’s logs are dropped with a warning;slf4j-jdk14inWEB-INF/libsends them to the server’smessages.log. - JDK 21. llm4s is JDK 21 bytecode, so the server must run on JDK 21 or newer. Open Liberty itself runs
Jakarta EE 10 on older JDKs too, so a server on one of those starts, then fails to deploy the application with an
UnsupportedClassVersionError. Point the server at a JDK 21 withJAVA_HOMEin itsserver.env. - Native image. Not supported: llm4s ships no GraalVM metadata yet (#1463).
Where next
- Java: conversations, completion options, structured output and failures from Java.
- Java threading and cancellation: which calls block and how to cancel them.
- Quarkus, Helidon and Micronaut: the same client in the other JVM frameworks.