diff --git a/README.md b/README.md index cae22e6..0d087bd 100644 --- a/README.md +++ b/README.md @@ -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 `/output/` when you run the tests. ## The `jlama` module needs a model and takes minutes diff --git a/embabel/README.md b/embabel/README.md new file mode 100644 index 0000000..4caef38 --- /dev/null +++ b/embabel/README.md @@ -0,0 +1,56 @@ +# embabel: goal-oriented agents for Spring developers + +Companion code for . + +| 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`. diff --git a/embabel/output/07-dependencies.txt b/embabel/output/07-dependencies.txt index 639ddc7..a8d8c64 100644 --- a/embabel/output/07-dependencies.txt +++ b/embabel/output/07-dependencies.txt @@ -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 diff --git a/embabel/output/08-boot-http.txt b/embabel/output/08-boot-http.txt new file mode 100644 index 0000000..868baa0 --- /dev/null +++ b/embabel/output/08-boot-http.txt @@ -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 diff --git a/embabel/output/09-wire-prompts.txt b/embabel/output/09-wire-prompts.txt new file mode 100644 index 0000000..e8da8cd --- /dev/null +++ b/embabel/output/09-wire-prompts.txt @@ -0,0 +1,7 @@ +First request body on the wire, same user question. The date is replaced with . + +Embabel createObject(prompt, Summary.class): +{"messages":[{"content":"Current date: \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"} diff --git a/embabel/output/10-boot-stuck.txt b/embabel/output/10-boot-stuck.txt new file mode 100644 index 0000000..909ac21 --- /dev/null +++ b/embabel/output/10-boot-stuck.txt @@ -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 diff --git a/embabel/output/11-boot-two-agents.txt b/embabel/output/11-boot-two-agents.txt new file mode 100644 index 0000000..4985f89 --- /dev/null +++ b/embabel/output/11-boot-two-agents.txt @@ -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.) diff --git a/embabel/output/12-retries-bad-reply-default.txt b/embabel/output/12-retries-bad-reply-default.txt new file mode 100644 index 0000000..8df960d --- /dev/null +++ b/embabel/output/12-retries-bad-reply-default.txt @@ -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 diff --git a/embabel/output/13-retries-500-default.txt b/embabel/output/13-retries-500-default.txt new file mode 100644 index 0000000..62872cf --- /dev/null +++ b/embabel/output/13-retries-500-default.txt @@ -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 diff --git a/embabel/output/14-boot-wrong-model.txt b/embabel/output/14-boot-wrong-model.txt new file mode 100644 index 0000000..84ceeb5 --- /dev/null +++ b/embabel/output/14-boot-wrong-model.txt @@ -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: []. diff --git a/embabel/output/15-unit-action.txt b/embabel/output/15-unit-action.txt new file mode 100644 index 0000000..0aa2900 --- /dev/null +++ b/embabel/output/15-unit-action.txt @@ -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 diff --git a/embabel/output/16-two-goals.txt b/embabel/output/16-two-goals.txt new file mode 100644 index 0000000..027652b --- /dev/null +++ b/embabel/output/16-two-goals.txt @@ -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. diff --git a/embabel/output/17-costs-swapped.txt b/embabel/output/17-costs-swapped.txt new file mode 100644 index 0000000..1b23dae --- /dev/null +++ b/embabel/output/17-costs-swapped.txt @@ -0,0 +1,3 @@ +Same two summarisers, costs swapped (LLM 0.1, local 0.9). + +ran: [findSources, summariseWithLlm, writeBrief] diff --git a/embabel/output/18-plain-guarded.txt b/embabel/output/18-plain-guarded.txt new file mode 100644 index 0000000..7663162 --- /dev/null +++ b/embabel/output/18-plain-guarded.txt @@ -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 diff --git a/embabel/output/19-mockito-boot.txt b/embabel/output/19-mockito-boot.txt new file mode 100644 index 0000000..755df7b --- /dev/null +++ b/embabel/output/19-mockito-boot.txt @@ -0,0 +1,3 @@ +@SpringBootTest + EmbabelMockitoIntegrationTest, no HTTP provider. + +result: Brief[text=Virtual threads: blocking is cheap again.] diff --git a/embabel/output/20-retries-bad-reply-tamed.txt b/embabel/output/20-retries-bad-reply-tamed.txt new file mode 100644 index 0000000..982755b --- /dev/null +++ b/embabel/output/20-retries-bad-reply-tamed.txt @@ -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 diff --git a/embabel/output/21-retries-500-tamed.txt b/embabel/output/21-retries-500-tamed.txt new file mode 100644 index 0000000..3b8a0e5 --- /dev/null +++ b/embabel/output/21-retries-500-tamed.txt @@ -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 diff --git a/embabel/output/22-boot-checked.txt b/embabel/output/22-boot-checked.txt new file mode 100644 index 0000000..a483338 --- /dev/null +++ b/embabel/output/22-boot-checked.txt @@ -0,0 +1,5 @@ +Profile guarded. + +GET /brief-checked?topic=quantum%20gravity + HTTP 422 {"status":"STUCK","actionsRun":1} + provider calls 0 diff --git a/embabel/output/23-base-url-v1.txt b/embabel/output/23-base-url-v1.txt new file mode 100644 index 0000000..928dbb8 --- /dev/null +++ b/embabel/output/23-base-url-v1.txt @@ -0,0 +1,5 @@ +base-url ends in /v1 + +Requests the fake provider received: + POST /v1/chat/completions + POST /v1/chat/completions diff --git a/embabel/output/24-two-goals-across-jvms.txt b/embabel/output/24-two-goals-across-jvms.txt new file mode 100644 index 0000000..ab0ae84 --- /dev/null +++ b/embabel/output/24-two-goals-across-jvms.txt @@ -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 diff --git a/embabel/pom.xml b/embabel/pom.xml index 72e5102..3e02c59 100644 --- a/embabel/pom.xml +++ b/embabel/pom.xml @@ -18,6 +18,27 @@ embabel-agent-api ${embabel.version} + + com.embabel.agent + embabel-agent-starter + ${embabel.version} + + + com.embabel.agent + embabel-agent-starter-openai-custom + ${embabel.version} + + + org.springframework.boot + spring-boot-starter-web + 4.1.1 + + + com.embabel.agent + embabel-agent-test + ${embabel.version} + test + org.junit.jupiter junit-jupiter diff --git a/embabel/scripts/two-goals-across-jvms.sh b/embabel/scripts/two-goals-across-jvms.sh new file mode 100755 index 0000000..d830bb2 --- /dev/null +++ b/embabel/scripts/two-goals-across-jvms.sh @@ -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" diff --git a/embabel/src/main/java/com/ankurm/agents/embabel/PlainGuardedResearch.java b/embabel/src/main/java/com/ankurm/agents/embabel/PlainGuardedResearch.java new file mode 100644 index 0000000..a832888 --- /dev/null +++ b/embabel/src/main/java/com/ankurm/agents/embabel/PlainGuardedResearch.java @@ -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 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 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(); + } +} diff --git a/embabel/src/main/java/com/ankurm/agents/embabel/TwoGoalsAgent.java b/embabel/src/main/java/com/ankurm/agents/embabel/TwoGoalsAgent.java new file mode 100644 index 0000000..018270d --- /dev/null +++ b/embabel/src/main/java/com/ankurm/agents/embabel/TwoGoalsAgent.java @@ -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); + } +} diff --git a/embabel/src/main/java/com/ankurm/agents/embabel/boot/AgentSelection.java b/embabel/src/main/java/com/ankurm/agents/embabel/boot/AgentSelection.java new file mode 100644 index 0000000..be13312 --- /dev/null +++ b/embabel/src/main/java/com/ankurm/agents/embabel/boot/AgentSelection.java @@ -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 { + } +} diff --git a/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefApplication.java b/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefApplication.java new file mode 100644 index 0000000..747fe1c --- /dev/null +++ b/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefApplication.java @@ -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); + } +} diff --git a/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefController.java b/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefController.java new file mode 100644 index 0000000..c3aa076 --- /dev/null +++ b/embabel/src/main/java/com/ankurm/agents/embabel/boot/BriefController.java @@ -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 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())); + } +} diff --git a/embabel/src/main/resources/application.yml b/embabel/src/main/resources/application.yml new file mode 100644 index 0000000..1ab94c1 --- /dev/null +++ b/embabel/src/main/resources/application.yml @@ -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} diff --git a/embabel/src/test/java/com/ankurm/agents/embabel/MockitoBootTest.java b/embabel/src/test/java/com/ankurm/agents/embabel/MockitoBootTest.java new file mode 100644 index 0000000..836b8bf --- /dev/null +++ b/embabel/src/test/java/com/ankurm/agents/embabel/MockitoBootTest.java @@ -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"); + } +} diff --git a/embabel/src/test/java/com/ankurm/agents/embabel/TestingLayersTest.java b/embabel/src/test/java/com/ankurm/agents/embabel/TestingLayersTest.java new file mode 100644 index 0000000..a219e49 --- /dev/null +++ b/embabel/src/test/java/com/ankurm/agents/embabel/TestingLayersTest.java @@ -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 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 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"); + } +} diff --git a/embabel/src/test/java/com/ankurm/agents/embabel/Transcript.java b/embabel/src/test/java/com/ankurm/agents/embabel/Transcript.java index 80e3ce3..14d6902 100644 --- a/embabel/src/test/java/com/ankurm/agents/embabel/Transcript.java +++ b/embabel/src/test/java/com/ankurm/agents/embabel/Transcript.java @@ -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); diff --git a/embabel/src/test/java/com/ankurm/agents/embabel/boot/BootTest.java b/embabel/src/test/java/com/ankurm/agents/embabel/boot/BootTest.java new file mode 100644 index 0000000..517489a --- /dev/null +++ b/embabel/src/test/java/com/ankurm/agents/embabel/boot/BootTest.java @@ -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 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 get(ConfigurableApplicationContext app, String topic) throws IOException, InterruptedException { + return getPath(app, "/brief", topic); + } + + private static HttpResponse 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: "); + } + + @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 .\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 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 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"); + } + } +} diff --git a/embabel/src/test/java/com/ankurm/agents/embabel/boot/FakeOpenAiServer.java b/embabel/src/test/java/com/ankurm/agents/embabel/boot/FakeOpenAiServer.java new file mode 100644 index 0000000..3cf051a --- /dev/null +++ b/embabel/src/test/java/com/ankurm/agents/embabel/boot/FakeOpenAiServer.java @@ -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 requests = new CopyOnWriteArrayList<>(); + final List paths = new CopyOnWriteArrayList<>(); + final List sdkRetryHeaders = new CopyOnWriteArrayList<>(); + volatile Function script; + private final HttpServer server; + + FakeOpenAiServer(Function 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 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); + } +} diff --git a/pom.xml b/pom.xml index adc3b9b..497cc1d 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,8 @@ 25 UTF-8 - 1.5.3 + + 1.5.4 1.0.0.Alpha3 0.8.4 0.38.0