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
+1
View File
@@ -11,6 +11,7 @@ the same facts, so the build fails when a claim stops being true.
| `agentic` | Agentic Workflows with LangChain4j: Sequential, Parallel, Loop and Supervisor Agents | the five workflow builders, state passing by key, supervisor JSON, error recovery |
| `advanced-rag` | Advanced RAG with LangChain4j: Query Transformation, Routing and Easy RAG | Easy RAG, query compression and expansion, query routing, minScore, content injection, chat-memory cost, `Result.sources()` |
| `local-tool-calling` | Tool Calling with Small Local Models: Which Ollama Models Actually Follow Your Schema? | six small Ollama models on the same MCP-served tool suite, scored for valid calls, schema violations, wrong values and spurious calls |
| `quarkus-vs-spring-ai` | Quarkus LangChain4j vs Spring AI: Same AI Service Built Twice | the same support assistant (system prompt, tool, RAG) in Quarkus 3.40 and Spring AI 2.1, wire-format diff, startup/memory numbers, Quarkus native image; standalone build with a stub LLM |
## Versions (verified on Maven Central, 2026-10-11)
+40
View File
@@ -0,0 +1,40 @@
# quarkus-vs-spring-ai
The same support assistant built twice: **Quarkus + Quarkus LangChain4j** and **Spring Boot + Spring AI**.
Companion to the ankurm.com post *Quarkus LangChain4j vs Spring AI: Same AI Service Built Twice*.
The assistant has a system prompt, one tool (`orderStatus`) and RAG over three policy files in `knowledge/`.
No API key is needed: both apps talk to `stub-llm`, a deterministic OpenAI-compatible stub (not a language model).
Timing numbers are therefore framework overhead only.
| Component | Version | Note |
|---|---|---|
| JDK | 25.0.5 (Temurin) | LTS; GraalVM for JDK 25.0.4 builds the native images |
| Quarkus | 3.40.1.1 | latest GA with a GA LangChain4j extension (Quarkus 4.0.1 is GA, its extension is 2.0.0.CR1) |
| Quarkus LangChain4j | 1.15.1 | brings LangChain4j 1.23.0 |
| Spring Boot | 4.2.0 | GA |
| Spring AI | 2.1.0 | GA |
## Run
```bash
export JAVA_HOME=/path/to/jdk-25
mvn install # builds both apps; the tests write output/11,12,21,22
scripts/start-stub.sh # stub LLM on :18089
java -Dquarkus.http.port=18080 -Dquarkus.langchain4j.openai.base-url=http://localhost:18089/v1 \
-jar quarkus-app/target/quarkus-app/quarkus-run.jar
curl 'localhost:18080/ask?q=Where+is+my+order+1001%3F'
```
`scripts/run-all.sh` regenerates all of `output/` (tests, wire capture, benchmarks; native step needs `GRAALVM_HOME`).
This module is a standalone Maven build: it is deliberately not part of the parent pom's `<modules>`.
## Layout
| Path | What |
|---|---|
| `quarkus-app/` | `SupportAssistant` (declarative AI service), `OrderTools`, `PolicyStore`, `PolicyRetrievalAugmentor` |
| `spring-ai-app/` | `AiConfig` (ChatClient, tools, `QuestionAnswerAdvisor`), `OrderTools`, `AskController` |
| `stub-llm/` | the OpenAI-compatible stub (chat completions and embeddings) |
| `scripts/` | `bench.py`, `wire.sh`, `run-all.sh` |
| `output/` | captured results the post quotes |
@@ -0,0 +1 @@
Returns policy: items can be returned within 30 days of delivery for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5 business days of the warehouse receiving the parcel.
@@ -0,0 +1 @@
Shipping policy: standard shipping takes 3 to 5 business days and is free for orders above 50 euros. Express shipping takes 1 to 2 business days and costs 9 euros. We ship to all EU countries and to Norway.
@@ -0,0 +1 @@
Warranty policy: every electronic product carries a 24 month warranty covering manufacturing defects. Accidental damage and water damage are not covered. Warranty claims need the original order number.
@@ -0,0 +1,4 @@
question: Where is my order 1001?
answer: STUB-ANSWER (from tool): Order 1001 is shipped on 2026-11-20, arriving in 2 days
chat requests sent to the stub for this question: 2
embedding requests for this question: 1
@@ -0,0 +1,4 @@
question: How many days do I have to return an item?
answer: STUB-ANSWER (echo): How many days do I have to return an item? Answer using the following information: Returns policy: items can be returned within 30 days of delivery for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5 business days of the warehouse receiving the parcel.
chat requests sent to the stub for this question: 1
embedding requests for this question: 1
@@ -0,0 +1,4 @@
question: Where is my order 1001?
answer: STUB-ANSWER (from tool): "Order 1001 is shipped on 2026-11-20, arriving in 2 days"
chat requests sent to the stub for this question: 2
embedding requests for this question: 2
@@ -0,0 +1,4 @@
question: How many days do I have to return an item?
answer: STUB-ANSWER (echo): How many days do I have to return an item? Context information is below, surrounded by --------------------- --------------------- Returns policy: items can be returned within 30 days of delivery for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5 business days of the warehouse receiving the parcel. --------------------- Given the context and provided history information and not prior knowledge, reply to the user comment. If the answer is not in the context, inform the user that you can't answer the question.
chat requests sent to the stub for this question: 1
embedding requests for this question: 1
@@ -0,0 +1,33 @@
##### quarkus: 3 chat requests for 2 questions
--- request 1: top-level keys = ['frequency_penalty', 'messages', 'model', 'presence_penalty', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'Where is my order 1001?'
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}}, "type": "function"}]
--- request 2: top-level keys = ['frequency_penalty', 'messages', 'model', 'presence_penalty', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'Where is my order 1001?'
[assistant] 'None' tool_calls=[{"id": "call_stub_1", "type": "function", "function": {"name": "orderStatus", "arguments": "{\"orderId\":\"1001\"}"}}]
[tool] 'Order 1001 is shipped on 2026-11-20, arriving in 2 days'
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}}, "type": "function"}]
--- request 3: top-level keys = ['frequency_penalty', 'messages', 'model', 'presence_penalty', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'How many days do I have to return an item?\n\nAnswer using the following information:\nReturns policy: items can '
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}}, "type": "function"}]
##### spring: 3 chat requests for 2 questions
--- request 1: top-level keys = ['messages', 'model', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'Where is my order 1001?\n\nContext information is below, surrounded by ---------------------\n\n------------------'
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}, "strict": false}, "type": "function"}]
--- request 2: top-level keys = ['messages', 'model', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'Where is my order 1001?\n\nContext information is below, surrounded by ---------------------\n\n------------------'
[assistant] '' tool_calls=[{"id": "call_stub_1", "function": {"arguments": "{\"orderId\":\"1001\"}", "name": "orderStatus"}, "type": "function"}]
[tool] '"Order 1001 is shipped on 2026-11-20, arriving in 2 days"'
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}, "strict": false}, "type": "function"}]
--- request 3: top-level keys = ['messages', 'model', 'tools']
[system] 'You are the support assistant of an online electronics shop. Answer in one sentence. Use the order tool for or'
[user] 'How many days do I have to return an item?\n\nContext information is below, surrounded by ---------------------\n'
tools: [{"function": {"description": "Looks up the delivery status of a customer order by its order number", "name": "orderStatus", "parameters": {"$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": {"orderId": {"description": "the numeric order number, for example 1001", "type": "string"}}, "required": ["orderId"], "type": "object"}, "strict": false}, "type": "function"}]
tool declaration identical: False
@@ -0,0 +1,23 @@
host: 2 cpus, load average at start 0.2 (other processes were running)
== quarkus-jvm (7 runs)
metric run1 run2 run3 run4 run5 run6 run7 median
t_port 2190 1594 1545 1386 1433 1454 1563 1545
t_first 2600 1922 1851 1641 1695 1735 1907 1851
cpu_first 3350 3030 2980 2720 2750 2860 3160 2980
rss_first 146.3 147.4 145.4 143.8 133.6 140.9 145.9 145.4
rss_after 172.4 173.5 168.2 174.1 170.1 172.5 169.5 172.4
p50 13.3 10.0 11.2 11.8 11.1 10.8 10.7 11.1
p95 28.2 23.2 24.3 23.7 23.9 18.2 21.7 23.7
== spring-jvm (7 runs)
metric run1 run2 run3 run4 run5 run6 run7 median
t_port 11053 4949 4816 4776 5049 4818 5345 4949
t_first 12002 5635 5548 5598 6065 5656 6277 5656
cpu_first 11770 10160 10280 10090 11150 10050 11490 10280
rss_first 301.2 300.2 326.2 306.5 326.4 308.1 300.0 306.5
rss_after 313.8 312.8 337.7 321.0 335.6 318.4 312.0 318.4
p50 11.2 9.6 10.3 10.5 8.6 9.9 9.4 9.9
p95 23.6 22.0 23.0 25.7 20.7 22.8 22.8 22.8
load average at end 2.2
@@ -0,0 +1,13 @@
host: 2 cpus, load average at start 0.2 (other processes were running)
== quarkus-native (7 runs)
metric run1 run2 run3 run4 run5 run6 run7 median
t_port 30 33 38 33 39 33 27 33
t_first 58 42 51 44 52 42 36 44
cpu_first 20 30 40 30 30 30 30 30
rss_first 52.0 51.9 51.9 51.9 52.1 51.9 51.9 51.9
rss_after 96.8 94.4 96.7 93.8 97.0 96.7 96.6 96.7
p50 3.6 3.5 3.4 3.5 3.1 3.2 3.3 3.4
p95 5.7 5.8 5.0 5.0 5.9 4.6 4.7 5.0
load average at end 0.3
@@ -0,0 +1,7 @@
Spring Boot 4.2.0 / Spring AI 2.1.0 native-image attempt (GraalVM for JDK 25.0.4, 2 CPUs, 8 GB host)
command: mvn -Pnative -DskipTests native:compile
Build resources:
- 4.87GB of memory (75.6% of system memory, in container)
- 2 thread(s) (100.0% of 2 available processor(s), determined at start)
Terminating due to java.lang.OutOfMemoryError: Java heap space
The Native Image build process ran out of memory.
+7
View File
@@ -0,0 +1,7 @@
Quarkus JVM (fast-jar) directory : 27964 KiB, 125 jars in lib/main
Spring Boot executable jar : 135777615 bytes, 120 nested jars
Quarkus native executable : 72223056 bytes
Quarkus native build time : 6m 25s (native-image step, 2 CPUs; a first attempt on a busier host took 15m 40s)
Largest Spring nested jar : openai-java-core-4.101.0.jar, 74924097 bytes
Quarkus native, self-reported : quarkus-app 1.0.0 native (powered by Quarkus 3.40.1.1) started in 0.087s
Quarkus dev mode, self-reported : quarkus-app 1.0.0 on JVM (powered by Quarkus 3.40.1.1) started in 4.303s. | Profile dev activated. Live Coding activated.
@@ -0,0 +1,7 @@
$ curl -s localhost:18080/q/dev-ui/quarkus-langchain4j-core-data.js # while running: mvn quarkus:dev
// Generated by Quarkus during Build
export const systemMessages = ["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."];
export const toolProviders = [];
export const aiservices = [{"clazz":"com.ankurm.qvs.SupportAssistant","tools":["com.ankurm.qvs.OrderTools"]}];
export const tools = [{"className":"com.ankurm.qvs.OrderTools","name":"orderStatus","description":"Looks up the delivery status of a customer order by its order number"}];
export const envVarMappings = {"OPENAI_API_KEY":"quarkus.langchain4j.openai.api-key"};
@@ -0,0 +1,29 @@
{
"model" : "stub-chat",
"messages" : [ {
"role" : "system",
"content" : "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."
}, {
"role" : "user",
"content" : "Where is my order 1001?"
} ],
"presence_penalty" : 0.0,
"frequency_penalty" : 0.0,
"tools" : [ {
"type" : "function",
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ]
}
}
} ]
}
@@ -0,0 +1,43 @@
{
"model" : "stub-chat",
"messages" : [ {
"role" : "system",
"content" : "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."
}, {
"role" : "user",
"content" : "Where is my order 1001?"
}, {
"role" : "assistant",
"tool_calls" : [ {
"id" : "call_stub_1",
"type" : "function",
"function" : {
"name" : "orderStatus",
"arguments" : "{\"orderId\":\"1001\"}"
}
} ]
}, {
"role" : "tool",
"tool_call_id" : "call_stub_1",
"content" : "Order 1001 is shipped on 2026-11-20, arriving in 2 days"
} ],
"presence_penalty" : 0.0,
"frequency_penalty" : 0.0,
"tools" : [ {
"type" : "function",
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ]
}
}
} ]
}
@@ -0,0 +1,29 @@
{
"model" : "stub-chat",
"messages" : [ {
"role" : "system",
"content" : "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."
}, {
"role" : "user",
"content" : "How many days do I have to return an item?\n\nAnswer using the following information:\nReturns policy: items can be returned within 30 days of delivery for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5 business days of the warehouse receiving the parcel."
} ],
"presence_penalty" : 0.0,
"frequency_penalty" : 0.0,
"tools" : [ {
"type" : "function",
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ]
}
}
} ]
}
@@ -0,0 +1,30 @@
{
"messages" : [ {
"content" : "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.",
"role" : "system"
}, {
"content" : "Where is my order 1001?\n\nContext information is below, surrounded by ---------------------\n\n---------------------\n---------------------\n\nGiven the context and provided history information and not prior knowledge,\nreply to the user comment. If the answer is not in the context, inform\nthe user that you can't answer the question.\n",
"role" : "user"
} ],
"model" : "stub-chat",
"tools" : [ {
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ],
"additionalProperties" : false
},
"strict" : false
},
"type" : "function"
} ]
}
@@ -0,0 +1,45 @@
{
"messages" : [ {
"content" : "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.",
"role" : "system"
}, {
"content" : "Where is my order 1001?\n\nContext information is below, surrounded by ---------------------\n\n---------------------\n---------------------\n\nGiven the context and provided history information and not prior knowledge,\nreply to the user comment. If the answer is not in the context, inform\nthe user that you can't answer the question.\n",
"role" : "user"
}, {
"role" : "assistant",
"content" : "",
"tool_calls" : [ {
"id" : "call_stub_1",
"function" : {
"arguments" : "{\"orderId\":\"1001\"}",
"name" : "orderStatus"
},
"type" : "function"
} ]
}, {
"content" : "\"Order 1001 is shipped on 2026-11-20, arriving in 2 days\"",
"role" : "tool",
"tool_call_id" : "call_stub_1"
} ],
"model" : "stub-chat",
"tools" : [ {
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ],
"additionalProperties" : false
},
"strict" : false
},
"type" : "function"
} ]
}
@@ -0,0 +1,30 @@
{
"messages" : [ {
"content" : "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.",
"role" : "system"
}, {
"content" : "How many days do I have to return an item?\n\nContext information is below, surrounded by ---------------------\n\n---------------------\nReturns policy: items can be returned within 30 days of delivery for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5 business days of the warehouse receiving the parcel.\n---------------------\n\nGiven the context and provided history information and not prior knowledge,\nreply to the user comment. If the answer is not in the context, inform\nthe user that you can't answer the question.\n",
"role" : "user"
} ],
"model" : "stub-chat",
"tools" : [ {
"function" : {
"name" : "orderStatus",
"description" : "Looks up the delivery status of a customer order by its order number",
"parameters" : {
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"orderId" : {
"type" : "string",
"description" : "the numeric order number, for example 1001"
}
},
"required" : [ "orderId" ],
"additionalProperties" : false
},
"strict" : false
},
"type" : "function"
} ]
}
+21
View File
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Standalone aggregator: Quarkus and Spring Boot each bring their own BOM, so this module is
deliberately NOT a child of the repository's parent pom and is not listed in its <modules>. -->
<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>
<groupId>com.ankurm.qvs</groupId>
<artifactId>quarkus-vs-spring-ai</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>stub-llm</module>
<module>quarkus-app</module>
<module>spring-ai-app</module>
</modules>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
+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);
}
}
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""
Startup / memory / latency harness. Runs every app RUNS times against the stub LLM, interleaved
(quarkus, spring, quarkus, spring, ...) so both see the same background load.
RUNS=7 python3 scripts/bench.py # needs the stub on :18089 (scripts/start-stub.sh)
Measured per run:
t_port ms from process launch until the app's TCP port accepts a connection
t_first ms from process launch until GET /ask?q=... returns 200 (first answered request)
cpu_first CPU milliseconds (user+sys, from /proc) consumed by then; far less sensitive to a busy host than wall time
rss_first RSS in MiB right after that first answer
rss_after RSS in MiB after 300 further requests (a mix of tool, RAG and plain questions)
p50 / p95 latency in ms over those 300 sequential requests
The model is a local stub, so these numbers are framework overhead and nothing else.
"""
import os, socket, statistics, subprocess, sys, time, urllib.parse, urllib.request
RUNS = int(os.environ.get("RUNS", "5"))
PORT = int(os.environ.get("APP_PORT", "18080"))
STUB = "http://localhost:18089/v1"
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
QUESTIONS = ["Where is my order 1001?", "How many days do I have to return an item?", "What is the weather in Paris"]
APPS = {
"quarkus-jvm": ["java", f"-Dquarkus.http.port={PORT}", f"-Dquarkus.langchain4j.openai.base-url={STUB}",
"-jar", f"{ROOT}/quarkus-app/target/quarkus-app/quarkus-run.jar"],
"spring-jvm": ["java", f"-Dserver.port={PORT}", f"-Dspring.ai.openai.base-url={STUB}",
"-jar", f"{ROOT}/spring-ai-app/target/spring-ai-app-1.0.0.jar"],
}
NATIVE = f"{ROOT}/quarkus-app/target/quarkus-app-1.0.0-runner"
if os.path.exists(NATIVE):
APPS["quarkus-native"] = [NATIVE, f"-Dquarkus.http.port={PORT}", f"-Dquarkus.langchain4j.openai.base-url={STUB}"]
if os.environ.get("ONLY"):
APPS = {k: v for k, v in APPS.items() if k in os.environ["ONLY"].split(",")}
def rss_mib(pid):
for line in open(f"/proc/{pid}/status"):
if line.startswith("VmRSS"):
return int(line.split()[1]) / 1024
def cpu_ms(pid):
f = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()
return (int(f[11]) + int(f[12])) * 1000 / os.sysconf("SC_CLK_TCK")
def ask(q):
with urllib.request.urlopen(f"http://localhost:{PORT}/ask?q=" + urllib.parse.quote(q), timeout=10) as r:
assert r.status == 200
return r.read()
def one_run(cmd):
t0 = time.perf_counter()
p = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
try:
while True:
try:
socket.create_connection(("localhost", PORT), timeout=0.05).close()
t_port = (time.perf_counter() - t0) * 1000
break
except OSError:
time.sleep(0.005)
if time.perf_counter() - t0 > 90:
raise SystemExit("app did not start")
while True:
try:
ask(QUESTIONS[0]); break
except Exception:
time.sleep(0.005)
t_first = (time.perf_counter() - t0) * 1000
rss_first, cpu_first = rss_mib(p.pid), cpu_ms(p.pid)
lat = []
for i in range(300):
s = time.perf_counter()
ask(QUESTIONS[i % 3])
lat.append((time.perf_counter() - s) * 1000)
lat.sort()
return dict(t_port=t_port, t_first=t_first, cpu_first=cpu_first, rss_first=rss_first,
rss_after=rss_mib(p.pid), p50=lat[149], p95=lat[284])
finally:
p.kill(); p.wait()
time.sleep(1.0)
def main():
print(f"host: {os.cpu_count()} cpus, load average at start {os.getloadavg()[0]:.1f} (other processes were running)")
rows = {name: [] for name in APPS}
for _ in range(RUNS):
for name, cmd in APPS.items():
rows[name].append(one_run(cmd))
for name, rs in rows.items():
print(f"\n== {name} ({RUNS} runs)")
print(f"{'metric':10s} " + " ".join(f"{'run'+str(i+1):>7s}" for i in range(RUNS)) + f" {'median':>8s}")
for k in ["t_port", "t_first", "cpu_first", "rss_first", "rss_after", "p50", "p95"]:
vals = [r[k] for r in rs]
fmt = "{:7.1f}" if k in ("rss_first", "rss_after", "p50", "p95") else "{:7.0f}"
print(f"{k:10s} " + " ".join(fmt.format(v) for v in vals) + " " + fmt.format(statistics.median(vals)).rjust(8))
print(f"\nload average at end {os.getloadavg()[0]:.1f}")
main()
+21
View File
@@ -0,0 +1,21 @@
# Shared helpers. Everything uses ports 18080 (app) and 18089 (stub) so it does not fight a dev server on 8080.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
STUB_URL="http://localhost:18089/v1"
Q_JAR="$ROOT/quarkus-app/target/quarkus-app/quarkus-run.jar"
S_JAR="$ROOT/spring-ai-app/target/spring-ai-app-1.0.0.jar"
STUB_JAR="$ROOT/stub-llm/target/stub-llm-1.0.0.jar"
# kill_jar <jar path>: kills by the jar's absolute path (never by a generic pattern like "spring-boot")
kill_jar() { for p in $(ps -eo pid,args | grep -F -- "$1" | grep -v grep | awk '{print $1}'); do kill -9 "$p" 2>/dev/null; done; }
start_stub() { # start_stub [record-dir]
kill_jar "$STUB_JAR"
local opts="-Dstub.port=18089"; [ -n "${1:-}" ] && opts="$opts -Dstub.record.dir=$1"
setsid nohup java $opts -jar "$STUB_JAR" > /tmp/stub-llm.log 2>&1 < /dev/null &
for i in $(seq 1 50); do curl -s localhost:18089/stats >/dev/null && return 0; sleep 0.2; done; return 1
}
start_quarkus() { setsid nohup java -Dquarkus.http.port=18080 -Dquarkus.langchain4j.openai.base-url=$STUB_URL -jar "$Q_JAR" > /tmp/quarkus-app.log 2>&1 < /dev/null & wait_app; }
start_spring() { setsid nohup java -Dserver.port=18080 -Dspring.ai.openai.base-url=$STUB_URL -jar "$S_JAR" > /tmp/spring-app.log 2>&1 < /dev/null & wait_app; }
wait_app() { for i in $(seq 1 300); do curl -s -o /dev/null "localhost:18080/ask?q=ping" && return 0; sleep 0.2; done; return 1; }
ask() { curl -s --get --data-urlencode "q=$1" localhost:18080/ask; echo; }
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Regenerates everything in output/. Needs JDK 25 on PATH. The native step needs GraalVM 25 (set GRAALVM_HOME) and is skipped without it.
set -eu
source "$(dirname "$0")/lib.sh"
cd "$ROOT"
mvn -B -q install # tests write output/11,12,21,22
scripts/wire.sh > /dev/null # output/30-wire-summary.txt and output/wire/*
start_stub
RUNS="${RUNS:-7}" ONLY=quarkus-jvm,spring-jvm python3 scripts/bench.py > output/40-bench-jvm.txt
if [ -n "${GRAALVM_HOME:-}" ]; then
(cd quarkus-app && JAVA_HOME="$GRAALVM_HOME" PATH="$GRAALVM_HOME/bin:$PATH" mvn -B -q -DskipTests \
-Dquarkus.native.enabled=true -Dquarkus.native.native-image-xmx=3g package)
RUNS="${RUNS:-7}" ONLY=quarkus-native python3 scripts/bench.py > output/41-bench-native.txt
fi
kill_jar "$STUB_JAR"
ls -la output
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
# Starts the stub LLM on :18089 in the background (optional arg: directory to record request bodies into).
source "$(dirname "$0")/lib.sh"
start_stub "${1:-}"
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Captures the HTTP requests each framework sends to the "LLM" for the same two questions.
set -u
source "$(dirname "$0")/lib.sh"
OUT="$ROOT/output/wire"; mkdir -p "$OUT/quarkus" "$OUT/spring"
for side in quarkus spring; do
rm -f "$OUT/$side"/*.json
start_stub "$OUT/$side" || { echo "stub failed"; exit 1; }
if [ $side = quarkus ]; then start_quarkus; else start_spring; fi
rm -f "$OUT/$side"/*.json && curl -s localhost:18089/stats >/dev/null # drop the readiness probe
ask "Where is my order 1001?" > /dev/null
ask "How many days do I have to return an item?" > /dev/null
[ $side = quarkus ] && kill_jar "$Q_JAR" || kill_jar "$S_JAR"
kill_jar "$STUB_JAR"; sleep 1
done
python3 "$ROOT/scripts/wire_summary.py" "$OUT" > "$ROOT/output/30-wire-summary.txt"
cat "$ROOT/output/30-wire-summary.txt"
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Summarises the recorded chat requests of both apps: shape, tool declaration, and prompt text."""
import glob, json, sys
root = sys.argv[1]
def load(side):
return [json.load(open(f)) for f in sorted(glob.glob(f"{root}/{side}/*-chat.json"))]
def show(side, reqs):
print(f"##### {side}: {len(reqs)} chat requests for 2 questions")
for i, r in enumerate(reqs, 1):
print(f"--- request {i}: top-level keys = {sorted(r)}")
for m in r["messages"]:
c = m.get("content")
if isinstance(c, list):
c = "".join(p.get("text", "") for p in c)
extra = f" tool_calls={json.dumps(m['tool_calls'])}" if m.get("tool_calls") else ""
print(f" [{m['role']}] {str(c)[:110]!r}{extra}")
if r.get("tools"):
print(" tools:", json.dumps(r["tools"], sort_keys=True))
print()
q, s = load("quarkus"), load("spring")
show("quarkus", q)
show("spring", s)
qt = [r["tools"] for r in q if r.get("tools")][0]
st = [r["tools"] for r in s if r.get("tools")][0]
print("tool declaration identical:", qt == st)
@@ -0,0 +1,81 @@
<?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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.qvs</groupId>
<artifactId>spring-ai-app</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
<spring-ai.version>2.1.0</spring-ai.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-vector-store-advisor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</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>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration><parameters>true</parameters></configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,53 @@
package com.ankurm.qvs;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* Spring AI has no "declare an interface" step. The equivalent of the Quarkus AI service is a
* ChatClient built from a builder: system prompt, tools and the RAG advisor are wired in code.
*/
@Configuration
public class AiConfig {
static final List<String> FILES = List.of("returns.txt", "shipping.txt", "warranty.txt");
@Bean
VectorStore policyStore(EmbeddingModel embeddingModel) throws IOException {
SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build();
List<Document> docs = new ArrayList<>();
for (String f : FILES) {
try (InputStream in = getClass().getResourceAsStream("/knowledge/" + f)) {
docs.add(new Document(new String(in.readAllBytes(), StandardCharsets.UTF_8).trim()));
}
}
store.add(docs);
return store;
}
@Bean
ChatClient supportAssistant(ChatClient.Builder builder, VectorStore policyStore, OrderTools tools) {
return builder
.defaultSystem("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.")
.defaultTools(tools)
.defaultAdvisors(QuestionAnswerAdvisor.builder(policyStore)
.searchRequest(SearchRequest.builder().topK(1).similarityThreshold(0.3).build())
.build())
.build();
}
}
@@ -0,0 +1,21 @@
package com.ankurm.qvs;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AskController {
private final ChatClient assistant;
AskController(ChatClient supportAssistant) {
this.assistant = supportAssistant;
}
@GetMapping(value = "/ask", produces = "text/plain")
String ask(@RequestParam("q") String q) {
return assistant.prompt().user(q).call().content();
}
}
@@ -0,0 +1,21 @@
package com.ankurm.qvs;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import java.util.Map;
/** The one tool both apps expose. Quarkus twin: quarkus-app/.../OrderTools.java. */
@Component
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(description = "Looks up the delivery status of a customer order by its order number")
public String orderStatus(@ToolParam(description = "the numeric order number, for example 1001") String orderId) {
return "Order " + orderId + " is " + ORDERS.getOrDefault(orderId, "unknown");
}
}
@@ -0,0 +1,11 @@
package com.ankurm.qvs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringAiApp {
public static void main(String[] args) {
SpringApplication.run(SpringAiApp.class, args);
}
}
@@ -0,0 +1,6 @@
# Point the OpenAI client at the stub. Swap base-url and api-key to use the real thing.
spring.ai.openai.base-url=http://localhost:8089/v1
spring.ai.openai.api-key=stub
spring.ai.openai.chat.options.model=stub-chat
spring.ai.openai.embedding.options.model=stub-embed
server.port=8080
@@ -0,0 +1,88 @@
package com.ankurm.qvs;
import com.ankurm.stub.StubLlmServer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
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 org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@SpringBootTest
@AutoConfigureMockMvc
class SupportAssistantTest {
static {
try {
StubLlmServer.start(8089); // must be up before the context embeds the policies
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Autowired
MockMvc mvc;
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 chatCount(String stats) {
return Integer.parseInt(stats.replaceAll(".*\"chat\":(\\d+).*", "$1"));
}
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");
}
String ask(String q) throws Exception {
return mvc.perform(get("/ask").param("q", q)).andReturn().getResponse().getContentAsString();
}
@Test
void orderQuestionCallsTheTool() throws Exception {
String q = "Where is my order 1001?";
String before = stats();
String answer = ask(q);
write("21-spring-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 = ask(q);
write("22-spring-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");
}
@Test
void unrelatedQuestionGetsNoContext() throws Exception {
assertFalse(ask("What is the weather in Paris").contains("policy:"));
}
}
+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;
}
}