Add quarkus-vs-spring-ai module: the same support assistant (system prompt, tool, RAG) built with Quarkus LangChain4j and Spring AI against a stub OpenAI-compatible server, with wire-format capture, startup/memory benchmarks and a Quarkus native image

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4XrpfdpsacrvqnrBM
This commit is contained in:
asmhatre
2026-11-27 00:08:03 +05:30
co-authored by Claude Sonnet 5.5
parent f4f90b3b30
commit 5e5326c810
46 changed files with 1395 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm.qvs</groupId>
<artifactId>quarkus-vs-spring-ai</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>quarkus-app</artifactId>
<properties>
<quarkus.platform.version>3.40.1.1</quarkus.platform.version>
<quarkus-langchain4j.version>1.15.1</quarkus-langchain4j.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus.platform</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.quarkiverse.langchain4j</groupId>
<artifactId>quarkus-langchain4j-bom</artifactId>
<version>${quarkus-langchain4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkiverse.langchain4j</groupId>
<artifactId>quarkus-langchain4j-openai</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ankurm.qvs</groupId>
<artifactId>stub-llm</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource><directory>src/main/resources</directory></resource>
<resource><directory>../knowledge</directory><targetPath>knowledge</targetPath></resource>
</resources>
<plugins>
<plugin>
<groupId>io.quarkus.platform</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals><goal>build</goal><goal>generate-code</goal><goal>generate-code-tests</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<configuration><parameters>true</parameters></configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<properties>
<quarkus.native.enabled>true</quarkus.native.enabled>
</properties>
</profile>
</profiles>
</project>
@@ -0,0 +1,23 @@
package com.ankurm.qvs;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
@Path("/ask")
public class AskResource {
private final SupportAssistant assistant;
AskResource(SupportAssistant assistant) {
this.assistant = assistant;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String ask(@QueryParam("q") String q) {
return assistant.ask(q);
}
}
@@ -0,0 +1,21 @@
package com.ankurm.qvs;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Map;
/** The one tool both apps expose. Spring AI twin: spring-ai-app/.../OrderTools.java. */
@ApplicationScoped
public class OrderTools {
private static final Map<String, String> ORDERS = Map.of(
"1001", "shipped on 2026-11-20, arriving in 2 days",
"1002", "being prepared in the warehouse");
@Tool("Looks up the delivery status of a customer order by its order number")
public String orderStatus(@P("the numeric order number, for example 1001") String orderId) {
return "Order " + orderId + " is " + ORDERS.getOrDefault(orderId, "unknown");
}
}
@@ -0,0 +1,32 @@
package com.ankurm.qvs;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.DefaultRetrievalAugmentor;
import dev.langchain4j.rag.RetrievalAugmentor;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.function.Supplier;
/** Plain LangChain4j RAG pipeline; Quarkus only needs to be told where to find it. */
@ApplicationScoped
public class PolicyRetrievalAugmentor implements Supplier<RetrievalAugmentor> {
private final RetrievalAugmentor augmentor;
PolicyRetrievalAugmentor(PolicyStore policies, EmbeddingModel embeddingModel) {
this.augmentor = DefaultRetrievalAugmentor.builder()
.contentRetriever(EmbeddingStoreContentRetriever.builder()
.embeddingStore(policies.store())
.embeddingModel(embeddingModel)
.maxResults(1)
.minScore(0.65) // LangChain4j scores are (cosine+1)/2, so 0.65 is cosine 0.3
.build())
.build();
}
@Override
public RetrievalAugmentor get() {
return augmentor;
}
}
@@ -0,0 +1,44 @@
package com.ankurm.qvs;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/** Loads the three policy files into an in-memory vector store when the application starts. */
@ApplicationScoped
public class PolicyStore {
static final List<String> FILES = List.of("returns.txt", "shipping.txt", "warranty.txt");
private final InMemoryEmbeddingStore<TextSegment> store = new InMemoryEmbeddingStore<>();
private final EmbeddingModel embeddingModel;
PolicyStore(EmbeddingModel embeddingModel) {
this.embeddingModel = embeddingModel;
}
void ingest(@Observes StartupEvent ev) throws IOException {
List<TextSegment> segments = new ArrayList<>();
for (String f : FILES) {
try (InputStream in = getClass().getResourceAsStream("/knowledge/" + f)) {
segments.add(TextSegment.from(new String(in.readAllBytes(), StandardCharsets.UTF_8).trim()));
}
}
List<Embedding> vectors = embeddingModel.embedAll(segments).content();
store.addAll(vectors, segments);
}
public InMemoryEmbeddingStore<TextSegment> store() {
return store;
}
}
@@ -0,0 +1,17 @@
package com.ankurm.qvs;
import dev.langchain4j.service.SystemMessage;
import io.quarkiverse.langchain4j.RegisterAiService;
/**
* The AI service, declared as an interface. Quarkus LangChain4j generates the implementation at
* BUILD time. The RAG augmentor and the tools are named right here in the annotation.
*/
@RegisterAiService(retrievalAugmentor = PolicyRetrievalAugmentor.class, tools = OrderTools.class)
public interface SupportAssistant {
@SystemMessage("You are the support assistant of an online electronics shop. "
+ "Answer in one sentence. Use the order tool for order questions "
+ "and the supplied policy text for policy questions.")
String ask(String question);
}
@@ -0,0 +1,9 @@
# Point the OpenAI client at the stub. Swap base-url and api-key to use the real thing.
quarkus.langchain4j.openai.base-url=http://localhost:8089/v1
quarkus.langchain4j.openai.api-key=stub
quarkus.langchain4j.openai.chat-model.model-name=stub-chat
quarkus.langchain4j.openai.embedding-model.model-name=stub-embed
quarkus.langchain4j.openai.timeout=10s
quarkus.http.port=8080
# Native image: the policy files are read from the classpath at runtime, so they must be embedded in the executable.
quarkus.native.resources.includes=knowledge/*.txt
@@ -0,0 +1,27 @@
package com.ankurm.qvs;
import com.ankurm.stub.StubLlmServer;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.common.QuarkusTestResourceLifecycleManager;
import java.util.Map;
/** Starts the stub LLM before the Quarkus app boots (the app embeds the policies at startup). */
public class StubResource implements QuarkusTestResourceLifecycleManager {
private HttpServer server;
@Override
public Map<String, String> start() {
try {
server = StubLlmServer.start(8089);
} catch (Exception e) {
throw new IllegalStateException(e);
}
return Map.of();
}
@Override
public void stop() {
server.stop(0);
}
}
@@ -0,0 +1,72 @@
package com.ankurm.qvs;
import io.quarkus.test.common.WithTestResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@WithTestResource(StubResource.class)
class SupportAssistantTest {
static String stats() throws IOException, InterruptedException {
return HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("http://localhost:8089/stats")).build(),
HttpResponse.BodyHandlers.ofString()).body();
}
static int count(String stats, String key) {
return Integer.parseInt(stats.replaceAll(".*\"" + key + "\":(\\d+).*", "$1"));
}
static void write(String name, String question, String answer, String before, String after) throws IOException {
Files.createDirectories(Path.of("../output"));
Files.writeString(Path.of("../output/" + name),
"question: " + question + "\nanswer: " + answer
+ "\nchat requests sent to the stub for this question: " + (count(after, "chat") - count(before, "chat"))
+ "\nembedding requests for this question: " + (count(after, "embeddings") - count(before, "embeddings")) + "\n");
}
@Test
void orderQuestionCallsTheTool() throws Exception {
String q = "Where is my order 1001?";
String before = stats();
String answer = given().queryParam("q", q).get("/ask").then().statusCode(200).extract().asString();
write("11-quarkus-tool-call.txt", q, answer, before, stats());
assertTrue(answer.contains("Order 1001 is shipped on 2026-11-20"), answer);
assertEquals(chatCount(before) + 2, chatCount(stats()), "tool call = two chat round trips");
}
@Test
void policyQuestionGetsRetrievedContext() throws Exception {
String q = "How many days do I have to return an item?";
String before = stats();
String answer = given().queryParam("q", q).get("/ask").then().statusCode(200).extract().asString();
write("12-quarkus-rag.txt", q, answer, before, stats());
assertTrue(answer.contains("within 30 days of delivery"), answer);
assertFalse(answer.contains("Shipping policy"), "only the best segment is injected");
}
static int chatCount(String stats) {
return Integer.parseInt(stats.replaceAll(".*\"chat\":(\\d+).*", "$1"));
}
@Test
void unrelatedQuestionGetsNoContext() throws Exception {
String q = "What is the weather in Paris";
String answer = given().queryParam("q", q).get("/ask").then().statusCode(200).extract().asString();
assertFalse(answer.contains("policy:"), answer);
}
}