Add tool-confirmation module: Spring AI 2.1 human-in-the-loop tool calls (requiresConfirmation, ToolCallConfirmationPolicy, ToolCallDecisions pause and resume), a server-side approval store with approver check, replay guard and audit log, and an approver page over SSE and htmx; 17 transcripts. The model is a scripted ChatModel; the htmx page was not opened in a browser. Spring Boot 4.1.3, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5x1ufsjyvu9RJFUUb
This commit is contained in:
@@ -36,5 +36,7 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur
|
||||
| [`batch-llm/`](batch-llm) | 100,000 synthetic support tickets classified by a `ChatClient` inside a Spring Batch 6 chunk step: a Resilience4j rate limiter and retry around the model call (and where Spring Batch's own retry and skip belong instead), replies that are not valid JSON skipped and recorded, a restart after `kill -9` in a second JVM that ends with a byte-identical result, and a cost ledger row committed with every chunk. **The model is a deterministic simulated `ChatModel`, not a language model; token counts are estimates and prices are configurable placeholders.** Spring Boot 4.1.2, Spring Batch 6.0.6, Spring AI 2.0.2, Resilience4j 2.4.0, Java 25. | [Spring AI + Spring Batch: Classifying 100,000 Support Tickets with an LLM](https://ankurm.com/spring-ai-spring-batch-llm-ticket-classification/) |
|
||||
| [`docker-model-runner/`](docker-model-runner) | The Spring AI OpenAI starter pointed at Docker Model Runner and at Ollama by changing only `base-url` and the model name (no `/v1` is appended: the path is used exactly as given), plus a benchmark runner: time to first token, decode tokens/second, container memory from `docker stats` and tool-call success over 10 runs. Measured with the real `docker/model-runner` v1.2.9 CPU image and Ollama 0.40.13 on one shared 2-vCPU sandbox, Qwen2.5-0.5B Q4_K_M; no GPU, and Docker Desktop's `docker model` path was not used. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Spring AI with Docker Model Runner vs Ollama: Local LLMs Benchmarked on the Same Laptop](https://ankurm.com/spring-ai-docker-model-runner-vs-ollama/) |
|
||||
| [`chat-ui-htmx/`](chat-ui-htmx) | A streaming chat page with no JavaScript of our own: htmx and its SSE extension (vendored) post the message and append each token from a `Flux<ServerSentEvent<String>>` over `ChatClient` with `MessageChatMemoryAdvisor` keyed by the HTTP session. Measured traps: EventSource strips one leading space per data line, model text must be HTML-escaped, a cancelled stream left the upstream connection open in 7 of 8 runs until an OkHttp interceptor made it `call.cancel()` (closed in 8 of 8 after), and the SDK's push source ignores back-pressure (`limitRate` changes nothing; a bounded buffer does). Checked in headless Chromium. **The model is a stub OpenAI-compatible SSE server I wrote, not a language model; no real provider was run.** Spring Boot 4.1.2, Spring AI 2.0.2, htmx 2.0.11, Java 25. | [Streaming AI Chat UI with Spring AI, SSE and htmx (No React Needed)](https://ankurm.com/spring-ai-streaming-chat-ui-sse-htmx/) |
|
||||
| [`tool-confirmation/`](tool-confirmation) | Human-in-the-loop tool calls in Spring AI 2.1: `@Tool(requiresConfirmation = true)`, `ToolCallConfirmationPolicy` (by metadata, by name, by argument), the pause and resume with `ToolCallDecisions`, deny messages, and what the application must add itself: a server-side pause store, an approver check, a replay guard (one winner among 16 concurrent approvers), an audit log, and an approver page over SSE and htmx with model-chosen arguments HTML-escaped. Also measured: an open SSE stream holds up Spring Boot's graceful shutdown. **The model is a scripted `ChatModel`, not a language model; the htmx page was not opened in a browser.** Spring Boot 4.1.3, Spring AI 2.1.0, Java 25. | [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/) |
|
||||
|
||||
|
||||
Upgrading from Spring AI 1.x: [migration guide](https://ankurm.com/spring-ai-1-to-2-migration-guide/).
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# tool-confirmation
|
||||
|
||||
Human-in-the-loop tool calls in Spring AI 2.1: `requiresConfirmation`, `ToolCallConfirmationPolicy`,
|
||||
`ToolCallDecisions`, the pause and the resume, and everything the framework leaves to the
|
||||
application -- where the paused reply lives, who may approve, a pause that resolves once, an audit
|
||||
log, and an approver page driven by Server-Sent Events and htmx. **The model is a hand-written
|
||||
`ScriptedChatModel`, not a language model**: every test queues the tool calls the "model" makes, so
|
||||
what is asserted is Spring AI's real pause/resume code, not how often a real model asks for a tool.
|
||||
|
||||
Companion code for [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/)
|
||||
on [ankurm.com](https://ankurm.com).
|
||||
|
||||
## Versions
|
||||
|
||||
| Component | Version |
|
||||
|---|---|
|
||||
| Spring Boot | 4.1.3 |
|
||||
| Spring AI | 2.1.0 (GA; Maven Central lists it under 2026-11-19) |
|
||||
| Java | 25 (Temurin 25.0.5.1) |
|
||||
| htmx / SSE extension | 2.0.11 (vendored in `src/main/resources/static/vendor`) |
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
./scripts/run-all.sh
|
||||
```
|
||||
|
||||
No API key, no network once Maven has its dependencies, no Docker. Every file in `output/` is
|
||||
written by the test suite itself (the `Transcript` helper), so each number in the article is an
|
||||
assertion that fails the build when it stops being true.
|
||||
|
||||
## What is here
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| [`tools/FlightTools.java`](src/main/java/com/ankurm/toolconfirmation/tools/FlightTools.java) | One harmless tool and two with `@Tool(requiresConfirmation = true)`. |
|
||||
| [`tools/TransferTools.java`](src/main/java/com/ankurm/toolconfirmation/tools/TransferTools.java) | A tool with no annotation, paused from the outside (by name, or by its arguments). |
|
||||
| [`tools/DeleteFileTool.java`](src/main/java/com/ankurm/toolconfirmation/tools/DeleteFileTool.java) | The programmatic way: `ToolMetadata.builder().requiresConfirmation(true)`. |
|
||||
| [`config/ConfirmationPolicies.java`](src/main/java/com/ankurm/toolconfirmation/config/ConfirmationPolicies.java) | A `ToolCallConfirmationPolicy` bean that pauses transfers over USD 1,000. |
|
||||
| [`config/ChatClientFactory.java`](src/main/java/com/ankurm/toolconfirmation/config/ChatClientFactory.java) | The one `ChatClient` construction, shared by the app and the tests. |
|
||||
| [`approval/ApprovalService.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalService.java) | Pause handling, the approver check, resume, audit. |
|
||||
| [`approval/ApprovalStore.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalStore.java) | Server-side pauses; `take` is atomic so one approver wins. |
|
||||
| [`approval/AuditLog.java`](src/main/java/com/ankurm/toolconfirmation/approval/AuditLog.java) | PAUSED / APPROVED / DENIED / refusals, with who and what. |
|
||||
| [`approval/ApprovalEvents.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalEvents.java) | SSE fan-out, completed on stop so graceful shutdown is not held up. |
|
||||
| [`web/ApiController.java`](src/main/java/com/ankurm/toolconfirmation/web/ApiController.java) | `/api/chat`, `/api/approvals`, `/api/approvals/{id}/decisions`, `/approvals/stream`. |
|
||||
| [`web/ApproverUiController.java`](src/main/java/com/ankurm/toolconfirmation/web/ApproverUiController.java) | The htmx fragments, with everything the model chose HTML-escaped. |
|
||||
| [`static/approver.html`](src/main/resources/static/approver.html) | The approver page: one SSE connection, no polling. |
|
||||
|
||||
## Output files
|
||||
|
||||
| File | What it captures |
|
||||
|---|---|
|
||||
| `output/01-pause-and-resume.txt` | One gated call: pause, nothing runs, allow, run, second model call. |
|
||||
| `output/02-whole-reply-pauses.txt` | A harmless call beside a gated one also waits; `awaitingDecision` lists only the gated key but every call needs a decision. |
|
||||
| `output/03-deny-messages.txt` | What the model receives for a bare deny and for a deny with a message. |
|
||||
| `output/04-policies.txt` | Ten policy / call combinations: which pause, which run. |
|
||||
| `output/05-resume-errors.txt` | The three `IllegalArgumentException`s of a refused resume, and an empty ledger. |
|
||||
| `output/06-replay-is-not-prevented.txt` | The same decisions twice: the tool runs twice. |
|
||||
| `output/07-multi-round-turn.txt` | A search round before the gated call is missing from the resumed request. |
|
||||
| `output/08-tools-property.txt` | `spring.ai.tools.confirmation.tools` pausing an unannotated tool. |
|
||||
| `output/09-confirmation-disabled.txt` | `enabled=false`: the startup warning, the flag ignored, the policy bean still applies. |
|
||||
| `output/10-http-flow.txt` | The API end to end: 200, 403, 400, 200, 409, 404. |
|
||||
| `output/11-audit-log.txt` | The audit lines for that exchange. |
|
||||
| `output/12-concurrent-approvers.txt` | Sixteen simultaneous approvals: one booking. |
|
||||
| `output/13-approver-ui-and-sse.txt` | SSE events, and an injected tool argument rendered escaped. |
|
||||
| `output/14-sse-and-graceful-shutdown.txt` | An open SSE stream against Boot's graceful shutdown, with and without closing it first. |
|
||||
| `output/15-api-surface.txt` | `javap -public` of the confirmation classes in the 2.1.0 jars, and the two properties with their defaults (`scripts/api-surface.sh`). |
|
||||
| `output/16-position-keys.txt` | Keys when a provider sends no id or the same id twice: `#0`, `#1`. |
|
||||
| `output/17-custom-manager.txt` | A `ToolCallingManager` wrapper that does not delegate the decision overload: the pause works, the resume throws. |
|
||||
|
||||
## What was NOT run
|
||||
|
||||
- No real model. Whether a particular provider's model asks for the tools you expect is a separate question.
|
||||
- The htmx page was never opened in a browser; the tests check the server side of it (events, fragments, escaping).
|
||||
- Streaming (`.stream()`), session memory and chat-memory resumption are described in the article from the reference documentation only.
|
||||
- The pause store is in memory and does not survive a restart; persisting it is left to you.
|
||||
- The approver identity is a request header so the check is visible. It is a stand-in for an authenticated principal.
|
||||
@@ -0,0 +1,23 @@
|
||||
# A gated tool pauses the loop; an approval resumes it
|
||||
|
||||
-- first request ----------------------------------------------
|
||||
model calls so far: 1
|
||||
reply text (content()): ''
|
||||
reply has tool calls: true
|
||||
awaitingDecision(reply): [call_1]
|
||||
isAwaitingDecision(reply): true
|
||||
tool call shown to the person: bookFlight {"flightNumber":"VX205"}
|
||||
ledger (real side effects): []
|
||||
metadata key holding the keys: spring.ai.tool-calls-awaiting-decision
|
||||
|
||||
-- after allow(call_1) + executeToolCalls ---------------------
|
||||
ledger (real side effects): [bookFlight VX205]
|
||||
conversationHistory():
|
||||
UserMessage[Book flight VX205 for tomorrow]
|
||||
AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}]
|
||||
ToolResponseMessage[call_1:bookFlight -> "Booked VX205, reference BK-5"]
|
||||
returnDirect(): false
|
||||
|
||||
-- resumed request --------------------------------------------
|
||||
model calls so far: 2
|
||||
final answer: Done. VX205 is booked.
|
||||
@@ -0,0 +1,13 @@
|
||||
# One gated call pauses the whole reply, including the harmless call beside it
|
||||
|
||||
calls in the reply: [call_1=searchFlights, call_2=bookFlight]
|
||||
awaitingDecision(reply): [call_2]
|
||||
ledger after the pause: []
|
||||
|
||||
decision for call_2 only -> IllegalArgumentException:
|
||||
Every tool call of the reply needs a decision; missing: [call_1]
|
||||
ledger after the refused resume: []
|
||||
|
||||
decisions for both -> ledger: [searchFlights BOS->SFO, bookFlight VX205]
|
||||
tool results, in the model's order:
|
||||
ToolResponseMessage[call_1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"][call_2:bookFlight -> "Booked VX205, reference BK-5"]
|
||||
@@ -0,0 +1,12 @@
|
||||
# What the model receives when a call is denied
|
||||
|
||||
DEFAULT_DENY_MESSAGE: The user did not allow this tool call.
|
||||
|
||||
history the model is sent next:
|
||||
UserMessage[Rebook me on VX205]
|
||||
AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}, call_2:cancelBooking{"reference":"BK-9"}]
|
||||
ToolResponseMessage[call_1:bookFlight -> The user did not allow this tool call.][call_2:cancelBooking -> The user wants an aisle seat, ask again.]
|
||||
|
||||
ledger (nothing ran): []
|
||||
returnDirect(): false
|
||||
model's next answer: Understood, I will ask which seat you prefer.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Which calls pause under which policy
|
||||
|
||||
policy | call result
|
||||
default (fromToolMetadata) | bookFlight PAUSES [c1]
|
||||
default (fromToolMetadata) | transferMoney 500 runs (ledger [transferMoney ACME 500])
|
||||
none() | bookFlight runs (ledger [bookFlight VX205])
|
||||
forTools("transferMoney") | transferMoney 500 PAUSES [c2]
|
||||
forTools("transferMoney") | bookFlight runs (ledger [bookFlight VX205])
|
||||
over-1000 argument policy | transferMoney 500 runs (ledger [transferMoney ACME 500])
|
||||
over-1000 argument policy | transferMoney 5000 PAUSES [c3]
|
||||
over-1000 argument policy | bookFlight runs (ledger [bookFlight VX205])
|
||||
fromToolMetadata().or(over-1000)| bookFlight PAUSES [c1]
|
||||
fromToolMetadata().or(over-1000)| transferMoney 5000 PAUSES [c3]
|
||||
@@ -0,0 +1,10 @@
|
||||
# Three refused resumes
|
||||
|
||||
1. no decision for call_1:
|
||||
IllegalArgumentException: Every tool call of the reply needs a decision; missing: [call_1]
|
||||
2. a decision for a key that is not in the reply (call_99):
|
||||
IllegalArgumentException: No tool call has the key 'call_99'; the reply's tool call keys: [call_1]
|
||||
3. allowed call, but its tool is not on the Prompt:
|
||||
IllegalArgumentException: The prompt does not carry the tool 'bookFlight' of the allowed call 'call_1'; an allowed call runs only with a tool of the prompt
|
||||
|
||||
ledger after all three: []
|
||||
@@ -0,0 +1,5 @@
|
||||
# executeToolCalls twice with the same decisions on the same reply
|
||||
|
||||
calls to executeToolCalls: 2
|
||||
ledger: [bookFlight VX205, bookFlight VX205]
|
||||
A customer is booked, and charged, twice.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Search (ungated) then book (gated) in one turn: what the model sees on each call
|
||||
|
||||
ledger at the pause: [searchFlights BOS->SFO]
|
||||
model calls: 3
|
||||
|
||||
prompt 1 sent to the model:
|
||||
UserMessage[Find a flight BOS to SFO and book the first one]
|
||||
|
||||
prompt 2 sent to the model:
|
||||
UserMessage[Find a flight BOS to SFO and book the first one]
|
||||
AssistantMessage[toolCalls=s1:searchFlights{"from":"BOS","to":"SFO"}]
|
||||
ToolResponseMessage[s1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"]
|
||||
|
||||
prompt 3 sent to the model:
|
||||
UserMessage[Find a flight BOS to SFO and book the first one]
|
||||
AssistantMessage[toolCalls=b1:bookFlight{"flightNumber":"VX205"}]
|
||||
ToolResponseMessage[b1:bookFlight -> "Booked VX205, reference BK-5"]
|
||||
|
||||
Prompt 2 had the search round; prompt 3 (the resume) does not.
|
||||
@@ -0,0 +1,5 @@
|
||||
# spring.ai.tools.confirmation.tools=transferMoney (a USD 5 transfer, far under the 1000 policy bean)
|
||||
|
||||
status: AWAITING_APPROVAL
|
||||
calls: [CallView[key=t1, name=transferMoney, arguments={"payee":"ACME","amount":5}]]
|
||||
ledger: []
|
||||
@@ -0,0 +1,6 @@
|
||||
# spring.ai.tools.confirmation.enabled=false
|
||||
|
||||
startup warning: WARN ToolCallingAutoConfiguration: Tool call confirmation is disabled (spring.ai.tools.confirmation.enabled=false): tools marked requiresConfirmation run as soon as the model calls them, without a person's confirmation.
|
||||
|
||||
bookFlight (requiresConfirmation = true): status=DONE ledger=[bookFlight VX205]
|
||||
transferMoney 5000 (policy bean): status=AWAITING_APPROVAL ledger=[bookFlight VX205]
|
||||
@@ -0,0 +1,27 @@
|
||||
# The approval API over HTTP
|
||||
|
||||
POST /api/chat (carol: Book VX205)
|
||||
-> 200 {"status":"AWAITING_APPROVAL","answer":null,"approvalId":"4dbe1483","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]}
|
||||
ledger: []
|
||||
|
||||
GET /api/approvals
|
||||
-> 200 [{"id":"4dbe1483","conversationId":"c1","requestedBy":"carol","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]}]
|
||||
|
||||
POST /api/approvals/4dbe1483/decisions X-Approver: mallory (allow call_1)
|
||||
-> 403 {"error":"'mallory' may not approve"}
|
||||
ledger: []
|
||||
|
||||
POST /api/approvals/4dbe1483/decisions X-Approver: alice (no decisions)
|
||||
-> 400 {"error":"Every tool call of the reply needs a decision; missing: [call_1]"}
|
||||
still pending: true
|
||||
|
||||
POST /api/approvals/4dbe1483/decisions X-Approver: alice (allow call_1)
|
||||
-> 200 {"status":"DONE","answer":"Booked VX205. Reference BK-5.","approvalId":null,"calls":[]}
|
||||
ledger: [bookFlight VX205]
|
||||
|
||||
POST /api/approvals/4dbe1483/decisions X-Approver: bob (the same pause again)
|
||||
-> 409 {"error":"approval 4dbe1483 was already resolved"}
|
||||
ledger: [bookFlight VX205]
|
||||
|
||||
POST /api/approvals/nope0000/decisions X-Approver: alice
|
||||
-> 404 {"error":"no such approval nope0000"}
|
||||
@@ -0,0 +1,7 @@
|
||||
# What the audit log recorded for that exchange
|
||||
|
||||
PAUSED approval=4dbe1483 actor=carol tool=bookFlight {"flightNumber":"VX205"}
|
||||
APPROVER_REFUSED approval=4dbe1483 actor=mallory tool=- not in the approver list
|
||||
DECISION_REJECTED approval=4dbe1483 actor=alice tool=- Every tool call of the reply needs a decision; missing: [call_1]
|
||||
APPROVED approval=4dbe1483 actor=alice tool=bookFlight {"flightNumber":"VX205"}
|
||||
REPLAY_REFUSED approval=4dbe1483 actor=bob tool=- pause already resolved
|
||||
@@ -0,0 +1,5 @@
|
||||
# 16 threads approve the same pause at once
|
||||
|
||||
1 x 200 DONE
|
||||
15 x 409 approval <id> was already resolved
|
||||
ledger: [bookFlight VX205]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Approver page: SSE events and an escaped fragment (injected tool argument)
|
||||
|
||||
tool argument chosen by the model: <img src=x onerror=alert(1)>
|
||||
|
||||
SSE lines the approver page received:
|
||||
event:hello
|
||||
data:connected
|
||||
event:approval-requested
|
||||
data:69b1d486
|
||||
event:approval-resolved
|
||||
data:69b1d486
|
||||
|
||||
GET /ui/approvals (the <pre> element):
|
||||
<pre>{"flightNumber":"<img src=x onerror=alert(1)>"}</pre>
|
||||
|
||||
POST /ui/approvals/69b1d486 (approver=alice, deny) ->
|
||||
<p class="ok">Decision recorded.</p>
|
||||
ledger: []
|
||||
|
||||
approver.html wiring:
|
||||
<!-- The page opens ONE SSE connection. Each event re-runs the hx-get below; the browser never polls. -->
|
||||
<body hx-ext="sse" sse-connect="/approvals/stream">
|
||||
<div id="pending" hx-get="/ui/approvals" hx-trigger="load, sse:approval-requested, sse:approval-resolved"></div>
|
||||
@@ -0,0 +1,5 @@
|
||||
# ctx.close() with one approver page connected (grace period 5000 ms)
|
||||
|
||||
streams left open: over 4000 ms
|
||||
streams completed by the lifecycle: under 2000 ms
|
||||
(the exact figures vary per run; the 5 s wall is the configured grace period)
|
||||
@@ -0,0 +1,63 @@
|
||||
# Public API of the confirmation classes, from spring-ai-model-2.1.0.jar (javap -public)
|
||||
|
||||
public interface org.springframework.ai.model.tool.ToolCallConfirmationPolicy {
|
||||
public abstract boolean requiresConfirmation(org.springframework.ai.chat.messages.AssistantMessage$ToolCall, org.springframework.ai.tool.metadata.ToolMetadata);
|
||||
public default org.springframework.ai.model.tool.ToolCallConfirmationPolicy or(org.springframework.ai.model.tool.ToolCallConfirmationPolicy);
|
||||
public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy none();
|
||||
public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy fromToolMetadata();
|
||||
public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy forTools(java.lang.String...);
|
||||
}
|
||||
|
||||
public class org.springframework.ai.model.tool.ToolCallConfirmationRequiredException extends java.lang.RuntimeException {
|
||||
public org.springframework.ai.model.tool.ToolCallConfirmationRequiredException(java.util.List<java.lang.String>);
|
||||
public java.util.List<java.lang.String> getToolCallIds();
|
||||
}
|
||||
|
||||
public final class org.springframework.ai.model.tool.ToolCallDecision extends java.lang.Record {
|
||||
public static final java.lang.String DEFAULT_DENY_MESSAGE;
|
||||
public org.springframework.ai.model.tool.ToolCallDecision(java.lang.String, boolean, java.lang.String);
|
||||
public static org.springframework.ai.model.tool.ToolCallDecision allow(java.lang.String);
|
||||
public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String);
|
||||
public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String, java.lang.String);
|
||||
public java.lang.String denyMessage();
|
||||
public final java.lang.String toString();
|
||||
public final int hashCode();
|
||||
public final boolean equals(java.lang.Object);
|
||||
public java.lang.String toolCallId();
|
||||
public boolean allowed();
|
||||
public java.lang.String message();
|
||||
}
|
||||
|
||||
public final class org.springframework.ai.model.tool.ToolCallDecisions extends java.lang.Record {
|
||||
public static final java.lang.String POSITION_KEY_PREFIX;
|
||||
public static final java.lang.String AWAITING_DECISION_METADATA_KEY;
|
||||
public org.springframework.ai.model.tool.ToolCallDecisions(java.util.List<org.springframework.ai.model.tool.ToolCallDecision>);
|
||||
public static org.springframework.ai.model.tool.ToolCallDecisions of(org.springframework.ai.model.tool.ToolCallDecision...);
|
||||
public org.springframework.ai.model.tool.ToolCallDecision decisionOn(java.lang.String);
|
||||
public static java.util.List<java.lang.String> toolCallKeys(org.springframework.ai.chat.messages.AssistantMessage);
|
||||
public static java.util.List<java.lang.String> awaitingDecision(org.springframework.ai.chat.model.ChatResponse);
|
||||
public static boolean isAwaitingDecision(org.springframework.ai.chat.model.ChatResponse);
|
||||
public final java.lang.String toString();
|
||||
public final int hashCode();
|
||||
public final boolean equals(java.lang.Object);
|
||||
public java.util.List<org.springframework.ai.model.tool.ToolCallDecision> decisions();
|
||||
}
|
||||
|
||||
public interface org.springframework.ai.tool.metadata.ToolMetadata {
|
||||
public default boolean returnDirect();
|
||||
public default boolean requiresConfirmation();
|
||||
public static org.springframework.ai.tool.metadata.DefaultToolMetadata$Builder builder();
|
||||
public static org.springframework.ai.tool.metadata.ToolMetadata from(java.lang.reflect.Method);
|
||||
}
|
||||
|
||||
# ToolCallingManager (the overload resumption uses is a default method)
|
||||
public interface org.springframework.ai.model.tool.ToolCallingManager {
|
||||
public abstract java.util.List<org.springframework.ai.tool.definition.ToolDefinition> resolveToolDefinitions(org.springframework.ai.model.tool.ToolCallingChatOptions);
|
||||
public abstract org.springframework.ai.model.tool.ToolExecutionResult executeToolCalls(org.springframework.ai.chat.prompt.Prompt, org.springframework.ai.chat.model.ChatResponse);
|
||||
public default org.springframework.ai.model.tool.ToolExecutionResult executeToolCalls(org.springframework.ai.chat.prompt.Prompt, org.springframework.ai.chat.model.ChatResponse, org.springframework.ai.model.tool.ToolCallDecisions);
|
||||
public static org.springframework.ai.model.tool.DefaultToolCallingManager$Builder builder();
|
||||
}
|
||||
|
||||
# Configuration properties, from spring-ai-autoconfigure-model-tool-2.1.0.jar
|
||||
spring.ai.tools.confirmation.enabled | default: True
|
||||
spring.ai.tools.confirmation.tools | default: None
|
||||
@@ -0,0 +1,7 @@
|
||||
# Tool call keys when ids are missing or repeated
|
||||
|
||||
POSITION_KEY_PREFIX: #
|
||||
two calls that both have id 'dup' -> keys: [#0, #1]
|
||||
awaitingDecision for that reply: [#0, #1]
|
||||
one call with an empty id -> keys: [#0]
|
||||
allow('#0') + deny('#1') -> ledger: [bookFlight VX205]
|
||||
@@ -0,0 +1,5 @@
|
||||
# A ToolCallingManager that wraps the default and forgets the decision overload
|
||||
|
||||
pause through the wrapping manager: awaitingDecision = [call_1]
|
||||
resume through the wrapping manager: UnsupportedOperationException: com.ankurm.toolconfirmation.CustomManagerTest$ForgetfulManager does not support tool call decisions
|
||||
ledger: []
|
||||
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.1.3</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>tool-confirmation</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>tool-confirmation</name>
|
||||
<description>Human-in-the-loop tool calls in Spring AI 2.1: requiresConfirmation, ToolCallConfirmationPolicy, ToolCallDecisions, pause and resume, an approval API with SSE and htmx, and an audit log.</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<!-- Spring AI is not managed by the Spring Boot BOM: this pair is yours to keep compatible. -->
|
||||
<spring-ai.version>2.1.0</spring-ai.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bom</artifactId>
|
||||
<version>${spring-ai.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-model-openai</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>-Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes output/15-api-surface.txt: the public API of the confirmation classes as the 2.1.0 jars
|
||||
# declare it (javap), and the two configuration properties from the autoconfigure metadata.
|
||||
# Requires the jars in ~/.m2 (run ./scripts/run-all.sh or any build once) and JDK 25 on PATH.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
M="${HOME}/.m2/repository/org/springframework/ai"
|
||||
MODEL="$M/spring-ai-model/2.1.0/spring-ai-model-2.1.0.jar"
|
||||
AUTO="$M/spring-ai-autoconfigure-model-tool/2.1.0/spring-ai-autoconfigure-model-tool-2.1.0.jar"
|
||||
OUT=output/15-api-surface.txt
|
||||
{
|
||||
echo "# Public API of the confirmation classes, from spring-ai-model-2.1.0.jar (javap -public)"
|
||||
echo
|
||||
for c in ToolCallConfirmationPolicy ToolCallConfirmationRequiredException ToolCallDecision ToolCallDecisions; do
|
||||
javap -cp "$MODEL" -public "org.springframework.ai.model.tool.$c" 2>/dev/null | grep -v '^Compiled from'
|
||||
echo
|
||||
done
|
||||
javap -cp "$MODEL" -public org.springframework.ai.tool.metadata.ToolMetadata 2>/dev/null | grep -v '^Compiled from'
|
||||
echo
|
||||
echo "# ToolCallingManager (the overload resumption uses is a default method)"
|
||||
javap -cp "$MODEL" -public org.springframework.ai.model.tool.ToolCallingManager 2>/dev/null | grep -v '^Compiled from'
|
||||
echo
|
||||
echo "# Configuration properties, from spring-ai-autoconfigure-model-tool-2.1.0.jar"
|
||||
unzip -p "$AUTO" META-INF/spring-configuration-metadata.json | python3 -c "
|
||||
import json, sys
|
||||
for p in json.load(sys.stdin)['properties']:
|
||||
if 'confirmation' in p['name']:
|
||||
print(p['name'], '| default:', p.get('defaultValue'))"
|
||||
} > "$OUT"
|
||||
cat "$OUT"
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file under output/ -- the test suite writes each one itself through the
|
||||
# Transcript helper, overwriting it in place. No file in output/ is hand-captured.
|
||||
# Needs JDK 25 on PATH (JAVA_HOME) and Maven; no API key, no Docker, no network once the
|
||||
# dependencies are in the local repository.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -rf target
|
||||
mvn -q test
|
||||
./scripts/api-surface.sh > /dev/null
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class ToolConfirmationApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ToolConfirmationApplication.class, args);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.SmartLifecycle;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/** Fan-out of "something changed" to every open approver page over Server-Sent Events. */
|
||||
@Component
|
||||
public class ApprovalEvents implements SmartLifecycle {
|
||||
|
||||
private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();
|
||||
private volatile boolean running;
|
||||
private final boolean closeStreamsOnStop;
|
||||
|
||||
/** The flag exists only so output/14 can measure the cost of leaving it off. Keep it true. */
|
||||
public ApprovalEvents(@Value("${app.approval.close-streams-on-stop:true}") boolean closeStreamsOnStop) {
|
||||
this.closeStreamsOnStop = closeStreamsOnStop;
|
||||
}
|
||||
|
||||
public SseEmitter subscribe() {
|
||||
SseEmitter emitter = new SseEmitter(0L);
|
||||
this.emitters.add(emitter);
|
||||
emitter.onCompletion(() -> this.emitters.remove(emitter));
|
||||
emitter.onTimeout(() -> this.emitters.remove(emitter));
|
||||
emitter.onError(e -> this.emitters.remove(emitter));
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("hello").data("connected"));
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.emitters.remove(emitter);
|
||||
}
|
||||
return emitter;
|
||||
}
|
||||
|
||||
public void publish(String eventName, String data) {
|
||||
for (SseEmitter emitter : this.emitters) {
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name(eventName).data(data));
|
||||
}
|
||||
catch (IOException | IllegalStateException e) {
|
||||
this.emitters.remove(emitter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Graceful shutdown waits for in-flight requests, and an open SSE stream is one that never
|
||||
* finishes: with Spring Boot's default 30 s grace period an open approver page delays every
|
||||
* stop by 30 s. {@code @PreDestroy} is too late (it runs after the web server has already
|
||||
* waited), so this stops first: the highest phase is stopped before the web server's.
|
||||
*/
|
||||
@Override
|
||||
public void start() {
|
||||
this.running = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (this.closeStreamsOnStop) {
|
||||
this.emitters.forEach(SseEmitter::complete);
|
||||
this.emitters.clear();
|
||||
}
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPhase() {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
public int subscribers() {
|
||||
return this.emitters.size();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/** A refusal that maps to an HTTP status. */
|
||||
public class ApprovalException extends RuntimeException {
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
public ApprovalException(HttpStatus status, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HttpStatus status() {
|
||||
return this.status;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Who may approve. Spring AI does not authenticate the approver: the framework hands your
|
||||
* application a paused reply and takes decisions back. Deciding WHO may decide is yours. This
|
||||
* module uses a plain name list so the check is visible; a real service would read the
|
||||
* authenticated principal and its authorities instead of a request parameter.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "app.approval")
|
||||
public record ApprovalProperties(List<String> approvers) {
|
||||
|
||||
public ApprovalProperties {
|
||||
approvers = approvers == null ? List.of() : List.copyOf(approvers);
|
||||
}
|
||||
|
||||
public boolean mayApprove(String name) {
|
||||
return name != null && this.approvers.contains(name);
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.ankurm.toolconfirmation.tools.ToolRegistry;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* The application half of human-in-the-loop. Spring AI supplies the pause and the resume; this
|
||||
* class supplies everything around them: where the paused reply lives, who may decide, that a pause
|
||||
* is resolved once, and a record of what happened.
|
||||
*/
|
||||
@Service
|
||||
public class ApprovalService {
|
||||
|
||||
public record Verdict(String key, boolean allow, String message) {
|
||||
}
|
||||
|
||||
private final ChatClient chatClient;
|
||||
private final ToolCallingManager toolCallingManager;
|
||||
private final ToolRegistry tools;
|
||||
private final ConversationStore conversations;
|
||||
private final ApprovalStore store;
|
||||
private final ApprovalProperties properties;
|
||||
private final AuditLog audit;
|
||||
private final ApprovalEvents events;
|
||||
|
||||
public ApprovalService(ChatClient chatClient, ToolCallingManager toolCallingManager, ToolRegistry tools,
|
||||
ConversationStore conversations, ApprovalStore store, ApprovalProperties properties, AuditLog audit,
|
||||
ApprovalEvents events) {
|
||||
this.chatClient = chatClient;
|
||||
this.toolCallingManager = toolCallingManager;
|
||||
this.tools = tools;
|
||||
this.conversations = conversations;
|
||||
this.store = store;
|
||||
this.properties = properties;
|
||||
this.audit = audit;
|
||||
this.events = events;
|
||||
}
|
||||
|
||||
/** A new user turn. Returns the answer, or a pause when a gated tool was requested. */
|
||||
public ChatResult chat(String conversationId, String user, String text) {
|
||||
List<Message> conversation = this.conversations.get(conversationId);
|
||||
conversation.add(new UserMessage(text));
|
||||
ChatResponse reply = this.chatClient.prompt().messages(conversation).call().chatResponse();
|
||||
return handle(conversationId, user, conversation, reply);
|
||||
}
|
||||
|
||||
/** An approver's verdicts for one paused turn. */
|
||||
public ChatResult decide(String approvalId, String approver, List<Verdict> verdicts) {
|
||||
PendingApproval pending = this.store.find(approvalId).orElse(null);
|
||||
if (pending == null) {
|
||||
if (this.store.wasResolved(approvalId)) {
|
||||
this.audit.record("REPLAY_REFUSED", approvalId, approver, "-", "pause already resolved");
|
||||
throw new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved");
|
||||
}
|
||||
throw new ApprovalException(HttpStatus.NOT_FOUND, "no such approval " + approvalId);
|
||||
}
|
||||
if (!this.properties.mayApprove(approver)) {
|
||||
this.audit.record("APPROVER_REFUSED", approvalId, String.valueOf(approver), "-", "not in the approver list");
|
||||
throw new ApprovalException(HttpStatus.FORBIDDEN, "'" + approver + "' may not approve");
|
||||
}
|
||||
pending = this.store.take(approvalId).orElseThrow(
|
||||
() -> new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved"));
|
||||
|
||||
ToolCallDecisions decisions = ToolCallDecisions.of(verdicts.stream()
|
||||
.map(v -> v.allow() ? ToolCallDecision.allow(v.key())
|
||||
: (v.message() == null || v.message().isBlank() ? ToolCallDecision.deny(v.key())
|
||||
: ToolCallDecision.deny(v.key(), v.message())))
|
||||
.toArray(ToolCallDecision[]::new));
|
||||
|
||||
ToolExecutionResult result;
|
||||
try {
|
||||
Prompt prompt = new Prompt(pending.conversation(),
|
||||
ToolCallingChatOptions.builder().toolCallbacks(this.tools.callbacks()).build());
|
||||
for (CallView call : pending.calls()) {
|
||||
ToolCallDecision decision = decisions.decisionOn(call.key());
|
||||
if (decision != null) {
|
||||
this.audit.record(decision.allowed() ? "APPROVED" : "DENIED", approvalId, approver, call.name(),
|
||||
call.arguments());
|
||||
}
|
||||
}
|
||||
result = this.toolCallingManager.executeToolCalls(prompt, pending.reply(), decisions);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// Nothing ran: the manager validates the whole decision list before executing any call.
|
||||
this.store.restore(pending);
|
||||
this.audit.record("DECISION_REJECTED", approvalId, approver, "-", e.getMessage());
|
||||
throw new ApprovalException(HttpStatus.BAD_REQUEST, e.getMessage());
|
||||
}
|
||||
|
||||
List<Message> history = new ArrayList<>(result.conversationHistory());
|
||||
ChatResponse next = this.chatClient.prompt().messages(history).call().chatResponse();
|
||||
this.events.publish("approval-resolved", approvalId);
|
||||
return handle(pending.conversationId(), pending.requestedBy(), history, next);
|
||||
}
|
||||
|
||||
private ChatResult handle(String conversationId, String user, List<Message> conversation, ChatResponse reply) {
|
||||
List<String> awaiting = ToolCallDecisions.awaitingDecision(reply);
|
||||
if (!awaiting.isEmpty()) {
|
||||
PendingApproval pending = new PendingApproval(UUID.randomUUID().toString().substring(0, 8),
|
||||
conversationId, user, Instant.now(), List.copyOf(conversation), reply, awaiting);
|
||||
this.store.add(pending);
|
||||
this.conversations.save(conversationId, conversation);
|
||||
for (CallView call : pending.calls()) {
|
||||
this.audit.record("PAUSED", pending.id(), user, call.name(), call.arguments());
|
||||
}
|
||||
this.events.publish("approval-requested", pending.id());
|
||||
return ChatResult.awaiting(pending);
|
||||
}
|
||||
AssistantMessage output = reply.getResult().getOutput();
|
||||
conversation.add(output);
|
||||
this.conversations.save(conversationId, conversation);
|
||||
return ChatResult.done(output.getText());
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* In-memory store of paused turns. {@link #take} removes and returns in one atomic step, so when
|
||||
* two approvers click at the same moment exactly one of them gets the pause, which is the replay
|
||||
* guard the framework does not provide. It does not survive a restart: a paused reply is ordinary
|
||||
* data, so a real service would persist it (and the conversation) in a database.
|
||||
*/
|
||||
@Component
|
||||
public class ApprovalStore {
|
||||
|
||||
private final Map<String, PendingApproval> pending = new ConcurrentHashMap<>();
|
||||
private final Set<String> issued = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public void add(PendingApproval approval) {
|
||||
this.issued.add(approval.id());
|
||||
this.pending.put(approval.id(), approval);
|
||||
}
|
||||
|
||||
public Optional<PendingApproval> find(String id) {
|
||||
return Optional.ofNullable(this.pending.get(id));
|
||||
}
|
||||
|
||||
/** Atomic: the first caller gets the pause, every later caller gets empty. */
|
||||
public Optional<PendingApproval> take(String id) {
|
||||
return Optional.ofNullable(this.pending.remove(id));
|
||||
}
|
||||
|
||||
/** Put a pause back when resuming failed before anything ran (a bad decision list). */
|
||||
public void restore(PendingApproval approval) {
|
||||
this.pending.put(approval.id(), approval);
|
||||
}
|
||||
|
||||
/** Known to this store once, and not pending now. Derived, so there is no window between the two. */
|
||||
public boolean wasResolved(String id) {
|
||||
return this.issued.contains(id) && !this.pending.containsKey(id);
|
||||
}
|
||||
|
||||
public List<PendingApproval> pending() {
|
||||
Collection<PendingApproval> all = this.pending.values();
|
||||
return all.stream().sorted(Comparator.comparing(PendingApproval::createdAt)).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* One line per decision point. The framework logs nothing about WHO approved WHAT, because it does
|
||||
* not know who anyone is; this is the record an auditor will ask for. Kept in memory here so tests
|
||||
* can read it back; in production write it to an append-only table.
|
||||
*/
|
||||
@Component
|
||||
public class AuditLog {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger("audit");
|
||||
|
||||
public record Event(Instant at, String type, String approvalId, String actor, String tool, String detail) {
|
||||
|
||||
public String line() {
|
||||
return "%s approval=%s actor=%s tool=%s %s".formatted(this.type, this.approvalId, this.actor,
|
||||
this.tool, this.detail);
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Event> events = new CopyOnWriteArrayList<>();
|
||||
|
||||
public void record(String type, String approvalId, String actor, String tool, String detail) {
|
||||
Event event = new Event(Instant.now(), type, approvalId, actor, tool, detail);
|
||||
this.events.add(event);
|
||||
log.info(event.line());
|
||||
}
|
||||
|
||||
public List<Event> events() {
|
||||
return List.copyOf(this.events);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.events.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
/** What an approver is shown for one call: the key to answer with, the tool, and its arguments. */
|
||||
public record CallView(String key, String name, String arguments) {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Either a final answer, or a pause the caller must route to an approver. */
|
||||
public record ChatResult(String status, String answer, String approvalId, List<CallView> calls) {
|
||||
|
||||
public static ChatResult done(String answer) {
|
||||
return new ChatResult("DONE", answer, null, List.of());
|
||||
}
|
||||
|
||||
public static ChatResult awaiting(PendingApproval approval) {
|
||||
return new ChatResult("AWAITING_APPROVAL", null, approval.id(), approval.calls());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** The conversation the application keeps. Spring AI keeps no state while a call is paused. */
|
||||
@Component
|
||||
public class ConversationStore {
|
||||
|
||||
private final Map<String, List<Message>> conversations = new ConcurrentHashMap<>();
|
||||
|
||||
public List<Message> get(String conversationId) {
|
||||
return new ArrayList<>(this.conversations.getOrDefault(conversationId, List.of()));
|
||||
}
|
||||
|
||||
public void save(String conversationId, List<Message> messages) {
|
||||
this.conversations.put(conversationId, List.copyOf(messages));
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.toolconfirmation.approval;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
|
||||
/**
|
||||
* A paused turn, kept SERVER-SIDE. The reply held here is the one the model actually produced;
|
||||
* the approver only ever sends keys and verdicts. If a client could replace the reply, it could run
|
||||
* any tool with any arguments and approve its own call.
|
||||
*/
|
||||
public record PendingApproval(String id, String conversationId, String requestedBy, Instant createdAt,
|
||||
List<Message> conversation, ChatResponse reply, List<String> awaiting) {
|
||||
|
||||
public List<CallView> calls() {
|
||||
AssistantMessage message = this.reply.getResult().getOutput();
|
||||
List<String> keys = ToolCallDecisions.toolCallKeys(message);
|
||||
List<CallView> views = new java.util.ArrayList<>();
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
AssistantMessage.ToolCall call = message.getToolCalls().get(i);
|
||||
views.add(new CallView(keys.get(i), call.name(), call.arguments()));
|
||||
}
|
||||
return views;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.ankurm.toolconfirmation.config;
|
||||
|
||||
import com.ankurm.toolconfirmation.tools.ToolRegistry;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class ChatClientConfig {
|
||||
|
||||
/**
|
||||
* {@code manager} is the auto-configured {@code ToolCallingManager}: it already carries the
|
||||
* policy built from the flag, the property and every policy bean.
|
||||
*/
|
||||
@Bean
|
||||
ChatClient chatClient(ChatModel chatModel, ToolCallingManager manager, ToolRegistry tools) {
|
||||
return ChatClientFactory.create(chatModel, manager, tools.callbacks());
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.toolconfirmation.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.ToolCallingAdvisor;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.tool.ToolCallback;
|
||||
|
||||
/**
|
||||
* The one place a {@link ChatClient} is built, shared by the Spring configuration and by the
|
||||
* plain unit tests, so the wiring under test is the wiring that ships.
|
||||
*
|
||||
* <p>The {@link ToolCallingManager} is passed to the advisor <em>and</em> reused to resume a
|
||||
* paused call. The confirmation check lives in the manager, not in the advisor, so a different
|
||||
* manager at resume time would apply a different policy.
|
||||
*/
|
||||
public final class ChatClientFactory {
|
||||
|
||||
private ChatClientFactory() {
|
||||
}
|
||||
|
||||
public static ChatClient create(ChatModel chatModel, ToolCallingManager manager, List<ToolCallback> tools) {
|
||||
ToolCallingAdvisor advisor = ToolCallingAdvisor.builder().toolCallingManager(manager).build();
|
||||
return ChatClient.builder(chatModel)
|
||||
.defaultOptions(baseOptions(chatModel))
|
||||
.defaultToolCallbacks(tools)
|
||||
.defaultAdvisors(advisor)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** ToolCallingAdvisor only engages when the request options are ToolCallingChatOptions. */
|
||||
private static ToolCallingChatOptions.Builder<?> baseOptions(ChatModel chatModel) {
|
||||
if (chatModel.getOptions() instanceof ToolCallingChatOptions existing) {
|
||||
return existing.mutate();
|
||||
}
|
||||
return ToolCallingChatOptions.builder();
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.toolconfirmation.config;
|
||||
|
||||
import org.springframework.ai.model.tool.ToolCallConfirmationPolicy;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* A policy bean. Spring AI's auto-configuration ORs every {@link ToolCallConfirmationPolicy}
|
||||
* bean with the {@code requiresConfirmation} flag and the {@code spring.ai.tools.confirmation.tools}
|
||||
* property: a bean can only add calls that need confirmation, never remove any.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class ConfirmationPolicies {
|
||||
|
||||
static final int TRANSFER_LIMIT = 1_000;
|
||||
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
|
||||
@Bean
|
||||
ToolCallConfirmationPolicy largeTransfers() {
|
||||
return (toolCall, toolMetadata) -> toolCall.name().equals("transferMoney")
|
||||
&& amountOf(toolCall.arguments()) > TRANSFER_LIMIT;
|
||||
}
|
||||
|
||||
/** Model-supplied JSON is untrusted: an unreadable amount is treated as "needs a person". */
|
||||
static int amountOf(String argumentsJson) {
|
||||
try {
|
||||
JsonNode amount = JSON.readTree(argumentsJson).path("amount");
|
||||
return amount.isNumber() ? amount.asInt() : Integer.MAX_VALUE;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.toolconfirmation.tools;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The record of real side effects. Every tool in this module writes one line here when it
|
||||
* actually runs, so a test can assert "nothing happened" while a call is paused, which is the
|
||||
* whole point of the feature.
|
||||
*/
|
||||
@Component
|
||||
public class BookingLedger {
|
||||
|
||||
private final List<String> entries = new CopyOnWriteArrayList<>();
|
||||
|
||||
public void record(String entry) {
|
||||
this.entries.add(entry);
|
||||
}
|
||||
|
||||
public List<String> entries() {
|
||||
return List.copyOf(this.entries);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.entries.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ankurm.toolconfirmation.tools;
|
||||
|
||||
import org.springframework.ai.tool.ToolCallback;
|
||||
import org.springframework.ai.tool.annotation.ToolParam;
|
||||
import org.springframework.ai.tool.function.FunctionToolCallback;
|
||||
import org.springframework.ai.tool.metadata.ToolMetadata;
|
||||
|
||||
/**
|
||||
* The programmatic way to set the flag: a {@link FunctionToolCallback} whose
|
||||
* {@link ToolMetadata} carries {@code requiresConfirmation(true)}. Same effect as the annotation,
|
||||
* for tools that are not methods on a bean.
|
||||
*/
|
||||
public final class DeleteFileTool {
|
||||
|
||||
public record DeleteRequest(@ToolParam(description = "Path of the file to delete") String path) {
|
||||
}
|
||||
|
||||
private DeleteFileTool() {
|
||||
}
|
||||
|
||||
public static ToolCallback create(BookingLedger ledger) {
|
||||
return FunctionToolCallback.builder("deleteFile", (DeleteRequest request) -> {
|
||||
ledger.record("deleteFile " + request.path());
|
||||
return "Deleted " + request.path();
|
||||
})
|
||||
.description("Delete a file by path. Irreversible.")
|
||||
.inputType(DeleteRequest.class)
|
||||
.toolMetadata(ToolMetadata.builder().requiresConfirmation(true).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.toolconfirmation.tools;
|
||||
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* One harmless tool and two that change the world. {@code requiresConfirmation = true} on the
|
||||
* annotation is the whole opt-in: it sets the flag on the {@code ToolMetadata} that Spring AI
|
||||
* builds for the method, and the default policy reads it.
|
||||
*/
|
||||
@Component
|
||||
public class FlightTools {
|
||||
|
||||
private final BookingLedger ledger;
|
||||
|
||||
public FlightTools(BookingLedger ledger) {
|
||||
this.ledger = ledger;
|
||||
}
|
||||
|
||||
@Tool(description = "Search flights between two cities. Read-only.")
|
||||
public String searchFlights(String from, String to) {
|
||||
this.ledger.record("searchFlights " + from + "->" + to);
|
||||
return "VX205 07:10 USD 240; VX311 18:40 USD 198";
|
||||
}
|
||||
|
||||
@Tool(description = "Book a flight by flight number. Charges the customer.", requiresConfirmation = true)
|
||||
public String bookFlight(String flightNumber) {
|
||||
this.ledger.record("bookFlight " + flightNumber);
|
||||
return "Booked " + flightNumber + ", reference BK-" + Math.abs(flightNumber.hashCode() % 1000);
|
||||
}
|
||||
|
||||
@Tool(description = "Cancel a booking by its reference.", requiresConfirmation = true)
|
||||
public String cancelBooking(String reference) {
|
||||
this.ledger.record("cancelBooking " + reference);
|
||||
return "Cancelled " + reference;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.toolconfirmation.tools;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.support.ToolCallbacks;
|
||||
import org.springframework.ai.tool.ToolCallback;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* One list of tool callbacks, used twice: registered on the {@code ChatClient} for the first
|
||||
* request, and handed to {@code Prompt} options again when a paused call is resumed. Resumption
|
||||
* never looks tools up by name on its own, so an allowed call whose tool is missing from the
|
||||
* prompt is an error (see output/05).
|
||||
*/
|
||||
@Component
|
||||
public class ToolRegistry {
|
||||
|
||||
private final List<ToolCallback> callbacks;
|
||||
|
||||
public ToolRegistry(FlightTools flightTools, TransferTools transferTools, BookingLedger ledger) {
|
||||
List<ToolCallback> all = new ArrayList<>();
|
||||
all.addAll(List.of(ToolCallbacks.from(flightTools)));
|
||||
all.addAll(List.of(ToolCallbacks.from(transferTools)));
|
||||
all.add(DeleteFileTool.create(ledger));
|
||||
this.callbacks = List.copyOf(all);
|
||||
}
|
||||
|
||||
public List<ToolCallback> callbacks() {
|
||||
return this.callbacks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ankurm.toolconfirmation.tools;
|
||||
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* A tool that is NOT annotated {@code requiresConfirmation}. It models a tool you cannot or will
|
||||
* not touch (a library, an MCP server): the policy has to name it from the outside, either by
|
||||
* name ({@code forTools}) or by inspecting the arguments (the policy bean in
|
||||
* {@code config.ConfirmationPolicies}).
|
||||
*/
|
||||
@Component
|
||||
public class TransferTools {
|
||||
|
||||
private final BookingLedger ledger;
|
||||
|
||||
public TransferTools(BookingLedger ledger) {
|
||||
this.ledger = ledger;
|
||||
}
|
||||
|
||||
@Tool(description = "Transfer money to a payee. Amount is in whole US dollars.")
|
||||
public String transferMoney(String payee, int amount) {
|
||||
this.ledger.record("transferMoney " + payee + " " + amount);
|
||||
return "Transferred USD " + amount + " to " + payee;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.ankurm.toolconfirmation.web;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalEvents;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalException;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalStore;
|
||||
import com.ankurm.toolconfirmation.approval.CallView;
|
||||
import com.ankurm.toolconfirmation.approval.ChatResult;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@RestController
|
||||
public class ApiController {
|
||||
|
||||
public record ChatRequest(String conversationId, String user, String message) {
|
||||
}
|
||||
|
||||
public record DecisionRequest(List<ApprovalService.Verdict> decisions) {
|
||||
}
|
||||
|
||||
public record PendingView(String id, String conversationId, String requestedBy, List<CallView> calls) {
|
||||
}
|
||||
|
||||
private final ApprovalService service;
|
||||
private final ApprovalStore store;
|
||||
private final ApprovalEvents events;
|
||||
|
||||
public ApiController(ApprovalService service, ApprovalStore store, ApprovalEvents events) {
|
||||
this.service = service;
|
||||
this.store = store;
|
||||
this.events = events;
|
||||
}
|
||||
|
||||
@PostMapping("/api/chat")
|
||||
public ChatResult chat(@RequestBody ChatRequest request) {
|
||||
return this.service.chat(request.conversationId(), request.user(), request.message());
|
||||
}
|
||||
|
||||
@GetMapping("/api/approvals")
|
||||
public List<PendingView> pending() {
|
||||
return this.store.pending()
|
||||
.stream()
|
||||
.map(p -> new PendingView(p.id(), p.conversationId(), p.requestedBy(), p.calls()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The approver's identity comes from a header here ONLY so the check is visible. */
|
||||
@PostMapping("/api/approvals/{id}/decisions")
|
||||
public ChatResult decide(@PathVariable String id, @RequestHeader("X-Approver") String approver,
|
||||
@RequestBody DecisionRequest request) {
|
||||
return this.service.decide(id, approver, request.decisions());
|
||||
}
|
||||
|
||||
@GetMapping("/approvals/stream")
|
||||
public SseEmitter stream() {
|
||||
return this.events.subscribe();
|
||||
}
|
||||
|
||||
@ExceptionHandler(ApprovalException.class)
|
||||
ResponseEntity<Map<String, String>> refused(ApprovalException e) {
|
||||
return ResponseEntity.status(e.status()).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.ankurm.toolconfirmation.web;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalException;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalStore;
|
||||
import com.ankurm.toolconfirmation.approval.CallView;
|
||||
import com.ankurm.toolconfirmation.approval.PendingApproval;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/**
|
||||
* Server-rendered HTML fragments for the htmx approver page (static/approver.html). Everything
|
||||
* that came from the model -- tool names and, above all, arguments -- is HTML-escaped, because the
|
||||
* model chose those strings and a prompt-injected model can choose markup.
|
||||
*/
|
||||
@RestController
|
||||
public class ApproverUiController {
|
||||
|
||||
private final ApprovalStore store;
|
||||
private final ApprovalService service;
|
||||
|
||||
public ApproverUiController(ApprovalStore store, ApprovalService service) {
|
||||
this.store = store;
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping(path = "/ui/approvals", produces = MediaType.TEXT_HTML_VALUE)
|
||||
public String list() {
|
||||
List<PendingApproval> pending = this.store.pending();
|
||||
if (pending.isEmpty()) {
|
||||
return "<p class=\"empty\">Nothing is waiting for approval.</p>";
|
||||
}
|
||||
StringBuilder html = new StringBuilder();
|
||||
for (PendingApproval p : pending) {
|
||||
html.append(card(p));
|
||||
}
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
@PostMapping(path = "/ui/approvals/{id}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
|
||||
produces = MediaType.TEXT_HTML_VALUE)
|
||||
public String decide(@PathVariable String id, @RequestBody MultiValueMap<String, String> form) {
|
||||
PendingApproval pending = this.store.find(id).orElse(null);
|
||||
if (pending == null) {
|
||||
return "<p class=\"error\">That approval is no longer pending.</p>" + list();
|
||||
}
|
||||
List<ApprovalService.Verdict> verdicts = pending.calls()
|
||||
.stream()
|
||||
.map(c -> new ApprovalService.Verdict(c.key(), "allow".equals(form.getFirst("decision-" + c.key())),
|
||||
form.getFirst("message-" + c.key())))
|
||||
.toList();
|
||||
try {
|
||||
this.service.decide(id, form.getFirst("approver"), verdicts);
|
||||
return "<p class=\"ok\">Decision recorded.</p>" + list();
|
||||
}
|
||||
catch (ApprovalException e) {
|
||||
return "<p class=\"error\">" + HtmlUtils.htmlEscape(e.getMessage()) + "</p>" + list();
|
||||
}
|
||||
}
|
||||
|
||||
static String card(PendingApproval p) {
|
||||
StringBuilder html = new StringBuilder();
|
||||
html.append("<form class=\"card\" hx-post=\"/ui/approvals/").append(HtmlUtils.htmlEscape(p.id()))
|
||||
.append("\" hx-target=\"#pending\" hx-swap=\"innerHTML\">");
|
||||
html.append("<h3>Approval ").append(HtmlUtils.htmlEscape(p.id())).append(" — requested by ")
|
||||
.append(HtmlUtils.htmlEscape(String.valueOf(p.requestedBy()))).append("</h3>");
|
||||
for (CallView call : p.calls()) {
|
||||
String key = HtmlUtils.htmlEscape(call.key());
|
||||
html.append("<div class=\"call\"><code>").append(HtmlUtils.htmlEscape(call.name())).append("</code> ")
|
||||
.append("<pre>").append(HtmlUtils.htmlEscape(call.arguments())).append("</pre>")
|
||||
.append("<label><input type=\"radio\" name=\"decision-").append(key)
|
||||
.append("\" value=\"allow\"> Allow</label> ")
|
||||
.append("<label><input type=\"radio\" name=\"decision-").append(key)
|
||||
.append("\" value=\"deny\" checked> Deny</label> ")
|
||||
.append("<input type=\"text\" name=\"message-").append(key)
|
||||
.append("\" placeholder=\"Message to the model if denied\"></div>");
|
||||
}
|
||||
html.append("<label>Approver <input type=\"text\" name=\"approver\" required></label> ");
|
||||
html.append("<button type=\"submit\">Submit decision</button></form>");
|
||||
return html.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
spring:
|
||||
application:
|
||||
name: tool-confirmation
|
||||
ai:
|
||||
openai:
|
||||
# No real key is needed to run this module's tests: they replace the ChatModel with a scripted
|
||||
# one. The placeholder only lets the context start standalone with a real key in OPENAI_API_KEY.
|
||||
api-key: ${OPENAI_API_KEY:demo-key-not-used-by-tests}
|
||||
|
||||
app:
|
||||
approval:
|
||||
approvers: alice,bob
|
||||
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Pending tool approvals</title>
|
||||
<script src="/vendor/htmx.min.js"></script>
|
||||
<script src="/vendor/htmx-ext-sse.js"></script>
|
||||
<style>
|
||||
body { font-family: system-ui, sans-serif; max-width: 42rem; margin: 2rem auto; padding: 0 1rem; }
|
||||
.card { border: 1px solid #b7bec9; border-radius: 6px; padding: 1rem; margin-bottom: 1rem; }
|
||||
.call pre { background: #f4f5f7; padding: .5rem; white-space: pre-wrap; }
|
||||
.error { color: #a33; } .ok { color: #2a6; }
|
||||
</style>
|
||||
</head>
|
||||
<!-- The page opens ONE SSE connection. Each event re-runs the hx-get below; the browser never polls. -->
|
||||
<body hx-ext="sse" sse-connect="/approvals/stream">
|
||||
<h1>Pending tool approvals</h1>
|
||||
<div id="pending" hx-get="/ui/approvals" hx-trigger="load, sse:approval-requested, sse:approval-resolved"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,2 @@
|
||||
d6fdc75f204e6bdefa99b69bf1e6d4ac69b8a364f77929f45c13476b4000f717 htmx.min.js
|
||||
3b5992a541619babefc4c169505af474df5c3039da51e59b96ccf9241ecd61d2 htmx-ext-sse.js
|
||||
@@ -0,0 +1,290 @@
|
||||
/*
|
||||
Server Sent Events Extension
|
||||
============================
|
||||
This extension adds support for Server Sent Events to htmx. See /www/extensions/sse.md for usage instructions.
|
||||
|
||||
*/
|
||||
|
||||
(function() {
|
||||
/** @type {import("../htmx").HtmxInternalApi} */
|
||||
var api
|
||||
|
||||
htmx.defineExtension('sse', {
|
||||
|
||||
/**
|
||||
* Init saves the provided reference to the internal HTMX API.
|
||||
*
|
||||
* @param {import("../htmx").HtmxInternalApi} api
|
||||
* @returns void
|
||||
*/
|
||||
init: function(apiRef) {
|
||||
// store a reference to the internal API.
|
||||
api = apiRef
|
||||
|
||||
// set a function in the public API for creating new EventSource objects
|
||||
if (htmx.createEventSource == undefined) {
|
||||
htmx.createEventSource = createEventSource
|
||||
}
|
||||
},
|
||||
|
||||
getSelectors: function() {
|
||||
return ['[sse-connect]', '[data-sse-connect]', '[sse-swap]', '[data-sse-swap]']
|
||||
},
|
||||
|
||||
/**
|
||||
* onEvent handles all events passed to this extension.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {Event} evt
|
||||
* @returns void
|
||||
*/
|
||||
onEvent: function(name, evt) {
|
||||
var parent = evt.target || evt.detail.elt
|
||||
switch (name) {
|
||||
case 'htmx:beforeCleanupElement':
|
||||
var internalData = api.getInternalData(parent)
|
||||
// Try to remove remove an EventSource when elements are removed
|
||||
var source = internalData.sseEventSource
|
||||
if (source) {
|
||||
api.triggerEvent(parent, 'htmx:sseClose', {
|
||||
source,
|
||||
type: 'nodeReplaced',
|
||||
})
|
||||
internalData.sseEventSource.close()
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
// Try to create EventSources when elements are processed
|
||||
case 'htmx:afterProcessNode':
|
||||
ensureEventSourceOnElement(parent)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/// ////////////////////////////////////////////
|
||||
// HELPER FUNCTIONS
|
||||
/// ////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* createEventSource is the default method for creating new EventSource objects.
|
||||
* it is hoisted into htmx.config.createEventSource to be overridden by the user, if needed.
|
||||
*
|
||||
* @param {string} url
|
||||
* @returns EventSource
|
||||
*/
|
||||
function createEventSource(url) {
|
||||
return new EventSource(url, { withCredentials: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* registerSSE looks for attributes that can contain sse events, right
|
||||
* now hx-trigger and sse-swap and adds listeners based on these attributes too
|
||||
* the closest event source
|
||||
*
|
||||
* @param {HTMLElement} elt
|
||||
*/
|
||||
function registerSSE(elt) {
|
||||
// Add message handlers for every `sse-swap` attribute
|
||||
if (api.getAttributeValue(elt, 'sse-swap')) {
|
||||
// Find closest existing event source
|
||||
var sourceElement = api.getClosestMatch(elt, hasEventSource)
|
||||
if (sourceElement == null) {
|
||||
// api.triggerErrorEvent(elt, "htmx:noSSESourceError")
|
||||
return null // no eventsource in parentage, orphaned element
|
||||
}
|
||||
|
||||
// Set internalData and source
|
||||
var internalData = api.getInternalData(sourceElement)
|
||||
var source = internalData.sseEventSource
|
||||
|
||||
var sseSwapAttr = api.getAttributeValue(elt, 'sse-swap')
|
||||
var sseEventNames = sseSwapAttr.split(',')
|
||||
|
||||
for (var i = 0; i < sseEventNames.length; i++) {
|
||||
const sseEventName = sseEventNames[i].trim()
|
||||
const listener = function(event) {
|
||||
// If the source is missing then close SSE
|
||||
if (maybeCloseSSESource(sourceElement)) {
|
||||
return
|
||||
}
|
||||
|
||||
// If the body no longer contains the element, remove the listener
|
||||
if (!api.bodyContains(elt)) {
|
||||
source.removeEventListener(sseEventName, listener)
|
||||
return
|
||||
}
|
||||
|
||||
// swap the response into the DOM and trigger a notification
|
||||
if (!api.triggerEvent(elt, 'htmx:sseBeforeMessage', event)) {
|
||||
return
|
||||
}
|
||||
swap(elt, event.data)
|
||||
api.triggerEvent(elt, 'htmx:sseMessage', event)
|
||||
}
|
||||
|
||||
// Register the new listener
|
||||
api.getInternalData(elt).sseEventListener = listener
|
||||
source.addEventListener(sseEventName, listener)
|
||||
}
|
||||
}
|
||||
|
||||
// Add message handlers for every `hx-trigger="sse:*"` attribute
|
||||
if (api.getAttributeValue(elt, 'hx-trigger')) {
|
||||
// Find closest existing event source
|
||||
var sourceElement = api.getClosestMatch(elt, hasEventSource)
|
||||
if (sourceElement == null) {
|
||||
// api.triggerErrorEvent(elt, "htmx:noSSESourceError")
|
||||
return null // no eventsource in parentage, orphaned element
|
||||
}
|
||||
|
||||
// Set internalData and source
|
||||
var internalData = api.getInternalData(sourceElement)
|
||||
var source = internalData.sseEventSource
|
||||
|
||||
var triggerSpecs = api.getTriggerSpecs(elt)
|
||||
triggerSpecs.forEach(function(ts) {
|
||||
if (ts.trigger.slice(0, 4) !== 'sse:') {
|
||||
return
|
||||
}
|
||||
|
||||
var listener = function (event) {
|
||||
if (maybeCloseSSESource(sourceElement)) {
|
||||
return
|
||||
}
|
||||
if (!api.bodyContains(elt)) {
|
||||
source.removeEventListener(ts.trigger.slice(4), listener)
|
||||
}
|
||||
// Trigger events to be handled by the rest of htmx
|
||||
htmx.trigger(elt, ts.trigger, event)
|
||||
htmx.trigger(elt, 'htmx:sseMessage', event)
|
||||
}
|
||||
|
||||
// Register the new listener
|
||||
api.getInternalData(elt).sseEventListener = listener
|
||||
source.addEventListener(ts.trigger.slice(4), listener)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ensureEventSourceOnElement creates a new EventSource connection on the provided element.
|
||||
* If a usable EventSource already exists, then it is returned. If not, then a new EventSource
|
||||
* is created and stored in the element's internalData.
|
||||
* @param {HTMLElement} elt
|
||||
* @param {number} retryCount
|
||||
* @returns {EventSource | null}
|
||||
*/
|
||||
function ensureEventSourceOnElement(elt, retryCount) {
|
||||
if (elt == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// handle extension source creation attribute
|
||||
if (api.getAttributeValue(elt, 'sse-connect')) {
|
||||
var sseURL = api.getAttributeValue(elt, 'sse-connect')
|
||||
if (sseURL == null) {
|
||||
return
|
||||
}
|
||||
|
||||
ensureEventSource(elt, sseURL, retryCount)
|
||||
}
|
||||
|
||||
registerSSE(elt)
|
||||
}
|
||||
|
||||
function ensureEventSource(elt, url, retryCount) {
|
||||
var source = htmx.createEventSource(url)
|
||||
|
||||
source.onerror = function(err) {
|
||||
// Log an error event
|
||||
api.triggerErrorEvent(elt, 'htmx:sseError', { error: err, source })
|
||||
|
||||
// If parent no longer exists in the document, then clean up this EventSource
|
||||
if (maybeCloseSSESource(elt)) {
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise, try to reconnect the EventSource
|
||||
if (source.readyState === EventSource.CLOSED) {
|
||||
retryCount = retryCount || 0
|
||||
retryCount = Math.max(Math.min(retryCount * 2, 128), 1)
|
||||
var timeout = retryCount * 500
|
||||
window.setTimeout(function() {
|
||||
ensureEventSourceOnElement(elt, retryCount)
|
||||
}, timeout)
|
||||
}
|
||||
}
|
||||
|
||||
source.onopen = function(evt) {
|
||||
api.triggerEvent(elt, 'htmx:sseOpen', { source })
|
||||
|
||||
if (retryCount && retryCount > 0) {
|
||||
const childrenToFix = elt.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]")
|
||||
for (let i = 0; i < childrenToFix.length; i++) {
|
||||
registerSSE(childrenToFix[i])
|
||||
}
|
||||
// We want to increase the reconnection delay for consecutive failed attempts only
|
||||
retryCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
api.getInternalData(elt).sseEventSource = source
|
||||
|
||||
|
||||
var closeAttribute = api.getAttributeValue(elt, "sse-close");
|
||||
if (closeAttribute) {
|
||||
// close eventsource when this message is received
|
||||
source.addEventListener(closeAttribute, function() {
|
||||
api.triggerEvent(elt, 'htmx:sseClose', {
|
||||
source,
|
||||
type: 'message',
|
||||
})
|
||||
source.close()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* maybeCloseSSESource confirms that the parent element still exists.
|
||||
* If not, then any associated SSE source is closed and the function returns true.
|
||||
*
|
||||
* @param {HTMLElement} elt
|
||||
* @returns boolean
|
||||
*/
|
||||
function maybeCloseSSESource(elt) {
|
||||
if (!api.bodyContains(elt)) {
|
||||
var source = api.getInternalData(elt).sseEventSource
|
||||
if (source != undefined) {
|
||||
api.triggerEvent(elt, 'htmx:sseClose', {
|
||||
source,
|
||||
type: 'nodeMissing',
|
||||
})
|
||||
source.close()
|
||||
// source = null
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} elt
|
||||
* @param {string} content
|
||||
*/
|
||||
function swap(elt, content) {
|
||||
api.withExtensions(elt, function(extension) {
|
||||
content = extension.transformResponse(content, null, elt)
|
||||
})
|
||||
|
||||
var swapSpec = api.getSwapSpecification(elt)
|
||||
var target = api.getTarget(elt)
|
||||
api.swap(target, content, swapSpec, { contextElement: elt })
|
||||
}
|
||||
|
||||
|
||||
function hasEventSource(node) {
|
||||
return api.getInternalData(node).sseEventSource != null
|
||||
}
|
||||
})()
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,109 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.AuditLog;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
|
||||
/**
|
||||
* The approval API end to end over MockMvc: a request that pauses, a stranger refused, a bad
|
||||
* decision list refused with the pause kept, the real approval, and a replay refused.
|
||||
*/
|
||||
@SpringBootTest(properties = "spring.ai.model.chat=none")
|
||||
@AutoConfigureMockMvc
|
||||
@Import(TestModelConfig.class)
|
||||
class ApprovalApiTest {
|
||||
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired BookingLedger ledger;
|
||||
@Autowired AuditLog audit;
|
||||
|
||||
private String send(Transcript t, MockHttpServletRequestBuilder request, String shown) throws Exception {
|
||||
MvcResult r = mvc.perform(request).andReturn();
|
||||
String body = r.getResponse().getContentAsString();
|
||||
t.line("%s", shown);
|
||||
t.line(" -> %d %s", r.getResponse().getStatus(), body);
|
||||
return body;
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullFlowOverHttp() throws Exception {
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
audit.clear();
|
||||
model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"))
|
||||
.respond("Booked VX205. Reference BK-5.");
|
||||
|
||||
String chatBody;
|
||||
String approvalId;
|
||||
try (Transcript t = new Transcript("10-http-flow.txt", "The approval API over HTTP")) {
|
||||
chatBody = send(t, post("/api/chat").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"conversationId\":\"c1\",\"user\":\"carol\",\"message\":\"Book VX205\"}"),
|
||||
"POST /api/chat (carol: Book VX205)");
|
||||
approvalId = chatBody.replaceAll(".*\"approvalId\":\"([^\"]+)\".*", "$1");
|
||||
t.line(" ledger: %s", ledger.entries());
|
||||
assertThat(chatBody).contains("AWAITING_APPROVAL");
|
||||
assertThat(ledger.entries()).isEmpty();
|
||||
|
||||
t.blank();
|
||||
send(t, get("/api/approvals"), "GET /api/approvals");
|
||||
|
||||
String allow = "{\"decisions\":[{\"key\":\"call_1\",\"allow\":true,\"message\":null}]}";
|
||||
t.blank();
|
||||
send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "mallory")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(allow),
|
||||
"POST /api/approvals/" + approvalId + "/decisions X-Approver: mallory (allow call_1)");
|
||||
t.line(" ledger: %s", ledger.entries());
|
||||
assertThat(ledger.entries()).isEmpty();
|
||||
|
||||
t.blank();
|
||||
send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "alice")
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"decisions\":[]}"),
|
||||
"POST /api/approvals/" + approvalId + "/decisions X-Approver: alice (no decisions)");
|
||||
t.line(" still pending: %s", mvc.perform(get("/api/approvals")).andReturn().getResponse()
|
||||
.getContentAsString().contains(approvalId));
|
||||
|
||||
t.blank();
|
||||
String done = send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "alice")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(allow),
|
||||
"POST /api/approvals/" + approvalId + "/decisions X-Approver: alice (allow call_1)");
|
||||
t.line(" ledger: %s", ledger.entries());
|
||||
assertThat(done).contains("DONE").contains("Booked VX205");
|
||||
assertThat(ledger.entries()).containsExactly("bookFlight VX205");
|
||||
|
||||
t.blank();
|
||||
send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "bob")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(allow),
|
||||
"POST /api/approvals/" + approvalId + "/decisions X-Approver: bob (the same pause again)");
|
||||
t.line(" ledger: %s", ledger.entries());
|
||||
assertThat(ledger.entries()).hasSize(1);
|
||||
|
||||
t.blank();
|
||||
send(t, post("/api/approvals/nope0000/decisions").header("X-Approver", "alice")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(allow),
|
||||
"POST /api/approvals/nope0000/decisions X-Approver: alice");
|
||||
}
|
||||
|
||||
try (Transcript t = new Transcript("11-audit-log.txt", "What the audit log recorded for that exchange")) {
|
||||
audit.events().forEach(e -> t.line("%s", e.line()));
|
||||
}
|
||||
assertThat(audit.events()).extracting(AuditLog.Event::type)
|
||||
.containsExactly("PAUSED", "APPROVER_REFUSED", "DECISION_REJECTED", "APPROVED", "REPLAY_REFUSED");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* The approver page's server side, on a real embedded server: the SSE stream carries events, the
|
||||
* HTML fragment escapes what the MODEL chose (an injected tool argument), and a form post resolves
|
||||
* the pause. The htmx page itself was not driven in a browser by this test.
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "spring.ai.model.chat=none")
|
||||
@Import(TestModelConfig.class)
|
||||
class ApproverUiTest {
|
||||
|
||||
@LocalServerPort int port;
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired BookingLedger ledger;
|
||||
|
||||
private static final String HOSTILE = "<img src=x onerror=alert(1)>";
|
||||
|
||||
private final HttpClient http = HttpClient.newHttpClient();
|
||||
|
||||
private String send(HttpRequest request) throws Exception {
|
||||
return http.send(request, HttpResponse.BodyHandlers.ofString()).body();
|
||||
}
|
||||
|
||||
private static void await(List<String> lines, String needle) throws InterruptedException {
|
||||
for (int i = 0; i < 100 && lines.stream().noneMatch(l -> l.contains(needle)); i++) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
assertThat(lines).anyMatch(l -> l.contains(needle));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fragmentsAreEscapedAndTheStreamCarriesEvents() throws Exception {
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
model.callTools(ScriptedChatModel.call("call_1", "bookFlight",
|
||||
"{\"flightNumber\":\"" + HOSTILE + "\"}")).respond("ok");
|
||||
|
||||
String base = "http://localhost:" + port;
|
||||
List<String> sse = new CopyOnWriteArrayList<>();
|
||||
var stream = http.sendAsync(HttpRequest.newBuilder(URI.create(base + "/approvals/stream"))
|
||||
.header("Accept", "text/event-stream").build(), HttpResponse.BodyHandlers.ofLines())
|
||||
.thenAccept(r -> r.body().forEach(sse::add));
|
||||
try {
|
||||
run(base, sse);
|
||||
}
|
||||
finally {
|
||||
stream.cancel(true);
|
||||
http.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private void run(String base, List<String> sse) throws Exception {
|
||||
String hostile = HOSTILE;
|
||||
await(sse, "event:hello");
|
||||
|
||||
String chat = send(HttpRequest.newBuilder(URI.create(base + "/api/chat"))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(
|
||||
"{\"conversationId\":\"ui\",\"user\":\"carol\",\"message\":\"Book it\"}"))
|
||||
.build());
|
||||
String id = chat.replaceAll(".*\"approvalId\":\"([^\"]+)\".*", "$1");
|
||||
await(sse, "event:approval-requested");
|
||||
|
||||
String fragment = send(HttpRequest.newBuilder(URI.create(base + "/ui/approvals")).build());
|
||||
String form = "approver=alice&decision-call_1=deny&message-call_1="
|
||||
+ URLEncoder.encode("Not that one", StandardCharsets.UTF_8);
|
||||
String after = send(HttpRequest.newBuilder(URI.create(base + "/ui/approvals/" + id))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.timeout(Duration.ofSeconds(20))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(form)).build());
|
||||
await(sse, "event:approval-resolved");
|
||||
String page = send(HttpRequest.newBuilder(URI.create(base + "/approver.html")).build());
|
||||
|
||||
try (Transcript t = new Transcript("13-approver-ui-and-sse.txt",
|
||||
"Approver page: SSE events and an escaped fragment (injected tool argument)")) {
|
||||
t.line("tool argument chosen by the model: %s", hostile);
|
||||
t.blank();
|
||||
t.line("SSE lines the approver page received:");
|
||||
sse.stream().filter(l -> !l.isBlank()).forEach(l -> t.line(" %s", l));
|
||||
t.blank();
|
||||
t.line("GET /ui/approvals (the <pre> element):");
|
||||
t.line(" %s", fragment.replaceAll("(?s).*(<pre>.*?</pre>).*", "$1"));
|
||||
t.blank();
|
||||
t.line("POST /ui/approvals/%s (approver=alice, deny) ->", id);
|
||||
t.line(" %s", after.replaceAll("(?s)^(<p[^>]*>.*?</p>).*", "$1"));
|
||||
t.line("ledger: %s", ledger.entries());
|
||||
t.blank();
|
||||
t.line("approver.html wiring:");
|
||||
page.lines().filter(l -> l.contains("sse-connect") || l.contains("hx-get")).map(String::strip)
|
||||
.forEach(l -> t.line(" %s", l));
|
||||
}
|
||||
|
||||
assertThat(fragment).contains("<img src=x onerror=alert(1)>").doesNotContain("<img src=x");
|
||||
assertThat(after).contains("Decision recorded");
|
||||
assertThat(ledger.entries()).isEmpty();
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalException;
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ChatResult;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** Sixteen approvers click Allow at the same instant: exactly one booking. */
|
||||
@SpringBootTest(properties = "spring.ai.model.chat=none")
|
||||
@Import(TestModelConfig.class)
|
||||
class ConcurrentApprovalTest {
|
||||
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired ApprovalService service;
|
||||
@Autowired BookingLedger ledger;
|
||||
|
||||
@Test
|
||||
void exactlyOneApproverWins() throws Exception {
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"))
|
||||
.respond("Booked.");
|
||||
ChatResult paused = service.chat("race", "carol", "Book VX205");
|
||||
|
||||
int approvers = 16;
|
||||
CountDownLatch go = new CountDownLatch(1);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(approvers);
|
||||
List<Future<String>> results = new ArrayList<>();
|
||||
for (int i = 0; i < approvers; i++) {
|
||||
results.add(pool.submit(() -> {
|
||||
go.await();
|
||||
try {
|
||||
service.decide(paused.approvalId(), "alice",
|
||||
List.of(new ApprovalService.Verdict("call_1", true, null)));
|
||||
return "200 DONE";
|
||||
}
|
||||
catch (ApprovalException e) {
|
||||
return e.status().value() + " " + e.getMessage().replace(paused.approvalId(), "<id>");
|
||||
}
|
||||
}));
|
||||
}
|
||||
go.countDown();
|
||||
List<String> outcomes = new ArrayList<>();
|
||||
for (Future<String> f : results) {
|
||||
outcomes.add(f.get(30, TimeUnit.SECONDS));
|
||||
}
|
||||
pool.shutdown();
|
||||
pool.awaitTermination(10, TimeUnit.SECONDS);
|
||||
|
||||
try (Transcript t = new Transcript("12-concurrent-approvers.txt",
|
||||
"16 threads approve the same pause at once")) {
|
||||
outcomes.stream().distinct().sorted().forEach(o -> t.line("%2d x %s",
|
||||
outcomes.stream().filter(o::equals).count(), o));
|
||||
t.line("ledger: %s", ledger.entries());
|
||||
}
|
||||
|
||||
assertThat(ledger.entries()).containsExactly("bookFlight VX205");
|
||||
assertThat(outcomes.stream().filter("200 DONE"::equals).count()).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ChatResult;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.system.CapturedOutput;
|
||||
import org.springframework.boot.test.system.OutputCaptureExtension;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** spring.ai.tools.confirmation.enabled=false: the flag is ignored, the policy bean is not. */
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
@SpringBootTest(properties = { "spring.ai.model.chat=none", "spring.ai.tools.confirmation.enabled=false" })
|
||||
@Import(TestModelConfig.class)
|
||||
class ConfirmationDisabledTest {
|
||||
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired ApprovalService service;
|
||||
@Autowired BookingLedger ledger;
|
||||
|
||||
@Test
|
||||
void theFlagStopsCountingButThePolicyBeanStillApplies(CapturedOutput output) {
|
||||
String warning = output.getAll().lines().filter(l -> l.contains("WARN") && l.contains("onfirmation"))
|
||||
.map(String::strip).findFirst().orElse("(no warning found)");
|
||||
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
model.callTools(ScriptedChatModel.call("b1", "bookFlight", "{\"flightNumber\":\"VX205\"}")).respond("Booked.");
|
||||
ChatResult flagged = service.chat("off-1", "carol", "Book VX205");
|
||||
String afterFlagged = ledger.entries().toString();
|
||||
|
||||
model.reset();
|
||||
model.callTools(ScriptedChatModel.call("t1", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5000}"));
|
||||
ChatResult large = service.chat("off-2", "carol", "Send ACME 5000");
|
||||
|
||||
try (Transcript t = new Transcript("09-confirmation-disabled.txt",
|
||||
"spring.ai.tools.confirmation.enabled=false")) {
|
||||
t.line("startup warning: %s", warning.replaceAll("^.*?(ToolCallingAutoConfiguration)\\s*:\\s*", "WARN $1: "));
|
||||
t.blank();
|
||||
t.line("bookFlight (requiresConfirmation = true): status=%s ledger=%s", flagged.status(), afterFlagged);
|
||||
t.line("transferMoney 5000 (policy bean): status=%s ledger=%s", large.status(),
|
||||
ledger.entries());
|
||||
}
|
||||
|
||||
assertThat(flagged.status()).isEqualTo("DONE");
|
||||
assertThat(afterFlagged).contains("bookFlight VX205");
|
||||
assertThat(large.status()).isEqualTo("AWAITING_APPROVAL");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.config.ChatClientFactory;
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
import org.springframework.ai.tool.definition.ToolDefinition;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* A manager that wraps the default one for logging or metrics implements the two abstract methods
|
||||
* and, if it forgets the third, resumption fails. The pause itself still works, which is what makes
|
||||
* the omission easy to ship.
|
||||
*/
|
||||
class CustomManagerTest {
|
||||
|
||||
/** Wraps the default manager and delegates ONLY the two abstract methods. */
|
||||
static final class ForgetfulManager implements ToolCallingManager {
|
||||
|
||||
private final ToolCallingManager delegate = ToolCallingManager.builder().build();
|
||||
|
||||
@Override
|
||||
public List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions options) {
|
||||
return delegate.resolveToolDefinitions(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse chatResponse) {
|
||||
return delegate.executeToolCalls(prompt, chatResponse);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrappingManagerThatDoesNotDelegateTheDecisionOverloadFailsOnResume() {
|
||||
Env env = new Env();
|
||||
ForgetfulManager forgetful = new ForgetfulManager();
|
||||
var client = ChatClientFactory.create(env.model, forgetful, env.tools.callbacks());
|
||||
env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"));
|
||||
|
||||
ChatResponse reply = client.prompt().messages(Env.user("Book VX205")).call().chatResponse();
|
||||
List<String> awaiting = ToolCallDecisions.awaitingDecision(reply);
|
||||
|
||||
String error;
|
||||
try {
|
||||
forgetful.executeToolCalls(env.promptFor(Env.user("Book VX205")), reply,
|
||||
ToolCallDecisions.of(ToolCallDecision.allow("call_1")));
|
||||
error = "(no exception)";
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
error = e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
|
||||
try (Transcript t = new Transcript("17-custom-manager.txt",
|
||||
"A ToolCallingManager that wraps the default and forgets the decision overload")) {
|
||||
t.line("pause through the wrapping manager: awaitingDecision = %s", awaiting);
|
||||
t.line("resume through the wrapping manager: %s", error);
|
||||
t.line("ledger: %s", env.ledger.entries());
|
||||
}
|
||||
assertThat(awaiting).containsExactly("call_1");
|
||||
assertThat(error).startsWith("UnsupportedOperationException");
|
||||
assertThat(env.ledger.entries()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Describe;
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** What the model is told when a person says no, with and without a message. */
|
||||
class DenyTest {
|
||||
|
||||
@Test
|
||||
void aDenialIsAToolResultTheModelCanReadAndReactTo() {
|
||||
Env env = new Env();
|
||||
env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"),
|
||||
ScriptedChatModel.call("call_2", "cancelBooking", "{\"reference\":\"BK-9\"}"))
|
||||
.respond("Understood, I will ask which seat you prefer.");
|
||||
|
||||
ChatResponse reply = env.ask("Rebook me on VX205");
|
||||
|
||||
try (Transcript t = new Transcript("03-deny-messages.txt", "What the model receives when a call is denied")) {
|
||||
ToolCallDecisions decisions = ToolCallDecisions.of(
|
||||
ToolCallDecision.deny("call_1"),
|
||||
ToolCallDecision.deny("call_2", "The user wants an aisle seat, ask again."));
|
||||
ToolExecutionResult result = env.resume(Env.user("Rebook me on VX205"), reply, decisions);
|
||||
Message last = result.conversationHistory().get(result.conversationHistory().size() - 1);
|
||||
|
||||
t.line("DEFAULT_DENY_MESSAGE: %s", ToolCallDecision.DEFAULT_DENY_MESSAGE);
|
||||
t.blank();
|
||||
t.line("history the model is sent next:");
|
||||
t.line("%s", Describe.messages(result.conversationHistory()));
|
||||
t.blank();
|
||||
t.line("ledger (nothing ran): %s", env.ledger.entries());
|
||||
t.line("returnDirect(): %s", result.returnDirect());
|
||||
|
||||
String answer = env.client.prompt().messages(result.conversationHistory()).call().content();
|
||||
t.line("model's next answer: %s", answer);
|
||||
|
||||
assertThat(env.ledger.entries()).isEmpty();
|
||||
assertThat(last.toString()).contains(ToolCallDecision.DEFAULT_DENY_MESSAGE)
|
||||
.contains("The user wants an aisle seat, ask again.");
|
||||
assertThat(result.returnDirect()).isFalse();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ChatResult;
|
||||
import com.ankurm.toolconfirmation.support.Describe;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* A turn that runs an ungated tool BEFORE reaching a gated one. The paused response holds only the
|
||||
* paused reply, so the application's copy of the conversation lacks the earlier round.
|
||||
*/
|
||||
@SpringBootTest(properties = "spring.ai.model.chat=none")
|
||||
@Import(TestModelConfig.class)
|
||||
class MultiRoundTest {
|
||||
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired ApprovalService service;
|
||||
@Autowired BookingLedger ledger;
|
||||
|
||||
@BeforeEach
|
||||
void reset() {
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEarlierRoundIsMissingFromTheResumedRequest() {
|
||||
model.callTools(ScriptedChatModel.call("s1", "searchFlights", "{\"from\":\"BOS\",\"to\":\"SFO\"}"))
|
||||
.callTools(ScriptedChatModel.call("b1", "bookFlight", "{\"flightNumber\":\"VX205\"}"))
|
||||
.respond("Booked VX205.");
|
||||
|
||||
ChatResult paused = service.chat("multi", "carol", "Find a flight BOS to SFO and book the first one");
|
||||
assertThat(paused.status()).isEqualTo("AWAITING_APPROVAL");
|
||||
List<?> ledgerAtPause = ledger.entries();
|
||||
service.decide(paused.approvalId(), "alice",
|
||||
List.of(new ApprovalService.Verdict("b1", true, null)));
|
||||
|
||||
try (Transcript t = new Transcript("07-multi-round-turn.txt",
|
||||
"Search (ungated) then book (gated) in one turn: what the model sees on each call")) {
|
||||
t.line("ledger at the pause: %s", ledgerAtPause);
|
||||
t.line("model calls: %d", model.callCount());
|
||||
for (int i = 0; i < model.prompts().size(); i++) {
|
||||
t.line("");
|
||||
t.line("prompt %d sent to the model:", i + 1);
|
||||
t.line("%s", Describe.messages(model.prompts().get(i).getInstructions()));
|
||||
}
|
||||
t.blank();
|
||||
t.line("Prompt 2 had the search round; prompt 3 (the resume) does not.");
|
||||
}
|
||||
|
||||
assertThat(model.callCount()).isEqualTo(3);
|
||||
assertThat(model.prompts().get(1).getInstructions()).hasSize(3);
|
||||
assertThat(model.prompts().get(2).getInstructions().toString()).doesNotContain("searchFlights");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.config.ChatClientFactory;
|
||||
import com.ankurm.toolconfirmation.support.Describe;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
import com.ankurm.toolconfirmation.tools.FlightTools;
|
||||
import com.ankurm.toolconfirmation.tools.TransferTools;
|
||||
import com.ankurm.toolconfirmation.tools.ToolRegistry;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* The whole feature in one test: a gated tool pauses the loop, nothing runs, the application
|
||||
* answers, the call runs, and the model is called again with the result.
|
||||
* Code under test: {@link com.ankurm.toolconfirmation.tools.FlightTools#bookFlight}.
|
||||
*/
|
||||
class PauseAndResumeTest {
|
||||
|
||||
@Test
|
||||
void gatedToolPausesThenRunsAfterApproval() {
|
||||
BookingLedger ledger = new BookingLedger();
|
||||
ToolRegistry tools = new ToolRegistry(new FlightTools(ledger), new TransferTools(ledger), ledger);
|
||||
ScriptedChatModel model = new ScriptedChatModel()
|
||||
.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"))
|
||||
.respond("Done. VX205 is booked.");
|
||||
ToolCallingManager manager = ToolCallingManager.builder().build();
|
||||
ChatClient client = ChatClientFactory.create(model, manager, tools.callbacks());
|
||||
|
||||
List<Message> conversation = List.of(new UserMessage("Book flight VX205 for tomorrow"));
|
||||
ChatResponse reply = client.prompt().messages(conversation).call().chatResponse();
|
||||
|
||||
List<String> awaiting = ToolCallDecisions.awaitingDecision(reply);
|
||||
AssistantMessage paused = reply.getResult().getOutput();
|
||||
|
||||
try (Transcript t = new Transcript("01-pause-and-resume.txt",
|
||||
"A gated tool pauses the loop; an approval resumes it")) {
|
||||
t.line("-- first request ----------------------------------------------");
|
||||
t.line("model calls so far: %d", model.callCount());
|
||||
t.line("reply text (content()): '%s'", paused.getText());
|
||||
t.line("reply has tool calls: %s", paused.hasToolCalls());
|
||||
t.line("awaitingDecision(reply): %s", awaiting);
|
||||
t.line("isAwaitingDecision(reply): %s", ToolCallDecisions.isAwaitingDecision(reply));
|
||||
t.line("tool call shown to the person: %s %s", paused.getToolCalls().get(0).name(),
|
||||
paused.getToolCalls().get(0).arguments());
|
||||
t.line("ledger (real side effects): %s", ledger.entries());
|
||||
t.line("metadata key holding the keys: %s", ToolCallDecisions.AWAITING_DECISION_METADATA_KEY);
|
||||
|
||||
assertThat(model.callCount()).isEqualTo(1);
|
||||
assertThat(awaiting).containsExactly("call_1");
|
||||
assertThat(ledger.entries()).isEmpty();
|
||||
|
||||
ToolCallDecisions decisions = ToolCallDecisions.of(ToolCallDecision.allow("call_1"));
|
||||
Prompt prompt = new Prompt(conversation,
|
||||
ToolCallingChatOptions.builder().toolCallbacks(tools.callbacks()).build());
|
||||
ToolExecutionResult result = manager.executeToolCalls(prompt, reply, decisions);
|
||||
|
||||
t.blank();
|
||||
t.line("-- after allow(call_1) + executeToolCalls ---------------------");
|
||||
t.line("ledger (real side effects): %s", ledger.entries());
|
||||
t.line("conversationHistory():");
|
||||
t.line("%s", Describe.messages(result.conversationHistory()));
|
||||
t.line("returnDirect(): %s", result.returnDirect());
|
||||
|
||||
String answer = client.prompt().messages(result.conversationHistory()).call().content();
|
||||
t.blank();
|
||||
t.line("-- resumed request --------------------------------------------");
|
||||
t.line("model calls so far: %d", model.callCount());
|
||||
t.line("final answer: %s", answer);
|
||||
|
||||
assertThat(ledger.entries()).containsExactly("bookFlight VX205");
|
||||
assertThat(model.callCount()).isEqualTo(2);
|
||||
assertThat(answer).isEqualTo("Done. VX205 is booked.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.model.tool.ToolCallConfirmationPolicy;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Which calls pause, under each policy. Every row asks the same two questions of a scripted model
|
||||
* (book a flight; transfer money) and reports what was left waiting for a person.
|
||||
*/
|
||||
class PolicyTest {
|
||||
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
|
||||
/** The same shape as config.ConfirmationPolicies.largeTransfers, written inline for the table. */
|
||||
private static final ToolCallConfirmationPolicy OVER_1000 = (call, metadata) -> call.name().equals("transferMoney")
|
||||
&& JSON.readTree(call.arguments()).path("amount").asInt() > 1_000;
|
||||
|
||||
private static String pausedFor(ToolCallConfirmationPolicy policy, AssistantMessage.ToolCall call) {
|
||||
Env env = policy == null ? new Env() : new Env(policy);
|
||||
env.model.callTools(call).respond("ok");
|
||||
var awaiting = ToolCallDecisions.awaitingDecision(env.ask("go"));
|
||||
return awaiting.isEmpty() ? "runs (ledger " + env.ledger.entries() + ")" : "PAUSES " + awaiting;
|
||||
}
|
||||
|
||||
@Test
|
||||
void policiesDecideWhichCallsPause() {
|
||||
var book = ScriptedChatModel.call("c1", "bookFlight", "{\"flightNumber\":\"VX205\"}");
|
||||
var small = ScriptedChatModel.call("c2", "transferMoney", "{\"payee\":\"ACME\",\"amount\":500}");
|
||||
var large = ScriptedChatModel.call("c3", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5000}");
|
||||
|
||||
Map<String, String> rows = new LinkedHashMap<>();
|
||||
rows.put("default (fromToolMetadata) | bookFlight ", pausedFor(null, book));
|
||||
rows.put("default (fromToolMetadata) | transferMoney 500 ", pausedFor(null, small));
|
||||
rows.put("none() | bookFlight ", pausedFor(ToolCallConfirmationPolicy.none(), book));
|
||||
rows.put("forTools(\"transferMoney\") | transferMoney 500 ",
|
||||
pausedFor(ToolCallConfirmationPolicy.forTools("transferMoney"), small));
|
||||
rows.put("forTools(\"transferMoney\") | bookFlight ",
|
||||
pausedFor(ToolCallConfirmationPolicy.forTools("transferMoney"), book));
|
||||
rows.put("over-1000 argument policy | transferMoney 500 ", pausedFor(OVER_1000, small));
|
||||
rows.put("over-1000 argument policy | transferMoney 5000 ", pausedFor(OVER_1000, large));
|
||||
rows.put("over-1000 argument policy | bookFlight ", pausedFor(OVER_1000, book));
|
||||
rows.put("fromToolMetadata().or(over-1000)| bookFlight ",
|
||||
pausedFor(ToolCallConfirmationPolicy.fromToolMetadata().or(OVER_1000), book));
|
||||
rows.put("fromToolMetadata().or(over-1000)| transferMoney 5000 ",
|
||||
pausedFor(ToolCallConfirmationPolicy.fromToolMetadata().or(OVER_1000), large));
|
||||
|
||||
try (Transcript t = new Transcript("04-policies.txt", "Which calls pause under which policy")) {
|
||||
t.line("%-32s| %-21s %s", "policy", "call", "result");
|
||||
rows.forEach((k, v) -> t.line("%s %s", k, v));
|
||||
}
|
||||
|
||||
assertThat(rows.get("default (fromToolMetadata) | bookFlight ")).startsWith("PAUSES");
|
||||
assertThat(rows.get("default (fromToolMetadata) | transferMoney 500 ")).startsWith("runs");
|
||||
assertThat(rows.get("none() | bookFlight ")).startsWith("runs");
|
||||
assertThat(rows.get("over-1000 argument policy | bookFlight "))
|
||||
.as("a policy that names only transfers does not cover the annotated tool")
|
||||
.startsWith("runs");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** A tool call key is the call's id, unless the provider sent none or sent the same id twice. */
|
||||
class PositionKeysTest {
|
||||
|
||||
@Test
|
||||
void missingOrDuplicateIdsFallBackToPositions() {
|
||||
Env env = new Env();
|
||||
env.model.callTools(
|
||||
ScriptedChatModel.call("dup", "bookFlight", "{\"flightNumber\":\"VX205\"}"),
|
||||
ScriptedChatModel.call("dup", "bookFlight", "{\"flightNumber\":\"VX311\"}"));
|
||||
ChatResponse reply = env.ask("Book both");
|
||||
AssistantMessage message = reply.getResult().getOutput();
|
||||
List<String> keys = ToolCallDecisions.toolCallKeys(message);
|
||||
|
||||
Env env2 = new Env();
|
||||
env2.model.callTools(ScriptedChatModel.call("", "bookFlight", "{\"flightNumber\":\"VX205\"}"));
|
||||
ChatResponse noId = env2.ask("Book it");
|
||||
|
||||
try (Transcript t = new Transcript("16-position-keys.txt", "Tool call keys when ids are missing or repeated")) {
|
||||
t.line("POSITION_KEY_PREFIX: %s", ToolCallDecisions.POSITION_KEY_PREFIX);
|
||||
t.line("two calls that both have id 'dup' -> keys: %s", keys);
|
||||
t.line("awaitingDecision for that reply: %s", ToolCallDecisions.awaitingDecision(reply));
|
||||
t.line("one call with an empty id -> keys: %s",
|
||||
ToolCallDecisions.toolCallKeys(noId.getResult().getOutput()));
|
||||
|
||||
// The keys work as decision keys.
|
||||
env.resume(Env.user("Book both"), reply,
|
||||
ToolCallDecisions.of(ToolCallDecision.allow("#0"), ToolCallDecision.deny("#1")));
|
||||
t.line("allow('#0') + deny('#1') -> ledger: %s", env.ledger.entries());
|
||||
}
|
||||
assertThat(keys).containsExactly("#0", "#1");
|
||||
assertThat(env.ledger.entries()).containsExactly("bookFlight VX205");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* The framework does not prevent replays: the same decisions on the same reply run the tool again.
|
||||
* The guard is the application's (see approval.ApprovalStore#take and output/10).
|
||||
*/
|
||||
class ReplayTest {
|
||||
|
||||
@Test
|
||||
void theSameDecisionsRunTheToolTwice() {
|
||||
Env env = new Env();
|
||||
env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"));
|
||||
List<Message> conversation = Env.user("Book VX205");
|
||||
ChatResponse reply = env.ask("Book VX205");
|
||||
ToolCallDecisions decisions = ToolCallDecisions.of(ToolCallDecision.allow("call_1"));
|
||||
|
||||
env.resume(conversation, reply, decisions);
|
||||
env.resume(conversation, reply, decisions);
|
||||
|
||||
try (Transcript t = new Transcript("06-replay-is-not-prevented.txt",
|
||||
"executeToolCalls twice with the same decisions on the same reply")) {
|
||||
t.line("calls to executeToolCalls: 2");
|
||||
t.line("ledger: %s", env.ledger.entries());
|
||||
t.line("A customer is booked, and charged, twice.");
|
||||
}
|
||||
assertThat(env.ledger.entries()).containsExactly("bookFlight VX205", "bookFlight VX205");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** The three ways a resume is refused, with the real messages, and proof that nothing ran. */
|
||||
class ResumeErrorsTest {
|
||||
|
||||
private static String message(Runnable r) {
|
||||
try {
|
||||
r.run();
|
||||
return "(no exception)";
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
return e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void badDecisionListsAreRefusedBeforeAnythingRuns() {
|
||||
Env env = new Env();
|
||||
env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"));
|
||||
List<Message> conversation = Env.user("Book VX205");
|
||||
ChatResponse reply = env.ask("Book VX205");
|
||||
|
||||
String missing = message(() -> env.resume(conversation, reply, ToolCallDecisions.of()));
|
||||
String unknown = message(() -> env.resume(conversation, reply, ToolCallDecisions.of(
|
||||
ToolCallDecision.allow("call_1"), ToolCallDecision.allow("call_99"))));
|
||||
// Same reply, but the Prompt carries no tools: resumption does not look tools up by name.
|
||||
Prompt noTools = new Prompt(conversation, ToolCallingChatOptions.builder().build());
|
||||
String notInPrompt = message(() -> env.manager.executeToolCalls(noTools, reply,
|
||||
ToolCallDecisions.of(ToolCallDecision.allow("call_1"))));
|
||||
|
||||
try (Transcript t = new Transcript("05-resume-errors.txt", "Three refused resumes")) {
|
||||
t.line("1. no decision for call_1:");
|
||||
t.line(" %s", missing);
|
||||
t.line("2. a decision for a key that is not in the reply (call_99):");
|
||||
t.line(" %s", unknown);
|
||||
t.line("3. allowed call, but its tool is not on the Prompt:");
|
||||
t.line(" %s", notInPrompt);
|
||||
t.blank();
|
||||
t.line("ledger after all three: %s", env.ledger.entries());
|
||||
}
|
||||
|
||||
assertThat(missing).startsWith("IllegalArgumentException");
|
||||
assertThat(unknown).startsWith("IllegalArgumentException");
|
||||
assertThat(notInPrompt).startsWith("IllegalArgumentException");
|
||||
assertThat(env.ledger.entries()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* How long does stopping the application take while one approver page is open? Spring Boot's web
|
||||
* server shuts down gracefully by default: it waits for in-flight requests, and an SSE stream never
|
||||
* finishes. The grace period is set to 5 s here so the test is quick; the default is 30 s.
|
||||
* Code: {@link com.ankurm.toolconfirmation.approval.ApprovalEvents} (a SmartLifecycle).
|
||||
*/
|
||||
class ShutdownTest {
|
||||
|
||||
private static long closeWithOneOpenStream(boolean closeStreamsOnStop) throws Exception {
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(ToolConfirmationApplication.class,
|
||||
TestModelConfig.class)
|
||||
.properties("server.port=0", "spring.ai.model.chat=none", "server.shutdown=graceful",
|
||||
"spring.lifecycle.timeout-per-shutdown-phase=5s", "spring.main.banner-mode=off",
|
||||
"logging.level.root=WARN", "app.approval.close-streams-on-stop=" + closeStreamsOnStop)
|
||||
.run();
|
||||
String port = ctx.getEnvironment().getProperty("local.server.port");
|
||||
HttpClient http = HttpClient.newHttpClient();
|
||||
List<String> lines = new CopyOnWriteArrayList<>();
|
||||
http.sendAsync(HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/approvals/stream")).build(),
|
||||
HttpResponse.BodyHandlers.ofLines()).thenAccept(r -> r.body().forEach(lines::add));
|
||||
for (int i = 0; i < 100 && lines.isEmpty(); i++) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
assertThat(lines).as("stream is open").isNotEmpty();
|
||||
long start = System.nanoTime();
|
||||
ctx.close();
|
||||
long millis = (System.nanoTime() - start) / 1_000_000;
|
||||
http.shutdownNow();
|
||||
return millis;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOpenStreamDelaysGracefulShutdownUnlessItIsClosedFirst() throws Exception {
|
||||
long left = closeWithOneOpenStream(false);
|
||||
long closed = closeWithOneOpenStream(true);
|
||||
|
||||
try (Transcript t = new Transcript("14-sse-and-graceful-shutdown.txt",
|
||||
"ctx.close() with one approver page connected (grace period 5000 ms)")) {
|
||||
t.line("streams left open: %s ms", left >= 4000 ? "over 4000" : String.valueOf(left));
|
||||
t.line("streams completed by the lifecycle: %s ms", closed < 2000 ? "under 2000" : String.valueOf(closed));
|
||||
t.line("(the exact figures vary per run; the 5 s wall is the configured grace period)");
|
||||
}
|
||||
|
||||
assertThat(left).isGreaterThan(4000);
|
||||
assertThat(closed).isLessThan(2000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import com.ankurm.toolconfirmation.approval.ApprovalService;
|
||||
import com.ankurm.toolconfirmation.approval.ChatResult;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.TestModelConfig;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** spring.ai.tools.confirmation.tools=transferMoney: pause a tool that carries no annotation. */
|
||||
@SpringBootTest(properties = { "spring.ai.model.chat=none", "spring.ai.tools.confirmation.tools=transferMoney" })
|
||||
@Import(TestModelConfig.class)
|
||||
class ToolsPropertyTest {
|
||||
|
||||
@Autowired ScriptedChatModel model;
|
||||
@Autowired ApprovalService service;
|
||||
@Autowired BookingLedger ledger;
|
||||
|
||||
@Test
|
||||
void aListedToolPausesWhateverItsMetadataSays() {
|
||||
model.reset();
|
||||
ledger.clear();
|
||||
model.callTools(ScriptedChatModel.call("t1", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5}"));
|
||||
|
||||
ChatResult result = service.chat("prop", "carol", "Send ACME five dollars");
|
||||
|
||||
try (Transcript t = new Transcript("08-tools-property.txt",
|
||||
"spring.ai.tools.confirmation.tools=transferMoney (a USD 5 transfer, far under the 1000 policy bean)")) {
|
||||
t.line("status: %s", result.status());
|
||||
t.line("calls: %s", result.calls());
|
||||
t.line("ledger: %s", ledger.entries());
|
||||
}
|
||||
assertThat(result.status()).isEqualTo("AWAITING_APPROVAL");
|
||||
assertThat(ledger.entries()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.toolconfirmation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.toolconfirmation.support.Describe;
|
||||
import com.ankurm.toolconfirmation.support.Env;
|
||||
import com.ankurm.toolconfirmation.support.ScriptedChatModel;
|
||||
import com.ankurm.toolconfirmation.support.Transcript;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* One reply, two tool calls: a harmless search and a gated booking. The documented rule is that
|
||||
* the whole reply pauses. This test shows what that means for the harmless call.
|
||||
*/
|
||||
class WholeReplyPausesTest {
|
||||
|
||||
@Test
|
||||
void anUngatedCallInTheSameReplyWaitsToo() {
|
||||
Env env = new Env();
|
||||
env.model.callTools(
|
||||
ScriptedChatModel.call("call_1", "searchFlights", "{\"from\":\"BOS\",\"to\":\"SFO\"}"),
|
||||
ScriptedChatModel.call("call_2", "bookFlight", "{\"flightNumber\":\"VX205\"}"))
|
||||
.respond("Booked.");
|
||||
|
||||
ChatResponse reply = env.ask("Find me a flight and book the first one");
|
||||
List<Message> conversation = Env.user("Find me a flight and book the first one");
|
||||
|
||||
try (Transcript t = new Transcript("02-whole-reply-pauses.txt",
|
||||
"One gated call pauses the whole reply, including the harmless call beside it")) {
|
||||
t.line("calls in the reply: %s", reply.getResult().getOutput().getToolCalls().stream()
|
||||
.map(c -> c.id() + "=" + c.name()).toList());
|
||||
t.line("awaitingDecision(reply): %s", ToolCallDecisions.awaitingDecision(reply));
|
||||
t.line("ledger after the pause: %s", env.ledger.entries());
|
||||
|
||||
assertThat(env.ledger.entries()).as("searchFlights is ungated but did not run").isEmpty();
|
||||
|
||||
// A decision is required for EVERY call, including the one the policy did not flag.
|
||||
ToolCallDecisions onlyGated = ToolCallDecisions.of(ToolCallDecision.allow("call_2"));
|
||||
String error = null;
|
||||
try {
|
||||
env.resume(conversation, reply, onlyGated);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
error = e.getMessage();
|
||||
}
|
||||
t.blank();
|
||||
t.line("decision for call_2 only -> IllegalArgumentException:");
|
||||
t.line(" %s", error);
|
||||
t.line("ledger after the refused resume: %s", env.ledger.entries());
|
||||
assertThat(error).isNotNull();
|
||||
assertThat(env.ledger.entries()).isEmpty();
|
||||
|
||||
ToolCallDecisions both = ToolCallDecisions.of(ToolCallDecision.allow("call_1"),
|
||||
ToolCallDecision.allow("call_2"));
|
||||
ToolExecutionResult result = env.resume(conversation, reply, both);
|
||||
t.blank();
|
||||
t.line("decisions for both -> ledger: %s", env.ledger.entries());
|
||||
t.line("tool results, in the model's order:");
|
||||
t.line("%s", Describe.message(result.conversationHistory().get(result.conversationHistory().size() - 1)));
|
||||
assertThat(env.ledger.entries()).containsExactly("searchFlights BOS->SFO", "bookFlight VX205");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.toolconfirmation.support;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.ToolResponseMessage;
|
||||
|
||||
/** Compact one-line renderings of messages for the transcripts. */
|
||||
public final class Describe {
|
||||
|
||||
private Describe() {
|
||||
}
|
||||
|
||||
public static String message(Message m) {
|
||||
if (m instanceof AssistantMessage a && a.hasToolCalls()) {
|
||||
return "AssistantMessage[toolCalls=" + a.getToolCalls().stream()
|
||||
.map(c -> c.id() + ":" + c.name() + c.arguments())
|
||||
.collect(Collectors.joining(", ")) + "]";
|
||||
}
|
||||
if (m instanceof ToolResponseMessage t) {
|
||||
return "ToolResponseMessage" + t.getResponses().stream()
|
||||
.map(r -> "[" + r.id() + ":" + r.name() + " -> " + r.responseData() + "]")
|
||||
.collect(Collectors.joining());
|
||||
}
|
||||
return m.getClass().getSimpleName() + "[" + m.getText() + "]";
|
||||
}
|
||||
|
||||
public static String messages(List<Message> ms) {
|
||||
return ms.stream().map(Describe::message).collect(Collectors.joining("\n ", " ", ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.toolconfirmation.support;
|
||||
|
||||
import com.ankurm.toolconfirmation.config.ChatClientFactory;
|
||||
import com.ankurm.toolconfirmation.tools.BookingLedger;
|
||||
import com.ankurm.toolconfirmation.tools.FlightTools;
|
||||
import com.ankurm.toolconfirmation.tools.ToolRegistry;
|
||||
import com.ankurm.toolconfirmation.tools.TransferTools;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallConfirmationPolicy;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
|
||||
/** A plain-JVM fixture: real tools, real manager, scripted model, no Spring context. */
|
||||
public final class Env {
|
||||
|
||||
public final BookingLedger ledger = new BookingLedger();
|
||||
public final ToolRegistry tools = new ToolRegistry(new FlightTools(ledger), new TransferTools(ledger), ledger);
|
||||
public final ScriptedChatModel model = new ScriptedChatModel();
|
||||
public final ToolCallingManager manager;
|
||||
public final ChatClient client;
|
||||
|
||||
public Env() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
/** @param policy {@code null} keeps the manager's default, {@code fromToolMetadata()} */
|
||||
public Env(ToolCallConfirmationPolicy policy) {
|
||||
var builder = ToolCallingManager.builder();
|
||||
if (policy != null) {
|
||||
builder.toolCallConfirmationPolicy(policy);
|
||||
}
|
||||
this.manager = builder.build();
|
||||
this.client = ChatClientFactory.create(model, manager, tools.callbacks());
|
||||
}
|
||||
|
||||
public static List<Message> user(String text) {
|
||||
return List.of(new UserMessage(text));
|
||||
}
|
||||
|
||||
public ChatResponse ask(String text) {
|
||||
return client.prompt().messages(user(text)).call().chatResponse();
|
||||
}
|
||||
|
||||
public Prompt promptFor(List<Message> conversation) {
|
||||
return new Prompt(conversation, ToolCallingChatOptions.builder().toolCallbacks(tools.callbacks()).build());
|
||||
}
|
||||
|
||||
public ToolExecutionResult resume(List<Message> conversation, ChatResponse reply, ToolCallDecisions decisions) {
|
||||
return manager.executeToolCalls(promptFor(conversation), reply, decisions);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.ankurm.toolconfirmation.support;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.model.Generation;
|
||||
import org.springframework.ai.chat.prompt.ChatOptions;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
|
||||
/**
|
||||
* A hand-written {@link ChatModel} that returns queued responses instead of calling a provider.
|
||||
* {@code ChatModel} has one abstract method, {@code call(Prompt)}. Every prompt the advisor sends is
|
||||
* recorded, so a test can assert what the model was shown on a resumed request. The queue can be
|
||||
* refilled and cleared, so one instance can sit in a Spring context across tests.
|
||||
*
|
||||
* <p>{@code getOptions()} must return {@link ToolCallingChatOptions}: ToolCallingAdvisor does
|
||||
* nothing at all otherwise (see tool-calling/ in this repository for how that was found).
|
||||
*/
|
||||
public class ScriptedChatModel implements ChatModel {
|
||||
|
||||
private final Queue<ChatResponse> script = new ConcurrentLinkedQueue<>();
|
||||
private final List<Prompt> prompts = new CopyOnWriteArrayList<>();
|
||||
|
||||
public ScriptedChatModel callTools(AssistantMessage.ToolCall... toolCalls) {
|
||||
AssistantMessage message = AssistantMessage.builder().content("").toolCalls(List.of(toolCalls)).build();
|
||||
this.script.add(new ChatResponse(List.of(new Generation(message))));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ScriptedChatModel respond(String text) {
|
||||
this.script.add(new ChatResponse(List.of(new Generation(new AssistantMessage(text)))));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ScriptedChatModel reset() {
|
||||
this.script.clear();
|
||||
this.prompts.clear();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatResponse call(Prompt prompt) {
|
||||
this.prompts.add(prompt);
|
||||
ChatResponse next = this.script.poll();
|
||||
if (next == null) {
|
||||
throw new IllegalStateException("ScriptedChatModel ran out of responses after " + this.prompts.size()
|
||||
+ " calls");
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
public List<Prompt> prompts() {
|
||||
return List.copyOf(this.prompts);
|
||||
}
|
||||
|
||||
public int callCount() {
|
||||
return this.prompts.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatOptions getOptions() {
|
||||
return ToolCallingChatOptions.builder().build();
|
||||
}
|
||||
|
||||
public static AssistantMessage.ToolCall call(String id, String name, String json) {
|
||||
return new AssistantMessage.ToolCall(id, "function", name, json);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.ankurm.toolconfirmation.support;
|
||||
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
/**
|
||||
* Puts a {@link ScriptedChatModel} in the Spring context in place of the OpenAI model. Tests set
|
||||
* {@code spring.ai.model.chat=none} so the provider starter creates no model of its own.
|
||||
*/
|
||||
@TestConfiguration(proxyBeanMethods = false)
|
||||
public class TestModelConfig {
|
||||
|
||||
@Bean
|
||||
ScriptedChatModel scriptedChatModel() {
|
||||
return new ScriptedChatModel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.toolconfirmation.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Writes a numbered transcript under {@code output/} and echoes it to the console. Every console
|
||||
* block quoted in the article comes out of one of these files verbatim.
|
||||
*/
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path path;
|
||||
private final StringWriter buffer = new StringWriter();
|
||||
private final PrintWriter out = new PrintWriter(buffer);
|
||||
|
||||
public Transcript(String fileName, String title) {
|
||||
this.path = Path.of("output", fileName);
|
||||
out.println("# " + title);
|
||||
out.println();
|
||||
}
|
||||
|
||||
public Transcript line(String format, Object... args) {
|
||||
out.println(args.length == 0 ? format : String.format(format, args));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Transcript blank() {
|
||||
out.println();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
out.flush();
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, buffer.toString());
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException("could not write " + path, e);
|
||||
}
|
||||
System.out.print(buffer);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user