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:
co-authored by
Claude Sonnet 5.5
parent
f4f90b3b30
commit
5e5326c810
@@ -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");
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+72
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user