embabel: move to 1.5.4, add Spring Boot application, deterministic testing layers and measured failure modes

Spring Boot starter and OpenAI-compatible model module behind a REST endpoint, tested against a fake provider
on localhost. FakeOperationContext and EmbabelMockitoIntegrationTest examples, retry multiplication, a STUCK
process surfacing as NullPointerException, two-goal agents, and plain Spring AI with the branches written.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6vDJ5fWY5uEZaJFNi
This commit is contained in:
Claude
2026-12-04 07:48:11 +05:30
parent 5323e6c71a
commit 38c9ca8452
34 changed files with 886 additions and 15 deletions
+3 -4
View File
@@ -6,7 +6,7 @@ facts, so the build fails when a claim stops being true.
| Module | Post | What it shows |
|---|---|---|
| `embabel` | Embabel: Goal-Oriented AI Agents on the JVM | actions, goals, conditions and cost-based planning with GOAP, compared with plain Spring AI |
| `embabel` | Embabel for Spring Developers: Goal-Oriented AI Agents with GOAP Planning | actions, goals, conditions and cost-based planning, the Spring Boot starter behind a REST endpoint, four ways to test without a model, retry multiplication measured against a fake provider, and plain Spring AI for contrast. See `embabel/README.md` |
| `a2a` | A2A Protocol in Java: Agents That Talk to Each Other | agent card, tasks, streaming, input-required and agent-to-agent calls with the A2A Java SDK |
| `onnx-djl` | Running ONNX Models in Java with ONNX Runtime and DJL | a DistilBERT sentiment model: DJL tokenizer, ONNX Runtime directly and through DJL's engine, batching, and a Spring Boot endpoint with latency numbers |
| `jlama` | Local LLM Inference in Pure Java with Jlama | load and run a 4-bit TinyLlama inside the JVM on the Vector API, tokens per second, streaming, and the same measurement against Ollama |
@@ -27,7 +27,7 @@ facts, so the build fails when a claim stops being true.
| Component | Version | Note |
|---|---|---|
| Embabel `embabel-agent-api` | 1.5.3 | brings Spring AI 2.0.1 and Spring Boot 4.1.1 transitively |
| Embabel `embabel-agent-api` and starters | 1.5.4 | verified on Maven Central 2026-12-04; brings Spring AI 2.0.1 and Spring Boot 4.1.1 transitively; 1.0.0 GA (2026-07-20) was on Spring Boot 3.5.14 |
| A2A Java SDK `io.github.a2asdk` | 1.0.0.Alpha3 | alpha; targets A2A protocol 1.0. The newest stable release, 0.3.3.Final, targets the 0.3 protocol and its API differs |
| Jlama `jlama-core` (`com.github.tjake`) | 0.8.4 | needs `--add-modules jdk.incubator.vector` at compile and run time |
| Model | `tjake/TinyLlama-1.1B-Chat-v1.0-Jlama-Q4` | 1.1 GB, downloaded by Jlama into `jlama/models/` on first run (git-ignored) |
@@ -61,8 +61,7 @@ mvn test # everything
mvn test -pl a2a -am # one module
```
No API key is needed. The A2A agents contain no model call, because the protocol is the subject. The Embabel tests use `ScriptedLlmOperations`, the scripted stand-in shipped inside
`embabel-agent-api`, and the Spring AI comparison uses a small scripted `ChatModel`.
No API key is needed. The A2A agents contain no model call, because the protocol is the subject. The Embabel tests use the stand-ins shipped with Embabel and a fake OpenAI-compatible server on localhost (see `embabel/README.md`).
Each module writes its transcripts to `<module>/output/` when you run the tests.
## The `jlama` module needs a model and takes minutes
+56
View File
@@ -0,0 +1,56 @@
# embabel: goal-oriented agents for Spring developers
Companion code for <https://ankurm.com/embabel-goal-oriented-ai-agents-jvm/>.
| Component | Version (checked on Maven Central 2026-12-04) |
|---|---|
| Embabel `embabel-agent-api`, `-starter`, `-starter-openai-custom`, `-test` | 1.5.4 (released 2026-10-28) |
| Brought in by it | Spring AI 2.0.1, Spring Boot 4.1.1, OpenAI Java SDK 4.49.0 |
| JDK | 25 |
1.0.0 went GA on 2026-07-20 and was built on Spring Boot 3.5.14 and Spring AI 1.1.7. The 4.x line starts with 1.5.0.
## Run
```bash
mvn test -pl embabel # 19 tests run, 2 slow ones skipped; no API key, no model
mvn test -pl embabel -Dslow=true # adds the two default-retry measurements, about 7 minutes of backoff
embabel/scripts/two-goals-across-jvms.sh # from the repository root
```
**No real LLM was called.** The model is either Embabel's `ScriptedLlmOperations`, its Mockito test base class,
`FakeOperationContext`, a scripted Spring AI `ChatModel`, or a fake OpenAI-compatible HTTP server on localhost.
The application is started from tests with `SpringApplication.run`; it was not launched from the command line and
was not pointed at a real provider. `application.yml` reads `LLM_BASE_URL`, `LLM_API_KEY` and `LLM_MODEL`; the request
path is the base URL plus `/chat/completions`.
## Code
| File | What it is |
|---|---|
| `ResearchAgent`, `Domain` | three actions over four records |
| `GuardedResearchAgent`, `ForgetfulGuardedAgent` | a condition, and the same with the `post` left out |
| `CostAwareResearchAgent` | two ways to produce a `Summary` |
| `TwoGoalsAgent` | two `@AchievesGoal` actions in one agent |
| `PlainResearch`, `PlainGuardedResearch` | the same job in plain Spring AI, without and with the hand-written branches |
| `boot/` | Spring Boot application, REST controller, profiles `guarded` and `two-agents` |
| `EmbabelTest`, `TestingLayersTest`, `MockitoBootTest`, `boot/BootTest` | the tests that write `output/` |
## Captured output
| File | Shows |
|---|---|
| 01, 02 | the planned order; a step skipped because its result was supplied |
| 03, 06 | a condition stopping a process; a condition no action establishes |
| 04, 17 | cost choosing the route; swapped costs swapping it |
| 05, 09 | same user prompts; different requests on the wire |
| 07 | dependency tree |
| 08, 23 | HTTP request end to end; request path with `/v1` |
| 10, 22 | a STUCK process as a 500 with a NullPointerException; checking the status instead |
| 11 | two agents that both produce a `Brief` |
| 12, 13, 20, 21 | provider requests per invocation, default retries and turned down |
| 14 | unknown default model fails at startup |
| 15, 18, 19 | one action as a unit test; plain Spring AI branches; Mockito integration test |
| 16, 24 | a two-goal agent that sometimes stops at the wrong goal |
Wall times in 12 and 13 are indicative. Files 12 and 13 are only rewritten with `-Dslow=true`.
+16 -8
View File
@@ -1,13 +1,21 @@
mvn dependency:tree for the embabel module, filtered to embabel, spring-ai, spring-boot and kotlin-stdlib:
mvn dependency:tree for the embabel module, filtered to embabel, spring-ai, spring-boot, openai-java and kotlin-stdlib:
com.ankurm.agents:embabel:jar:1.0.0
com.embabel.agent:embabel-agent-api:jar:1.5.3:compile
com.embabel.agent:embabel-agent-ai:jar:1.5.3:compile
com.embabel.common:embabel-common-core:jar:2.0.4:compile
com.embabel.common:embabel-common-util:jar:2.0.4:compile
ch.qos.logback:logback-classic:jar:1.5.38:compile
com.embabel.common:embabel-common-textio:jar:2.0.4:compile
com.embabel.agent:embabel-agent-api:jar:1.5.4:compile
com.embabel.agent:embabel-agent-ai:jar:1.5.4:compile
com.embabel.common:embabel-common-core:jar:2.0.5:compile
com.embabel.common:embabel-common-util:jar:2.0.5:compile
com.embabel.common:embabel-common-textio:jar:2.0.5:compile
org.jetbrains.kotlin:kotlin-stdlib:jar:2.2.21:compile
org.springframework.boot:spring-boot:jar:4.1.1:compile
org.springframework.ai:spring-ai-client-chat:jar:2.0.1:compile
org.springframework.ai:spring-ai-model:jar:2.0.1:compile
org.springframework.ai:spring-ai-commons:jar:2.0.1:compile
com.embabel.agent:embabel-agent-starter:jar:1.5.4:compile
com.embabel.agent:embabel-agent-platform-autoconfigure:jar:1.5.4:compile
com.embabel.agent:embabel-agent-starter-openai-custom:jar:1.5.4:compile
com.embabel.agent:embabel-agent-openai-custom-autoconfigure:jar:1.5.4:compile
com.embabel.agent:embabel-agent-openai:jar:1.5.4:compile
com.embabel.agent:embabel-agent-byok:jar:1.5.4:compile
org.springframework.ai:spring-ai-openai:jar:2.0.1:compile
com.openai:openai-java-core:jar:4.49.0:compile
org.springframework.boot:spring-boot:jar:4.1.1:compile
com.embabel.agent:embabel-agent-test:jar:1.5.4:test
+6
View File
@@ -0,0 +1,6 @@
GET /brief?topic=virtual%20threads
HTTP 200 {"text":"Virtual threads: blocking is cheap again."}
Requests the fake provider received (base-url had no path):
POST /chat/completions
POST /chat/completions
+7
View File
@@ -0,0 +1,7 @@
First request body on the wire, same user question. The date is replaced with <today>.
Embabel createObject(prompt, Summary.class):
{"messages":[{"content":"Current date: <today>\n\n\n\nYour response should be in JSON format.\nDo not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.\nDo not include markdown code blocks in your response.\nRemove the ```json markdown from the output.\nHere is the JSON Schema instance your output must adhere to:\n```{\n \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\n \"type\" : \"object\",\n \"properties\" : {\n \"text\" : {\n \"type\" : \"string\"\n }\n },\n \"additionalProperties\" : false\n}```\n","role":"system"},{"content":"Summarise these notes in one sentence: JEP 444 makes virtual threads final in Java 21. Virtual threads are cheap to block, so thread-per-request scales again.","role":"user"}],"model":"scripted-model"}
Plain Spring AI chat.prompt().user(prompt).call().content():
{"messages":[{"content":"Summarise these notes in one sentence: JEP 444 makes virtual threads final in Java 21. Virtual threads are cheap to block, so thread-per-request scales again.","role":"user"}],"model":"scripted-model"}
+11
View File
@@ -0,0 +1,11 @@
Profile guarded.
GET /brief?topic=virtual%20threads
HTTP 200, provider calls 2
GET /brief?topic=quantum%20gravity
HTTP 500 {"status":500,"error":"Internal Server Error","path":"/brief"}
provider calls 0
The exception AgentInvocation.invoke threw:
java.lang.NullPointerException: get(...) must not be null
+9
View File
@@ -0,0 +1,9 @@
Profile two-agents: ResearchAgent and CostAwareResearchAgent are both deployed.
Deployed agents: [CostAwareResearchAgent, ResearchAgent]
Three calls to GET /brief:
HTTP 200, provider calls 1
HTTP 200, provider calls 1
HTTP 200, provider calls 1
(2 provider calls means ResearchAgent ran; 1 means CostAwareResearchAgent ran.)
@@ -0,0 +1,7 @@
Every reply is HTTP 200 with plain prose instead of JSON. Default retry settings.
One call to AgentInvocation.invoke
requests the provider received: 50
of those, by the OpenAI SDK's x-stainless-retry-count header: {0=50}
wall time, seconds (indicative): 182
exception: java.util.concurrent.ExecutionException: com.embabel.agent.core.support.InvalidLlmReturnFormatException: Invalid LLM return when expecting com.ankurm.agents.embabel.Domain$Summary: Root cause=tools.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
@@ -0,0 +1,7 @@
Every reply is HTTP 500. embabel.agent.platform.models.openai.custom.max-attempts=1, everything else default.
One call to AgentInvocation.invoke
requests the provider received: 150
of those, by the OpenAI SDK's x-stainless-retry-count header: {0=50, 1=50, 2=50}
wall time, seconds (indicative): 249
exception: java.util.concurrent.ExecutionException: com.openai.errors.InternalServerException: 500: upstream exploded
+4
View File
@@ -0,0 +1,4 @@
embabel.models.default-llm=gpt-typo while the registered model is scripted-model.
Application start fails. Root cause:
java.lang.IllegalArgumentException: Default LLM 'gpt-typo' is neither a registered model nor a configured role. Set the 'embabel.models.default-llm' property to one of the available models: [scripted-model], or to one of the roles: [].
+5
View File
@@ -0,0 +1,5 @@
FakeOperationContext, one action called as an ordinary method.
returned: Summary[text=Virtual threads make blocking cheap.]
prompt: Summarise these notes in one sentence: note one. note two.
LLM calls recorded: 1
+6
View File
@@ -0,0 +1,6 @@
50 fresh platforms, each asked for a Brief; every process ended COMPLETED.
TwoGoalsAgent (@AchievesGoal on summarise and writeBrief): Brief produced in 0 of 50 runs
Same, with @AchievesGoal(value = 1.0) on writeBrief: Brief produced in 50 of 50 runs
The first figure is not stable from one JVM run to the next.
+3
View File
@@ -0,0 +1,3 @@
Same two summarisers, costs swapped (LLM 0.1, local 0.9).
ran: [findSources, summariseWithLlm, writeBrief]
+5
View File
@@ -0,0 +1,5 @@
PlainGuardedResearch, the three branches written by hand.
known sources -> first prompt: Summarise these notes in one sentence: A note we already had.
unknown topic -> result Optional.empty, LLM calls 0
cheap summary -> LLM calls 1
+3
View File
@@ -0,0 +1,3 @@
@SpringBootTest + EmbabelMockitoIntegrationTest, no HTTP provider.
result: Brief[text=Virtual threads: blocking is cheap again.]
@@ -0,0 +1,7 @@
Every reply is plain prose. data-binding.max-attempts=1, action-qos.default.max-attempts=1.
One call to AgentInvocation.invoke
requests the provider received: 1
of those, by the OpenAI SDK's x-stainless-retry-count header: {0=1}
wall time, seconds (indicative): 0
exception: java.util.concurrent.ExecutionException: com.embabel.agent.core.support.InvalidLlmReturnFormatException: Invalid LLM return when expecting com.ankurm.agents.embabel.Domain$Summary: Root cause=tools.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
+7
View File
@@ -0,0 +1,7 @@
Every reply is HTTP 500. data-binding.max-attempts=1, action-qos.default.max-attempts=1.
One call to AgentInvocation.invoke
requests the provider received: 3
of those, by the OpenAI SDK's x-stainless-retry-count header: {0=1, 1=1, 2=1}
wall time, seconds (indicative): 1
exception: java.util.concurrent.ExecutionException: com.openai.errors.InternalServerException: 500: upstream exploded
+5
View File
@@ -0,0 +1,5 @@
Profile guarded.
GET /brief-checked?topic=quantum%20gravity
HTTP 422 {"status":"STUCK","actionsRun":1}
provider calls 0
+5
View File
@@ -0,0 +1,5 @@
base-url ends in /v1
Requests the fake provider received:
POST /v1/chat/completions
POST /v1/chat/completions
@@ -0,0 +1,10 @@
Asked for a Brief, 50 runs per JVM, eight JVMs in a row (scripts/two-goals-across-jvms.sh).
JVM 1 | equal goals: 0 of 50 runs | valued goal: 50 of 50 runs
JVM 2 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
JVM 3 | equal goals: 0 of 50 runs | valued goal: 50 of 50 runs
JVM 4 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
JVM 5 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
JVM 6 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
JVM 7 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
JVM 8 | equal goals: 50 of 50 runs | valued goal: 50 of 50 runs
+21
View File
@@ -18,6 +18,27 @@
<artifactId>embabel-agent-api</artifactId>
<version>${embabel.version}</version>
</dependency>
<dependency>
<groupId>com.embabel.agent</groupId>
<artifactId>embabel-agent-starter</artifactId>
<version>${embabel.version}</version>
</dependency>
<dependency>
<groupId>com.embabel.agent</groupId>
<artifactId>embabel-agent-starter-openai-custom</artifactId>
<version>${embabel.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.embabel.agent</groupId>
<artifactId>embabel-agent-test</artifactId>
<version>${embabel.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Runs the two-goal experiment in eight separate JVMs and collects the first figure from each.
# Run from the repository root.
set -euo pipefail
out=embabel/output/24-two-goals-across-jvms.txt
tmp=$(mktemp)
for i in 1 2 3 4 5 6 7 8; do
mvn -B -q test -pl embabel -Dtest='TestingLayersTest#askingATwoGoalAgentForOneOfTheGoals' "$@" > /dev/null
echo "JVM $i | equal goals: $(sed -n 's/^TwoGoalsAgent.*produced in //p' embabel/output/16-two-goals.txt) | valued goal: $(sed -n 's/^Same.*produced in //p' embabel/output/16-two-goals.txt)" >> "$tmp"
done
{ echo "Asked for a Brief, 50 runs per JVM, eight JVMs in a row (scripts/two-goals-across-jvms.sh)."; echo; cat "$tmp"; } > "$out"
rm "$tmp"
@@ -0,0 +1,43 @@
package com.ankurm.agents.embabel;
import com.ankurm.agents.embabel.Domain.Brief;
import com.ankurm.agents.embabel.Domain.Sources;
import com.ankurm.agents.embabel.Domain.Summary;
import com.ankurm.agents.embabel.Domain.Topic;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import java.util.Optional;
import java.util.function.Function;
/**
* Plain Spring AI again, now doing by hand what the planner did for free in the other agents: skip the lookup
* when the caller already has sources, refuse to summarise nothing, and choose the cheaper summariser.
*/
public class PlainGuardedResearch {
private final ChatClient chat;
private final ResearchAgent search = new ResearchAgent();
private final Function<Sources, Summary> summariser;
public PlainGuardedResearch(ChatModel model, boolean cheapSummary) {
this.chat = ChatClient.create(model);
this.summariser = cheapSummary
? sources -> new Summary(sources.items().getFirst())
: sources -> new Summary(ask("Summarise these notes in one sentence: " + String.join(" ", sources.items())));
}
/** @param known sources the caller already has, or null to look them up */
public Optional<Brief> research(Topic topic, Sources known) {
Sources sources = known != null ? known : search.findSources(topic);
if (sources.items().isEmpty()) {
return Optional.empty();
}
Summary summary = summariser.apply(sources);
return Optional.of(new Brief(ask("Write a two-line brief titled '" + topic.text() + "' from: " + summary.text())));
}
private String ask(String prompt) {
return chat.prompt().user(prompt).call().content();
}
}
@@ -0,0 +1,34 @@
package com.ankurm.agents.embabel;
import com.ankurm.agents.embabel.Domain.Brief;
import com.ankurm.agents.embabel.Domain.Sources;
import com.ankurm.agents.embabel.Domain.Summary;
import com.ankurm.agents.embabel.Domain.Topic;
import com.embabel.agent.api.annotation.AchievesGoal;
import com.embabel.agent.api.annotation.Action;
import com.embabel.agent.api.annotation.Agent;
import com.embabel.agent.api.common.OperationContext;
/** One agent, two goals: a Summary on its own, or the full Brief. */
@Agent(description = "Researches a topic; can stop at a summary or go on to a brief")
public class TwoGoalsAgent {
private final ResearchAgent delegate = new ResearchAgent();
@Action
public Sources findSources(Topic topic) {
return delegate.findSources(topic);
}
@AchievesGoal(description = "A one-sentence summary")
@Action
public Summary summarise(Sources sources, OperationContext context) {
return delegate.summarise(sources, context);
}
@AchievesGoal(description = "A short brief about the topic")
@Action
public Brief writeBrief(Topic topic, Summary summary, OperationContext context) {
return delegate.writeBrief(topic, summary, context);
}
}
@@ -0,0 +1,35 @@
package com.ankurm.agents.embabel.boot;
import com.ankurm.agents.embabel.CostAwareResearchAgent;
import com.ankurm.agents.embabel.GuardedResearchAgent;
import com.ankurm.agents.embabel.ResearchAgent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
/**
* Which agents the application deploys, by Spring profile, so one app shows the working case and two failures.
* Agents are imported explicitly because the parent package also holds deliberately broken variants.
*/
public class AgentSelection {
@Configuration
@Profile("!guarded & !two-agents")
@Import(ResearchAgent.class)
static class Default {
}
/** One agent that refuses to summarise nothing: shows what an HTTP caller sees when a process is STUCK. */
@Configuration
@Profile("guarded")
@Import(GuardedResearchAgent.class)
static class Guarded {
}
/** Two agents that both produce a Brief: shows which one a result-type invocation picks. */
@Configuration
@Profile("two-agents")
@Import({ResearchAgent.class, CostAwareResearchAgent.class})
static class TwoAgents {
}
}
@@ -0,0 +1,17 @@
package com.ankurm.agents.embabel.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* The research agent inside an ordinary Spring Boot web application. The Embabel starter auto-configures the
* agent platform; the agent is a normal bean. Which agent is deployed is decided in {@link AgentSelection}.
* No enabling annotation is needed: {@code @EnableAgents} is deprecated for removal in the 1.5.x jar.
*/
@SpringBootApplication
public class BriefApplication {
public static void main(String[] args) {
SpringApplication.run(BriefApplication.class, args);
}
}
@@ -0,0 +1,45 @@
package com.ankurm.agents.embabel.boot;
import com.ankurm.agents.embabel.Domain.Brief;
import com.ankurm.agents.embabel.Domain.Topic;
import com.embabel.agent.api.invocation.AgentInvocation;
import com.embabel.agent.core.AgentPlatform;
import com.embabel.agent.core.AgentProcess;
import com.embabel.agent.core.AgentProcessStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* Asks the platform for a Brief. It names no agent and no action: the result type picks an agent that can
* produce it. {@code /brief} is the obvious version; {@code /brief-checked} looks at the process status, because
* {@code invoke} throws a bare NullPointerException when a process ends without a result.
*/
@RestController
public class BriefController {
private final AgentPlatform platform;
public BriefController(AgentPlatform platform) {
this.platform = platform;
}
@GetMapping("/brief")
public Brief brief(@RequestParam String topic) {
return AgentInvocation.create(platform, Brief.class).invoke(new Topic(topic));
}
@GetMapping("/brief-checked")
public ResponseEntity<Object> briefChecked(@RequestParam String topic) {
AgentProcess process = AgentInvocation.create(platform, Brief.class).run(new Topic(topic));
Brief brief = process.last(Brief.class);
if (process.getStatus() == AgentProcessStatusCode.COMPLETED && brief != null) {
return ResponseEntity.ok(brief);
}
return ResponseEntity.unprocessableEntity()
.body(Map.of("status", process.getStatus().name(), "actionsRun", process.getHistory().size()));
}
}
@@ -0,0 +1,12 @@
# Any OpenAI-compatible endpoint works here. The tests point base-url at a scripted fake server.
embabel:
models:
default-llm: ${LLM_MODEL:scripted-model}
agent:
platform:
models:
openai:
custom:
base-url: ${LLM_BASE_URL:http://localhost:11434}
api-key: ${LLM_API_KEY:not-a-real-key}
models: ${LLM_MODEL:scripted-model}
@@ -0,0 +1,31 @@
package com.ankurm.agents.embabel;
import com.ankurm.agents.embabel.Domain.Brief;
import com.ankurm.agents.embabel.Domain.Summary;
import com.ankurm.agents.embabel.Domain.Topic;
import com.ankurm.agents.embabel.boot.BriefApplication;
import com.embabel.agent.api.invocation.AgentInvocation;
import com.embabel.agent.test.integration.EmbabelMockitoIntegrationTest;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
/** The Spring context is real; the model operations are Mockito mocks supplied by embabel-agent-test. */
@SpringBootTest(classes = BriefApplication.class)
class MockitoBootTest extends EmbabelMockitoIntegrationTest {
@Test
void stubTheModelByPromptAndType() {
whenCreateObject(prompt -> prompt.startsWith("Summarise"), Summary.class)
.thenReturn(new Summary("Virtual threads make blocking cheap."));
whenCreateObject(prompt -> prompt.startsWith("Write a two-line brief"), Brief.class)
.thenReturn(new Brief("Virtual threads: blocking is cheap again."));
Brief brief = AgentInvocation.create(agentPlatform, Brief.class).invoke(new Topic("virtual threads"));
assertThat(brief.text()).isEqualTo("Virtual threads: blocking is cheap again.");
verifyCreateObject(prompt -> prompt.contains("JEP 444"), Summary.class);
Transcript.write("19-mockito-boot.txt", "@SpringBootTest + EmbabelMockitoIntegrationTest, no HTTP provider.\n\nresult: " + brief + "\n");
}
}
@@ -0,0 +1,159 @@
package com.ankurm.agents.embabel;
import com.ankurm.agents.embabel.Domain.Brief;
import com.ankurm.agents.embabel.Domain.Sources;
import com.ankurm.agents.embabel.Domain.Summary;
import com.ankurm.agents.embabel.Domain.Topic;
import com.embabel.agent.api.annotation.AchievesGoal;
import com.embabel.agent.api.annotation.Action;
import com.embabel.agent.api.annotation.Agent;
import com.embabel.agent.api.annotation.support.AgentMetadataReader;
import com.embabel.agent.api.common.OperationContext;
import com.embabel.agent.api.invocation.AgentInvocation;
import com.embabel.agent.core.AgentPlatform;
import com.embabel.agent.core.AgentProcess;
import com.embabel.agent.core.ProcessOptions;
import com.embabel.agent.test.integration.IntegrationTestUtils;
import com.embabel.agent.test.integration.ScriptedLlmOperations;
import com.embabel.agent.test.unit.FakeOperationContext;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
class TestingLayersTest {
@Test
void oneActionAsAPlainMethodCall() {
FakeOperationContext context = FakeOperationContext.Companion.create();
context.expectResponse(new Summary("Virtual threads make blocking cheap."));
Summary out = new ResearchAgent().summarise(new Sources(List.of("note one.", "note two.")), context);
var call = context.getLlmInvocations().getFirst();
assertThat(out.text()).isEqualTo("Virtual threads make blocking cheap.");
assertThat(call.getPrompt()).isEqualTo("Summarise these notes in one sentence: note one. note two.");
Transcript.write("15-unit-action.txt", "FakeOperationContext, one action called as an ordinary method.\n\nreturned: " + out
+ "\nprompt: " + call.getPrompt() + "\nLLM calls recorded: " + context.getLlmInvocations().size() + "\n");
}
private static AgentPlatform platform(ScriptedLlmOperations llm, Object... agents) {
AgentPlatform platform = IntegrationTestUtils.dummyAgentPlatform(llm);
for (Object a : agents) platform.deploy((com.embabel.agent.core.Agent) new AgentMetadataReader().createAgentMetadata(a));
return platform;
}
private static ScriptedLlmOperations summaryThenBrief() {
ScriptedLlmOperations llm = new ScriptedLlmOperations();
llm.returnObject(new Summary("Virtual threads make blocking cheap."));
llm.returnObject(new Brief("Virtual threads: blocking is cheap again."));
return llm;
}
/** Asks 50 fresh platforms for a Brief and counts how many processes actually produced one. */
private static int briefsProducedInFiftyRuns(Supplier<Object> agent) {
int briefs = 0;
for (int i = 0; i < 50; i++) {
AgentProcess p = AgentInvocation.create(platform(summaryThenBrief(), agent.get()), Brief.class)
.run(new Topic("virtual threads"));
assertThat(p.getStatus().name()).isEqualTo("COMPLETED");
if (p.last(Brief.class) != null) briefs++;
}
return briefs;
}
@Test
void askingATwoGoalAgentForOneOfTheGoals() {
int equalGoals = briefsProducedInFiftyRuns(TwoGoalsAgent::new);
int valuedGoal = briefsProducedInFiftyRuns(ValuedGoalsAgent::new);
Transcript.write("16-two-goals.txt", "50 fresh platforms, each asked for a Brief; every process ended COMPLETED.\n\n"
+ "TwoGoalsAgent (@AchievesGoal on summarise and writeBrief): Brief produced in " + equalGoals + " of 50 runs\n"
+ "Same, with @AchievesGoal(value = 1.0) on writeBrief: Brief produced in " + valuedGoal + " of 50 runs\n"
+ "\nThe first figure is not stable from one JVM run to the next.\n");
assertThat(valuedGoal).isEqualTo(50);
}
/** TwoGoalsAgent with a higher value on the Brief goal. */
@Agent(description = "Two goals, the brief worth more")
static class ValuedGoalsAgent {
private final TwoGoalsAgent d = new TwoGoalsAgent();
@Action
public Sources findSources(Topic topic) {
return d.findSources(topic);
}
@AchievesGoal(description = "A one-sentence summary")
@Action
public Summary summarise(Sources sources, OperationContext context) {
return d.summarise(sources, context);
}
@AchievesGoal(description = "A short brief about the topic", value = 1.0)
@Action
public Brief writeBrief(Topic topic, Summary summary, OperationContext context) {
return d.writeBrief(topic, summary, context);
}
}
/** CostAwareResearchAgent with the two cost numbers swapped. */
@Agent(description = "Costs swapped")
static class SwappedCosts {
private final CostAwareResearchAgent d = new CostAwareResearchAgent();
@Action
public Sources findSources(Topic topic) {
return d.findSources(topic);
}
@Action(cost = 0.1)
public Summary summariseWithLlm(Sources sources, OperationContext context) {
return d.summariseWithLlm(sources, context);
}
@Action(cost = 0.9)
public Summary summariseLocally(Sources sources) {
return d.summariseLocally(sources);
}
@AchievesGoal(description = "A short brief about the topic")
@Action
public Brief writeBrief(Topic topic, Summary summary, OperationContext context) {
return d.writeBrief(topic, summary, context);
}
}
@Test
void swappingTheCostsSwapsTheRoute() {
ScriptedLlmOperations llm = new ScriptedLlmOperations();
llm.returnObject(new Summary("s"));
llm.returnObject(new Brief("b"));
AgentPlatform platform = platform(llm, new SwappedCosts());
AgentProcess p = platform.runAgentFrom(platform.agents().getFirst(), ProcessOptions.DEFAULT, Map.of("it", new Topic("virtual threads")));
List<String> ran = p.getHistory().stream().map(a -> a.getActionName().replaceAll(".*\\.", "")).toList();
assertThat(ran).containsExactly("findSources", "summariseWithLlm", "writeBrief");
Transcript.write("17-costs-swapped.txt", "Same two summarisers, costs swapped (LLM 0.1, local 0.9).\n\nran: " + ran + "\n");
}
@Test
void thePlainVersionNeedsThoseBranchesWritten() {
var skip = new ScriptedChatModel("s", "b");
new PlainGuardedResearch(skip, false).research(new Topic("virtual threads"), new Sources(List.of("A note we already had.")));
var empty = new ScriptedChatModel();
var none = new PlainGuardedResearch(empty, false).research(new Topic("quantum gravity"), null);
var cheap = new ScriptedChatModel("b");
new PlainGuardedResearch(cheap, true).research(new Topic("virtual threads"), null);
assertThat(skip.prompts.getFirst()).contains("A note we already had.");
assertThat(none).isEmpty();
assertThat(empty.prompts).isEmpty();
assertThat(cheap.prompts).hasSize(1);
Transcript.write("18-plain-guarded.txt", "PlainGuardedResearch, the three branches written by hand.\n\n"
+ "known sources -> first prompt: " + skip.prompts.getFirst()
+ "\nunknown topic -> result " + none + ", LLM calls " + empty.prompts.size()
+ "\ncheap summary -> LLM calls " + cheap.prompts.size() + "\n");
}
}
@@ -5,14 +5,14 @@ import java.nio.file.Files;
import java.nio.file.Path;
/** Writes what a test observed to output/NN-name.txt so every figure in the post comes from a file. */
final class Transcript {
public final class Transcript {
private static final Path DIR = Path.of("output");
private Transcript() {
}
static void write(String name, String content) {
public static void write(String name, String content) {
try {
Files.createDirectories(DIR);
Files.writeString(DIR.resolve(name), content);
@@ -0,0 +1,213 @@
package com.ankurm.agents.embabel.boot;
import com.ankurm.agents.embabel.Domain.Topic;
import com.ankurm.agents.embabel.PlainResearch;
import com.ankurm.agents.embabel.Transcript;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Starts the real application (Embabel starter, OpenAI-compatible model module, embedded Tomcat) against a
* scripted fake provider on localhost. Everything between the controller and the HTTP socket is the real code.
*/
class BootTest {
private static ConfigurableApplicationContext start(FakeOpenAiServer fake, String... extra) {
String baseUrl = "--embabel.agent.platform.models.openai.custom.base-url=";
List<String> args = new ArrayList<>(List.of("--server.port=0"));
args.addAll(List.of(extra));
if (args.stream().noneMatch(a -> a.startsWith(baseUrl))) args.add(baseUrl + fake.url());
return SpringApplication.run(BriefApplication.class, args.toArray(String[]::new));
}
private static HttpResponse<String> get(ConfigurableApplicationContext app, String topic) throws IOException, InterruptedException {
return getPath(app, "/brief", topic);
}
private static HttpResponse<String> getPath(ConfigurableApplicationContext app, String path, String topic) throws IOException, InterruptedException {
String port = app.getEnvironment().getProperty("local.server.port");
URI uri = URI.create("http://127.0.0.1:" + port + path + "?topic=" + topic.replace(" ", "%20"));
return HttpClient.newHttpClient().send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString());
}
/** The error body without its timestamp, so reruns produce the same transcript. */
private static String stable(String body) {
return body.replaceAll("\"timestamp\":\"[^\"]*\",", "");
}
private static String normalise(String request) {
return request.replaceAll("Current date: \\d{4}-\\d{2}-\\d{2}", "Current date: <today>");
}
@Test
void anHttpRequestRunsTheAgentEndToEnd() throws Exception {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy); var app = start(fake)) {
var res = get(app, "virtual threads");
assertThat(res.statusCode()).isEqualTo(200);
assertThat(res.body()).isEqualTo("{\"text\":\"Virtual threads: blocking is cheap again.\"}");
assertThat(fake.paths).containsExactly("POST /chat/completions", "POST /chat/completions");
Transcript.write("08-boot-http.txt", "GET /brief?topic=virtual%20threads\n HTTP " + res.statusCode() + " " + res.body()
+ "\n\nRequests the fake provider received (base-url had no path):\n " + String.join("\n ", fake.paths) + "\n");
assertThat(fake.requests.getFirst()).contains("Current date: ").contains("JSON Schema").contains("\"role\":\"system\"");
String embabelWire = normalise(fake.requests.getFirst());
fake.reset(body -> new FakeOpenAiServer.Reply(200, "Virtual threads make blocking cheap."));
var model = OpenAiChatModel.builder()
.options(OpenAiChatOptions.builder().baseUrl(fake.url()).apiKey("x").model("scripted-model").build())
.build();
new PlainResearch(model).research(new Topic("virtual threads"));
String plainWire = fake.requests.getFirst();
assertThat(plainWire).doesNotContain("JSON Schema").doesNotContain("\"role\":\"system\"");
Transcript.write("09-wire-prompts.txt", "First request body on the wire, same user question. The date is replaced with <today>.\n\n"
+ "Embabel createObject(prompt, Summary.class):\n" + embabelWire
+ "\n\nPlain Spring AI chat.prompt().user(prompt).call().content():\n" + plainWire + "\n");
}
}
@Test
void aStuckProcessBecomesAServerError() throws Exception {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy); var app = start(fake, "--spring.profiles.active=guarded")) {
var known = get(app, "virtual threads");
int callsForKnown = fake.requests.size();
fake.reset(FakeOpenAiServer::happy);
var unknown = get(app, "quantum gravity");
assertThat(known.statusCode()).isEqualTo(200);
assertThat(unknown.statusCode()).isEqualTo(500);
assertThat(fake.requests).isEmpty();
Throwable thrown = invokeDirectly(app, "quantum gravity");
Transcript.write("10-boot-stuck.txt", "Profile guarded.\n\nGET /brief?topic=virtual%20threads\n HTTP " + known.statusCode()
+ ", provider calls " + callsForKnown + "\n\nGET /brief?topic=quantum%20gravity\n HTTP " + unknown.statusCode()
+ " " + stable(unknown.body()) + "\n provider calls " + fake.requests.size()
+ "\n\nThe exception AgentInvocation.invoke threw:\n " + thrown.getClass().getName() + ": " + thrown.getMessage() + "\n");
}
}
private static Throwable invokeDirectly(ConfigurableApplicationContext app, String topic) {
try {
app.getBean(BriefController.class).brief(topic);
} catch (Throwable t) {
return t;
}
throw new AssertionError("expected a failure");
}
@Test
void twoAgentsProducingTheSameType() throws Exception {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy); var app = start(fake, "--spring.profiles.active=two-agents")) {
List<String> runs = new ArrayList<>();
for (int i = 0; i < 3; i++) {
fake.reset(FakeOpenAiServer::happy);
var res = get(app, "virtual threads");
runs.add("HTTP " + res.statusCode() + ", provider calls " + fake.requests.size());
}
var platform = app.getBean(com.embabel.agent.core.AgentPlatform.class);
Transcript.write("11-boot-two-agents.txt", "Profile two-agents: ResearchAgent and CostAwareResearchAgent are both deployed.\n"
+ "Deployed agents: " + platform.agents().stream().map(a -> a.getName()).sorted().toList()
+ "\n\nThree calls to GET /brief:\n " + String.join("\n ", runs)
+ "\n\n(2 provider calls means ResearchAgent ran; 1 means CostAwareResearchAgent ran.)\n");
}
}
@Test
void theRequestPathIsBaseUrlPlusChatCompletions() throws Exception {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy);
var app = start(fake, "--embabel.agent.platform.models.openai.custom.base-url=" + fake.url() + "/v1")) {
assertThat(get(app, "virtual threads").statusCode()).isEqualTo(200);
assertThat(fake.paths).containsOnly("POST /v1/chat/completions");
Transcript.write("23-base-url-v1.txt", "base-url ends in /v1\n\nRequests the fake provider received:\n " + String.join("\n ", fake.paths) + "\n");
}
}
private static final FakeOpenAiServer.Reply PROSE = new FakeOpenAiServer.Reply(200, "Sure! Virtual threads are great.");
private static final FakeOpenAiServer.Reply BOOM = new FakeOpenAiServer.Reply(500, "upstream exploded");
/** Default retry settings. About four minutes, almost all of it backoff: run with -Dslow=true. */
@Test
@EnabledIfSystemProperty(named = "slow", matches = "true")
void aReplyThatIsNotJsonWithDefaultRetries() throws Exception {
failureRun("12-retries-bad-reply-default.txt", "Every reply is HTTP 200 with plain prose instead of JSON. Default retry settings.", PROSE, 50);
}
/** As above for a failing provider, with the custom provider's own max-attempts lowered to 1. */
@Test
@EnabledIfSystemProperty(named = "slow", matches = "true")
void aProviderThatReturns500WithDefaultRetries() throws Exception {
failureRun("13-retries-500-default.txt", "Every reply is HTTP 500. embabel.agent.platform.models.openai.custom.max-attempts=1, everything else default.",
BOOM, 150, "--embabel.agent.platform.models.openai.custom.max-attempts=1");
}
private static final String[] TAMED = {
"--embabel.agent.platform.llm-operations.data-binding.max-attempts=1",
"--embabel.agent.platform.action-qos.default.max-attempts=1"};
@Test
void aReplyThatIsNotJsonWithRetriesTurnedDown() throws Exception {
failureRun("20-retries-bad-reply-tamed.txt", "Every reply is plain prose. data-binding.max-attempts=1, action-qos.default.max-attempts=1.", PROSE, 1, TAMED);
}
@Test
void aProviderThatReturns500WithRetriesTurnedDown() throws Exception {
failureRun("21-retries-500-tamed.txt", "Every reply is HTTP 500. data-binding.max-attempts=1, action-qos.default.max-attempts=1.", BOOM, 3, TAMED);
}
private void failureRun(String file, String what, FakeOpenAiServer.Reply reply, int expectedRequests, String... extra) throws Exception {
try (var fake = new FakeOpenAiServer(body -> reply); var app = start(fake, extra)) {
long t0 = System.nanoTime();
Throwable thrown = invokeDirectly(app, "virtual threads");
long seconds = Math.round((System.nanoTime() - t0) / 1e9);
String msg = String.valueOf(thrown.getMessage()).lines().findFirst().orElse("");
Map<String, Long> bySdkAttempt = fake.sdkRetryHeaders.stream()
.collect(Collectors.groupingBy(h -> h, TreeMap::new, Collectors.counting()));
Transcript.write(file, what + "\n\nOne call to AgentInvocation.invoke\n requests the provider received: " + fake.requests.size()
+ "\n of those, by the OpenAI SDK's x-stainless-retry-count header: " + bySdkAttempt
+ "\n wall time, seconds (indicative): " + seconds
+ "\n exception: " + thrown.getClass().getName() + ": " + (msg.length() > 300 ? msg.substring(0, 300) + " ..." : msg) + "\n");
assertThat(fake.requests).hasSize(expectedRequests);
}
}
@Test
void checkingTheProcessStatusGivesACleanAnswer() throws Exception {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy); var app = start(fake, "--spring.profiles.active=guarded")) {
var res = getPath(app, "/brief-checked", "quantum gravity");
assertThat(res.statusCode()).isEqualTo(422);
Transcript.write("22-boot-checked.txt", "Profile guarded.\n\nGET /brief-checked?topic=quantum%20gravity\n HTTP " + res.statusCode() + " " + res.body()
+ "\n provider calls " + fake.requests.size() + "\n");
}
}
@Test
void aDefaultModelNobodyRegisteredFailsAtStartup() {
try (var fake = new FakeOpenAiServer(FakeOpenAiServer::happy)) {
Throwable thrown = null;
try (var app = start(fake, "--embabel.models.default-llm=gpt-typo")) {
assertThat(app).isNotNull();
} catch (Throwable t) {
thrown = t;
}
assertThat(thrown).isNotNull();
Throwable root = thrown;
while (root.getCause() != null) root = root.getCause();
Transcript.write("14-boot-wrong-model.txt", "embabel.models.default-llm=gpt-typo while the registered model is scripted-model.\n\n"
+ "Application start fails. Root cause:\n " + root.getClass().getName() + ": " + root.getMessage() + "\n");
}
}
}
@@ -0,0 +1,78 @@
package com.ankurm.agents.embabel.boot;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
/** A scripted stand-in for an OpenAI-compatible provider. It records every request body it receives. */
final class FakeOpenAiServer implements AutoCloseable {
record Reply(int status, String content) {
}
final List<String> requests = new CopyOnWriteArrayList<>();
final List<String> paths = new CopyOnWriteArrayList<>();
final List<String> sdkRetryHeaders = new CopyOnWriteArrayList<>();
volatile Function<String, Reply> script;
private final HttpServer server;
FakeOpenAiServer(Function<String, Reply> script) {
this.script = script;
try {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
server.createContext("/", exchange -> {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
requests.add(body);
sdkRetryHeaders.add(String.valueOf(exchange.getRequestHeaders().getFirst("x-stainless-retry-count")));
paths.add(exchange.getRequestMethod() + " " + exchange.getRequestURI().getPath());
Reply r = this.script.apply(body);
String json = r.status() == 200
? "{\"id\":\"x\",\"object\":\"chat.completion\",\"created\":0,\"model\":\"scripted-model\",\"choices\":[{\"index\":0,"
+ "\"message\":{\"role\":\"assistant\",\"content\":" + quote(r.content()) + "},\"finish_reason\":\"stop\"}],"
+ "\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}"
: "{\"error\":{\"message\":" + quote(r.content()) + "}}";
byte[] out = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(r.status(), out.length);
exchange.getResponseBody().write(out);
exchange.close();
});
server.start();
}
/** Answers the summarise prompt and the brief prompt with JSON that binds to the matching record. */
static Reply happy(String requestBody) {
return requestBody.contains("Summarise these notes")
? new Reply(200, "{\"text\":\"Virtual threads make blocking cheap.\"}")
: new Reply(200, "{\"text\":\"Virtual threads: blocking is cheap again.\"}");
}
String url() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
void reset(Function<String, Reply> newScript) {
requests.clear();
sdkRetryHeaders.clear();
paths.clear();
script = newScript;
}
private static String quote(String s) {
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
}
@Override
public void close() {
server.stop(0);
}
}
+2 -1
View File
@@ -32,7 +32,8 @@
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Verified on Maven Central 2026-10-11 -->
<embabel.version>1.5.3</embabel.version>
<!-- embabel verified 2026-12-04 -->
<embabel.version>1.5.4</embabel.version>
<a2a.sdk.version>1.0.0.Alpha3</a2a.sdk.version>
<jlama.version>0.8.4</jlama.version>
<djl.version>0.38.0</djl.version>