Compare commits

..
18 Commits
Author SHA1 Message Date
Claude c8fa0912f7 Add ai-21-migration module: upgrading Spring AI 2.0.x to 2.1.0, measured. One probe source tree run on 2.0.0, 2.0.2, 2.0.3 and 2.1.0 (Anthropic prompt tokens with caching, auth header, discarded temperature, thinking parts, message mutability, entity() on refusals), three compile breaks, API and configuration diffs from the jars, ChatMemory to session copy, a wrapping ToolCallingManager under tool confirmation, the OpenAI Responses switch, VectorStore.upsert on real pgvector, a grep checklist and an OpenRewrite recipe. Scripted and local fake models; no provider called. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7N4ZDbUtA3ofqAqRV
2026-12-03 09:46:46 +05:30
AnkurandClaude Sonnet 5.5 8f69e7bf50 Add cloud-providers module: keyless Spring AI on Amazon Bedrock (AWS default credential chain under IRSA and EKS Pod Identity) and Azure OpenAI (managed identity, Microsoft Entra ID bearer tokens), an audit advisor, and the traps reproduced (leftover static key beats the role, AWS_REGION ignored by Bedrock auto-configuration, short-lived credentials refetched per call, azure-identity missing, leftover OPENAI_API_KEY, other modalities defaulting to OpenAI, SigV4 session token in AWS SDK DEBUG logs). No AWS account or Azure subscription used: a local server stands in for STS, Bedrock, the Azure identity endpoint and Azure OpenAI; the Spring AI, AWS SDK and azure-identity code is real. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
2026-11-29 13:25:58 +05:30
AnkurandClaude Sonnet 5.5 98ed878675 Add rag-eval module: retrieval metrics, golden dataset and a JUnit regression gate
hit@k, recall@k, precision@k, MRR and nDCG@k in plain Java with their edge
cases pinned by tests, a 30-question graded golden dataset over a 40-passage
runbook, a paired bootstrap, and a gate (baseline + tolerance + no new misses)
shown failing on a tokenizer that drops digits. BM25, a hashed-trigram vector
(not a neural embedding) and RRF; no model, no network. Java 25, JUnit 6.1.3.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7F47n8shUHpexxavn
2026-11-25 13:20:18 +05:30
Claude 0bb301d361 README: remove blank line that split the module table
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4gvXXQgw1eTk5EoTT
2026-11-24 06:07:40 +05:30
Claude 02c3cbf439 Add prompt-caching module: Spring AI 2.1 Anthropic cache strategies on the real request (breakpoints per strategy, hit/miss/write in Usage, one changed word, multi-block system caching, minimum length, 5-minute and 1-hour lifetimes, the 20-block lookback), OpenAI automatic caching with prompt_cache_key, and a cost table. The vendors are a local server applying their documented rules; no vendor API called. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4gvXXQgw1eTk5EoTT
2026-11-24 06:07:23 +05:30
Claude 45d83826da 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
2026-11-24 05:57:07 +05:30
Claude 7612fca082 Add session-memory module: Spring AI 2.1 Session API (event log, turn-aware windows, compaction with summarizer, SessionAdvisors, JDBC on PostgreSQL 16) with 14 transcripts and the 2.0 ChatMemory deprecation warnings from javac. Spring Boot 4.1.1, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6jDW7zqoKDMTRrCyq
2026-11-22 18:39:32 +05:30
asmhatreandClaude Sonnet 5.5 0006167c24 Add mcp-advanced module: resources, prompts, sampling and elicitation on Spring AI 2.0.2 and MCP Java SDK 2.1.0
An incident-desk MCP server with a fixed resource, two resource templates, a prompt, a tool that borrows the client's model (sampling) and a tool that asks the operator to approve a restart (elicitation). Driven by a plain SDK client in JUnit and by raw curl, so the JSON-RPC for both server-to-client requests is committed. Also captured: a client that declared neither capability (a gated tool degrades, an ungated one returns an isError result), a slow client hitting the server request timeout, and protocol=STATELESS silently dropping every tool that takes McpSyncRequestContext (one WARN line, an empty tools/list). Negotiated protocol version is 2025-11-25; the 2026-07-28 spec is not implemented by SDK 2.1.0. No docs/ folder.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5jAFLJrmUXmbo5EuV
2026-11-10 18:47:09 +00:00
asmhatreandClaude Sonnet 5.5 68da642f9a Add chat-ui-htmx module: streaming chat page on Spring AI 2.0.2 with htmx and its SSE extension (vendored), MessageChatMemoryAdvisor keyed by the HTTP session, a Stop button, and the traps measured: 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 calls Call.cancel (8 of 8 closed after), and the SDK push source ignores back-pressure (limitRate changes only the demand; a bounded buffer works). The model is a stub OpenAI-compatible SSE server written for the module; no real provider was run.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6Kg9RWSTJzyz6KP9X
2026-10-31 04:02:56 +00:00
asmhatreandClaude Sonnet 5.5 c97bcf9adf Add docker-model-runner module: Spring AI OpenAI starter against Docker Model Runner and Ollama with a benchmark runner (time to first token, decode tokens/second, container memory, tool-call success); real docker/model-runner v1.2.9 CPU image and Ollama 0.40.13 on a shared 2-vCPU sandbox, no GPU
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4VQVEJWetTT1dYzyJ
2026-10-29 06:24:00 +00:00
asmhatreandClaude Sonnet 5.5 6d792f00e0 Add batch-llm module: 100,000 synthetic tickets classified by a ChatClient in a Spring Batch 6 chunk step with Resilience4j rate limiting and retry, skip-and-record for malformed JSON, restart after kill -9 in a second JVM, and a per-chunk cost ledger. The model is a deterministic simulated ChatModel; prices are configurable placeholders. No provider called.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4VQVEJWetTT1dYzyJ
2026-10-29 06:10:22 +00:00
asmhatreandClaude Sonnet 5.5 aa8b1604ed Add image-gen module: Spring AI ImageModel options on the wire, a moderation gate, and safe storage of generated images in MinIO (sniffed content type, byte and pixel caps, server-chosen keys, capped URL fetcher); per-provider cost table dated 2026-10-28. ImageModel and ModerationModel are hand-written fakes; MinIO is real via Testcontainers; no image provider called.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7rnC7jppGGdHGESvy
2026-10-28 18:36:40 +00:00
asmhatreandClaude Sonnet 5.5 108fc44542 Add graphrag-neo4j module: structured-output entity and relation extraction into a typed Neo4j graph with a vector index, multi-hop retrieval by span linking and variable-length Cypher paths, compared with plain vector RAG over the same 35 chunks and 9 questions (complete evidence 7/9 vs 5/9 at k=8); Testcontainers on neo4j:2026.10.1 and 5.26. The extraction step is a rule-based stand-in, not a language model.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CifR2BE7PBvRy5hT8TS9oz
2026-10-26 02:03:40 +00:00
asmhatreandClaude Sonnet 5.5 279be7eb9f Add audio module: meeting minutes with Spring AI speech-to-text, structured output and text-to-speech
OpenAiAudioTranscriptionModel -> ChatClient.entity(Minutes.class) -> OpenAiAudioSpeechModel,
WAV chunking at a silence under the 25 MB upload limit, SDK retry behaviour, the 4096-character
speech limit and a cost model. Audio endpoints are a local mock and the chat model a stub; no real
model was called. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CifR2BE7PBvRy5hT8TS9oz
2026-10-26 02:00:28 +00:00
Claude ff58ff0189 rerank: use an example where the cross-encoder fixes the order in 02, correct the download size
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Cfo2K4u4rF18QsPXPFnytf
2026-10-24 18:03:45 +00:00
Claude a429aa40f6 Add rerank module: bi-encoder retrieval plus an ONNX Runtime cross-encoder reranker behind a Spring AI DocumentPostProcessor; hit@k and MRR by pool size and question kind, latency by candidates, batch size, threads and int8, and five reproduced traps. Local MiniLM models, no database or API key.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Cfo2K4u4rF18QsPXPFnytf
2026-10-24 18:00:05 +00:00
Claude 2ccf1d8d19 Add hybrid-search module: vector, tsvector and BM25 fused with Reciprocal Rank Fusion in Java and SQL over one PostgreSQL table; quality by query type, held-out k check, plans and latency at 50k rows
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0146opDKBYtADXvkc39zdiyw
2026-10-22 18:04:49 +00:00
Claude d7e68a14af Add rag-ingestion module: PDF, Word and HTML readers and chunking strategies compared by retrieval hit rate; metadata in the embedding, content-hash idempotent ingestion, re-embedding cost of an edit
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0146opDKBYtADXvkc39zdiyw
2026-10-22 18:04:49 +00:00
657 changed files with 26802 additions and 0 deletions
+16
View File
@@ -9,10 +9,12 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur
| [`mcp-server/`](mcp-server) | An order-lookup service exposed as MCP tools, a resource, and a prompt with `@McpTool`/`@McpResource`/`@McpPrompt`, served over Streamable HTTP (Spring AI 2.0's default MCP server transport). Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Build an MCP Server with Spring AI 2.0](https://ankurm.com/spring-ai-2-0-mcp-server-streamable-http/) |
| [`mcp-client/`](mcp-client) | `ChatClient` calling tools from two real external MCP servers (filesystem, git) over stdio via `defaultToolCallbacks(ToolCallbackProvider...)`, contrasted with a local `@Tool` method, with every call logged through one Micrometer `ObservationHandler`. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Spring AI MCP Client: Calling External MCP Servers from ChatClient](https://ankurm.com/spring-ai-2-0-mcp-client/) |
| [`mcp-secure/`](mcp-secure) | The mcp-server article's order-lookup tools behind a real OAuth2 resource server: JWT validation, one scope per tool via `@PreAuthorize`, unauthenticated tool discovery rejected outright, and every call audit-logged through MDC -- denials included. Spring Boot 4.1.1, Spring AI 2.0.1, Spring Security 7.1.1, Java 25. | [Securing an MCP Server with Spring Security 7](https://ankurm.com/spring-ai-2-0-mcp-server-security/) |
| [`mcp-advanced/`](mcp-advanced) | An incident-desk MCP server using resources (fixed and templated), a prompt, sampling and elicitation, driven by a plain MCP SDK client and by raw curl so the JSON-RPC is visible; includes what a client without those capabilities sees, a slow client hitting the server timeout, and the STATELESS protocol mode silently dropping every tool that needs a callback. Spring Boot 4.1.2, Spring AI 2.0.2, MCP Java SDK 2.1.0, Java 25. | [MCP Beyond Tools in Java: Resources, Prompts, Sampling and Elicitation](https://ankurm.com/mcp-resources-prompts-sampling-elicitation-java/) |
| [`tool-calling/`](tool-calling) | `@Tool` methods, `ToolCallingAdvisor` (the advisor-layer replacement for Spring AI 1.x's per-model tool loop), `returnDirect`, `ToolContext`, and `ToolSearchToolCallingAdvisor` for progressive disclosure across a 230-tool synthetic library -- every test driven by a hand-written `ScriptedChatModel`, no live model anywhere. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Tool Calling in Spring AI 2.0](https://ankurm.com/spring-ai-2-0-tool-calling/) |
| [`structured-output/`](structured-output) | `ChatClient.entity()` mapping LLM responses to Java records, lists and maps; `StructuredOutputValidationAdvisor` retrying non-conforming JSON with a real enum-constrained schema, including a captured run that exhausts every retry without throwing. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Structured Output in Spring AI 2.0](https://ankurm.com/spring-ai-2-0-structured-output/) |
| [`ollama-local/`](ollama-local) | Chat and embeddings against a real local `qwen2.5:0.5b`/`all-minilm`, no API key, driven by a Testcontainers-managed Ollama container started from a baked image; a confirmed model unload via `keep_alive: 0` and `/api/ps`, not a scripted model anywhere. Spring Boot 4.1.1, Spring AI 2.0.1, Testcontainers 2.0.5, Java 25. | [Run LLMs Locally with Spring AI and Ollama](https://ankurm.com/spring-ai-2-0-ollama-local/) |
| [`chat-memory/`](chat-memory) | `MessageChatMemoryAdvisor`, `MessageWindowChatMemory`, the JDBC and Redis `ChatMemoryRepository`, per-user conversation IDs and a token-budget memory of our own, with the traps reproduced against a real PostgreSQL 16 and Redis Stack: a 36-character `conversation_id`, tool messages dropped on save, concurrent writers, a 1.x table under the 2.0 repository, and a Redis repository that silently steps aside for a custom `ChatMemory`. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Chat Memory in Spring AI 2.0: JDBC, Redis and Windowed Conversations](https://ankurm.com/spring-ai-2-0-chat-memory-jdbc-redis-windowed-conversations/) |
| [`session-memory/`](session-memory) | The Spring AI 2.1 Session API that replaces `ChatMemory`: the append-only event log, turn-aware windows, `WindowCompactionStrategy` with a `ChatModelSummarizer`, `SessionAdvisors` on a `ChatClient`, the JDBC repository on a real PostgreSQL 16, and the 2.0 `ChatMemory` deprecation warnings captured from `javac`. Spring Boot 4.1.1, Spring AI 2.1.0, Java 25. | [Chat Memory to Session Memory in Spring AI 2.1](https://ankurm.com/spring-ai-2-0-chat-memory-jdbc-redis-windowed-conversations/) |
| [`advisors/`](advisors) | Three custom advisors -- a logger, a PII redactor (with a stream-safe restore) and a per-request / per-user token budget -- and tests for how the chain is ordered, what `BaseAdvisor` does on a stream, where an advisor sits relative to memory and the tool loop, and what a refusal looks like on a call, a stream and over HTTP (429). A recording stub model, no live model. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Writing Custom Advisors in Spring AI 2.0: Logging, PII Redaction and Token Budgets](https://ankurm.com/spring-ai-2-0-custom-advisors-logging-pii-redaction-token-budgets/) |
| [`vector-stores/`](vector-stores) | The same 30,000-document dataset behind `VectorStore` on pgvector, Redis, Qdrant and Elasticsearch: ingest time, recall@10, latency, metadata filtering and running cost, with the defaults that cost recall reproduced (Elasticsearch's quantised mapping, Redis `EF_RUNTIME`, pgvector post-filtering, Qdrant payload indexes). Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Choosing a Vector Store for Spring AI](https://ankurm.com/spring-ai-2-0-vector-store-comparison-pgvector-redis-qdrant-elasticsearch/) |
| [`evaluation/`](evaluation) | Testing an LLM app: `RelevancyEvaluator` and `FactCheckingEvaluator` (exactly what they send and which judge replies they accept), a 12-case golden dataset with a pass-rate gate, a deterministic judge for CI, simulated judge noise, a 1-5 graded evaluator and a composite. Stub models only; the one live-judge test is skipped without a key. Spring Boot 4.1.1, Spring AI 2.0.1, JUnit 6, Java 25. | [Testing LLM Apps in Java: Spring AI Evaluators and LLM-as-Judge in JUnit 6](https://ankurm.com/spring-ai-2-0-testing-llm-apps-evaluators-llm-as-judge-junit-6/) |
@@ -25,5 +27,19 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur
| [`semantic-cache/`](semantic-cache) | A `CallAdvisor` that serves a stored answer when a new question embeds close to an old one, over a Redis Stack vector index and a real in-process embedding model (all-MiniLM-L6-v2). A labelled set of 30 intents x 4 phrasings plus 20 off-topic questions swept across thresholds (hit rate against wrong answers), 600 requests replayed with an illustrative cost model, and the traps reproduced: Spring AI's score is `(1 + cosine) / 2`, reset-password and reset-2FA are close enough to answer for each other, a tenant filter, expiry, and an index built for another embedding model. The chat model is a script that counts calls; one test uses a real local model. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Semantic Caching for LLM Calls in Spring Boot with Redis Vector Search](https://ankurm.com/semantic-caching-for-llm-calls-in-spring-boot-with-redis-vector-search/) |
| [`langchain4j-interop/`](langchain4j-interop) | The same order assistant in Spring AI 2.0.1 and LangChain4j 1.22.0 in one Spring Boot 4.1.1 app, against a local fake OpenAI server: the bean collision when both OpenAI starters are present, the two requests compared on the wire, a throwing tool and a looping model (what each framework bounds), the meters each records, one MCP tool server used from both, and which lines of the 2025 version of the article still compile. Java 25. | [Spring AI vs LangChain4j in 2026: Is the Pairing Still Worth It?](https://ankurm.com/spring-ai-langchain4j-production-ai-microservices-java/) |
| [`agent-skills/`](agent-skills) | `SKILL.md` folders loaded on demand by the `Skill` tool from `spring-ai-agent-utils` 0.13.0: what the model sees before it loads anything (name and description only), the two-call load round trip, unknown, duplicate and description-less skills, and listing size against inlining every body (character counts). Scripted chat model, no live model. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Agent Skills in Spring AI: Packaging Reusable Capabilities for Your Agents](https://ankurm.com/agent-skills-spring-ai-packaging-reusable-capabilities/) |
| [`rag-ingestion/`](rag-ingestion) | PDF, Word and HTML versions of one 12-section runbook through `PagePdfDocumentReader`, `TikaDocumentReader` and `JsoupDocumentReader`, then `TokenTextSplitter` at six sizes, a paragraph chunker, a sentence splitter and a section chunker; retrieval hit@1/3/5 on 37 fixed questions, metadata in the embedding, content-hash idempotent ingestion into pgvector and the re-embedding cost of one edit. Local all-MiniLM-L6-v2; a synthetic corpus, so differences of two or three questions are noise. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Spring AI RAG Ingestion Pipeline: PDF, Word and HTML Readers with Chunking Strategies Compared](https://ankurm.com/spring-ai-rag-ingestion-pipeline-pdf-word-html-chunking/) |
| [`hybrid-search/`](hybrid-search) | Vector, `tsvector` and a Java Okapi BM25 over one PostgreSQL table (pgvector HNSW + GIN), fused with Reciprocal Rank Fusion in Java and in a single SQL statement, behind a `DocumentRetriever` for `RetrievalAugmentationAdvisor`. 60 questions in four kinds over 94 passages: hybrid helps exact error codes and hurts paraphrases; `k` tuned on the evaluation set did not hold up on held-out folds; plans and latency at 94 and 50,094 rows. Local all-MiniLM-L6-v2. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Hybrid Search in Java: BM25 + Vector with PostgreSQL and Reciprocal Rank Fusion](https://ankurm.com/hybrid-search-java-pgvector-tsvector-reciprocal-rank-fusion/) |
| [`rerank/`](rerank) | A bi-encoder (all-MiniLM-L6-v2) retrieves candidates, a cross-encoder (ms-marco-MiniLM-L-6-v2) rescores them, and a `DocumentPostProcessor` keeps the top 5 for `RetrievalAugmentationAdvisor`. Both models run in-process through ONNX Runtime 1.31.0 with DJL tokenizers 0.39.0 (no database, no API key). 60 questions over 94 passages: hit@1 41 to 49 and MRR 0.78 to 0.87, almost all of it on exact error codes, with paraphrases slightly worse; pool size, batch size, threads and int8 against latency on 2 vCPUs; and five traps reproduced (missing `token_type_ids`, swapped pair order, logits are not probabilities, truncation, a pool that is too small). Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Reranking RAG Results in Java: Cross-Encoder Reranker with ONNX Runtime Before the LLM](https://ankurm.com/reranking-rag-results-java-cross-encoder-onnx-runtime-spring-ai/) |
| [`audio/`](audio) | A meeting-minutes generator: `OpenAiAudioTranscriptionModel` -> `ChatClient.entity(Minutes.class)` -> `OpenAiAudioSpeechModel`. Splitting a 30 MB recording at a silence under the 25 MB upload limit (and what a blind split does), SDK retries that re-upload the file, the 4096-character speech limit, three replies that fail to parse, and a cost model with formulas. The audio endpoints are a local mock and the chat model a stub; no real model was called. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Speech-to-Text and Text-to-Speech with Spring AI: Build a Meeting-Minutes Generator](https://ankurm.com/spring-ai-speech-to-text-text-to-speech-meeting-minutes/) |
| [`graphrag-neo4j/`](graphrag-neo4j) | Entities and relations extracted with `ChatClient.entity(...)` into a typed Neo4j graph with a vector index on entity names (Testcontainers, `neo4j:2026.10.1-community`; also run on 5.26), then multi-hop retrieval by span linking, variable-length Cypher paths and path ranking, against plain vector RAG over the same 35 chunks and 9 questions: complete evidence 7/9 for the graph, 5/9 for vector k=8, 2/9 for k=4, with the traps reproduced (duplicate entity under an alias, an embedding merge that joins the wrong incidents, a reply with a sentence before the JSON fence, a hostile relation type, hop explosion). **The extraction step is a rule-based stand-in, not a language model**; Neo4j, embeddings and Cypher are real. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [GraphRAG in Java with Neo4j and Spring AI](https://ankurm.com/graphrag-java-neo4j-spring-ai-knowledge-graph/) |
| [`image-gen/`](image-gen) | `ImageModel` and `ImagePrompt` with `OpenAiImageOptions` (what the real `OpenAiImageModel` puts on the wire, a per-call options object that silently resets the model, a `List<ImageMessage>` prompt that throws), a prompt gate with `ModerationModel` that fails closed, and safe storage in MinIO: sniffed content type, byte and pixel caps, server-chosen keys, a fetcher for provider URLs, presigned reads. A per-image price table from the vendors' pages dated 2026-10-28. No image provider called: the `ImageModel` and `ModerationModel` are hand-written fakes and a mock server; the MinIO tests use a real server through Testcontainers. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Image Generation and Vision in Spring AI: ImageModel, Prompt Options and Safe Storage](https://ankurm.com/spring-ai-image-generation-imagemodel-s3-minio-safe-storage/) |
| [`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/) |
| [`prompt-caching/`](prompt-caching) | Provider-side prompt caching on Spring AI 2.1: where each `AnthropicCacheStrategy` puts `cache_control` on the real request, what a hit, a miss and a write look like in `Usage` (`getPromptTokens()` now includes the cached tokens, which it did not on 2.0.1), what one changed word invalidates, 5-minute and 1-hour lifetimes, the 20-block lookback in a long chat, OpenAI's automatic caching with `prompt_cache_key`, and a cost table (a 5-minute entry that expires between requests makes caching cost more than none). **No vendor API called: the vendors are a local server that applies their documented rules; tokens are characters / 4 and prices are list prices read on 2026-11-24.** Spring Boot 4.2.0, Spring AI 2.1.0, Java 25. | [Prompt Caching in Spring AI](https://ankurm.com/spring-ai-prompt-caching-anthropic-openai-cost-table/) |
| [`rag-eval/`](rag-eval) | Retrieval metrics in plain Java: hit@k, recall@k, precision@k, MRR and nDCG@k with their edge cases (duplicate chunks, short lists, no relevant passage) pinned by tests, a 30-question golden dataset with graded judgements over a 40-passage runbook, a paired bootstrap (no difference between the four retrievers had an interval that excluded zero), and a JUnit gate with a baseline, a tolerance and a no-new-misses rule that fails a build on a tokenizer that drops digits. **The retrievers are BM25, a hashed-trigram vector that is not a neural embedding, and their fusion; the corpus and questions are synthetic. No model was used.** Java 25, JUnit 6.1.3, no Spring. | [Measuring RAG Retrieval Quality in Java: recall@k, MRR, nDCG and a Golden Dataset in JUnit](https://ankurm.com/rag-retrieval-evaluation-java-recall-mrr-ndcg-golden-dataset/) |
| [`cloud-providers/`](cloud-providers) | Keyless Spring AI on Amazon Bedrock and Azure OpenAI, with no API key or secret key in the application: the AWS default credential chain under IRSA and EKS Pod Identity, a managed identity and Microsoft Entra ID bearer tokens on Azure (and why the dedicated Azure OpenAI starter is not in the 2.1.0 BOM), an audit advisor, and the traps reproduced: a leftover static key beats the role, `AWS_REGION` is ignored by Bedrock auto-configuration, short-lived credentials refetched on every call, `azure-identity` missing from the classpath, other modalities defaulting to OpenAI, and the SigV4 session token showing up in AWS SDK DEBUG logs. **No AWS account or Azure subscription was used: a local server stands in for STS, Bedrock, the Azure identity endpoint and Azure OpenAI; the Spring AI, AWS SDK and azure-identity code is real.** Spring Boot 4.2.0, Spring AI 2.1.0, Java 25. | [Spring AI on Amazon Bedrock and Azure OpenAI: Keyless Auth with IAM Roles and Entra ID](https://ankurm.com/spring-ai-bedrock-azure-openai-keyless-auth-iam-entra-id/) |
| [`ai-21-migration/`](ai-21-migration) | Upgrading from Spring AI 2.0.x to 2.1.0: one set of probes run against 2.0.0, 2.0.2, 2.0.3 and 2.1.0, three compile breaks, an API and configuration diff made from the jars, `ChatMemory` to session copying, `VectorStore.upsert` on pgvector, a grep checklist and an OpenRewrite recipe. Scripted and local fake models only; no provider called. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25. | [Spring AI 2.0 to 2.1 Migration Guide](https://ankurm.com/spring-ai-2-0-to-2-1-migration-guide/) |
Upgrading from Spring AI 1.x: [migration guide](https://ankurm.com/spring-ai-1-to-2-migration-guide/).
+3
View File
@@ -0,0 +1,3 @@
target/
jars-cache/
target-main.log
+61
View File
@@ -0,0 +1,61 @@
# ai-21-migration
Companion code for [Spring AI 2.0 to 2.1 Migration Guide](https://ankurm.com/spring-ai-2-0-to-2-1-migration-guide/) on ankurm.com.
No model provider is called anywhere and no API key is needed. Chat models are scripted or are the real
Spring AI model classes pointed at a small local HTTP server written for this module. PostgreSQL with
pgvector is real, through Testcontainers.
## Versions
| | |
|---|---|
| Spring AI | 2.1.0 (probes also run on 2.0.0, 2.0.2, 2.0.3) |
| Spring Boot | 4.2.0 (probes on 2.0.x use 4.1.0) |
| JDK | 25 |
| OpenRewrite | rewrite-maven-plugin 6.46.1, rewrite-spring 6.37.1 |
## Layout
| Path | What it is |
|---|---|
| `probes/` | One source tree compiled and run against four Spring AI versions, so each difference is measured |
| `broken/src/` | Three files that compile on 2.0.3 and not on 2.1.0 |
| `src/` | The 2.1.0 replacement code and its tests |
| `legacy-app/` | A deliberately 2.0-style project, input for the checklist and the recipe |
| `rewrite.yml` | Two OpenRewrite recipes, to be run one after the other |
| `scripts/grep-checklist.sh` | Run it against your own project |
| `tools/ApiDiff.java` | Public API difference between two sets of jars (JDK class-file API) |
## Run
```bash
scripts/run-all.sh # everything; needs Maven, Docker and network access
mvn test # just the 2.1.0 module (Docker needed for UpsertTest)
(cd probes && mvn test -Dspring-ai.version=2.0.3 -Dboot.version=4.1.0)
scripts/grep-checklist.sh /path/to/project
```
Maven Central rate-limits bursts of downloads; if `api-diff.sh` stops with HTTP 429, wait and run it again.
## Captured output
| File | Shows |
|---|---|
| `output/01-usage-*.txt` | Anthropic prompt and total tokens with caching, per version |
| `output/02-request-*.txt` | Auth header, API version, sampling field and WARN lines |
| `output/03-thinking-*.txt` | Generations returned for a thinking reply |
| `output/04-messages-*.txt` | Message mutability and equality |
| `output/05-refusals-*.txt` | `entity()` on filtered and guarded replies |
| `output/06-legacy-warnings.txt` | javac removal warnings for 2.0-style code |
| `output/07-compile-breaks.txt` | The three compile errors |
| `output/08-session-migration.txt` | Copying `ChatMemory` into a session |
| `output/09-tool-manager.txt` | A wrapping `ToolCallingManager` and tool confirmation |
| `output/10-openai-api-switch.txt` | `spring.ai.openai.chat.api=responses` |
| `output/11-upsert.txt` | `VectorStore.upsert` on SimpleVectorStore and pgvector |
| `output/12-uncached.txt` | Full-price input tokens |
| `output/13-api-diff.txt` | Removed and newly deprecated API, 2.0.3 to 2.1.0 |
| `output/14-config-diff.txt` | Configuration property differences |
| `output/15-bom-diff.txt` | BOM artifacts and dependency versions |
| `output/16-grep-checklist.txt` | The checklist run on `legacy-app` |
| `output/17-openrewrite.txt` | The recipe's diff and the compile results |
@@ -0,0 +1,7 @@
import java.util.Map;
import org.springframework.ai.bedrock.converse.BedrockChatOptions;
class BedrockParams {
Map<String, String> params = Map.of("anthropic_version", "bedrock-2023-05-31");
Object options = BedrockChatOptions.builder().requestParameters(params).build();
}
@@ -0,0 +1,5 @@
import org.springframework.ai.deepseek.DeepSeekAssistantMessage;
class DeepSeekPrefix {
Object prefix = DeepSeekAssistantMessage.prefixAssistantMessage("```java\n");
}
@@ -0,0 +1,5 @@
import org.springframework.ai.google.genai.GoogleGenAiChatModel;
class ThoughtKey {
String key = GoogleGenAiChatModel.THOUGHT_METADATA_KEY;
}
+50
View File
@@ -0,0 +1,50 @@
<?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.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>legacy-app</artifactId>
<version>1.0.0</version>
<description>A deliberately 2.0-style application: the input for scripts/openrewrite.sh and scripts/grep-checklist.sh.</description>
<properties>
<java.version>25</java.version>
<spring-ai.version>2.0.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-client-chat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory-redis</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,33 @@
package com.ankurm.legacy;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.metadata.Usage;
public class SupportBot {
public String ask(ChatClient.Builder builder, ChatMemory memory, String user, String question) {
return builder.defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
.build()
.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, user))
.call()
.content();
}
public AnthropicChatOptions options() {
return AnthropicChatOptions.builder()
.model("claude-sonnet-4-5")
.temperature(0.2)
.topK(40)
.maxTokens(1024)
.build();
}
public long billableInput(Usage usage) {
return usage.getPromptTokens() + usage.getCacheReadInputTokens() + usage.getCacheWriteInputTokens();
}
}
@@ -0,0 +1,3 @@
spring.ai.anthropic.chat.temperature=0.2
spring.ai.chat.memory.redis.host=localhost
spring.ai.chat.memory.repository.jdbc.initialize-schema=always
@@ -0,0 +1,6 @@
# Anthropic usage with cache tokens (Spring AI 2.0.0)
server reports: input_tokens=50 cache_creation=300 cache_read=2000 output=100
call() promptTokens=50 completionTokens=100 totalTokens=150 cacheRead=2000 cacheWrite=300
call() prompt + cacheRead + cacheWrite (the old workaround) = 2350
stream() promptTokens=50 completionTokens=100 totalTokens=150 cacheRead=null cacheWrite=null
stream() prompt + cacheRead + cacheWrite (the old workaround) = 50
@@ -0,0 +1,6 @@
# Anthropic usage with cache tokens (Spring AI 2.0.2)
server reports: input_tokens=50 cache_creation=300 cache_read=2000 output=100
call() promptTokens=50 completionTokens=100 totalTokens=150 cacheRead=2000 cacheWrite=300
call() prompt + cacheRead + cacheWrite (the old workaround) = 2350
stream() promptTokens=50 completionTokens=100 totalTokens=150 cacheRead=null cacheWrite=null
stream() prompt + cacheRead + cacheWrite (the old workaround) = 50
@@ -0,0 +1,6 @@
# Anthropic usage with cache tokens (Spring AI 2.0.3)
server reports: input_tokens=50 cache_creation=300 cache_read=2000 output=100
call() promptTokens=2350 completionTokens=100 totalTokens=2450 cacheRead=2000 cacheWrite=300
call() prompt + cacheRead + cacheWrite (the old workaround) = 4650
stream() promptTokens=2350 completionTokens=100 totalTokens=2450 cacheRead=2000 cacheWrite=300
stream() prompt + cacheRead + cacheWrite (the old workaround) = 4650
@@ -0,0 +1,6 @@
# Anthropic usage with cache tokens (Spring AI 2.1.0)
server reports: input_tokens=50 cache_creation=300 cache_read=2000 output=100
call() promptTokens=2350 completionTokens=100 totalTokens=2450 cacheRead=2000 cacheWrite=300
call() prompt + cacheRead + cacheWrite (the old workaround) = 4650
stream() promptTokens=2350 completionTokens=100 totalTokens=2450 cacheRead=2000 cacheWrite=300
stream() prompt + cacheRead + cacheWrite (the old workaround) = 4650
@@ -0,0 +1,5 @@
# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.0)
header no Authorization header
header x-api-key: <key>
header anthropic-version: 2023-06-01
body "temperature":0.2
@@ -0,0 +1,5 @@
# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.2)
header no Authorization header
header x-api-key: <key>
header anthropic-version: 2023-06-01
body "temperature":0.2
@@ -0,0 +1,5 @@
# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.3)
header no Authorization header
header x-api-key: <key>
header anthropic-version: 2023-06-01
body "temperature":0.2
@@ -0,0 +1,7 @@
# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.1.0)
header Authorization: Bearer <key>
header no x-api-key header
header anthropic-version: 2026-10-21
body no temperature field
WARN org.springframework.ai.anthropic.AnthropicChatModel -- Anthropic API 2026-10-21 does not support temperature, topP or topK; ignoring temperature=0.2, topP=null, topK=null
WARN org.springframework.ai.anthropic.AnthropicChatModel -- Anthropic API 2026-10-21 does not support temperature, topP or topK; ignoring temperature=0.2, topP=null, topK=null
@@ -0,0 +1,5 @@
# A reply with one thinking block and one text block (Spring AI 2.0.0)
getResults().size() = 2
getResult().getOutput().getText() = The user greets me.
generation 0: text=The user greets me. metadata keys=[messageType, signature]
generation 1: text=Hello there. metadata keys=[messageType]
@@ -0,0 +1,5 @@
# A reply with one thinking block and one text block (Spring AI 2.0.2)
getResults().size() = 2
getResult().getOutput().getText() = Hello there.
generation 0: text=Hello there. metadata keys=[anthropicThinkingContents, messageType]
generation 1: text=The user greets me. metadata keys=[messageType, signature]
@@ -0,0 +1,5 @@
# A reply with one thinking block and one text block (Spring AI 2.0.3)
getResults().size() = 2
getResult().getOutput().getText() = Hello there.
generation 0: text=Hello there. metadata keys=[anthropicThinkingContents, messageType]
generation 1: text=The user greets me. metadata keys=[messageType, signature]
@@ -0,0 +1,4 @@
# A reply with one thinking block and one text block (Spring AI 2.1.0)
getResults().size() = 1
getResult().getOutput().getText() = Hello there.
generation 0: text=Hello there. metadata keys=[messageType]
@@ -0,0 +1,4 @@
# Message mutability and equality (Spring AI 2.0.0)
userMessage.getMedia().add(..) returns true
assistant.getToolCalls().clear() throws UnsupportedOperationException
same text, different image: equals() = true
@@ -0,0 +1,4 @@
# Message mutability and equality (Spring AI 2.0.2)
userMessage.getMedia().add(..) returns true
assistant.getToolCalls().clear() throws UnsupportedOperationException
same text, different image: equals() = true
@@ -0,0 +1,4 @@
# Message mutability and equality (Spring AI 2.0.3)
userMessage.getMedia().add(..) returns true
assistant.getToolCalls().clear() throws UnsupportedOperationException
same text, different image: equals() = true
@@ -0,0 +1,4 @@
# Message mutability and equality (Spring AI 2.1.0)
userMessage.getMedia().add(..) throws UnsupportedOperationException
assistant.getToolCalls().clear() throws UnsupportedOperationException
same text, different image: equals() = false
@@ -0,0 +1,8 @@
# entity() on a filtered reply and on a SafeGuardAdvisor refusal (Spring AI 2.0.0)
finishReason=content_filter, empty text
entity(Answer.class) throws MismatchedInputException
responseEntity(..).entity() throws MismatchedInputException
content() returns ''
SafeGuardAdvisor blocks the word 'password'
entity(Answer.class) throws StreamReadException
finishReason returns 'null'
@@ -0,0 +1,8 @@
# entity() on a filtered reply and on a SafeGuardAdvisor refusal (Spring AI 2.0.2)
finishReason=content_filter, empty text
entity(Answer.class) throws MismatchedInputException
responseEntity(..).entity() throws MismatchedInputException
content() returns ''
SafeGuardAdvisor blocks the word 'password'
entity(Answer.class) throws StreamReadException
finishReason returns 'null'
@@ -0,0 +1,8 @@
# entity() on a filtered reply and on a SafeGuardAdvisor refusal (Spring AI 2.0.3)
finishReason=content_filter, empty text
entity(Answer.class) throws MismatchedInputException
responseEntity(..).entity() throws MismatchedInputException
content() returns ''
SafeGuardAdvisor blocks the word 'password'
entity(Answer.class) throws StreamReadException
finishReason returns 'null'
@@ -0,0 +1,8 @@
# entity() on a filtered reply and on a SafeGuardAdvisor refusal (Spring AI 2.1.0)
finishReason=content_filter, empty text
entity(Answer.class) throws ContentFilteredException
responseEntity(..).entity() returns null
content() returns ''
SafeGuardAdvisor blocks the word 'password'
entity(Answer.class) throws GuardrailRefusalException
finishReason returns 'guardrailRefusal'
@@ -0,0 +1,9 @@
# javac -Xlint:deprecation,removal on probes/.../LegacyAssistant.java (from the Maven build log)
Spring AI 2.0.3: 0 warnings
Spring AI 2.1.0: 6 warnings
LegacyAssistant.java:[20,9] chat.memory.ChatMemory in chat.memory has been deprecated and marked for removal
LegacyAssistant.java:[21,43] chat.memory.InMemoryChatMemoryRepository in chat.memory has been deprecated and marked for removal
LegacyAssistant.java:[20,29] chat.memory.MessageWindowChatMemory in chat.memory has been deprecated and marked for removal
LegacyAssistant.java:[25,34] chat.client.advisor.MessageChatMemoryAdvisor in chat.client.advisor has been deprecated and marked for removal
LegacyAssistant.java:[32,40] chat.memory.ChatMemory in chat.memory has been deprecated and marked for removal
LegacyAssistant.java:[40,17] [removal] temperature(Double) in anthropic.AnthropicChatOptions.AbstractBuilder has been deprecated and marked for removal
@@ -0,0 +1,16 @@
# javac on broken/src/*.java against two Spring AI versions
== Spring AI 2.0.3
BedrockParams.java: compiles
DeepSeekPrefix.java: compiles
ThoughtKey.java: compiles
== Spring AI 2.1.0
BedrockParams.java: FAILS
BedrockParams.java:6: error: incompatible types: Map<String,String> cannot be converted to Map<String,Object>
DeepSeekPrefix.java: FAILS
DeepSeekPrefix.java:4: error: cannot find symbol
symbol: method prefixAssistantMessage(String)
ThoughtKey.java: FAILS
ThoughtKey.java:4: error: cannot find symbol
symbol: variable THOUGHT_METADATA_KEY
@@ -0,0 +1,10 @@
# Copying a ChatMemory conversation into a session (scripted model)
added to memory: 1 system message + 4 turns, maxMessages=5
memory holds: system:Be brief. | user:question 3 | assistant:answer 3 | user:question 4 | assistant:answer 4
copied: 4 messages
copied again: 0 messages (already has events)
session holds: user:question 3 | assistant:answer 3 | user:question 4 | assistant:answer 4
appendMessage(system): IllegalArgumentException: Storing a SystemMessage in session 'c2' is disabled. System prompts are configuration: supply them on every request (e.g. ChatClient defaultSystem/.system, or your own prompt builder) and keep per-session settings in Session.metadata. To store system messages anyway, use DefaultSessionService.builder().allowSystemMessages(true) or set spring.ai.session.allow-system-messages=true. See the "System Messages" reference page.
next prompt the model sees: user:question 3 | assistant:answer 3 | user:question 4 | assistant:answer 4 | user:question 5
ChatMemory.CONVERSATION_ID = chat_memory_conversation_id
MemoryAdvisor.CONVERSATION_ID = chat_memory_conversation_id
@@ -0,0 +1,7 @@
# A custom ToolCallingManager and a tool that requires confirmation (scripted model)
manager written for 2.0 (two methods)
paused reply, awaiting [call_1], tool ran: []
resume: UnsupportedOperationException: com.ankurm.aimigration.ToolManagerTest$Old does not support tool call decisions
LoggingToolCallingManager (three methods)
paused reply, awaiting [call_1], tool ran: []
resume: ok, tool ran: [A-17]
@@ -0,0 +1,9 @@
# spring.ai.openai.chat.model=my-model and .temperature=0.1, with and without spring.ai.openai.chat.api (local fake server)
spring.ai.openai.chat.api unset
bean: OpenAiChatModel
POST /v1/chat/completions
body: model="my-model" temperature=0.1
spring.ai.openai.chat.api = responses
bean: OpenAiResponsesChatModel
POST /v1/responses
body: model="gpt-5-mini" temperature=(not sent)
+11
View File
@@ -0,0 +1,11 @@
# VectorStore.upsert on SimpleVectorStore and on PgVectorStore (pgvector/pgvector:pg17)
SimpleVectorStore.upsert: UnsupportedOperationException: SimpleVectorStore does not support upsert
PgVectorStore.upsert twice, same id
rows in vector_store: 1
embedding model calls: 0
similaritySearch(float[], request)
text: second version
embedding model calls: 0
stored metadata distance=42 reads back as: 42
getScore(): 1.0
upsert with a 2-wide vector: IllegalArgumentException: Embedding at index 0 has dimension 2 but the store expects dimension 3
+2
View File
@@ -0,0 +1,2 @@
# UncachedTokens.of on the 2.1.0 usage values
promptTokens=2350 cacheRead=2000 cacheWrite=300 -> full-price input = 50
+100
View File
@@ -0,0 +1,100 @@
# public API, Spring AI 2.0.3 -> 2.1.0 (tools/ApiDiff.java over every non-starter jar in the BOM)
REMOVED public types: 3
org.springframework.ai.bedrock.converse.BedrockReasoningContent$Builder [spring-ai-bedrock-converse]
org.springframework.ai.mcp.annotation.spring.scan.AbstractAnnotatedMethodBeanPostProcessor [spring-ai-mcp-annotations]
org.springframework.ai.mcp.server.common.autoconfigure.annotations.McpServerAnnotationScannerAutoConfiguration$ServerAnnotatedMethodBeanPostProcessor [spring-ai-autoconfigure-mcp-server-common]
REMOVED public/protected members of types that still exist: 29
org.springframework.ai.chat.client.advisor.api.BaseChatMemoryAdvisor#getConversationId(Map)String
org.springframework.ai.chat.messages.AssistantMessage#equals(Object)boolean
org.springframework.ai.chat.messages.AssistantMessage#hashCode()int
org.springframework.ai.chat.messages.SystemMessage#equals(Object)boolean
org.springframework.ai.chat.messages.SystemMessage#hashCode()int
org.springframework.ai.chat.messages.ToolResponseMessage#equals(Object)boolean
org.springframework.ai.chat.messages.ToolResponseMessage#hashCode()int
org.springframework.ai.deepseek.DeepSeekAssistantMessage#prefixAssistantMessage(String)DeepSeekAssistantMessage
org.springframework.ai.deepseek.DeepSeekAssistantMessage#prefixAssistantMessage(String,String)DeepSeekAssistantMessage
org.springframework.ai.google.genai.GoogleGenAiChatModel#THOUGHT_METADATA_KEY
org.springframework.ai.mcp.client.common.autoconfigure.McpToolCallbackAutoConfiguration#mcpAsyncToolCallbacks(ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)AsyncMcpToolCallbackProvider
org.springframework.ai.mcp.client.common.autoconfigure.McpToolCallbackAutoConfiguration#mcpToolCallbacks(ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)SyncMcpToolCallbackProvider
org.springframework.ai.mcp.server.common.autoconfigure.McpServerAutoConfiguration#mcpAsyncServer(McpServerTransportProviderBase,McpSchema$ServerCapabilities$Builder,McpServerProperties,McpServerChangeNotificationProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,Optional)McpAsyncServer
org.springframework.ai.mcp.server.common.autoconfigure.McpServerAutoConfiguration#mcpSyncServer(McpServerTransportProviderBase,McpSchema$ServerCapabilities$Builder,McpServerProperties,McpServerChangeNotificationProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider,Optional)McpSyncServer
org.springframework.ai.mcp.server.common.autoconfigure.annotations.McpServerAnnotationScannerAutoConfiguration#serverAnnotatedMethodBeanPostProcessor(McpServerAnnotationScannerAutoConfiguration$ServerMcpAnnotatedBeans,McpServerAnnotationScannerProperties)McpServerAnnotationScannerAutoConfiguration$ServerAnnotatedMethodBeanPostProcessor
org.springframework.ai.mcp.server.common.autoconfigure.annotations.McpServerAnnotationScannerAutoConfiguration$ServerMcpAnnotatedBeans#<init>()void
org.springframework.ai.mcp.server.webflux.autoconfigure.McpServerSseWebFluxAutoConfiguration#webFluxTransport(JsonMapper,McpServerSseProperties)WebFluxSseServerTransportProvider
org.springframework.ai.mcp.server.webflux.autoconfigure.McpServerStatelessWebFluxAutoConfiguration#webFluxStatelessServerTransport(JsonMapper,McpServerStreamableHttpProperties)WebFluxStatelessServerTransport
org.springframework.ai.mcp.server.webflux.autoconfigure.McpServerStreamableHttpWebFluxAutoConfiguration#webFluxStreamableServerTransportProvider(JsonMapper,McpServerStreamableHttpProperties)WebFluxStreamableServerTransportProvider
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerSseWebMvcAutoConfiguration#webMvcSseServerTransportProvider(JsonMapper,McpServerSseProperties)WebMvcSseServerTransportProvider
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStatelessWebMvcAutoConfiguration#webMvcStatelessServerTransport(JsonMapper,McpServerStreamableHttpProperties)WebMvcStatelessServerTransport
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStreamableHttpWebMvcAutoConfiguration#webMvcStreamableServerTransportProvider(JsonMapper,McpServerStreamableHttpProperties)WebMvcStreamableServerTransportProvider
org.springframework.ai.model.openai.autoconfigure.OpenAiAudioSpeechAutoConfiguration#openAiSdkAudioSpeechModel(OpenAiCommonProperties,OpenAiAudioSpeechProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiAudioSpeechModel
org.springframework.ai.model.openai.autoconfigure.OpenAiAudioTranscriptionAutoConfiguration#openAiSdkAudioTranscriptionModel(OpenAiCommonProperties,OpenAiAudioTranscriptionProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiAudioTranscriptionModel
org.springframework.ai.model.openai.autoconfigure.OpenAiChatAutoConfiguration#openAiChatModel(OpenAiCommonProperties,OpenAiChatProperties,ToolCallingManager,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiChatModel
org.springframework.ai.model.openai.autoconfigure.OpenAiEmbeddingAutoConfiguration#openAiEmbeddingModel(OpenAiCommonProperties,OpenAiEmbeddingProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiEmbeddingModel
org.springframework.ai.model.openai.autoconfigure.OpenAiImageAutoConfiguration#openAiImageModel(OpenAiCommonProperties,OpenAiImageProperties,ObjectProvider,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiImageModel
org.springframework.ai.model.openai.autoconfigure.OpenAiModerationAutoConfiguration#openAiSdkModerationModel(OpenAiCommonProperties,OpenAiModerationProperties,ObjectProvider,ObjectProvider,ObjectProvider)OpenAiModerationModel
org.springframework.ai.openai.metadata.OpenAiAudioTranscriptionResponseMetadata#getUsage()Object
NEWLY @Deprecated (types and members that existed before): 62
org.springframework.ai.anthropic.AnthropicChatModel#THINKING_METADATA_KEY @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.anthropic.AnthropicChatModel#THINKING_TEXT_METADATA_KEY @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.anthropic.AnthropicChatOptions#getTemperature()Double @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.anthropic.AnthropicChatOptions#getTopK()Integer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.anthropic.AnthropicChatOptions#getTopP()Double @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.ChatMemory @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.ChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.InMemoryChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.MessageWindowChatMemory @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.cassandra.CassandraChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.cassandra.CassandraChatMemoryRepositoryConfig @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.cassandra.SchemaUtil @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.H2ChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.HsqldbChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.MysqlChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.OracleChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.PostgresChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.SqlServerChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.jdbc.SqliteChatMemoryRepositoryDialect @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.mongo.Conversation @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.mongo.MongoChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.MediaAttributes @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.MessageAttributes @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.Neo4jChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.Neo4jChatMemoryRepositoryConfig @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.ToolCallAttributes @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.neo4j.ToolResponseAttributes @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.redis.AdvancedRedisChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.redis.RedisChatMemoryConfig @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.memory.repository.redis.RedisChatMemoryRepository @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.messages.AbstractMessage#textContent @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.messages.AssistantMessage#media @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.messages.ToolResponseMessage#responses @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.chat.messages.UserMessage#media @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.deepseek.DeepSeekAssistantMessage @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.deepseek.api.DeepSeekApi#chatCompletionStream(DeepSeekApi$ChatCompletionRequest,HttpHeaders)Flux @Deprecated(forRemoval=true, since=2.1.0)
org.springframework.ai.mcp.customizer.McpAsyncServerCustomizer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.mcp.customizer.McpStatelessAsyncServerCustomizer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.mcp.customizer.McpStatelessSyncServerCustomizer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.mcp.customizer.McpSyncServerCustomizer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.mistralai.MistralAiChatModel#THINKING_CONTENT_METADATA @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#getTemperature()Double @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#getTopK()Integer @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#getTopP()Double @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#setTemperature(Double)void @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#setTopK(Integer)void @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatProperties#setTopP(Double)void @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.autoconfigure.ChatMemoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.cassandra.autoconfigure.CassandraChatMemoryRepositoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.cassandra.autoconfigure.CassandraChatMemoryRepositoryProperties @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.jdbc.autoconfigure.JdbcChatMemoryRepositoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.jdbc.autoconfigure.JdbcChatMemoryRepositoryProperties @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.mongo.autoconfigure.MongoChatMemoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.mongo.autoconfigure.MongoChatMemoryIndexCreatorAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.mongo.autoconfigure.MongoChatMemoryProperties @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.neo4j.autoconfigure.Neo4jChatMemoryRepositoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.neo4j.autoconfigure.Neo4jChatMemoryRepositoryProperties @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.redis.autoconfigure.RedisChatMemoryRepositoryAutoConfiguration @Deprecated(since=2.1.0, forRemoval=true)
org.springframework.ai.model.chat.memory.repository.redis.autoconfigure.RedisChatMemoryRepositoryProperties @Deprecated(since=2.1.0, forRemoval=true)
+49
View File
@@ -0,0 +1,49 @@
# configuration metadata, Spring AI 2.0.3 -> 2.1.0
properties: old=957 new=1084
REMOVED: 0
NEWLY DEPRECATED: 20
spring.ai.anthropic.chat.temperature
spring.ai.anthropic.chat.top-k
spring.ai.anthropic.chat.top-p
spring.ai.chat.memory.repository.cassandra.initialize-schema
spring.ai.chat.memory.repository.cassandra.keyspace
spring.ai.chat.memory.repository.cassandra.messages-column
spring.ai.chat.memory.repository.cassandra.table
spring.ai.chat.memory.repository.cassandra.time-to-live
spring.ai.chat.memory.repository.jdbc.continue-on-error -> spring.ai.session.repository.jdbc.continue-on-error
spring.ai.chat.memory.repository.jdbc.initialize-schema -> spring.ai.session.repository.jdbc.initialize-schema
spring.ai.chat.memory.repository.jdbc.platform -> spring.ai.session.repository.jdbc.platform
spring.ai.chat.memory.repository.jdbc.schema -> spring.ai.session.repository.jdbc.schema
spring.ai.chat.memory.repository.mongo.create-indices
spring.ai.chat.memory.repository.mongo.ttl
spring.ai.chat.memory.repository.neo4j.media-label
spring.ai.chat.memory.repository.neo4j.message-label
spring.ai.chat.memory.repository.neo4j.metadata-label
spring.ai.chat.memory.repository.neo4j.session-label
spring.ai.chat.memory.repository.neo4j.tool-call-label
spring.ai.chat.memory.repository.neo4j.tool-response-label
ADDED: 127, by prefix
spring.ai.chat.client 2
spring.ai.google.genai 25
spring.ai.mcp.client 2
spring.ai.mcp.server 13
spring.ai.ollama.decision 1
spring.ai.ollama.init 2
spring.ai.openai.chat 1
spring.ai.openai.decision 16
spring.ai.openai.responses 42
spring.ai.session.allow-system-messages 1
spring.ai.session.repository 5
spring.ai.session.time-to-live 1
spring.ai.systemone.api-key 1
spring.ai.systemone.base-url 1
spring.ai.systemone.decision 2
spring.ai.systemone.retry 4
spring.ai.systemone.timeout 1
spring.ai.tools.confirmation 2
spring.ai.vectorstore.pgvector 3
spring.ai.vectorstore.qdrant 1
spring.ai.vectorstore.redis 1
+33
View File
@@ -0,0 +1,33 @@
# spring-ai-bom: managed artifacts
2.0.0: 161
2.0.3: 167
2.1.0: 181
in 2.0.3 but not 2.1.0:
new in 2.1.0 compared with 2.0.3:
spring-ai-autoconfigure-model-decision-observation
spring-ai-autoconfigure-model-session
spring-ai-autoconfigure-model-session-jdbc
spring-ai-autoconfigure-model-systemone
spring-ai-google-genai-transcription
spring-ai-google-genai-tts
spring-ai-session
spring-ai-session-advisor
spring-ai-session-jdbc
spring-ai-starter-model-google-genai-transcription
spring-ai-starter-model-google-genai-tts
spring-ai-starter-model-session-jdbc
spring-ai-starter-model-systemone
spring-ai-systemone
# versions in the root pom.xml of each release tag
property 2.0.0 2.0.3 2.1.0
spring-boot.version 4.1.0 4.1.3 4.2.0
anthropic-sdk.version 2.40.1 2.75.0 3.8.0
openai-sdk.version 4.39.1 4.101.0 4.101.0
com.google.genai.version 1.58.0 1.65.0 1.73.0
mcp.sdk.version 2.0.0 2.1.0 2.2.0
awssdk.version 2.41.22 2.55.14 2.55.14
kotlin.version 2.3.20 2.3.20 2.4.21
java.version 17 17 17
@@ -0,0 +1,33 @@
# Spring AI 2.1 upgrade checklist: legacy-app
[ ] ChatMemory API: deprecated, removed in 3.0.0 (move to sessions)
src/main/java/com/ankurm/legacy/SupportBot.java:11: public String ask(ChatClient.Builder builder, ChatMemory memory, String user, String question) {
src/main/java/com/ankurm/legacy/SupportBot.java:12: return builder.defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
src/main/java/com/ankurm/legacy/SupportBot.java:16: .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, user))
src/main/java/com/ankurm/legacy/SupportBot.java:5:import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
src/main/java/com/ankurm/legacy/SupportBot.java:6:import org.springframework.ai.chat.memory.ChatMemory;
[ ] Chat memory modules and properties
pom.xml:47: <artifactId>spring-ai-autoconfigure-model-chat-memory-redis</artifactId>
[ ] Chat memory properties (JDBC ones have spring.ai.session replacements)
src/main/resources/application.properties:2:spring.ai.chat.memory.redis.host=localhost
src/main/resources/application.properties:3:spring.ai.chat.memory.repository.jdbc.initialize-schema=always
[ ] Anthropic sampling options: discarded with a WARN on 2.1.0
src/main/java/com/ankurm/legacy/SupportBot.java:24: .temperature(0.2)
src/main/java/com/ankurm/legacy/SupportBot.java:25: .topK(40)
[ ] Anthropic sampling properties
src/main/resources/application.properties:1:spring.ai.anthropic.chat.temperature=0.2
[ ] Token arithmetic on cache counters: prompt tokens include them since 2.0.3
src/main/java/com/ankurm/legacy/SupportBot.java:31: return usage.getPromptTokens() + usage.getCacheReadInputTokens() + usage.getCacheWriteInputTokens();
[ ] Spring AI and Spring Boot versions
pom.xml:21: <spring-ai.version>2.0.0</spring-ai.version>
pom.xml:28: <artifactId>spring-ai-bom</artifactId>
pom.xml:29: <version>${spring-ai.version}</version>
pom.xml:9: <artifactId>spring-boot-starter-parent</artifactId>
A hit is a place to read, not proof of a problem. No hit is not proof of safety.
+71
View File
@@ -0,0 +1,71 @@
# rewrite-maven-plugin 6.46.1 + rewrite-spring 6.37.1 with rewrite.yml on a copy of legacy-app
compile before (Boot 4.1.0, Spring AI 2.0.0): ok
--- before/pom.xml
+++ app/pom.xml
@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
- <version>4.1.0</version>
+ <version>4.2.0</version>
<relativePath/>
</parent>
@@ -18,7 +18,7 @@
<properties>
<java.version>25</java.version>
- <spring-ai.version>2.0.0</spring-ai.version>
+ <spring-ai.version>2.1.0</spring-ai.version>
</properties>
<dependencyManagement>
@@ -44,7 +44,7 @@
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
- <artifactId>spring-ai-autoconfigure-model-chat-memory-redis</artifactId>
+ <artifactId>spring-ai-autoconfigure-model-chat-memory-repository-redis</artifactId>
</dependency>
</dependencies>
</project>
--- before/src/main/java/com/ankurm/legacy/SupportBot.java
+++ app/src/main/java/com/ankurm/legacy/SupportBot.java
@@ -3,6 +3,7 @@
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
+import org.springframework.ai.chat.client.advisor.api.MemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.metadata.Usage;
@@ -13,7 +14,7 @@
.build()
.prompt()
.user(question)
- .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, user))
+ .advisors(a -> a.param(MemoryAdvisor.CONVERSATION_ID, user))
.call()
.content();
}
@@ -21,8 +22,6 @@
public AnthropicChatOptions options() {
return AnthropicChatOptions.builder()
.model("claude-sonnet-4-5")
- .temperature(0.2)
- .topK(40)
.maxTokens(1024)
.build();
}
--- before/src/main/resources/application.properties
+++ app/src/main/resources/application.properties
@@ -1,3 +1,2 @@
-spring.ai.anthropic.chat.temperature=0.2
-spring.ai.chat.memory.redis.host=localhost
+spring.ai.chat.memory.repository.redis.host=localhost
spring.ai.chat.memory.repository.jdbc.initialize-schema=always
compile after (Boot 4.2.0, Spring AI 2.1.0): ok
both recipes in one invocation, sampling calls left in SupportBot.java:
25: .temperature(0.2)
26: .topK(40)
+60
View File
@@ -0,0 +1,60 @@
<?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.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>ai-21-migration</artifactId>
<version>1.0.0</version>
<name>ai-21-migration</name>
<description>Upgrading Spring AI 2.0 to 2.1: the replacement code, tested with scripted and fake models.</description>
<properties>
<java.version>25</java.version>
<spring-ai.version>2.1.0</spring-ai.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-client-chat</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-session</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-session-advisor</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-openai</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-pgvector-store</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-postgresql</artifactId><scope>test</scope></dependency>
</dependencies>
<build>
<plugins>
<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>
+68
View File
@@ -0,0 +1,68 @@
<?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>
<groupId>com.ankurm</groupId>
<artifactId>ai-21-migration-probes</artifactId>
<version>1.0.0</version>
<description>One source tree, compiled and run against several Spring AI versions: mvn test -Dspring-ai.version=2.0.3 -Dboot.version=4.1.0</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-ai.version>2.1.0</spring-ai.version>
<boot.version>4.2.0</boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<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-client-chat</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-anthropic</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-google-genai</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-deepseek</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bedrock-converse</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<showDeprecation>true</showDeprecation>
<compilerArgs><arg>-Xlint:deprecation,removal</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<argLine>-Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
<systemPropertyVariables><probe.version>${spring-ai.version}</probe.version></systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,43 @@
package com.ankurm.aimigration.probes;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
/**
* Ordinary 2.0-style code. It compiles on 2.0.3 with no warnings from these lines and on 2.1.0
* with removal warnings. See output/06-legacy-warnings.txt.
*/
public class LegacyAssistant {
private final ChatClient chat;
public LegacyAssistant(ChatModel model) {
ChatMemory memory = MessageWindowChatMemory.builder()
.chatMemoryRepository(new InMemoryChatMemoryRepository())
.maxMessages(20)
.build();
this.chat = ChatClient.builder(model)
.defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
.build();
}
public String ask(String conversationId, String question) {
return chat.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();
}
public static AnthropicChatOptions options() {
return AnthropicChatOptions.builder()
.model("claude-sonnet-4-5")
.temperature(0.2)
.build();
}
}
@@ -0,0 +1,86 @@
package com.ankurm.aimigration.probes;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.ai.anthropic.AnthropicChatModel;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
/** The same calls against the real AnthropicChatModel of whatever version is on the class path. */
@ExtendWith(OutputCaptureExtension.class)
class AnthropicProbeTest {
private static AnthropicChatModel model(FakeAnthropic fake, boolean sampling) {
var options = AnthropicChatOptions.builder().baseUrl(fake.url()).apiKey("test-key")
.model("claude-sonnet-4-5").maxTokens(1024).maxRetries(0);
if (sampling) {
options.temperature(0.2);
}
return AnthropicChatModel.builder().options(options.build()).build();
}
@Test
void promptTokensWithCaching() throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("01-usage", "Anthropic usage with cache tokens")) {
t.line("server reports: input_tokens=" + FakeAnthropic.INPUT + " cache_creation=" + FakeAnthropic.CACHE_WRITE
+ " cache_read=" + FakeAnthropic.CACHE_READ + " output=" + FakeAnthropic.OUTPUT);
var model = model(fake, false);
print(t, "call() ", model.call(new Prompt("hi")).getMetadata().getUsage());
List<ChatResponse> chunks = model.stream(new Prompt("hi")).collectList().block();
Usage streamed = chunks.stream().map(r -> r.getMetadata().getUsage())
.filter(u -> u.getTotalTokens() != null && u.getTotalTokens() > 0).reduce((a, b) -> b).orElseThrow();
print(t, "stream()", streamed);
}
}
private static void print(Transcript t, String label, Usage u) {
t.line(label + " promptTokens=" + u.getPromptTokens() + " completionTokens=" + u.getCompletionTokens()
+ " totalTokens=" + u.getTotalTokens() + " cacheRead=" + u.getCacheReadInputTokens()
+ " cacheWrite=" + u.getCacheWriteInputTokens());
// The workaround many 2.0.x dashboards carry: add the cache counters to the prompt count.
long adjusted = u.getPromptTokens() + orZero(u.getCacheReadInputTokens()) + orZero(u.getCacheWriteInputTokens());
t.line(label + " prompt + cacheRead + cacheWrite (the old workaround) = " + adjusted);
}
private static long orZero(Long value) {
return value == null ? 0 : value;
}
@Test
void requestAndSampling(CapturedOutput log) throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("02-request", "What AnthropicChatModel sends, temperature=0.2 set")) {
model(fake, true).call(new Prompt("hi"));
var seen = fake.seen.get(0);
String auth = seen.headers().containsKey("authorization")
? "Authorization: " + seen.headers().get("authorization").split(" ")[0] + " <key>" : "no Authorization header";
t.line("header " + auth);
t.line("header " + (seen.headers().containsKey("x-api-key") ? "x-api-key: <key>" : "no x-api-key header"));
t.line("header anthropic-version: " + seen.headers().get("anthropic-version"));
var temperature = Pattern.compile("\"temperature\":[0-9.]+").matcher(seen.body());
t.line("body " + (temperature.find() ? temperature.group() : "no temperature field"));
log.getOut().lines().filter(l -> l.contains("WARN") && l.toLowerCase().contains("temperature"))
.map(l -> l.substring(l.indexOf("WARN"))).forEach(t::line);
}
}
@Test
void thinkingBlocks() throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("03-thinking", "A reply with one thinking block and one text block")) {
ChatResponse r = model(fake, false).call(new Prompt("hi"));
t.line("getResults().size() = " + r.getResults().size());
t.line("getResult().getOutput().getText() = " + r.getResult().getOutput().getText());
int i = 0;
for (Generation g : r.getResults()) {
t.line("generation " + i++ + ": text=" + g.getOutput().getText()
+ " metadata keys=" + g.getOutput().getMetadata().keySet().stream().sorted().toList());
}
}
}
}
@@ -0,0 +1,84 @@
package com.ankurm.aimigration.probes;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* A local stand-in for the Anthropic Messages API. No vendor is called. It always answers with
* the same thinking block, text block and usage numbers, and records what it received.
*/
final class FakeAnthropic implements AutoCloseable {
record Seen(Map<String, String> headers, String body) { }
static final int INPUT = 50;
static final int CACHE_WRITE = 300;
static final int CACHE_READ = 2000;
static final int OUTPUT = 100;
final List<Seen> seen = new ArrayList<>();
private final HttpServer server;
FakeAnthropic() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> headers = exchange.getRequestHeaders().entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toLowerCase(), e -> String.join(",", e.getValue())));
seen.add(new Seen(headers, body));
boolean stream = body.contains("\"stream\":true");
byte[] reply = (stream ? sse() : json()).getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("content-type", stream ? "text/event-stream" : "application/json");
exchange.sendResponseHeaders(200, reply.length);
exchange.getResponseBody().write(reply);
exchange.close();
});
server.start();
}
String url() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
private static String usage(int output) {
return """
{"input_tokens":%d,"cache_creation_input_tokens":%d,"cache_read_input_tokens":%d,"output_tokens":%d}"""
.formatted(INPUT, CACHE_WRITE, CACHE_READ, output);
}
private static String json() {
return """
{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-5",
"content":[{"type":"thinking","thinking":"The user greets me.","signature":"sig-abc"},
{"type":"text","text":"Hello there."}],
"stop_reason":"end_turn","stop_sequence":null,"usage":%s}""".formatted(usage(OUTPUT));
}
private static String sse() {
StringBuilder s = new StringBuilder();
event(s, "message_start", """
{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":%s}}"""
.formatted(usage(1)));
event(s, "content_block_start", "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}");
event(s, "content_block_delta", "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello there.\"}}");
event(s, "content_block_stop", "{\"type\":\"content_block_stop\",\"index\":0}");
event(s, "message_delta", "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":" + OUTPUT + "}}");
event(s, "message_stop", "{\"type\":\"message_stop\"}");
return s.toString();
}
private static void event(StringBuilder s, String name, String data) {
s.append("event: ").append(name).append('\n').append("data: ").append(data).append("\n\n");
}
@Override
public void close() {
server.stop(0);
}
}
@@ -0,0 +1,73 @@
package com.ankurm.aimigration.probes;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
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.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.MimeTypeUtils;
/** Behaviour that changes without a compile error. The model is a lambda; nothing is called. */
class MessageAndGuardrailProbeTest {
record Answer(String city) { }
private static Media image(byte b) {
return new Media(MimeTypeUtils.IMAGE_PNG, new ByteArrayResource(new byte[] { b }));
}
private static String attempt(java.util.concurrent.Callable<Object> c) {
try {
return "returns " + c.call();
} catch (Exception e) {
return "throws " + e.getClass().getSimpleName();
}
}
@Test
void messages() {
try (var t = new Transcript("04-messages", "Message mutability and equality")) {
var user = UserMessage.builder().text("look").media(image((byte) 1)).build();
t.line("userMessage.getMedia().add(..) " + attempt(() -> user.getMedia().add(image((byte) 2))));
var reply = AssistantMessage.builder().content("ok")
.toolCalls(List.of(new AssistantMessage.ToolCall("1", "function", "f", "{}"))).build();
t.line("assistant.getToolCalls().clear() " + attempt(() -> { reply.getToolCalls().clear(); return "cleared"; }));
var a = UserMessage.builder().text("look").media(image((byte) 1)).build();
var b = UserMessage.builder().text("look").media(image((byte) 2)).build();
t.line("same text, different image: equals() = " + a.equals(b));
}
}
/** A custom or scripted model that finished because a content filter stopped it. */
private static final ChatModel FILTERED = prompt -> new ChatResponse(List.of(new Generation(
new AssistantMessage(""), ChatGenerationMetadata.builder().finishReason("content_filter").build())));
private static final ChatModel NEVER_CALLED = prompt -> {
throw new AssertionError("the guard should have blocked this");
};
@Test
void refusals() {
try (var t = new Transcript("05-refusals", "entity() on a filtered reply and on a SafeGuardAdvisor refusal")) {
var filtered = ChatClient.create(FILTERED);
t.line("finishReason=content_filter, empty text");
t.line(" entity(Answer.class) " + attempt(() -> filtered.prompt().user("q").call().entity(Answer.class)));
t.line(" responseEntity(..).entity() " + attempt(() -> filtered.prompt().user("q").call().responseEntity(Answer.class).entity()));
t.line(" content() " + attempt(() -> "'" + filtered.prompt().user("q").call().content() + "'"));
var guarded = ChatClient.builder(NEVER_CALLED)
.defaultAdvisors(SafeGuardAdvisor.builder().sensitiveWords(List.of("password")).build()).build();
t.line("SafeGuardAdvisor blocks the word 'password'");
t.line(" entity(Answer.class) " + attempt(() -> guarded.prompt().user("the password?").call().entity(Answer.class)));
t.line(" finishReason " + attempt(() -> "'" + guarded.prompt().user("the password?").call()
.chatResponse().getResult().getMetadata().getFinishReason() + "'"));
}
}
}
@@ -0,0 +1,35 @@
package com.ankurm.aimigration.probes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Writes {@code ../output/<name>-<spring-ai version>.txt}; the article quotes these files verbatim. */
final class Transcript implements AutoCloseable {
static final String VERSION = System.getProperty("probe.version", "unknown");
private final Path path;
private final StringBuilder out = new StringBuilder();
Transcript(String name, String title) {
this.path = Path.of("..", "output", name + "-" + VERSION + ".txt");
line("# " + title + " (Spring AI " + VERSION + ")");
}
Transcript line(String text) {
out.append(text).append('\n');
return this;
}
@Override
public void close() {
try {
Files.createDirectories(path.getParent());
Files.writeString(path, out.toString());
} catch (IOException e) {
throw new IllegalStateException(e);
}
System.out.print(out);
}
}
+45
View File
@@ -0,0 +1,45 @@
---
# Run this first: it moves the build and the configuration. Run it while the project still resolves 2.0.
type: specs.openrewrite.org/v1beta/recipe
name: com.ankurm.SpringAi20To21Build
displayName: Spring AI 2.0 to 2.1, build and properties
description: Version bumps, the Redis chat memory rename and the Anthropic sampling properties.
recipeList:
- org.openrewrite.maven.UpgradeParentVersion:
groupId: org.springframework.boot
artifactId: spring-boot-starter-parent
newVersion: 4.2.0
- org.openrewrite.maven.ChangePropertyValue:
key: spring-ai.version
newValue: 2.1.0
- org.openrewrite.maven.ChangeDependencyGroupIdAndArtifactId:
oldGroupId: org.springframework.ai
oldArtifactId: spring-ai-autoconfigure-model-chat-memory-redis
newArtifactId: spring-ai-autoconfigure-model-chat-memory-repository-redis
- org.openrewrite.java.spring.ChangeSpringPropertyKey:
oldPropertyKey: spring.ai.chat.memory.redis
newPropertyKey: spring.ai.chat.memory.repository.redis
- org.openrewrite.java.spring.DeleteSpringProperty:
propertyKey: spring.ai.anthropic.chat.temperature
- org.openrewrite.java.spring.DeleteSpringProperty:
propertyKey: spring.ai.anthropic.chat.top-p
- org.openrewrite.java.spring.DeleteSpringProperty:
propertyKey: spring.ai.anthropic.chat.top-k
---
# Run this second, in a new Maven invocation, so that types resolve against the 2.1.0 jars.
type: specs.openrewrite.org/v1beta/recipe
name: com.ankurm.SpringAi20To21Code
displayName: Spring AI 2.0 to 2.1, the safe code edits
description: >
Removes Anthropic sampling calls and moves the conversation-id constant. It does not move
ChatMemory code to sessions: that needs a person.
recipeList:
- org.openrewrite.java.RemoveMethodInvocations:
methodPattern: org.springframework.ai.anthropic.AnthropicChatOptions$AbstractBuilder temperature(..)
- org.openrewrite.java.RemoveMethodInvocations:
methodPattern: org.springframework.ai.anthropic.AnthropicChatOptions$AbstractBuilder topP(..)
- org.openrewrite.java.RemoveMethodInvocations:
methodPattern: org.springframework.ai.anthropic.AnthropicChatOptions$AbstractBuilder topK(..)
- org.openrewrite.java.ReplaceConstantWithAnotherConstant:
existingFullyQualifiedConstantName: org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID
fullyQualifiedConstantName: org.springframework.ai.chat.client.advisor.api.MemoryAdvisor.CONVERSATION_ID
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Public API and configuration-property differences between two Spring AI releases.
set -euo pipefail
cd "$(dirname "$0")/.."
old=${1:-2.0.3}; new=${2:-2.1.0}
scripts/fetch-jars.sh "$old"; scripts/fetch-jars.sh "$new"
java tools/ApiDiff.java "jars-cache/$old" "jars-cache/$new" | sed "1i # public API, Spring AI $old -> $new (tools/ApiDiff.java over every non-starter jar in the BOM)" > output/13-api-diff.txt
{ echo "# configuration metadata, Spring AI $old -> $new"; python3 -I scripts/config-diff.py "jars-cache/$old" "jars-cache/$new"; } > output/14-config-diff.txt
echo "wrote output/13-api-diff.txt and output/14-config-diff.txt"
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Artifacts and a few dependency versions: Spring AI 2.0.0, 2.0.3 and 2.1.0.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p target/bom
for v in 2.0.0 2.0.3 2.1.0; do
curl -s -f --retry 5 "https://repo1.maven.org/maven2/org/springframework/ai/spring-ai-bom/$v/spring-ai-bom-$v.pom" -o "target/bom/$v.pom"
sed -n 's:.*<artifactId>\(spring-ai-[^<]*\)</artifactId>.*:\1:p' "target/bom/$v.pom" | sort -u | grep -v '^spring-ai-bom$' > "target/bom/$v.txt"
curl -s -f --retry 5 "https://raw.githubusercontent.com/spring-projects/spring-ai/v$v/pom.xml" -o "target/bom/$v.root.xml"
done
{
echo "# spring-ai-bom: managed artifacts"
for v in 2.0.0 2.0.3 2.1.0; do echo "$v: $(wc -l < target/bom/$v.txt)"; done
echo; echo "in 2.0.3 but not 2.1.0:"; comm -23 target/bom/2.0.3.txt target/bom/2.1.0.txt | sed 's/^/ /'
echo; echo "new in 2.1.0 compared with 2.0.3:"; comm -13 target/bom/2.0.3.txt target/bom/2.1.0.txt | sed 's/^/ /'
echo; echo "# versions in the root pom.xml of each release tag"
printf '%-28s %-10s %-10s %-10s\n' property 2.0.0 2.0.3 2.1.0
for p in spring-boot.version anthropic-sdk.version openai-sdk.version com.google.genai.version mcp.sdk.version awssdk.version kotlin.version java.version; do
row=$(for v in 2.0.0 2.0.3 2.1.0; do sed -n "s:.*<$p>\([^<]*\)</$p>.*:\1:p" "target/bom/$v.root.xml" | head -1 | xargs printf '%-10s '; done)
printf '%-28s %s\n' "$p" "$row"
done
} > output/15-bom-diff.txt
cat output/15-bom-diff.txt
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Compile each file in broken/src against 2.0.3 and 2.1.0 and keep javac's own words.
set -euo pipefail
cd "$(dirname "$0")/.."
out=output/07-compile-breaks.txt
echo "# javac on broken/src/*.java against two Spring AI versions" > "$out"
for pair in 2.0.3:4.1.0 2.1.0:4.2.0; do
v=${pair%:*}
(cd probes && mvn -B -q dependency:build-classpath -Dspring-ai.version="$v" -Dboot.version="${pair#*:}" -Dmdep.outputFile="target/cp-$v.txt" >/dev/null 2>&1)
cp=$(cat "probes/target/cp-$v.txt")
echo >> "$out"; echo "== Spring AI $v" >> "$out"
for f in broken/src/*.java; do
tmp=$(mktemp -d)
if msg=$(javac -J-Duser.language=en -proc:none -d "$tmp" -cp "$cp" "$f" 2>&1); then
echo "$(basename "$f"): compiles" >> "$out"
else
echo "$(basename "$f"): FAILS" >> "$out"
echo "$msg" | grep -v -e 'Picked up' | grep -e 'error:' -e 'symbol:' | sed -e "s#^$f# $(basename "$f")#" -e 's/^ *symbol:/ symbol:/' >> "$out"
fi
done
done
cat "$out"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Compare Spring Boot configuration metadata between two directories of jars.
usage: python3 -I scripts/config-diff.py target/jars/2.0.3 target/jars/2.1.0"""
import collections
import glob
import json
import sys
import zipfile
def load(directory):
props = {}
for jar in sorted(glob.glob(directory + "/*.jar")):
with zipfile.ZipFile(jar) as z:
if "META-INF/spring-configuration-metadata.json" in z.namelist():
data = json.loads(z.read("META-INF/spring-configuration-metadata.json"))
for p in data.get("properties", []):
props.setdefault(p["name"], p)
return props
old, new = load(sys.argv[1]), load(sys.argv[2])
removed = sorted(set(old) - set(new))
added = sorted(set(new) - set(old))
deprecated = [n for n in sorted(set(old) & set(new)) if new[n].get("deprecated") and not old[n].get("deprecated")]
print(f"properties: old={len(old)} new={len(new)}")
print(f"\nREMOVED: {len(removed)}")
for n in removed:
print(" " + n)
print(f"\nNEWLY DEPRECATED: {len(deprecated)}")
for n in deprecated:
replacement = new[n].get("deprecation", {}).get("replacement")
print(f" {n}" + (f" -> {replacement}" if replacement else ""))
print(f"\nADDED: {len(added)}, by prefix")
for prefix, count in sorted(collections.Counter(".".join(n.split(".")[:4]) for n in added).items()):
print(f" {prefix} {count}")
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# The three spring-ai-tool-search-tool-* entries are skipped: Maven Central answered 404 for their jars.
# Download every non-starter jar listed in the Spring AI BOM of one version into target/jars/<version>.
set -euo pipefail
v=${1:?version}
dir="$(cd "$(dirname "$0")/.." && pwd)/jars-cache/$v"
base=https://repo1.maven.org/maven2/org/springframework/ai
mkdir -p "$dir"
curl -s -f --retry 5 "$base/spring-ai-bom/$v/spring-ai-bom-$v.pom" -o "$dir/../$v.bom"
sed -n 's:.*<artifactId>\(spring-ai-[^<]*\)</artifactId>.*:\1:p' "$dir/../$v.bom" | sort -u \
| grep -v -e '^spring-ai-bom$' -e '^spring-ai-starter' -e '^spring-ai-tool-search-tool-' > "$dir/../$v.artifacts"
while read -r a; do
[ -s "$dir/$a.jar" ] && continue
code=$(curl -s -f --retry 8 --retry-delay 10 -o "$dir/$a.jar" -w '%{http_code}' "$base/$a/$v/$a-$v.jar" || true)
case $code in
200) ;;
404) echo "in the BOM but not on Maven Central: $a $v" >&2 ;;
*) echo "download failed (HTTP $code): $a $v; run again later" >&2; exit 1 ;;
esac
sleep 1
done < "$dir/../$v.artifacts"
echo "$v: $(ls "$dir" | wc -l) jars"
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Search a project for code and configuration that needs a decision on the way to Spring AI 2.1.
# usage: scripts/grep-checklist.sh <project-dir>
dir=${1:?project directory}
cd "$dir" || exit 2
check() { # title, extended regex, file globs...
local title=$1 regex=$2; shift 2
local includes=(); for g in "$@"; do includes+=("--include=$g"); done
local hits; hits=$(grep -rnE "${includes[@]}" --exclude-dir=target --exclude-dir=build -e "$regex" . | sed 's#^\./##' | sort)
if [ -n "$hits" ]; then echo; echo "[ ] $title"; echo "$hits" | sed 's/^ */ /'; fi
}
code=('*.java' '*.kt')
conf=('*.properties' '*.yml' '*.yaml')
build=('pom.xml' '*.gradle' '*.kts' '*.toml')
echo "# Spring AI 2.1 upgrade checklist: $(basename "$PWD")"
check "ChatMemory API: deprecated, removed in 3.0.0 (move to sessions)" \
'MessageChatMemoryAdvisor|MessageWindowChatMemory|ChatMemoryRepository|ChatMemory\b' "${code[@]}"
check "Chat memory modules and properties" 'chat-memory-repository|chat-memory-redis' "${build[@]}"
check "Chat memory properties (JDBC ones have spring.ai.session replacements)" 'spring\.ai\.chat\.memory' "${conf[@]}"
check "Anthropic sampling options: discarded with a WARN on 2.1.0" '\.(temperature|topP|topK)\(' "${code[@]}"
check "Anthropic sampling properties" 'spring\.ai\.anthropic\.chat\.(options\.)?(temperature|top-p|top-k)' "${conf[@]}"
check "Token arithmetic on cache counters: prompt tokens include them since 2.0.3" 'getCache(Read|Write)InputTokens' "${code[@]}"
check "x-api-key handling: Anthropic keys now travel as Authorization: Bearer" '[Xx]-[Aa][Pp][Ii]-[Kk]ey' "${code[@]}" "${conf[@]}" '*.conf'
check "Reasoning read from metadata or extra generations" '"(isThought|thinking|signature|reasoningContent|thinking_content)"|THOUGHT_METADATA_KEY|THINKING_[A-Z_]*METADATA|getReasoningContent|DeepSeekAssistantMessage' "${code[@]}"
check "Mutating message lists (now unmodifiable)" 'get(Media|ToolCalls)\(\)\.(add|addAll|remove|removeIf|clear)\(' "${code[@]}"
check "Custom ToolCallingManager: delegate the ToolCallDecisions overload" 'implements +ToolCallingManager|: *ToolCallingManager' "${code[@]}"
check "Bedrock requestParameters widened to Map<String, Object>" 'requestParameters' "${code[@]}"
check "entity() with filtered or guarded replies: exception types changed" 'SafeGuardAdvisor' "${code[@]}"
check "pgvector 'distance' metadata key" 'getMetadata\(\)\.get\("distance"\)|DocumentMetadata\.DISTANCE' "${code[@]}"
check "MCP server customizers: deprecated in 2.1.0" 'Mcp(Async|Sync|StatelessAsync|StatelessSync)ServerCustomizer' "${code[@]}"
check "TikaDocumentReader: 10,000,000 character limit since 2.0.3" 'new TikaDocumentReader' "${code[@]}"
check "SemanticCacheAdvisor: a scope resolver is mandatory since 2.0.2" 'SemanticCacheAdvisor' "${code[@]}"
check "Tool resolution fallback: off by default since 2.0.1" 'ToolCallbackResolver' "${code[@]}"
check "Spring AI and Spring Boot versions" 'spring-ai(\.version|-bom)|spring-boot-starter-parent' "${build[@]}"
echo
echo "A hit is a place to read, not proof of a problem. No hit is not proof of safety."
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Copy legacy-app, compile it as it is (2.0.0), run rewrite.yml, show the diff, compile again.
set -euo pipefail
cd "$(dirname "$0")/.."
work=$(mktemp -d)
cp -r legacy-app "$work/app"; cp rewrite.yml "$work/app/"; cp -r legacy-app "$work/before"
out=output/17-openrewrite.txt
echo "# rewrite-maven-plugin 6.46.1 + rewrite-spring 6.37.1 with rewrite.yml on a copy of legacy-app" > "$out"
(cd "$work/app" && mvn -B -q compile >/dev/null 2>&1) && echo "compile before (Boot 4.1.0, Spring AI 2.0.0): ok" >> "$out"
for recipe in com.ankurm.SpringAi20To21Build com.ankurm.SpringAi20To21Code; do
(cd "$work/app" && mvn -B org.openrewrite.maven:rewrite-maven-plugin:6.46.1:run \
-Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:6.37.1 \
-Drewrite.activeRecipes="$recipe" > "$work/rewrite.log" 2>&1) || { tail -40 "$work/rewrite.log"; exit 1; }
done
mv "$work/app/rewrite.yml" "$work/rewrite.used.yml"
(cd "$work" && diff -ru -x target before app | sed -E 's/^(---|\+\+\+) ([^\t]+)\t.*/\1 \2/' | grep -v '^diff ') >> "$out" || true
(cd "$work/app" && mvn -B clean compile > "$work/after.log" 2>&1) && echo "compile after (Boot 4.2.0, Spring AI 2.1.0): ok" >> "$out" \
|| { echo "compile after: FAILED" >> "$out"; grep ERROR "$work/after.log" | head >> "$out"; }
# The same two recipes in ONE Maven invocation: types are still those of 2.0.0.
cp -r legacy-app "$work/one"; cp rewrite.yml "$work/one/"
(cd "$work/one" && mvn -B org.openrewrite.maven:rewrite-maven-plugin:6.46.1:run \
-Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:6.37.1 \
-Drewrite.activeRecipes=com.ankurm.SpringAi20To21Build,com.ankurm.SpringAi20To21Code > "$work/one.log" 2>&1)
{ echo; echo "both recipes in one invocation, sampling calls left in SupportBot.java:"
grep -nE '\.(temperature|topK|topP)\(' "$work/one/src/main/java/com/ankurm/legacy/SupportBot.java" || echo " none"; } >> "$out"
cat "$out"
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25, Maven, Docker (for 11-upsert) and network
# access to Maven Central and GitHub. No model provider is called and no API key is needed.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p target
echo "== probes: one source tree against four Spring AI versions"
for pair in 2.0.0:4.1.0 2.0.2:4.1.0 2.0.3:4.1.0 2.1.0:4.2.0; do
v=${pair%:*}
(cd probes && mvn -B clean test -Dspring-ai.version="$v" -Dboot.version="${pair#*:}" > "../target/probe-$v.log")
done
{
echo "# javac -Xlint:deprecation,removal on probes/.../LegacyAssistant.java (from the Maven build log)"
for v in 2.0.3 2.1.0; do echo "Spring AI $v: $(grep -c 'WARNING.*LegacyAssistant' "target/probe-$v.log" || true) warnings"; done
grep 'WARNING.*LegacyAssistant' target/probe-2.1.0.log \
| sed -E 's#.*LegacyAssistant.java:#LegacyAssistant.java:#; s/org\.springframework\.ai\.//g; s/@org\.jspecify\.annotations\.Nullable java\.lang\.//'
} > output/06-legacy-warnings.txt
echo "== compile breaks"; scripts/compile-breaks.sh > /dev/null
echo "== 2.1.0 module"; mvn -B clean test > target-main.log; mkdir -p target && mv target-main.log target/main.log
echo "== API, config, BOM"; scripts/api-diff.sh > /dev/null; scripts/bom-diff.sh > /dev/null
echo "== checklist"; scripts/grep-checklist.sh legacy-app > output/16-grep-checklist.txt
echo "== OpenRewrite"; scripts/openrewrite.sh > /dev/null
echo done
@@ -0,0 +1,41 @@
package com.ankurm.aimigration;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
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;
/** A wrapping manager as it has to look on 2.1: the third method is a default that throws. */
public class LoggingToolCallingManager implements ToolCallingManager {
private static final Logger log = LoggerFactory.getLogger(LoggingToolCallingManager.class);
private final ToolCallingManager delegate;
public LoggingToolCallingManager(ToolCallingManager delegate) {
this.delegate = delegate;
}
@Override
public List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions options) {
return delegate.resolveToolDefinitions(options);
}
@Override
public ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse response) {
log.info("executing tool calls");
return delegate.executeToolCalls(prompt, response);
}
@Override
public ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse response, ToolCallDecisions decisions) {
log.info("resuming tool calls with {} decision(s)", decisions.decisions().size());
return delegate.executeToolCalls(prompt, response, decisions);
}
}
@@ -0,0 +1,35 @@
package com.ankurm.aimigration;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.session.CreateSessionRequest;
import org.springframework.ai.session.SessionService;
/**
* One-off copy of a conversation from the deprecated {@link ChatMemory} into a session.
* It can only copy what the memory still holds: a window has already discarded older turns.
* System messages are skipped, because a session refuses them unless told otherwise.
*/
@SuppressWarnings("removal")
public final class MemoryToSessionCopier {
private MemoryToSessionCopier() {
}
/** @return the number of messages written, 0 if the session already had events. */
public static int copy(ChatMemory from, SessionService to, String conversationId) {
to.findOrCreate(CreateSessionRequest.builder().id(conversationId).build());
if (!to.getEvents(conversationId).isEmpty()) {
return 0;
}
int copied = 0;
for (Message message : from.get(conversationId)) {
if (message.getMessageType() != MessageType.SYSTEM) {
to.appendMessage(conversationId, message);
copied++;
}
}
return copied;
}
}
@@ -0,0 +1,12 @@
package com.ankurm.aimigration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MigrationApplication {
public static void main(String[] args) {
SpringApplication.run(MigrationApplication.class, args);
}
}
@@ -0,0 +1,26 @@
package com.ankurm.aimigration;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.session.SessionService;
import org.springframework.ai.session.advisor.SessionAdvisors;
/** The 2.1 replacement for a ChatClient built on MessageChatMemoryAdvisor. */
public class SessionAssistant {
private final ChatClient chat;
public SessionAssistant(ChatModel model, SessionService sessions) {
this.chat = ChatClient.builder(model)
.defaultAdvisors(SessionAdvisors.builder(sessions).build())
.build();
}
public String ask(String sessionId, String question) {
return chat.prompt()
.user(question)
.advisors(SessionAdvisors.session(sessionId))
.call()
.content();
}
}
@@ -0,0 +1,21 @@
package com.ankurm.aimigration;
import org.springframework.ai.chat.metadata.Usage;
/**
* Since Spring AI 2.0.3 (and so in 2.1.0) an Anthropic or Bedrock Converse prompt-token count
* includes the cache reads and writes. Subtract them to get the full-price input; never add them.
*/
public final class UncachedTokens {
private UncachedTokens() {
}
public static long of(Usage usage) {
return usage.getPromptTokens() - orZero(usage.getCacheReadInputTokens()) - orZero(usage.getCacheWriteInputTokens());
}
private static long orZero(Long value) {
return value == null ? 0 : value;
}
}
@@ -0,0 +1,3 @@
spring.main.web-application-type=none
# The tests build their own DataSource; do not require one to start.
spring.autoconfigure.exclude=org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration
@@ -0,0 +1,76 @@
package com.ankurm.aimigration;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.aimigration.support.Transcript;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.boot.builder.SpringApplicationBuilder;
/** A local server records which OpenAI endpoint and which settings the auto-configured model uses. */
class OpenAiApiSwitchTest {
private static final String CHAT = """
{"id":"c1","object":"chat.completion","created":1,"model":"m","choices":[{"index":0,"finish_reason":"stop",
"message":{"role":"assistant","content":"hi"}}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}""";
private static final String RESPONSES = """
{"id":"r1","object":"response","created_at":1,"status":"completed","model":"m",
"output":[{"id":"msg1","type":"message","status":"completed","role":"assistant",
"content":[{"type":"output_text","text":"hi","annotations":[]}]}],
"parallel_tool_calls":true,"tool_choice":"auto","tools":[],
"usage":{"input_tokens":1,"input_tokens_details":{"cached_tokens":0},"output_tokens":1,
"output_tokens_details":{"reasoning_tokens":0},"total_tokens":2}}""";
private static String field(String body, String name) {
var m = Pattern.compile("\"" + name + "\":(\"[^\"]*\"|[0-9.]+)").matcher(body);
return name + "=" + (m.find() ? m.group(1) : "(not sent)");
}
@Test
void theSameChatPropertiesUnderBothApis() throws IOException {
List<String[]> seen = new ArrayList<>();
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", x -> {
seen.add(new String[] { x.getRequestURI().getPath(), new String(x.getRequestBody().readAllBytes(), StandardCharsets.UTF_8) });
byte[] reply = (x.getRequestURI().getPath().endsWith("/responses") ? RESPONSES : CHAT).getBytes(StandardCharsets.UTF_8);
x.getResponseHeaders().add("content-type", "application/json");
x.sendResponseHeaders(200, reply.length);
x.getResponseBody().write(reply);
x.close();
});
server.start();
try (var t = new Transcript("10-openai-api-switch.txt", "spring.ai.openai.chat.model=my-model and .temperature=0.1, with and without spring.ai.openai.chat.api (local fake server)")) {
for (String api : new String[] { null, "responses" }) {
var args = new ArrayList<>(List.of(
"--spring.ai.openai.base-url=http://127.0.0.1:" + server.getAddress().getPort() + "/v1",
"--spring.ai.openai.api-key=test-key",
"--spring.ai.openai.chat.model=my-model",
"--spring.ai.openai.chat.temperature=0.1"));
if (api != null) {
args.add("--spring.ai.openai.chat.api=" + api);
}
try (var context = new SpringApplicationBuilder(MigrationApplication.class).logStartupInfo(false)
.run(args.toArray(String[]::new))) {
var model = context.getBean(ChatModel.class);
model.call("hello");
var request = seen.getLast();
t.line("spring.ai.openai.chat.api " + (api == null ? "unset" : "= " + api));
t.line(" bean: " + model.getClass().getSimpleName());
t.line(" POST " + request[0]);
t.line(" body: " + field(request[1], "model") + " " + field(request[1], "temperature"));
}
}
assertThat(seen).hasSize(2);
} finally {
server.stop(0);
}
}
}
@@ -0,0 +1,66 @@
package com.ankurm.aimigration;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.aimigration.support.ScriptedChatModel;
import com.ankurm.aimigration.support.Transcript;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.advisor.api.MemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.session.CreateSessionRequest;
import org.springframework.ai.session.DefaultSessionService;
import org.springframework.ai.session.InMemorySessionRepository;
import org.springframework.ai.session.SessionService;
@SuppressWarnings("removal")
class SessionMigrationTest {
private static String show(List<? extends Message> messages) {
var parts = new ArrayList<String>();
messages.forEach(m -> parts.add(m.getMessageType().getValue() + ":" + m.getText()));
return String.join(" | ", parts);
}
@Test
void copyAWindowIntoASession() {
ChatMemory memory = MessageWindowChatMemory.builder()
.chatMemoryRepository(new InMemoryChatMemoryRepository()).maxMessages(5).build();
memory.add("c1", new SystemMessage("Be brief."));
for (int turn = 1; turn <= 4; turn++) {
memory.add("c1", List.of(new UserMessage("question " + turn), new AssistantMessage("answer " + turn)));
}
SessionService sessions = DefaultSessionService.builder()
.sessionRepository(InMemorySessionRepository.builder().build()).build();
try (var t = new Transcript("08-session-migration.txt", "Copying a ChatMemory conversation into a session (scripted model)")) {
t.line("added to memory: 1 system message + 4 turns, maxMessages=5");
t.line("memory holds: " + show(memory.get("c1")));
t.line("copied: " + MemoryToSessionCopier.copy(memory, sessions, "c1") + " messages");
t.line("copied again: " + MemoryToSessionCopier.copy(memory, sessions, "c1") + " messages (already has events)");
t.line("session holds: " + show(sessions.getMessages("c1")));
sessions.findOrCreate(CreateSessionRequest.builder().id("c2").build());
try {
sessions.appendMessage("c2", new SystemMessage("Be brief."));
t.line("appendMessage(system): accepted");
} catch (RuntimeException e) {
t.line("appendMessage(system): " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
var model = new ScriptedChatModel().reply("answer 5");
new SessionAssistant(model, sessions).ask("c1", "question 5");
t.line("next prompt the model sees: " + show(model.prompts.get(0).getInstructions()));
t.line("ChatMemory.CONVERSATION_ID = " + ChatMemory.CONVERSATION_ID);
t.line("MemoryAdvisor.CONVERSATION_ID = " + MemoryAdvisor.CONVERSATION_ID);
assertThat(model.prompts.get(0).getInstructions()).hasSizeGreaterThan(2);
}
}
}
@@ -0,0 +1,80 @@
package com.ankurm.aimigration;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.aimigration.support.ScriptedChatModel;
import com.ankurm.aimigration.support.Transcript;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.ToolCallingAdvisor;
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.ai.support.ToolCallbacks;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.definition.ToolDefinition;
class ToolManagerTest {
static class Orders {
final List<String> ran = new ArrayList<>();
@Tool(description = "Refund an order", requiresConfirmation = true)
String refund(String orderId) {
ran.add(orderId);
return "refunded " + orderId;
}
}
/** Written for 2.0: both abstract methods delegated, nothing else. It still compiles. */
static class Old implements ToolCallingManager {
private final ToolCallingManager delegate = ToolCallingManager.builder().build();
@Override
public List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions o) {
return delegate.resolveToolDefinitions(o);
}
@Override
public ToolExecutionResult executeToolCalls(Prompt p, ChatResponse r) {
return delegate.executeToolCalls(p, r);
}
}
private static String run(Transcript t, String label, ToolCallingManager manager) {
var orders = new Orders();
var model = new ScriptedChatModel().callTool("call_1", "refund", "{\"orderId\":\"A-17\"}");
var chat = ChatClient.builder(model)
.defaultAdvisors(ToolCallingAdvisor.builder().toolCallingManager(manager).build()).build();
ChatResponse paused = chat.prompt().user("Refund A-17").tools(orders).call().chatResponse();
t.line(label);
t.line(" paused reply, awaiting " + ToolCallDecisions.awaitingDecision(paused) + ", tool ran: " + orders.ran);
var prompt = new Prompt(List.of(new UserMessage("Refund A-17")),
ToolCallingChatOptions.builder().toolCallbacks(ToolCallbacks.from(orders)).build());
String outcome;
try {
manager.executeToolCalls(prompt, paused, ToolCallDecisions.of(ToolCallDecision.allow("call_1")));
outcome = "ok, tool ran: " + orders.ran;
} catch (RuntimeException e) {
outcome = e.getClass().getSimpleName() + ": " + e.getMessage();
}
t.line(" resume: " + outcome);
return outcome;
}
@Test
void wrappingManagers() {
try (var t = new Transcript("09-tool-manager.txt", "A custom ToolCallingManager and a tool that requires confirmation (scripted model)")) {
assertThat(run(t, "manager written for 2.0 (two methods)", new Old())).startsWith("Unsupported");
assertThat(run(t, "LoggingToolCallingManager (three methods)",
new LoggingToolCallingManager(ToolCallingManager.builder().build()))).startsWith("ok");
}
}
}
@@ -0,0 +1,27 @@
package com.ankurm.aimigration;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.aimigration.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.metadata.Usage;
class UncachedTokensTest {
/** The numbers AnthropicChatModel 2.1.0 reported in output/01-usage-2.1.0.txt. */
private static final Usage REPORTED = new Usage() {
public Integer getPromptTokens() { return 2350; }
public Integer getCompletionTokens() { return 100; }
public Object getNativeUsage() { return null; }
public Long getCacheReadInputTokens() { return 2000L; }
public Long getCacheWriteInputTokens() { return 300L; }
};
@Test
void subtractDoNotAdd() {
try (var t = new Transcript("12-uncached.txt", "UncachedTokens.of on the 2.1.0 usage values")) {
t.line("promptTokens=2350 cacheRead=2000 cacheWrite=300 -> full-price input = " + UncachedTokens.of(REPORTED));
}
assertThat(UncachedTokens.of(REPORTED)).isEqualTo(50);
}
}
@@ -0,0 +1,89 @@
package com.ankurm.aimigration;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.aimigration.support.Transcript;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.vectorstore.EmbeddedDocument;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;
/** VectorStore.upsert against a real pgvector container. The embedding model is a counting fake. */
class UpsertTest {
static class CountingEmbeddingModel implements EmbeddingModel {
final AtomicInteger calls = new AtomicInteger();
@Override
public EmbeddingResponse call(EmbeddingRequest request) {
calls.incrementAndGet();
var out = new ArrayList<Embedding>();
for (int i = 0; i < request.getInstructions().size(); i++) {
out.add(new Embedding(new float[] { 1, 0, 0 }, i));
}
return new EmbeddingResponse(out);
}
@Override
public float[] embed(Document document) {
calls.incrementAndGet();
return new float[] { 1, 0, 0 };
}
}
@Test
void upsertAndTheDistanceKey() throws Exception {
var embeddings = new CountingEmbeddingModel();
String id = UUID.nameUUIDFromBytes("doc-1".getBytes(StandardCharsets.UTF_8)).toString();
try (var t = new Transcript("11-upsert.txt", "VectorStore.upsert on SimpleVectorStore and on PgVectorStore (pgvector/pgvector:pg17)")) {
var simple = SimpleVectorStore.builder(embeddings).build();
try {
simple.upsert(List.of(new EmbeddedDocument(new Document(id, "text", Map.of()), new float[] { 1, 0, 0 })));
t.line("SimpleVectorStore.upsert: ok");
} catch (UnsupportedOperationException e) {
t.line("SimpleVectorStore.upsert: UnsupportedOperationException: " + e.getMessage());
}
try (var pg = new PostgreSQLContainer(DockerImageName.parse("pgvector/pgvector:pg17").asCompatibleSubstituteFor("postgres"))) {
pg.start();
var jdbc = new JdbcTemplate(new DriverManagerDataSource(pg.getJdbcUrl(), pg.getUsername(), pg.getPassword()));
var store = PgVectorStore.builder(jdbc, embeddings).dimensions(3).initializeSchema(true).build();
store.afterPropertiesSet();
int before = embeddings.calls.get();
store.upsert(List.of(new EmbeddedDocument(new Document(id, "first version", Map.of("distance", 42)), new float[] { 0, 1, 0 })));
store.upsert(List.of(new EmbeddedDocument(new Document(id, "second version", Map.of("distance", 42)), new float[] { 0, 1, 0 })));
t.line("PgVectorStore.upsert twice, same id");
t.line(" rows in vector_store: " + jdbc.queryForObject("select count(*) from vector_store", Integer.class));
t.line(" embedding model calls: " + (embeddings.calls.get() - before));
var hit = store.similaritySearch(new float[] { 0, 1, 0 }, SearchRequest.builder().topK(1).build()).get(0);
t.line("similaritySearch(float[], request)");
t.line(" text: " + hit.getText());
t.line(" embedding model calls: " + (embeddings.calls.get() - before));
t.line(" stored metadata distance=42 reads back as: " + hit.getMetadata().get("distance"));
t.line(" getScore(): " + hit.getScore());
try {
store.upsert(List.of(new EmbeddedDocument(new Document(UUID.randomUUID().toString(), "short", Map.of()), new float[] { 1, 0 })));
t.line("upsert with a 2-wide vector: accepted");
} catch (RuntimeException e) {
t.line("upsert with a 2-wide vector: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
assertThat(hit.getText()).isEqualTo("second version");
}
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.aimigration.support;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
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;
/** Not a language model: replies come from a queue, and every prompt is recorded. */
public class ScriptedChatModel implements ChatModel {
public final List<Prompt> prompts = new ArrayList<>();
private final Deque<AssistantMessage> replies = new ArrayDeque<>();
public ScriptedChatModel reply(String text) {
replies.add(new AssistantMessage(text));
return this;
}
public ScriptedChatModel callTool(String id, String name, String arguments) {
replies.add(AssistantMessage.builder()
.toolCalls(List.of(new AssistantMessage.ToolCall(id, "function", name, arguments))).build());
return this;
}
@Override
public ChatResponse call(Prompt prompt) {
prompts.add(prompt);
return new ChatResponse(List.of(new Generation(replies.remove())));
}
@Override
public ChatOptions getOptions() {
return ToolCallingChatOptions.builder().build();
}
}
@@ -0,0 +1,33 @@
package com.ankurm.aimigration.support;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Writes a numbered transcript under {@code output/}; the article quotes these files verbatim. */
public final class Transcript implements AutoCloseable {
private final Path path;
private final StringBuilder out = new StringBuilder();
public Transcript(String file, String title) {
this.path = Path.of("output", file);
line("# " + title);
}
public Transcript line(String text) {
out.append(text).append('\n');
return this;
}
@Override
public void close() {
try {
Files.createDirectories(path.getParent());
Files.writeString(path, out.toString());
} catch (IOException e) {
throw new IllegalStateException(e);
}
System.out.print(out);
}
}
+114
View File
@@ -0,0 +1,114 @@
import java.io.IOException;
import java.lang.classfile.*;
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
import java.lang.reflect.AccessFlag;
import java.nio.file.*;
import java.util.*;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
* Compares the public API of two sets of Spring AI jars with the JDK class-file API.
* Usage: java tools/ApiDiff.java <oldJarDir> <newJarDir>
* Prints removed public types and members, and what is newly annotated {@code @Deprecated}.
*/
public class ApiDiff {
record Item(String jar, Set<String> flags, String deprecated) { }
public static void main(String[] args) throws IOException {
Map<String, Item> before = scan(Path.of(args[0]));
Map<String, Item> after = scan(Path.of(args[1]));
var removedTypes = before.keySet().stream().filter(k -> !k.contains("#") && !after.containsKey(k)).sorted().toList();
var removedMembers = before.keySet().stream()
.filter(k -> k.contains("#") && !after.containsKey(k) && after.containsKey(owner(k)))
.sorted().toList();
var newlyDeprecated = after.entrySet().stream()
.filter(e -> e.getValue().deprecated() != null)
.filter(e -> before.containsKey(e.getKey()) && before.get(e.getKey()).deprecated() == null)
.map(Map.Entry::getKey).sorted().toList();
System.out.println("REMOVED public types: " + removedTypes.size());
removedTypes.forEach(k -> System.out.println(" " + k + " [" + before.get(k).jar() + "]"));
System.out.println();
System.out.println("REMOVED public/protected members of types that still exist: " + removedMembers.size());
removedMembers.forEach(k -> System.out.println(" " + k));
System.out.println();
System.out.println("NEWLY @Deprecated (types and members that existed before): " + newlyDeprecated.size());
// A deprecated type implies its members; list types first, then members of other types.
var deprecatedTypes = newlyDeprecated.stream().filter(k -> !k.contains("#")).collect(Collectors.toSet());
for (String k : newlyDeprecated) {
if (k.contains("#") && deprecatedTypes.contains(owner(k))) {
continue;
}
System.out.println(" " + k + " " + after.get(k).deprecated());
}
}
static String owner(String key) {
return key.substring(0, key.indexOf('#'));
}
static Map<String, Item> scan(Path dir) throws IOException {
Map<String, Item> result = new TreeMap<>();
try (var jars = Files.list(dir)) {
for (Path jar : jars.filter(p -> p.toString().endsWith(".jar")).sorted().toList()) {
try (var jf = new JarFile(jar.toFile())) {
for (var entry : jf.stream().filter(e -> e.getName().startsWith("org/springframework/ai/")
&& e.getName().endsWith(".class")).toList()) {
ClassModel cm = ClassFile.of().parse(jf.getInputStream(entry).readAllBytes());
if (!visible(cm.flags().flags()) || cm.thisClass().asInternalName().matches(".*\\$\\d.*")) {
continue;
}
String type = cm.thisClass().asInternalName().replace('/', '.');
String name = jar.getFileName().toString().replace(".jar", "");
result.put(type, new Item(name, Set.of(), deprecation(cm)));
for (MethodModel m : cm.methods()) {
var f = m.flags().flags();
if (visible(f) && !f.contains(AccessFlag.SYNTHETIC) && !f.contains(AccessFlag.BRIDGE)) {
String sig = m.methodTypeSymbol().displayDescriptor();
result.put(type + "#" + m.methodName().stringValue() + sig, new Item(name, Set.of(), deprecation(m)));
}
}
for (FieldModel field : cm.fields()) {
var f = field.flags().flags();
if (visible(f) && !f.contains(AccessFlag.SYNTHETIC)) {
result.put(type + "#" + field.fieldName().stringValue(), new Item(name, Set.of(), deprecation(field)));
}
}
}
}
}
}
return result;
}
static boolean visible(Set<AccessFlag> flags) {
return flags.contains(AccessFlag.PUBLIC) || flags.contains(AccessFlag.PROTECTED);
}
static String deprecation(AttributedElement element) {
var attr = element.findAttribute(Attributes.runtimeVisibleAnnotations());
if (attr.isEmpty()) {
return null;
}
for (var a : attr.get().annotations()) {
if (a.classSymbol().descriptorString().equals("Ljava/lang/Deprecated;")) {
String text = a.elements().stream()
.map(e -> e.name().stringValue() + "=" + value(e.value()))
.collect(Collectors.joining(", "));
return "@Deprecated(" + text + ")";
}
}
return null;
}
static String value(AnnotationValue v) {
return switch (v) {
case AnnotationValue.OfString s -> s.stringValue();
case AnnotationValue.OfBoolean b -> String.valueOf(b.booleanValue());
default -> v.toString();
};
}
}
+1
View File
@@ -0,0 +1 @@
target/
+37
View File
@@ -0,0 +1,37 @@
# audio
A meeting-minutes generator on Spring AI 2.0.2: a recording goes through `OpenAiAudioTranscriptionModel`, the transcript becomes a typed `Minutes` record with `ChatClient.entity(...)`, and the action items are read back with `OpenAiAudioSpeechModel`. Files over the upload limit are split in the middle of a silence; a cost model with formulas prices a meeting.
**No real model was called.** The two audio endpoints (`/v1/audio/transcriptions`, `/v1/audio/speech`) are a local **mock** (`src/test/.../support/FakeAudioServer.java`) that the real Spring AI classes and the OpenAI Java SDK talk to over HTTP, so the requests in `output/` are what those classes really send. The "recording" is 30 synthetic tones, one per scripted sentence, and the mock's "transcription" decodes the pitch back into the sentence. The chat model is a scripted **stub**. Nothing here measures the accuracy, latency or price of any real model; the cost table applies OpenAI's published prices (read on 2026-10-26) to stated assumptions.
| | |
|---|---|
| Spring Boot | 4.1.2 |
| Spring AI | 2.0.2 (`spring-ai-openai`, `spring-ai-client-chat`) |
| Java | 25 |
| Run | `scripts/run-all.sh` (about 45 s) |
## Source
| File | What it is |
|---|---|
| [`MinutesService`](src/main/java/com/ankurm/audio/MinutesService.java) | transcribe (chunked) -> `summarise` -> `readAloud` (split at 4096 characters) |
| [`SilenceChunker`](src/main/java/com/ankurm/audio/SilenceChunker.java) | splits a WAV under a byte budget, cutting in the middle of the longest silence it finds; also the blind baseline |
| [`Minutes`](src/main/java/com/ankurm/audio/Minutes.java) | the record the model's reply is parsed into |
| [`NamedBytes`](src/main/java/com/ankurm/audio/NamedBytes.java) | a `ByteArrayResource` with a file name (the extension is how the upload is typed) |
| [`CostModel`](src/main/java/com/ankurm/audio/CostModel.java) | the three cost formulas and the prices they were run with |
| [`Wav`](src/main/java/com/ankurm/audio/Wav.java) | the 60 lines of RIFF/WAVE the chunker needs |
## Captured output (`output/`)
| File | Shows |
|---|---|
| `01-api-shape.txt` | class names and defaults in the 2.0.2 jars |
| `02-transcribe-small.txt`, `02b-filename.txt` | the multipart request; file name and extension |
| `03-large-file.txt` | 413 on a 30 MB file; two silence-aligned chunks recover every line |
| `04-blind-split.txt` | cutting every N bytes lands inside a sentence |
| `05-structured-output.txt`, `05b-bad-replies.txt` | the schema appended to the prompt; three replies that fail to parse |
| `06-speech.txt`, `06b-speech-split.txt` | the speech request; the 4096-character wall; splitting |
| `07-retries.txt` | SDK retries re-upload the whole file |
| `08-cost.txt` | cost per meeting length; file size per encoding |
| `09-end-to-end.txt` | the three steps wired together |
+15
View File
@@ -0,0 +1,15 @@
# Spring AI 2.0.2 audio classes and defaults (read from the jars)
speech-to-text interface : org.springframework.ai.audio.transcription.TranscriptionModel
speech-to-text OpenAI : org.springframework.ai.openai.OpenAiAudioTranscriptionModel
text-to-speech interface : org.springframework.ai.audio.tts.TextToSpeechModel
text-to-speech OpenAI : org.springframework.ai.openai.OpenAiAudioSpeechModel
transcription DEFAULT_TRANSCRIPTION_MODEL = whisper-1
transcription DEFAULT_RESPONSE_FORMAT = text
speech DEFAULT_SPEECH_MODEL = gpt-4o-mini-tts
speech DEFAULT_VOICE = alloy
speech DEFAULT_RESPONSE_FORMAT = mp3
speech DEFAULT_SPEED = 1.0
both DEFAULT_TIMEOUT = PT1M
both DEFAULT_MAX_RETRIES = 3
+18
View File
@@ -0,0 +1,18 @@
# One 60-second clip (1920044 bytes WAV) through OpenAiAudioTranscriptionModel -- MOCK server
model option: whisper-1
request : POST /v1/audio/transcriptions (multipart, 1920524 bytes)
fields : {model=whisper-1, response_format=text}
file part : name=standup.wav type=application/octet-stream bytes=1920044
transcribe(Resource) -> "Okay, let's get started with the Falcon weekly sync. First item is the release date for version two point four."
with language=en and prompt, fields now: {model=whisper-1, language=en, prompt=Falcon weekly sync, response_format=text}
response metadata class: OpenAiAudioTranscriptionResponseMetadata
model option: gpt-transcribe
request : POST /v1/audio/transcriptions (multipart, 1920529 bytes)
fields : {model=gpt-transcribe, response_format=text}
file part : name=standup.wav type=application/octet-stream bytes=1920044
transcribe(Resource) -> "Okay, let's get started with the Falcon weekly sync. First item is the release date for version two point four."
with language=en and prompt, fields now: {model=gpt-transcribe, language=en, prompt=Falcon weekly sync, response_format=text}
response metadata class: OpenAiAudioTranscriptionResponseMetadata
+5
View File
@@ -0,0 +1,5 @@
# The upload's file name decides whether it is accepted -- MOCK server
file name standup.wav -> ok: 52 chars
file name standup.flac -> BadRequestException: 400: mock: Invalid file format. Supported formats: [mp3, mp4, mpeg, mpga, m4a, wav, webm]
file name standup -> BadRequestException: 400: mock: Invalid file format. Supported formats: [mp3, mp4, mpeg, mpga, m4a, wav, webm]
+14
View File
@@ -0,0 +1,14 @@
# A 16-minute recording, 30,278,444 bytes -- MOCK server
1) the whole file in one request (mock limit 26,214,400 bytes):
exception: com.openai.errors.UnexpectedStatusCodeException
message : 413: mock: Maximum content size limit (26214400) exceeded (30278929 bytes read)
2) MinutesService.transcribe: budget 24,000,000 bytes per chunk, silence of at least 2.0 s, RMS below 500
chunk 0: 0.0 s -> 733.5 s 23,472,022 bytes cut: mid-silence
chunk 1: 733.5 s -> 946.2 s 6,806,466 bytes cut: end of file
requests the mock saw: 2
- file=part-00-meeting.wav bytes=23,472,022 prompt=(none)
- file=part-01-meeting.wav bytes=6,806,466 prompt="...the on call rotation changes next month."
script lines recovered: 30 of 30, in order: true
[inaudible] markers: 0
+8
View File
@@ -0,0 +1,8 @@
# Cutting every 24,000,000 bytes, wherever that lands -- MOCK server
chunk 0: 0.0 s -> 750.0 s 24,000,000 bytes boundary falls INSIDE sentence 23 ("Everyone should check the new rotation sheet before the end of this week.")
chunk 1: 750.0 s -> 946.2 s 6,278,488 bytes boundary falls at end of file
script lines recovered: 29 of 30; [inaudible] markers: 2
(mock rule: a tone cut to under 60% of its length is reported as [inaudible]; a real model would not fail this
cleanly -- OpenAI's guide only says splitting mid-sentence can remove context and reduce accuracy.)
+58
View File
@@ -0,0 +1,58 @@
# entity(Minutes.class) against a STUB ChatModel
messages sent to the model:
[SYSTEM] 222 chars
[USER] 2799 chars
tail of the USER message (the format instructions Spring AI appended):
Your response should be in JSON format.
Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.
Do not include markdown code blocks in your response.
Remove the ```json markdown from the output.
Here is the JSON Schema instance your output must adhere to:
```{
"$schema" : "https://json-schema.org/draft/2020-12/schema",
"type" : "object",
"properties" : {
"actionItems" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"due" : {
"type" : "string"
},
"owner" : {
"type" : "string"
},
"task" : {
"type" : "string"
}
},
"required" : [ "due", "owner", "task" ],
"additionalProperties" : false
}
},
"decisions" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"title" : {
"type" : "string"
}
},
"required" : [ "actionItems", "decisions", "title" ],
"additionalProperties" : false
}```
parsed: Falcon weekly sync
decisions : 2
action item : Rahul | Fix the login timeout bug | due: before the release on the fourteenth of November
action item : Priya | Send the revised budget to finance | due: Friday
action item : Sana | Open tickets for both export endpoint issues | due: today
spoken form:
Falcon weekly sync. 2 decisions. Ship version 2.4 on the fourteenth of November. The data pipeline migrates to the new cluster next sprint. 3 action items. Rahul: Fix the login timeout bug, due before the release on the fourteenth of November. Priya: Send the revised budget to finance, due Friday. Sana: Open tickets for both export endpoint issues, due today.
+5
View File
@@ -0,0 +1,5 @@
# Three replies a model can give instead of clean JSON (STUB model)
wrapped in a markdown fence with a sentence before it -> StreamReadException: Unrecognized token 'Here': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false...
truncated: closing brace missing -> UnexpectedEndOfInputException: Unexpected end-of-input: expected close marker for Object (start marker at [Source: REDACTED (`StreamReadFeatu...
prose instead of JSON -> StreamReadException: Unrecognized token 'I': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') ...
+11
View File
@@ -0,0 +1,11 @@
# OpenAiAudioSpeechModel -- MOCK server
speech.call(String) with every default:
request json : {"input":"Three action items.","model":"gpt-4o-mini-tts","voice":"alloy","response_format":"mp3","speed":1.0}
response : 20310 bytes
with TextToSpeechPrompt and options:
request json : {"input":"Rahul: fix the login timeout bug.","model":"gpt-4o-mini-tts","voice":"coral","instructions":"Calm, like a project manager reading notes.","response_format":"wav","speed":1.1}
response : 35244 bytes, starts with RIFF
input of 5000 characters -> BadRequestException: 400: mock: the maximum length of input is 4096 characters, got 5000
+6
View File
@@ -0,0 +1,6 @@
# Splitting a long read-back at sentence ends
text: 11051 characters, 120 sentences
part 0: 4038 characters, ends with " take space."
part 1: 4047 characters, ends with " take space."
part 2: 2964 characters, ends with " take space."
+6
View File
@@ -0,0 +1,6 @@
# A 120-second clip (3840044 bytes) against a flaky endpoint -- MOCK server
maxRetries=0, server fails the first 2 requests with 429 -> RateLimitException requests: 1, bytes uploaded: 3,840,523
maxRetries=0, server fails the first 2 requests with 400 -> BadRequestException requests: 1, bytes uploaded: 3,840,523
maxRetries=3, server fails the first 2 requests with 429 -> ok requests: 3, bytes uploaded: 11,521,569
maxRetries=3, server fails the first 2 requests with 400 -> BadRequestException requests: 1, bytes uploaded: 3,840,523
+14
View File
@@ -0,0 +1,14 @@
# Cost of one meeting, USD (prices of 2026-10-26; word and token counts are ASSUMPTIONS)
assumptions: 150 words/minute spoken, 0.75 words/token, summary output 600 tokens, read-back 120 words
prices : gpt-transcribe $0.0045/min | whisper-1 $0.006/min | gpt-4o-mini $0.15 in / $0.60 out per 1M | tts-1 $15 per 1M chars
minutes words gpt-transc whisper-1 summary tts-1 total(gt)
15 2,250 0.0675 0.0900 0.0008 0.0108 0.0791
30 4,500 0.1350 0.1800 0.0013 0.0108 0.1471
60 9,000 0.2700 0.3600 0.0022 0.0108 0.2830
120 18,000 0.5400 0.7200 0.0040 0.0108 0.5548
transcription is billed on audio duration, not file size: a 60-minute recording costs $0.2700 whatever its encoding.
size of 60 minutes: 16 kHz mono 16-bit WAV = 115.2 MB | 64 kbit/s mp3 = 28.8 MB | 32 kbit/s mp3 = 14.4 MB
minutes that fit in 25,000,000 bytes: WAV 13.0 | 64 kbit/s 52 | 32 kbit/s 104
+7
View File
@@ -0,0 +1,7 @@
# Recording -> transcript -> Minutes -> audio (MOCK audio server, STUB chat model)
1) transcribe: 30,278,444 bytes -> 2 request(s) -> 1701 characters
2) summarise : transcript of 292 words reached the chat model as the user message: true
2 action items: [ActionItem[owner=Rahul, task=Fix the login timeout bug, due=before the release], ActionItem[owner=Priya, task=Send the revised budget to finance, due=Friday]]
3) read back : 1 clip(s), 221910 bytes, spoken text: Falcon weekly sync. 1 decision. Ship version 2.4 on the fourteenth of November. 2 action items. Rahul: Fix the login timeout bug, due before the release. Priya: Send the revised budget to finance, due Friday.
speech request: {"input":"Falcon weekly sync. 1 decision. Ship version 2.4 on the fourteenth of November. 2 action items. Rahul: Fix the login timeout bug, due before the release. Priya: Send the revised budget to finance, due Friday.","model":"gpt-4o-mini-tts","voice":"coral","response_format":"wav","speed":1.0}
+59
View File
@@ -0,0 +1,59 @@
<?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.2</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>audio</artifactId>
<version>1.0.0</version>
<name>audio</name>
<description>Meeting-minutes generator on Spring AI audio: OpenAiAudioTranscriptionModel, a structured-output ChatClient for action items, OpenAiAudioSpeechModel for read-back, WAV chunking for the upload limit and a cost model. Run against a local mock server.</description>
<properties>
<java.version>25</java.version>
<spring-ai.version>2.0.2</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-client-chat</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai</artifactId></dependency>
<dependency><groupId>tools.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<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>
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Regenerates every file under output/ from the test suite. No API key, no Docker, no network
# beyond Maven Central: the audio endpoints are a local mock and the chat model is a stub.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -rf target output
mvn -q -B test 2>&1 | grep -E "Tests run:|BUILD|FAIL|ERROR" || true
ls output
@@ -0,0 +1,50 @@
package com.ankurm.audio;
/**
* The cost of one meeting as three line items. Prices are inputs, not constants of nature: the
* defaults in {@link Prices#OPENAI_2026_10_26} were read off OpenAI's pricing and model pages on
* 2026-10-26 and will drift.
*
* <pre>
* transcription = minutes x pricePerMinute (audio length, not file size)
* summary = tokensIn x in/1e6 + tokensOut x out/1e6
* read-back = characters x pricePerMillionChars/1e6 (tts-1 family, billed per character)
* | speechTokens x audioOut/1e6 + textTokens x textIn/1e6 (gpt-4o-mini-tts, billed per token)
* </pre>
*/
public final class CostModel {
/** Dollar prices. {@code ttsPerMillionChars} applies to tts-1 / tts-1-hd; the *Token* fields to gpt-4o-mini-tts. */
public record Prices(double transcribePerMinute, double chatInPerMillion, double chatOutPerMillion,
double ttsPerMillionChars, double miniTtsTextInPerMillion, double miniTtsAudioOutPerMillion) {
/** gpt-transcribe, gpt-4o-mini (chat), tts-1, gpt-4o-mini-tts as listed on 2026-10-26. */
public static final Prices OPENAI_2026_10_26 = new Prices(0.0045, 0.15, 0.60, 15.0, 0.60, 12.0);
/** whisper-1 for the transcription line, everything else as above. */
public static final Prices WHISPER_1 = new Prices(0.006, 0.15, 0.60, 15.0, 0.60, 12.0);
}
/** Rule-of-thumb token estimate: about 0.75 English words per token. An assumption, not a measurement. */
public static final double WORDS_PER_TOKEN = 0.75;
/** Spoken English runs at roughly 150 words per minute. Also an assumption. */
public static final double WORDS_PER_MINUTE = 150;
private CostModel() {}
public static double transcription(double minutes, Prices p) {
return minutes * p.transcribePerMinute();
}
public static double summary(double transcriptWords, double outputTokens, Prices p) {
double tokensIn = transcriptWords / WORDS_PER_TOKEN;
return tokensIn * p.chatInPerMillion() / 1e6 + outputTokens * p.chatOutPerMillion() / 1e6;
}
public static double readBackPerChar(int characters, Prices p) {
return characters * p.ttsPerMillionChars() / 1e6;
}
public static double readBackPerToken(double textTokens, double audioTokens, Prices p) {
return textTokens * p.miniTtsTextInPerMillion() / 1e6 + audioTokens * p.miniTtsAudioOutPerMillion() / 1e6;
}
}
@@ -0,0 +1,29 @@
package com.ankurm.audio;
import java.util.List;
/**
* What we want back from the model. Spring AI turns this record into a JSON Schema, appends it to
* the prompt, and parses the reply into it ({@code ChatClient...entity(Minutes.class)}).
*/
public record Minutes(String title, List<String> decisions, List<ActionItem> actionItems) {
/** {@code due} is free text ("Friday", "14 November") because a meeting rarely says an ISO date. */
public record ActionItem(String owner, String task, String due) {}
/** The text we hand to text-to-speech: short, spoken-friendly, no markup. */
public String toSpokenText() {
StringBuilder sb = new StringBuilder(title).append(". ");
if (!decisions.isEmpty()) {
sb.append(decisions.size()).append(decisions.size() == 1 ? " decision. " : " decisions. ");
decisions.forEach(d -> sb.append(d.endsWith(".") ? d : d + ".").append(' '));
}
sb.append(actionItems.size()).append(actionItems.size() == 1 ? " action item. " : " action items. ");
for (ActionItem a : actionItems) {
sb.append(a.owner()).append(": ").append(a.task());
if (a.due() != null && !a.due().isBlank()) sb.append(", due ").append(a.due());
sb.append(". ");
}
return sb.toString().trim();
}
}
@@ -0,0 +1,101 @@
package com.ankurm.audio;
import java.util.ArrayList;
import java.util.List;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.TranscriptionModel;
import org.springframework.ai.audio.tts.TextToSpeechModel;
import org.springframework.ai.audio.tts.TextToSpeechPrompt;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions;
/**
* Audio in, minutes out, audio back: transcribe (chunking if the file is too big), summarise into a
* typed {@link Minutes}, read it aloud. Each step takes the Spring AI interface, not the OpenAI
* class, so a different provider's TranscriptionModel / TextToSpeechModel drops in.
*/
public class MinutesService {
/** OpenAI's documented ceiling is "25 MB" without saying MB or MiB, so stay under 25,000,000 bytes. */
public static final long UPLOAD_BUDGET_BYTES = 24_000_000L;
/** The speech endpoint's documented maximum input length, in characters. */
public static final int TTS_MAX_CHARS = 4096;
private static final String SYSTEM = """
You write meeting minutes from a raw transcript.
Only include action items that someone explicitly agreed to do.
Use the speaker's own words for the task. If no due date was said, use an empty string.
Do not invent owners.""";
private final TranscriptionModel transcription;
private final ChatClient chat;
private final TextToSpeechModel speech;
private final SilenceChunker chunker;
private final String transcriptionModelName;
private final String speechModelName;
public MinutesService(TranscriptionModel transcription, ChatClient chat, TextToSpeechModel speech,
String transcriptionModelName, String speechModelName) {
this.transcription = transcription;
this.chat = chat;
this.speech = speech;
this.transcriptionModelName = transcriptionModelName;
this.speechModelName = speechModelName;
this.chunker = new SilenceChunker(UPLOAD_BUDGET_BYTES, 2.0, 500);
}
/** Records what happened, for the transcripts and the cost model. */
public record Transcription(String text, List<SilenceChunker.Chunk> chunks, List<String> pieces) {}
/** Transcribe a WAV of any size. Chunks run in order because each carries the tail of the one before as context. */
public Transcription transcribe(byte[] wav, String filename) {
List<SilenceChunker.Chunk> chunks = chunker.split(wav);
List<String> pieces = new ArrayList<>();
for (SilenceChunker.Chunk c : chunks) {
String previousTail = pieces.isEmpty() ? null : tail(pieces.getLast(), 200);
OpenAiAudioTranscriptionOptions.Builder opts = OpenAiAudioTranscriptionOptions.builder().model(transcriptionModelName);
if (previousTail != null) opts.prompt(previousTail);
String name = chunks.size() == 1 ? filename : "part-%02d-%s".formatted(c.index(), filename);
pieces.add(transcription.call(new AudioTranscriptionPrompt(new NamedBytes(c.wav(), name), opts.build()))
.getResult().getOutput());
}
return new Transcription(String.join(" ", pieces), chunks, pieces);
}
public Minutes summarise(String transcript) {
// transcript goes in as the user message itself, not through a {placeholder}: a transcript with
// braces in it would otherwise be read as template variables.
return chat.prompt().system(SYSTEM).user(transcript).call().entity(Minutes.class);
}
/** One audio clip per piece of at most {@link #TTS_MAX_CHARS} characters, cut on sentence ends. */
public List<byte[]> readAloud(Minutes minutes, String voice) {
List<byte[]> clips = new ArrayList<>();
for (String part : splitForSpeech(minutes.toSpokenText(), TTS_MAX_CHARS)) {
OpenAiAudioSpeechOptions opts = OpenAiAudioSpeechOptions.builder()
.model(speechModelName).voice(voice).responseFormat("wav").build();
clips.add(speech.call(new TextToSpeechPrompt(part, opts)).getResult().getOutput());
}
return clips;
}
static List<String> splitForSpeech(String text, int max) {
List<String> parts = new ArrayList<>();
StringBuilder cur = new StringBuilder();
for (String sentence : text.split("(?<=[.!?])\\s+")) {
if (cur.length() + sentence.length() + 1 > max && !cur.isEmpty()) {
parts.add(cur.toString().trim());
cur.setLength(0);
}
cur.append(sentence).append(' ');
}
if (!cur.isEmpty()) parts.add(cur.toString().trim());
return parts;
}
private static String tail(String s, int n) {
return s.length() <= n ? s : s.substring(s.length() - n);
}
}
@@ -0,0 +1,23 @@
package com.ankurm.audio;
import org.springframework.core.io.ByteArrayResource;
/**
* A {@link ByteArrayResource} that reports a file name. The name matters: the transcription
* endpoint decides the audio format from the extension on the multipart upload, and a bare
* ByteArrayResource has none.
*/
public class NamedBytes extends ByteArrayResource {
private final String filename;
public NamedBytes(byte[] bytes, String filename) {
super(bytes);
this.filename = filename;
}
@Override
public String getFilename() {
return filename;
}
}
@@ -0,0 +1,98 @@
package com.ankurm.audio;
import java.util.ArrayList;
import java.util.List;
/**
* Splits a WAV file into pieces that each fit under an upload limit, cutting in the middle of the
* longest silence it can find instead of at an arbitrary byte. The OpenAI speech-to-text guide
* says to avoid "splitting in the middle of a sentence, which can remove context and reduce
* accuracy"; this is that advice as code.
*/
public final class SilenceChunker {
/** One piece: where it starts in the original recording, and its own valid WAV bytes. */
public record Chunk(int index, double startSeconds, double endSeconds, byte[] wav, String cutKind) {
public int bytes() { return wav.length; }
}
private static final int WINDOW_MS = 100;
private final long maxBytes;
private final double minSilenceSeconds;
private final int silenceRms;
/**
* @param maxBytes hard ceiling for each chunk, header included
* @param minSilenceSeconds shortest quiet stretch worth cutting in
* @param silenceRms windows whose RMS is below this count as quiet (16-bit scale)
*/
public SilenceChunker(long maxBytes, double minSilenceSeconds, int silenceRms) {
this.maxBytes = maxBytes;
this.minSilenceSeconds = minSilenceSeconds;
this.silenceRms = silenceRms;
}
public List<Chunk> split(byte[] wav) {
Wav.Info info = Wav.parse(wav);
if (wav.length <= maxBytes) {
return List.of(new Chunk(0, 0, info.seconds(), wav, "none (fits)"));
}
int maxFrames = (int) ((maxBytes - 44) / info.bytesPerFrame());
int win = info.sampleRate() * WINDOW_MS / 1000;
int total = info.frames();
List<Chunk> out = new ArrayList<>();
int start = 0;
while (start < total) {
int limit = Math.min(total, start + maxFrames);
if (limit == total) {
out.add(chunk(out.size(), wav, info, start, total, "end of file"));
break;
}
int cut = quietCut(wav, info, win, start + maxFrames / 2, limit);
String kind = "mid-silence";
if (cut < 0) { cut = limit; kind = "HARD CUT (no silence found)"; }
out.add(chunk(out.size(), wav, info, start, cut, kind));
start = cut;
}
return out;
}
/** Naive baseline: every {@code maxBytes}, wherever that lands. */
public List<Chunk> splitBlindly(byte[] wav) {
Wav.Info info = Wav.parse(wav);
int maxFrames = (int) ((maxBytes - 44) / info.bytesPerFrame());
List<Chunk> out = new ArrayList<>();
for (int s = 0; s < info.frames(); s += maxFrames) {
out.add(chunk(out.size(), wav, info, s, Math.min(info.frames(), s + maxFrames), "fixed size"));
}
return out;
}
private Chunk chunk(int i, byte[] wav, Wav.Info info, int from, int to, String kind) {
return new Chunk(i, (double) from / info.sampleRate(), (double) to / info.sampleRate(),
Wav.slice(wav, info, from, to), kind);
}
/** Middle frame of the LAST quiet run (at least minSilenceSeconds long) inside [from, limit), or -1. */
private int quietCut(byte[] wav, Wav.Info info, int win, int from, int limit) {
int minWindows = (int) Math.ceil(minSilenceSeconds * 1000 / WINDOW_MS);
int runStart = -1, bestMid = -1;
for (int f = from; f + win <= limit; f += win) {
boolean quiet = rms(wav, info, f, win) < silenceRms;
if (quiet && runStart < 0) runStart = f;
if ((!quiet || f + 2 * win > limit) && runStart >= 0) {
int end = quiet ? f + win : f;
if ((end - runStart) / win >= minWindows) bestMid = runStart + (end - runStart) / 2;
runStart = -1;
}
}
return bestMid;
}
private static double rms(byte[] wav, Wav.Info info, int from, int n) {
double sum = 0;
for (int i = 0; i < n; i++) { double s = Wav.sample(wav, info, from + i); sum += s * s; }
return Math.sqrt(sum / n);
}
}
@@ -0,0 +1,68 @@
package com.ankurm.audio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
/**
* Just enough RIFF/WAVE to read and write 16-bit PCM. Production code would hand this to ffmpeg
* or a library; it is here so the chunking logic is visible and testable with no native binary.
*/
public final class Wav {
/** Format and position of the PCM payload inside a WAV file. */
public record Info(int sampleRate, int channels, int bitsPerSample, int dataOffset, int dataLength) {
public int bytesPerFrame() { return channels * bitsPerSample / 8; }
public int frames() { return dataLength / bytesPerFrame(); }
public double seconds() { return (double) frames() / sampleRate; }
}
private Wav() {}
public static Info parse(byte[] wav) {
ByteBuffer b = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN);
if (wav.length < 44 || b.getInt(0) != 0x46464952 /* RIFF */ || b.getInt(8) != 0x45564157 /* WAVE */) {
throw new IllegalArgumentException("not a RIFF/WAVE file");
}
int pos = 12, rate = 0, channels = 0, bits = 0;
while (pos + 8 <= wav.length) {
int id = b.getInt(pos);
int len = b.getInt(pos + 4);
if (id == 0x20746d66 /* "fmt " */) {
channels = b.getShort(pos + 10);
rate = b.getInt(pos + 12);
bits = b.getShort(pos + 22);
} else if (id == 0x61746164 /* "data" */) {
int available = Math.min(len < 0 ? Integer.MAX_VALUE : len, wav.length - (pos + 8));
if (bits != 16) throw new IllegalArgumentException("only 16-bit PCM is supported, got " + bits);
return new Info(rate, channels, bits, pos + 8, available);
}
pos += 8 + len + (len & 1);
}
throw new IllegalArgumentException("no data chunk");
}
/** Wraps raw PCM in a canonical 44-byte header. */
public static byte[] wrap(byte[] pcm, int offset, int length, int sampleRate, int channels, int bits) {
ByteBuffer b = ByteBuffer.allocate(44 + length).order(ByteOrder.LITTLE_ENDIAN);
b.putInt(0x46464952).putInt(36 + length).putInt(0x45564157);
b.putInt(0x20746d66).putInt(16).putShort((short) 1).putShort((short) channels).putInt(sampleRate)
.putInt(sampleRate * channels * bits / 8).putShort((short) (channels * bits / 8)).putShort((short) bits);
b.putInt(0x61746164).putInt(length);
b.put(pcm, offset, length);
return b.array();
}
/** A new, valid WAV file holding frames [fromFrame, toFrame) of {@code wav}. */
public static byte[] slice(byte[] wav, Info info, int fromFrame, int toFrame) {
int from = info.dataOffset() + fromFrame * info.bytesPerFrame();
int len = (toFrame - fromFrame) * info.bytesPerFrame();
return wrap(Arrays.copyOfRange(wav, from, from + len), 0, len, info.sampleRate(), info.channels(), info.bitsPerSample());
}
/** Sample {@code frame} of channel 0 as a signed 16-bit value. */
public static short sample(byte[] wav, Info info, int frame) {
int p = info.dataOffset() + frame * info.bytesPerFrame();
return (short) ((wav[p] & 0xff) | (wav[p + 1] << 8));
}
}
@@ -0,0 +1,37 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.audio.transcription.TranscriptionModel;
import org.springframework.ai.audio.tts.TextToSpeechModel;
import org.springframework.ai.openai.AbstractOpenAiOptions;
import org.springframework.ai.openai.OpenAiAudioSpeechModel;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
import org.springframework.ai.openai.OpenAiAudioTranscriptionModel;
import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions;
/** What the shipped 2.0.2 classes are called and what their defaults are. Nothing is sent anywhere. */
class ApiShapeTest {
@Test
void namesAndDefaults() {
try (Transcript t = new Transcript("01-api-shape.txt", "Spring AI 2.0.2 audio classes and defaults (read from the jars)")) {
t.line("speech-to-text interface : %s", TranscriptionModel.class.getName());
t.line("speech-to-text OpenAI : %s", OpenAiAudioTranscriptionModel.class.getName());
t.line("text-to-speech interface : %s", TextToSpeechModel.class.getName());
t.line("text-to-speech OpenAI : %s", OpenAiAudioSpeechModel.class.getName());
t.blank();
t.line("transcription DEFAULT_TRANSCRIPTION_MODEL = %s", OpenAiAudioTranscriptionOptions.DEFAULT_TRANSCRIPTION_MODEL);
t.line("transcription DEFAULT_RESPONSE_FORMAT = %s", OpenAiAudioTranscriptionOptions.DEFAULT_RESPONSE_FORMAT);
t.line("speech DEFAULT_SPEECH_MODEL = %s", OpenAiAudioSpeechOptions.DEFAULT_SPEECH_MODEL);
t.line("speech DEFAULT_VOICE = %s", OpenAiAudioSpeechOptions.DEFAULT_VOICE);
t.line("speech DEFAULT_RESPONSE_FORMAT = %s", OpenAiAudioSpeechOptions.DEFAULT_RESPONSE_FORMAT);
t.line("speech DEFAULT_SPEED = %s", OpenAiAudioSpeechOptions.DEFAULT_SPEED);
t.line("both DEFAULT_TIMEOUT = %s", AbstractOpenAiOptions.DEFAULT_TIMEOUT);
t.line("both DEFAULT_MAX_RETRIES = %d", AbstractOpenAiOptions.DEFAULT_MAX_RETRIES);
}
assertThat(OpenAiAudioTranscriptionOptions.DEFAULT_TRANSCRIPTION_MODEL).isNotBlank();
}
}
@@ -0,0 +1,37 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.audio.CostModel.Prices;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
/** The cost formulas applied to meetings of different length. Prices are inputs read from OpenAI's pages on 2026-10-26. */
class CostTest {
@Test
void perMeeting() {
try (Transcript t = new Transcript("08-cost.txt", "Cost of one meeting, USD (prices of 2026-10-26; word and token counts are ASSUMPTIONS)")) {
t.line("assumptions: %.0f words/minute spoken, %.2f words/token, summary output 600 tokens, read-back 120 words", CostModel.WORDS_PER_MINUTE, CostModel.WORDS_PER_TOKEN);
t.line("prices : gpt-transcribe $0.0045/min | whisper-1 $0.006/min | gpt-4o-mini $0.15 in / $0.60 out per 1M | tts-1 $15 per 1M chars");
t.blank();
t.line("%8s %10s %10s %10s %10s %10s %10s", "minutes", "words", "gpt-transc", "whisper-1", "summary", "tts-1", "total(gt)");
for (int minutes : new int[] { 15, 30, 60, 120 }) {
double words = minutes * CostModel.WORDS_PER_MINUTE;
double a = CostModel.transcription(minutes, Prices.OPENAI_2026_10_26);
double w = CostModel.transcription(minutes, Prices.WHISPER_1);
double s = CostModel.summary(words, 600, Prices.OPENAI_2026_10_26);
double r = CostModel.readBackPerChar((int) (120 * 6.0), Prices.OPENAI_2026_10_26);
t.line("%8d %,10.0f %10.4f %10.4f %10.4f %10.4f %10.4f", minutes, words, a, w, s, r, a + s + r);
}
t.blank();
double perHour = CostModel.transcription(60, Prices.OPENAI_2026_10_26);
double wavBytes = 16_000 * 2 * 60 * 60, mp3At64 = 64_000 / 8.0 * 60 * 60, mp3At32 = 32_000 / 8.0 * 60 * 60;
t.line("transcription is billed on audio duration, not file size: a 60-minute recording costs $%.4f whatever its encoding.", perHour);
t.line("size of 60 minutes: 16 kHz mono 16-bit WAV = %.1f MB | 64 kbit/s mp3 = %.1f MB | 32 kbit/s mp3 = %.1f MB", wavBytes / 1e6, mp3At64 / 1e6, mp3At32 / 1e6);
t.line("minutes that fit in 25,000,000 bytes: WAV %.1f | 64 kbit/s %.0f | 32 kbit/s %.0f", 25_000_000 / (16_000 * 2.0) / 60,
25_000_000 / (64_000 / 8.0) / 60, 25_000_000 / (32_000 / 8.0) / 60);
assertThat(perHour).isEqualTo(0.27, org.assertj.core.data.Offset.offset(1e-9));
}
}
}
@@ -0,0 +1,89 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import com.ankurm.audio.support.FakeAudioServer;
import com.ankurm.audio.support.MeetingFixture;
import com.ankurm.audio.support.Models;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
/** A 30 MB recording: refused whole, accepted in silence-aligned pieces, damaged by a blind split. MOCK server. */
class LargeFileTest {
private static final byte[] WAV = MeetingFixture.wav();
@Test
void tooBigThenChunked() throws Exception {
try (FakeAudioServer server = new FakeAudioServer();
Transcript t = new Transcript("03-large-file.txt", "A %.0f-minute recording, %,d bytes -- MOCK server".formatted(
MeetingFixture.totalSeconds() / 60, WAV.length))) {
var model = Models.transcription(server.baseUrl(), "gpt-transcribe", 0);
t.line("1) the whole file in one request (mock limit %,d bytes):", FakeAudioServer.UPLOAD_LIMIT);
Throwable thrown = null;
try {
model.transcribe(new NamedBytes(WAV, "meeting.wav"));
} catch (RuntimeException e) {
thrown = e;
}
assertThat(thrown).isNotNull();
t.line(" exception: %s", thrown.getClass().getName());
t.line(" message : %s", thrown.getMessage());
t.blank();
server.clear();
var service = new MinutesService(model, ChatClient.create(new com.ankurm.audio.support.ScriptedChatModel("{}")), null,
"gpt-transcribe", "gpt-4o-mini-tts");
MinutesService.Transcription tr = service.transcribe(WAV, "meeting.wav");
t.line("2) MinutesService.transcribe: budget %,d bytes per chunk, silence of at least 2.0 s, RMS below 500", MinutesService.UPLOAD_BUDGET_BYTES);
for (var c : tr.chunks()) {
t.line(" chunk %d: %7.1f s -> %7.1f s %,11d bytes cut: %s", c.index(), c.startSeconds(), c.endSeconds(), c.bytes(), c.cutKind());
}
t.line(" requests the mock saw: %d", server.seen().size());
for (var s : server.seen()) {
t.line(" - file=%s bytes=%,d prompt=%s", s.filename(), s.fileBytes(),
s.fields().containsKey("prompt") ? "\"..." + s.fields().get("prompt").substring(Math.max(0, s.fields().get("prompt").length() - 40)) + "\"" : "(none)");
}
List<String> expected = MeetingFixture.SCRIPT;
String joined = tr.text();
long found = expected.stream().filter(joined::contains).count();
t.line(" script lines recovered: %d of %d, in order: %s", found, expected.size(),
joined.equals(String.join(" ", expected)));
t.line(" [inaudible] markers: %d", joined.split("\\[inaudible]", -1).length - 1);
assertThat(joined).isEqualTo(String.join(" ", expected));
assertThat(tr.chunks()).hasSizeGreaterThan(1).allSatisfy(c -> assertThat(c.bytes()).isLessThanOrEqualTo((int) MinutesService.UPLOAD_BUDGET_BYTES));
}
}
@Test
void blindSplitCutsASentence() throws Exception {
var chunker = new SilenceChunker(MinutesService.UPLOAD_BUDGET_BYTES, 2.0, 500);
try (FakeAudioServer server = new FakeAudioServer();
Transcript t = new Transcript("04-blind-split.txt", "Cutting every 24,000,000 bytes, wherever that lands -- MOCK server")) {
var model = Models.transcription(server.baseUrl(), "gpt-transcribe", 0);
var chunks = chunker.splitBlindly(WAV);
StringBuilder all = new StringBuilder();
for (var c : chunks) {
int inside = MeetingFixture.sentenceAt(c.endSeconds());
t.line("chunk %d: %7.1f s -> %7.1f s %,d bytes boundary falls %s", c.index(), c.startSeconds(), c.endSeconds(), c.bytes(),
c.index() == chunks.size() - 1 ? "at end of file"
: inside >= 0 ? "INSIDE sentence " + inside + " (\"" + MeetingFixture.SCRIPT.get(inside) + "\")" : "in silence");
all.append(model.transcribe(new NamedBytes(c.wav(), "part-" + c.index() + ".wav"))).append(' ');
}
String text = all.toString().trim();
long found = MeetingFixture.SCRIPT.stream().filter(text::contains).count();
t.blank();
t.line("script lines recovered: %d of %d; [inaudible] markers: %d", found, MeetingFixture.SCRIPT.size(),
text.split("\\[inaudible]", -1).length - 1);
t.line("(mock rule: a tone cut to under 60% of its length is reported as [inaudible]; a real model would not fail this");
t.line(" cleanly -- OpenAI's guide only says splitting mid-sentence can remove context and reduce accuracy.)");
assertThat(found).isLessThan(MeetingFixture.SCRIPT.size());
assertThat(text).contains("[inaudible]");
}
}
}
@@ -0,0 +1,43 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.audio.support.FakeAudioServer;
import com.ankurm.audio.support.MeetingFixture;
import com.ankurm.audio.support.Models;
import com.ankurm.audio.support.ScriptedChatModel;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
/** Audio in, minutes out, audio back, with all three real/stub parts wired through MinutesService. */
class MeetingEndToEndTest {
@Test
void wholePipeline() throws Exception {
String reply = """
{"title":"Falcon weekly sync","decisions":["Ship version 2.4 on the fourteenth of November"],
"actionItems":[{"owner":"Rahul","task":"Fix the login timeout bug","due":"before the release"},
{"owner":"Priya","task":"Send the revised budget to finance","due":"Friday"}]}""";
ScriptedChatModel chat = new ScriptedChatModel(reply);
try (FakeAudioServer server = new FakeAudioServer();
Transcript t = new Transcript("09-end-to-end.txt", "Recording -> transcript -> Minutes -> audio (MOCK audio server, STUB chat model)")) {
var service = new MinutesService(Models.transcription(server.baseUrl(), "gpt-transcribe", 0), ChatClient.create(chat),
Models.speech(server.baseUrl(), "gpt-4o-mini-tts"), "gpt-transcribe", "gpt-4o-mini-tts");
byte[] wav = MeetingFixture.wav();
var tr = service.transcribe(wav, "falcon-sync.wav");
t.line("1) transcribe: %,d bytes -> %d request(s) -> %d characters", wav.length, tr.chunks().size(), tr.text().length());
Minutes minutes = service.summarise(tr.text());
t.line("2) summarise : transcript of %d words reached the chat model as the user message: %s",
tr.text().split("\\s+").length,
chat.prompts().getFirst().getInstructions().stream().anyMatch(m -> m.getText().contains(MeetingFixture.SCRIPT.getFirst())));
t.line(" %d action items: %s", minutes.actionItems().size(), minutes.actionItems());
var clips = service.readAloud(minutes, "coral");
t.line("3) read back : %d clip(s), %d bytes, spoken text: %s", clips.size(), clips.getFirst().length, minutes.toSpokenText());
t.line(" speech request: %s", server.seen().getLast().json());
assertThat(clips).hasSize(1);
assertThat(Wav.parse(clips.getFirst()).seconds()).isGreaterThan(1.0);
}
}
}
@@ -0,0 +1,39 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.audio.support.FakeAudioServer;
import com.ankurm.audio.support.MeetingFixture;
import com.ankurm.audio.support.Models;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
/** What the OpenAI SDK underneath Spring AI does with a failing endpoint. MOCK server. */
class RetryTest {
@Test
void retriesAreTheSdksNotSpringsAndEachOneReuploadsTheFile() throws Exception {
byte[] whole = MeetingFixture.wav();
byte[] clip = Wav.slice(whole, Wav.parse(whole), 0, 120 * MeetingFixture.SAMPLE_RATE);
try (FakeAudioServer server = new FakeAudioServer();
Transcript t = new Transcript("07-retries.txt", "A 120-second clip (" + clip.length + " bytes) against a flaky endpoint -- MOCK server")) {
for (int maxRetries : new int[] { 0, 3 }) {
for (int status : new int[] { 429, 400 }) {
server.clear();
server.failNext(2, status);
var model = Models.transcription(server.baseUrl(), "gpt-transcribe", maxRetries);
String outcome;
try {
model.transcribe(new NamedBytes(clip, "x.wav"));
outcome = "ok";
} catch (RuntimeException e) {
outcome = e.getClass().getSimpleName();
}
long bytes = server.seen().stream().mapToLong(FakeAudioServer.Seen::bodyBytes).sum();
t.line("maxRetries=%d, server fails the first 2 requests with %d -> %-26s requests: %d, bytes uploaded: %,d",
maxRetries, status, outcome, server.seen().size(), bytes);
}
}
}
}
}
@@ -0,0 +1,68 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import com.ankurm.audio.support.FakeAudioServer;
import com.ankurm.audio.support.Models;
import com.ankurm.audio.support.ScriptedChatModel;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.audio.tts.TextToSpeechPrompt;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
/** Text to speech: the wire format, the 4096-character wall, and splitting around it. MOCK server. */
class SpeechTest {
@Test
void wireAndLimit() throws Exception {
try (FakeAudioServer server = new FakeAudioServer();
Transcript t = new Transcript("06-speech.txt", "OpenAiAudioSpeechModel -- MOCK server")) {
var speech = Models.speech(server.baseUrl(), "gpt-4o-mini-tts");
byte[] bytes = speech.call("Three action items.");
t.line("speech.call(String) with every default:");
t.line(" request json : %s", server.seen().getLast().json());
t.line(" response : %d bytes", bytes.length);
t.blank();
var opts = OpenAiAudioSpeechOptions.builder().model("gpt-4o-mini-tts").voice("coral").responseFormat("wav").speed(1.1)
.instructions("Calm, like a project manager reading notes.").build();
byte[] wav = speech.call(new TextToSpeechPrompt("Rahul: fix the login timeout bug.", opts)).getResult().getOutput();
t.line("with TextToSpeechPrompt and options:");
t.line(" request json : %s", server.seen().getLast().json());
t.line(" response : %d bytes, starts with %s", wav.length, new String(wav, 0, 4));
t.blank();
String tooLong = "word ".repeat(1000); // 5000 characters
String outcome;
try {
speech.call(new TextToSpeechPrompt(tooLong, opts));
outcome = "accepted";
} catch (RuntimeException e) {
outcome = e.getClass().getSimpleName() + ": " + e.getMessage();
}
t.line("input of %d characters -> %s", tooLong.length(), outcome);
assertThat(outcome).contains("4096");
}
}
@Test
void splittingOnSentenceEnds() throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 120; i++) sb.append("Action item number ").append(i).append(" is assigned to somebody with a long enough description to take space.").append(' ');
String text = sb.toString().trim();
List<String> parts = MinutesService.splitForSpeech(text, MinutesService.TTS_MAX_CHARS);
try (Transcript t = new Transcript("06b-speech-split.txt", "Splitting a long read-back at sentence ends")) {
t.line("text: %d characters, %d sentences", text.length(), 120);
for (int i = 0; i < parts.size(); i++) {
String p = parts.get(i);
t.line("part %d: %4d characters, ends with \"%s\"", i, p.length(), p.substring(p.length() - 12));
}
}
assertThat(parts).allSatisfy(p -> assertThat(p.length()).isLessThanOrEqualTo(MinutesService.TTS_MAX_CHARS));
assertThat(String.join(" ", parts)).isEqualTo(text);
}
}
@@ -0,0 +1,83 @@
package com.ankurm.audio;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.audio.support.MeetingFixture;
import com.ankurm.audio.support.ScriptedChatModel;
import com.ankurm.audio.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
/** Structured output for action items. The chat model is a STUB that replays canned JSON; it is not a language model. */
class SummariseTest {
private static final String GOOD = """
{"title":"Falcon weekly sync",
"decisions":["Ship version 2.4 on the fourteenth of November","The data pipeline migrates to the new cluster next sprint"],
"actionItems":[
{"owner":"Rahul","task":"Fix the login timeout bug","due":"before the release on the fourteenth of November"},
{"owner":"Priya","task":"Send the revised budget to finance","due":"Friday"},
{"owner":"Sana","task":"Open tickets for both export endpoint issues","due":"today"}]}""";
@Test
void promptAndParsedRecord() {
ScriptedChatModel model = new ScriptedChatModel(GOOD);
var service = new MinutesService(null, ChatClient.create(model), null, "gpt-transcribe", "gpt-4o-mini-tts");
String transcript = String.join(" ", MeetingFixture.SCRIPT);
Minutes m = service.summarise(transcript);
try (Transcript t = new Transcript("05-structured-output.txt", "entity(Minutes.class) against a STUB ChatModel")) {
t.line("messages sent to the model:");
for (Message msg : model.prompts().getFirst().getInstructions()) {
String text = msg.getText();
t.line(" [%s] %d chars", msg.getMessageType(), text.length());
}
String user = model.prompts().getFirst().getInstructions().stream()
.filter(x -> x.getMessageType().name().equals("USER")).findFirst().orElseThrow().getText();
int at = user.indexOf("Your response should be in JSON format.");
t.line("");
t.line("tail of the USER message (the format instructions Spring AI appended):");
t.line("%s", user.substring(at));
t.blank();
t.line("parsed: %s", m.title());
t.line(" decisions : %d", m.decisions().size());
m.actionItems().forEach(a -> t.line(" action item : %-6s | %s | due: %s", a.owner(), a.task(), a.due()));
t.blank();
t.line("spoken form:");
t.line(" %s", m.toSpokenText());
}
assertThat(m.actionItems()).hasSize(3);
assertThat(m.actionItems().getFirst().owner()).isEqualTo("Rahul");
}
@Test
void whatABadReplyLooksLike() {
try (Transcript t = new Transcript("05b-bad-replies.txt", "Three replies a model can give instead of clean JSON (STUB model)")) {
String[] replies = {
"Here are the minutes:\n```json\n" + GOOD + "\n```",
"{\"title\":\"Falcon weekly sync\",\"decisions\":[],\"actionItems\":[{\"owner\":\"Rahul\",\"task\":\"Fix it\",\"due\":null}]",
"I could not find any action items in this transcript."
};
String[] labels = { "wrapped in a markdown fence with a sentence before it", "truncated: closing brace missing", "prose instead of JSON" };
for (int i = 0; i < replies.length; i++) {
var service = new MinutesService(null, ChatClient.create(new ScriptedChatModel(replies[i])), null, "x", "y");
String outcome;
try {
Minutes m = service.summarise("anything");
outcome = "parsed: " + m.actionItems().size() + " action item(s), first due=" + m.actionItems().getFirst().due();
} catch (RuntimeException e) {
outcome = e.getClass().getSimpleName() + ": " + first(e.getMessage());
}
t.line("%-52s -> %s", labels[i], outcome);
}
}
}
private static String first(String s) {
if (s == null) return "(no message)";
String one = s.replace('\n', ' ');
return one.length() > 110 ? one.substring(0, 110) + "..." : one;
}
}

Some files were not shown because too many files have changed in this diff Show More