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
+42
View File
@@ -0,0 +1,42 @@
<?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>stub-llm</artifactId>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.21.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.0</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.ankurm.stub.StubLlmServer</mainClass>
</transformer>
</transformers>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,157 @@
package com.ankurm.stub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A deterministic stand-in for an OpenAI-compatible endpoint. It is NOT a language model.
*
* <ul>
* <li>POST /v1/embeddings: hashed bag-of-words vectors, so retrieval is repeatable.</li>
* <li>POST /v1/chat/completions: a three-rule script. (1) The last message is a tool result:
* answer with it. (2) Tools are offered and the user mentions "order 1001": call the first
* tool, passing the number in the tool's first declared parameter. (3) Otherwise echo the
* last user message, which makes retrieved context visible in the answer.</li>
* <li>With -Dstub.record.dir=DIR every request body is saved, so the wire formats of two
* frameworks can be diffed.</li>
* </ul>
*/
public class StubLlmServer {
static final ObjectMapper JSON = new ObjectMapper();
static final Pattern ORDER = Pattern.compile("order\\s*#?\\s*(\\d+)", Pattern.CASE_INSENSITIVE);
static final int DIMS = 1024;
static final java.util.Set<String> STOP = java.util.Set.of("the", "and", "for", "are", "you", "have", "how", "many",
"what", "when", "does", "can", "with", "from", "that", "this", "all", "any", "about", "tell", "within", "per", "not");
static final AtomicInteger CHAT = new AtomicInteger(), EMBED = new AtomicInteger(), SEQ = new AtomicInteger();
static Path recordDir;
public static void main(String[] args) throws Exception {
start(Integer.parseInt(System.getProperty("stub.port", "8089")));
}
/** Starts the stub on the given port; also used by the tests of both apps. */
public static HttpServer start(int port) throws IOException {
String rec = System.getProperty("stub.record.dir");
if (rec != null) { recordDir = Path.of(rec); Files.createDirectories(recordDir); }
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.setExecutor(Executors.newFixedThreadPool(4));
server.createContext("/v1/chat/completions", ex -> handle(ex, "chat"));
server.createContext("/v1/embeddings", ex -> handle(ex, "embed"));
server.createContext("/stats", ex -> reply(ex, "{\"chat\":" + CHAT + ",\"embeddings\":" + EMBED + "}"));
server.start();
System.out.println("stub-llm listening on :" + port);
return server;
}
static void handle(HttpExchange ex, String kind) throws IOException {
try {
JsonNode req = JSON.readTree(ex.getRequestBody());
if (recordDir != null && kind.equals("chat")) {
Files.writeString(recordDir.resolve(String.format("%03d-chat.json", SEQ.incrementAndGet())),
JSON.writerWithDefaultPrettyPrinter().writeValueAsString(req));
}
reply(ex, JSON.writeValueAsString(kind.equals("chat") ? chat(req) : embeddings(req)));
} catch (Exception e) {
e.printStackTrace();
byte[] b = ("{\"error\":{\"message\":\"" + e + "\"}}").getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(500, b.length);
ex.getResponseBody().write(b);
ex.close();
}
}
static void reply(HttpExchange ex, String body) throws IOException {
byte[] b = body.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, b.length);
ex.getResponseBody().write(b);
ex.close();
}
static ObjectNode chat(JsonNode req) {
CHAT.incrementAndGet();
ArrayNode messages = (ArrayNode) req.get("messages");
JsonNode last = messages.get(messages.size() - 1);
String lastUser = "";
for (JsonNode m : messages) if ("user".equals(m.path("role").asText())) lastUser = text(m.get("content"));
ObjectNode message = JSON.createObjectNode().put("role", "assistant");
String finish = "stop";
if ("tool".equals(last.path("role").asText())) {
message.put("content", "STUB-ANSWER (from tool): " + text(last.get("content")));
} else if (req.has("tools") && req.get("tools").size() > 0 && ORDER.matcher(lastUser).find()) {
Matcher m = ORDER.matcher(lastUser);
m.find();
JsonNode fn = req.get("tools").get(0).get("function");
String param = fn.get("parameters").get("properties").fieldNames().next();
ObjectNode args = JSON.createObjectNode().put(param, m.group(1));
ObjectNode call = JSON.createObjectNode().put("id", "call_stub_1").put("type", "function");
call.set("function", JSON.createObjectNode().put("name", fn.get("name").asText()).put("arguments", args.toString()));
message.putNull("content");
message.set("tool_calls", JSON.createArrayNode().add(call));
finish = "tool_calls";
} else {
message.put("content", "STUB-ANSWER (echo): " + lastUser.replaceAll("\\s+", " "));
}
ObjectNode out = JSON.createObjectNode();
out.put("id", "chatcmpl-stub").put("object", "chat.completion").put("created", 1700000000L)
.put("model", req.path("model").asText("stub"));
ObjectNode choice = JSON.createObjectNode().put("index", 0).put("finish_reason", finish);
choice.set("message", message);
out.set("choices", JSON.createArrayNode().add(choice));
out.set("usage", JSON.createObjectNode().put("prompt_tokens", 1).put("completion_tokens", 1).put("total_tokens", 2));
return out;
}
static String text(JsonNode c) {
if (c == null || c.isNull()) return "";
if (c.isTextual()) return c.asText();
StringBuilder sb = new StringBuilder(); // content-parts form
for (JsonNode p : c) sb.append(p.path("text").asText());
return sb.toString();
}
static ObjectNode embeddings(JsonNode req) {
EMBED.incrementAndGet();
JsonNode in = req.get("input");
ArrayNode data = JSON.createArrayNode();
int i = 0;
if (in.isArray()) for (JsonNode s : in) data.add(vec(s.asText(), i++)); else data.add(vec(in.asText(), 0));
ObjectNode out = JSON.createObjectNode().put("object", "list").put("model", req.path("model").asText("stub-embed"));
out.set("data", data);
out.set("usage", JSON.createObjectNode().put("prompt_tokens", 1).put("total_tokens", 1));
return out;
}
static ObjectNode vec(String s, int index) {
double[] v = new double[DIMS];
for (String t : s.toLowerCase().split("[^a-z0-9]+")) {
if (t.length() <= 2 || STOP.contains(t)) continue;
t = t.replaceAll("(ed|ing|s)$", ""); // crude stemming: return/returned/returns
v[Math.floorMod(t.hashCode(), DIMS)] += 1;
}
double n = 0; for (double d : v) n += d * d;
n = Math.sqrt(n == 0 ? 1 : n);
ArrayNode a = JSON.createArrayNode();
for (double d : v) a.add(d / n);
ObjectNode o = JSON.createObjectNode().put("object", "embedding").put("index", index);
o.set("embedding", a);
return o;
}
}