From 5e5326c8106baaf2762463b7064ec30277396a25 Mon Sep 17 00:00:00 2001 From: asmhatre Date: Fri, 27 Nov 2026 00:05:25 +0530 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017ic4b4XrpfdpsacrvqnrBM --- README.md | 1 + quarkus-vs-spring-ai/README.md | 40 +++++ quarkus-vs-spring-ai/knowledge/returns.txt | 1 + quarkus-vs-spring-ai/knowledge/shipping.txt | 1 + quarkus-vs-spring-ai/knowledge/warranty.txt | 1 + .../output/11-quarkus-tool-call.txt | 4 + .../output/12-quarkus-rag.txt | 4 + .../output/21-spring-tool-call.txt | 4 + quarkus-vs-spring-ai/output/22-spring-rag.txt | 4 + .../output/30-wire-summary.txt | 33 ++++ quarkus-vs-spring-ai/output/40-bench-jvm.txt | 23 +++ .../output/41-bench-native.txt | 13 ++ .../output/42-spring-native-attempt.txt | 7 + quarkus-vs-spring-ai/output/43-sizes.txt | 7 + .../output/50-quarkus-devui-data.txt | 7 + .../output/wire/quarkus/002-chat.json | 29 ++++ .../output/wire/quarkus/003-chat.json | 43 +++++ .../output/wire/quarkus/004-chat.json | 29 ++++ .../output/wire/spring/002-chat.json | 30 ++++ .../output/wire/spring/003-chat.json | 45 +++++ .../output/wire/spring/004-chat.json | 30 ++++ quarkus-vs-spring-ai/pom.xml | 21 +++ quarkus-vs-spring-ai/quarkus-app/pom.xml | 108 ++++++++++++ .../main/java/com/ankurm/qvs/AskResource.java | 23 +++ .../main/java/com/ankurm/qvs/OrderTools.java | 21 +++ .../ankurm/qvs/PolicyRetrievalAugmentor.java | 32 ++++ .../main/java/com/ankurm/qvs/PolicyStore.java | 44 +++++ .../java/com/ankurm/qvs/SupportAssistant.java | 17 ++ .../src/main/resources/application.properties | 9 + .../java/com/ankurm/qvs/StubResource.java | 27 +++ .../com/ankurm/qvs/SupportAssistantTest.java | 72 ++++++++ quarkus-vs-spring-ai/scripts/bench.py | 99 +++++++++++ quarkus-vs-spring-ai/scripts/lib.sh | 21 +++ quarkus-vs-spring-ai/scripts/run-all.sh | 16 ++ quarkus-vs-spring-ai/scripts/start-stub.sh | 4 + quarkus-vs-spring-ai/scripts/wire.sh | 17 ++ quarkus-vs-spring-ai/scripts/wire_summary.py | 28 ++++ quarkus-vs-spring-ai/spring-ai-app/pom.xml | 81 +++++++++ .../main/java/com/ankurm/qvs/AiConfig.java | 53 ++++++ .../java/com/ankurm/qvs/AskController.java | 21 +++ .../main/java/com/ankurm/qvs/OrderTools.java | 21 +++ .../main/java/com/ankurm/qvs/SpringAiApp.java | 11 ++ .../src/main/resources/application.properties | 6 + .../com/ankurm/qvs/SupportAssistantTest.java | 88 ++++++++++ quarkus-vs-spring-ai/stub-llm/pom.xml | 42 +++++ .../java/com/ankurm/stub/StubLlmServer.java | 157 ++++++++++++++++++ 46 files changed, 1395 insertions(+) create mode 100644 quarkus-vs-spring-ai/README.md create mode 100644 quarkus-vs-spring-ai/knowledge/returns.txt create mode 100644 quarkus-vs-spring-ai/knowledge/shipping.txt create mode 100644 quarkus-vs-spring-ai/knowledge/warranty.txt create mode 100644 quarkus-vs-spring-ai/output/11-quarkus-tool-call.txt create mode 100644 quarkus-vs-spring-ai/output/12-quarkus-rag.txt create mode 100644 quarkus-vs-spring-ai/output/21-spring-tool-call.txt create mode 100644 quarkus-vs-spring-ai/output/22-spring-rag.txt create mode 100644 quarkus-vs-spring-ai/output/30-wire-summary.txt create mode 100644 quarkus-vs-spring-ai/output/40-bench-jvm.txt create mode 100644 quarkus-vs-spring-ai/output/41-bench-native.txt create mode 100644 quarkus-vs-spring-ai/output/42-spring-native-attempt.txt create mode 100644 quarkus-vs-spring-ai/output/43-sizes.txt create mode 100644 quarkus-vs-spring-ai/output/50-quarkus-devui-data.txt create mode 100644 quarkus-vs-spring-ai/output/wire/quarkus/002-chat.json create mode 100644 quarkus-vs-spring-ai/output/wire/quarkus/003-chat.json create mode 100644 quarkus-vs-spring-ai/output/wire/quarkus/004-chat.json create mode 100644 quarkus-vs-spring-ai/output/wire/spring/002-chat.json create mode 100644 quarkus-vs-spring-ai/output/wire/spring/003-chat.json create mode 100644 quarkus-vs-spring-ai/output/wire/spring/004-chat.json create mode 100644 quarkus-vs-spring-ai/pom.xml create mode 100644 quarkus-vs-spring-ai/quarkus-app/pom.xml create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/AskResource.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/OrderTools.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyRetrievalAugmentor.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyStore.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/SupportAssistant.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/main/resources/application.properties create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/StubResource.java create mode 100644 quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java create mode 100644 quarkus-vs-spring-ai/scripts/bench.py create mode 100755 quarkus-vs-spring-ai/scripts/lib.sh create mode 100755 quarkus-vs-spring-ai/scripts/run-all.sh create mode 100755 quarkus-vs-spring-ai/scripts/start-stub.sh create mode 100755 quarkus-vs-spring-ai/scripts/wire.sh create mode 100644 quarkus-vs-spring-ai/scripts/wire_summary.py create mode 100644 quarkus-vs-spring-ai/spring-ai-app/pom.xml create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AiConfig.java create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AskController.java create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/OrderTools.java create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/SpringAiApp.java create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/main/resources/application.properties create mode 100644 quarkus-vs-spring-ai/spring-ai-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java create mode 100644 quarkus-vs-spring-ai/stub-llm/pom.xml create mode 100644 quarkus-vs-spring-ai/stub-llm/src/main/java/com/ankurm/stub/StubLlmServer.java diff --git a/README.md b/README.md index 6a89e4b..1dfc31d 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/quarkus-vs-spring-ai/README.md b/quarkus-vs-spring-ai/README.md new file mode 100644 index 0000000..f2694ed --- /dev/null +++ b/quarkus-vs-spring-ai/README.md @@ -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 ``. + +## 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 | diff --git a/quarkus-vs-spring-ai/knowledge/returns.txt b/quarkus-vs-spring-ai/knowledge/returns.txt new file mode 100644 index 0000000..7e79e5d --- /dev/null +++ b/quarkus-vs-spring-ai/knowledge/returns.txt @@ -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. diff --git a/quarkus-vs-spring-ai/knowledge/shipping.txt b/quarkus-vs-spring-ai/knowledge/shipping.txt new file mode 100644 index 0000000..fbebc4e --- /dev/null +++ b/quarkus-vs-spring-ai/knowledge/shipping.txt @@ -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. diff --git a/quarkus-vs-spring-ai/knowledge/warranty.txt b/quarkus-vs-spring-ai/knowledge/warranty.txt new file mode 100644 index 0000000..9afe550 --- /dev/null +++ b/quarkus-vs-spring-ai/knowledge/warranty.txt @@ -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. diff --git a/quarkus-vs-spring-ai/output/11-quarkus-tool-call.txt b/quarkus-vs-spring-ai/output/11-quarkus-tool-call.txt new file mode 100644 index 0000000..9b69ec1 --- /dev/null +++ b/quarkus-vs-spring-ai/output/11-quarkus-tool-call.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/12-quarkus-rag.txt b/quarkus-vs-spring-ai/output/12-quarkus-rag.txt new file mode 100644 index 0000000..03dc566 --- /dev/null +++ b/quarkus-vs-spring-ai/output/12-quarkus-rag.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/21-spring-tool-call.txt b/quarkus-vs-spring-ai/output/21-spring-tool-call.txt new file mode 100644 index 0000000..32433cb --- /dev/null +++ b/quarkus-vs-spring-ai/output/21-spring-tool-call.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/22-spring-rag.txt b/quarkus-vs-spring-ai/output/22-spring-rag.txt new file mode 100644 index 0000000..f46f5dc --- /dev/null +++ b/quarkus-vs-spring-ai/output/22-spring-rag.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/30-wire-summary.txt b/quarkus-vs-spring-ai/output/30-wire-summary.txt new file mode 100644 index 0000000..fd823aa --- /dev/null +++ b/quarkus-vs-spring-ai/output/30-wire-summary.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/40-bench-jvm.txt b/quarkus-vs-spring-ai/output/40-bench-jvm.txt new file mode 100644 index 0000000..38200a5 --- /dev/null +++ b/quarkus-vs-spring-ai/output/40-bench-jvm.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/41-bench-native.txt b/quarkus-vs-spring-ai/output/41-bench-native.txt new file mode 100644 index 0000000..92cbf5e --- /dev/null +++ b/quarkus-vs-spring-ai/output/41-bench-native.txt @@ -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 diff --git a/quarkus-vs-spring-ai/output/42-spring-native-attempt.txt b/quarkus-vs-spring-ai/output/42-spring-native-attempt.txt new file mode 100644 index 0000000..0295a2e --- /dev/null +++ b/quarkus-vs-spring-ai/output/42-spring-native-attempt.txt @@ -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. diff --git a/quarkus-vs-spring-ai/output/43-sizes.txt b/quarkus-vs-spring-ai/output/43-sizes.txt new file mode 100644 index 0000000..4bfaf6d --- /dev/null +++ b/quarkus-vs-spring-ai/output/43-sizes.txt @@ -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. diff --git a/quarkus-vs-spring-ai/output/50-quarkus-devui-data.txt b/quarkus-vs-spring-ai/output/50-quarkus-devui-data.txt new file mode 100644 index 0000000..013e415 --- /dev/null +++ b/quarkus-vs-spring-ai/output/50-quarkus-devui-data.txt @@ -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"}; diff --git a/quarkus-vs-spring-ai/output/wire/quarkus/002-chat.json b/quarkus-vs-spring-ai/output/wire/quarkus/002-chat.json new file mode 100644 index 0000000..f8cdb62 --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/quarkus/002-chat.json @@ -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" ] + } + } + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/output/wire/quarkus/003-chat.json b/quarkus-vs-spring-ai/output/wire/quarkus/003-chat.json new file mode 100644 index 0000000..477e3d1 --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/quarkus/003-chat.json @@ -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" ] + } + } + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/output/wire/quarkus/004-chat.json b/quarkus-vs-spring-ai/output/wire/quarkus/004-chat.json new file mode 100644 index 0000000..2cac185 --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/quarkus/004-chat.json @@ -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" ] + } + } + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/output/wire/spring/002-chat.json b/quarkus-vs-spring-ai/output/wire/spring/002-chat.json new file mode 100644 index 0000000..4e7d876 --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/spring/002-chat.json @@ -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" + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/output/wire/spring/003-chat.json b/quarkus-vs-spring-ai/output/wire/spring/003-chat.json new file mode 100644 index 0000000..e76d6ef --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/spring/003-chat.json @@ -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" + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/output/wire/spring/004-chat.json b/quarkus-vs-spring-ai/output/wire/spring/004-chat.json new file mode 100644 index 0000000..7e31fe0 --- /dev/null +++ b/quarkus-vs-spring-ai/output/wire/spring/004-chat.json @@ -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" + } ] +} \ No newline at end of file diff --git a/quarkus-vs-spring-ai/pom.xml b/quarkus-vs-spring-ai/pom.xml new file mode 100644 index 0000000..354c852 --- /dev/null +++ b/quarkus-vs-spring-ai/pom.xml @@ -0,0 +1,21 @@ + + + + 4.0.0 + com.ankurm.qvs + quarkus-vs-spring-ai + 1.0.0 + pom + + stub-llm + quarkus-app + spring-ai-app + + + 25 + UTF-8 + + diff --git a/quarkus-vs-spring-ai/quarkus-app/pom.xml b/quarkus-vs-spring-ai/quarkus-app/pom.xml new file mode 100644 index 0000000..825fd3f --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + com.ankurm.qvs + quarkus-vs-spring-ai + 1.0.0 + + quarkus-app + + + 3.40.1.1 + 1.15.1 + + + + + + io.quarkus.platform + quarkus-bom + ${quarkus.platform.version} + pom + import + + + io.quarkiverse.langchain4j + quarkus-langchain4j-bom + ${quarkus-langchain4j.version} + pom + import + + + + + + + io.quarkiverse.langchain4j + quarkus-langchain4j-openai + + + io.quarkus + quarkus-rest + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + com.ankurm.qvs + stub-llm + ${project.version} + test + + + + + + src/main/resources + ../knowledgeknowledge + + + + io.quarkus.platform + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + buildgenerate-codegenerate-code-tests + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + true + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + + org.jboss.logmanager.LogManager + + + + + + + + + native + + true + + + + diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/AskResource.java b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/AskResource.java new file mode 100644 index 0000000..53e80e9 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/AskResource.java @@ -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); + } +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/OrderTools.java b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/OrderTools.java new file mode 100644 index 0000000..d0d8d16 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/OrderTools.java @@ -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 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"); + } +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyRetrievalAugmentor.java b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyRetrievalAugmentor.java new file mode 100644 index 0000000..840209f --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyRetrievalAugmentor.java @@ -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 { + + 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; + } +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyStore.java b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyStore.java new file mode 100644 index 0000000..d9d4870 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/PolicyStore.java @@ -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 FILES = List.of("returns.txt", "shipping.txt", "warranty.txt"); + + private final InMemoryEmbeddingStore store = new InMemoryEmbeddingStore<>(); + private final EmbeddingModel embeddingModel; + + PolicyStore(EmbeddingModel embeddingModel) { + this.embeddingModel = embeddingModel; + } + + void ingest(@Observes StartupEvent ev) throws IOException { + List 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 vectors = embeddingModel.embedAll(segments).content(); + store.addAll(vectors, segments); + } + + public InMemoryEmbeddingStore store() { + return store; + } +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/SupportAssistant.java b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/SupportAssistant.java new file mode 100644 index 0000000..82a221c --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/java/com/ankurm/qvs/SupportAssistant.java @@ -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); +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/main/resources/application.properties b/quarkus-vs-spring-ai/quarkus-app/src/main/resources/application.properties new file mode 100644 index 0000000..63219b7 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/main/resources/application.properties @@ -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 diff --git a/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/StubResource.java b/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/StubResource.java new file mode 100644 index 0000000..ce6bf43 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/StubResource.java @@ -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 start() { + try { + server = StubLlmServer.start(8089); + } catch (Exception e) { + throw new IllegalStateException(e); + } + return Map.of(); + } + + @Override + public void stop() { + server.stop(0); + } +} diff --git a/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java b/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java new file mode 100644 index 0000000..f539848 --- /dev/null +++ b/quarkus-vs-spring-ai/quarkus-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java @@ -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); + } +} diff --git a/quarkus-vs-spring-ai/scripts/bench.py b/quarkus-vs-spring-ai/scripts/bench.py new file mode 100644 index 0000000..725eda9 --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/bench.py @@ -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() diff --git a/quarkus-vs-spring-ai/scripts/lib.sh b/quarkus-vs-spring-ai/scripts/lib.sh new file mode 100755 index 0000000..7f8c0d2 --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/lib.sh @@ -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 : 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; } diff --git a/quarkus-vs-spring-ai/scripts/run-all.sh b/quarkus-vs-spring-ai/scripts/run-all.sh new file mode 100755 index 0000000..3653d8b --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/run-all.sh @@ -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 diff --git a/quarkus-vs-spring-ai/scripts/start-stub.sh b/quarkus-vs-spring-ai/scripts/start-stub.sh new file mode 100755 index 0000000..d05e5e3 --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/start-stub.sh @@ -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:-}" diff --git a/quarkus-vs-spring-ai/scripts/wire.sh b/quarkus-vs-spring-ai/scripts/wire.sh new file mode 100755 index 0000000..3a28521 --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/wire.sh @@ -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" diff --git a/quarkus-vs-spring-ai/scripts/wire_summary.py b/quarkus-vs-spring-ai/scripts/wire_summary.py new file mode 100644 index 0000000..1d48d19 --- /dev/null +++ b/quarkus-vs-spring-ai/scripts/wire_summary.py @@ -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) diff --git a/quarkus-vs-spring-ai/spring-ai-app/pom.xml b/quarkus-vs-spring-ai/spring-ai-app/pom.xml new file mode 100644 index 0000000..4bb3429 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + com.ankurm.qvs + spring-ai-app + 1.0.0 + + + 25 + 2.1.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-starter-model-openai + + + org.springframework.ai + spring-ai-vector-store-advisor + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + com.ankurm.qvs + stub-llm + ${project.version} + test + + + + + + src/main/resources + ../knowledgeknowledge + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + true + + + + diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AiConfig.java b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AiConfig.java new file mode 100644 index 0000000..cffd934 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AiConfig.java @@ -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 FILES = List.of("returns.txt", "shipping.txt", "warranty.txt"); + + @Bean + VectorStore policyStore(EmbeddingModel embeddingModel) throws IOException { + SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build(); + List 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(); + } +} diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AskController.java b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AskController.java new file mode 100644 index 0000000..a9ab2c9 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/AskController.java @@ -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(); + } +} diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/OrderTools.java b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/OrderTools.java new file mode 100644 index 0000000..8a04182 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/OrderTools.java @@ -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 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"); + } +} diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/SpringAiApp.java b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/SpringAiApp.java new file mode 100644 index 0000000..4b46235 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/main/java/com/ankurm/qvs/SpringAiApp.java @@ -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); + } +} diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/main/resources/application.properties b/quarkus-vs-spring-ai/spring-ai-app/src/main/resources/application.properties new file mode 100644 index 0000000..0305b0e --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/main/resources/application.properties @@ -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 diff --git a/quarkus-vs-spring-ai/spring-ai-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java b/quarkus-vs-spring-ai/spring-ai-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java new file mode 100644 index 0000000..74f4ea0 --- /dev/null +++ b/quarkus-vs-spring-ai/spring-ai-app/src/test/java/com/ankurm/qvs/SupportAssistantTest.java @@ -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:")); + } +} diff --git a/quarkus-vs-spring-ai/stub-llm/pom.xml b/quarkus-vs-spring-ai/stub-llm/pom.xml new file mode 100644 index 0000000..32f3caa --- /dev/null +++ b/quarkus-vs-spring-ai/stub-llm/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + com.ankurm.qvs + quarkus-vs-spring-ai + 1.0.0 + + stub-llm + + + com.fasterxml.jackson.core + jackson-databind + 2.21.1 + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + shade + + + + com.ankurm.stub.StubLlmServer + + + false + + + + + + + diff --git a/quarkus-vs-spring-ai/stub-llm/src/main/java/com/ankurm/stub/StubLlmServer.java b/quarkus-vs-spring-ai/stub-llm/src/main/java/com/ankurm/stub/StubLlmServer.java new file mode 100644 index 0000000..2758d25 --- /dev/null +++ b/quarkus-vs-spring-ai/stub-llm/src/main/java/com/ankurm/stub/StubLlmServer.java @@ -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. + * + *
    + *
  • POST /v1/embeddings: hashed bag-of-words vectors, so retrieval is repeatable.
  • + *
  • 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.
  • + *
  • With -Dstub.record.dir=DIR every request body is saved, so the wire formats of two + * frameworks can be diffed.
  • + *
+ */ +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 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; + } +}