diff --git a/README.md b/README.md index 1ae60ba..94ceb3b 100644 --- a/README.md +++ b/README.md @@ -40,5 +40,6 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur | [`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/). diff --git a/ai-21-migration/.gitignore b/ai-21-migration/.gitignore new file mode 100644 index 0000000..53ad825 --- /dev/null +++ b/ai-21-migration/.gitignore @@ -0,0 +1,3 @@ +target/ +jars-cache/ +target-main.log diff --git a/ai-21-migration/README.md b/ai-21-migration/README.md new file mode 100644 index 0000000..6862b55 --- /dev/null +++ b/ai-21-migration/README.md @@ -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 | diff --git a/ai-21-migration/broken/src/BedrockParams.java b/ai-21-migration/broken/src/BedrockParams.java new file mode 100644 index 0000000..1b4310d --- /dev/null +++ b/ai-21-migration/broken/src/BedrockParams.java @@ -0,0 +1,7 @@ +import java.util.Map; +import org.springframework.ai.bedrock.converse.BedrockChatOptions; + +class BedrockParams { + Map params = Map.of("anthropic_version", "bedrock-2023-05-31"); + Object options = BedrockChatOptions.builder().requestParameters(params).build(); +} diff --git a/ai-21-migration/broken/src/DeepSeekPrefix.java b/ai-21-migration/broken/src/DeepSeekPrefix.java new file mode 100644 index 0000000..2630418 --- /dev/null +++ b/ai-21-migration/broken/src/DeepSeekPrefix.java @@ -0,0 +1,5 @@ +import org.springframework.ai.deepseek.DeepSeekAssistantMessage; + +class DeepSeekPrefix { + Object prefix = DeepSeekAssistantMessage.prefixAssistantMessage("```java\n"); +} diff --git a/ai-21-migration/broken/src/ThoughtKey.java b/ai-21-migration/broken/src/ThoughtKey.java new file mode 100644 index 0000000..c36a723 --- /dev/null +++ b/ai-21-migration/broken/src/ThoughtKey.java @@ -0,0 +1,5 @@ +import org.springframework.ai.google.genai.GoogleGenAiChatModel; + +class ThoughtKey { + String key = GoogleGenAiChatModel.THOUGHT_METADATA_KEY; +} diff --git a/ai-21-migration/legacy-app/pom.xml b/ai-21-migration/legacy-app/pom.xml new file mode 100644 index 0000000..ffbcacd --- /dev/null +++ b/ai-21-migration/legacy-app/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.0 + + + + com.ankurm + legacy-app + 1.0.0 + A deliberately 2.0-style application: the input for scripts/openrewrite.sh and scripts/grep-checklist.sh. + + + 25 + 2.0.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-client-chat + + + org.springframework.ai + spring-ai-anthropic + + + org.springframework.ai + spring-ai-autoconfigure-model-chat-memory-redis + + + diff --git a/ai-21-migration/legacy-app/src/main/java/com/ankurm/legacy/SupportBot.java b/ai-21-migration/legacy-app/src/main/java/com/ankurm/legacy/SupportBot.java new file mode 100644 index 0000000..4e36846 --- /dev/null +++ b/ai-21-migration/legacy-app/src/main/java/com/ankurm/legacy/SupportBot.java @@ -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(); + } +} diff --git a/ai-21-migration/legacy-app/src/main/resources/application.properties b/ai-21-migration/legacy-app/src/main/resources/application.properties new file mode 100644 index 0000000..aceaff2 --- /dev/null +++ b/ai-21-migration/legacy-app/src/main/resources/application.properties @@ -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 diff --git a/ai-21-migration/output/01-usage-2.0.0.txt b/ai-21-migration/output/01-usage-2.0.0.txt new file mode 100644 index 0000000..3c5170d --- /dev/null +++ b/ai-21-migration/output/01-usage-2.0.0.txt @@ -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 diff --git a/ai-21-migration/output/01-usage-2.0.2.txt b/ai-21-migration/output/01-usage-2.0.2.txt new file mode 100644 index 0000000..4488447 --- /dev/null +++ b/ai-21-migration/output/01-usage-2.0.2.txt @@ -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 diff --git a/ai-21-migration/output/01-usage-2.0.3.txt b/ai-21-migration/output/01-usage-2.0.3.txt new file mode 100644 index 0000000..8d23f56 --- /dev/null +++ b/ai-21-migration/output/01-usage-2.0.3.txt @@ -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 diff --git a/ai-21-migration/output/01-usage-2.1.0.txt b/ai-21-migration/output/01-usage-2.1.0.txt new file mode 100644 index 0000000..b79de1d --- /dev/null +++ b/ai-21-migration/output/01-usage-2.1.0.txt @@ -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 diff --git a/ai-21-migration/output/02-request-2.0.0.txt b/ai-21-migration/output/02-request-2.0.0.txt new file mode 100644 index 0000000..8ef6aa7 --- /dev/null +++ b/ai-21-migration/output/02-request-2.0.0.txt @@ -0,0 +1,5 @@ +# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.0) +header no Authorization header +header x-api-key: +header anthropic-version: 2023-06-01 +body "temperature":0.2 diff --git a/ai-21-migration/output/02-request-2.0.2.txt b/ai-21-migration/output/02-request-2.0.2.txt new file mode 100644 index 0000000..2d15b43 --- /dev/null +++ b/ai-21-migration/output/02-request-2.0.2.txt @@ -0,0 +1,5 @@ +# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.2) +header no Authorization header +header x-api-key: +header anthropic-version: 2023-06-01 +body "temperature":0.2 diff --git a/ai-21-migration/output/02-request-2.0.3.txt b/ai-21-migration/output/02-request-2.0.3.txt new file mode 100644 index 0000000..5d8ef98 --- /dev/null +++ b/ai-21-migration/output/02-request-2.0.3.txt @@ -0,0 +1,5 @@ +# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.0.3) +header no Authorization header +header x-api-key: +header anthropic-version: 2023-06-01 +body "temperature":0.2 diff --git a/ai-21-migration/output/02-request-2.1.0.txt b/ai-21-migration/output/02-request-2.1.0.txt new file mode 100644 index 0000000..cd85f0b --- /dev/null +++ b/ai-21-migration/output/02-request-2.1.0.txt @@ -0,0 +1,7 @@ +# What AnthropicChatModel sends, temperature=0.2 set (Spring AI 2.1.0) +header Authorization: Bearer +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 diff --git a/ai-21-migration/output/03-thinking-2.0.0.txt b/ai-21-migration/output/03-thinking-2.0.0.txt new file mode 100644 index 0000000..4be3f1a --- /dev/null +++ b/ai-21-migration/output/03-thinking-2.0.0.txt @@ -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] diff --git a/ai-21-migration/output/03-thinking-2.0.2.txt b/ai-21-migration/output/03-thinking-2.0.2.txt new file mode 100644 index 0000000..eb20686 --- /dev/null +++ b/ai-21-migration/output/03-thinking-2.0.2.txt @@ -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] diff --git a/ai-21-migration/output/03-thinking-2.0.3.txt b/ai-21-migration/output/03-thinking-2.0.3.txt new file mode 100644 index 0000000..7aa689d --- /dev/null +++ b/ai-21-migration/output/03-thinking-2.0.3.txt @@ -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] diff --git a/ai-21-migration/output/03-thinking-2.1.0.txt b/ai-21-migration/output/03-thinking-2.1.0.txt new file mode 100644 index 0000000..687eed5 --- /dev/null +++ b/ai-21-migration/output/03-thinking-2.1.0.txt @@ -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] diff --git a/ai-21-migration/output/04-messages-2.0.0.txt b/ai-21-migration/output/04-messages-2.0.0.txt new file mode 100644 index 0000000..5fc2b35 --- /dev/null +++ b/ai-21-migration/output/04-messages-2.0.0.txt @@ -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 diff --git a/ai-21-migration/output/04-messages-2.0.2.txt b/ai-21-migration/output/04-messages-2.0.2.txt new file mode 100644 index 0000000..c3615de --- /dev/null +++ b/ai-21-migration/output/04-messages-2.0.2.txt @@ -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 diff --git a/ai-21-migration/output/04-messages-2.0.3.txt b/ai-21-migration/output/04-messages-2.0.3.txt new file mode 100644 index 0000000..b97049b --- /dev/null +++ b/ai-21-migration/output/04-messages-2.0.3.txt @@ -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 diff --git a/ai-21-migration/output/04-messages-2.1.0.txt b/ai-21-migration/output/04-messages-2.1.0.txt new file mode 100644 index 0000000..4e53bb3 --- /dev/null +++ b/ai-21-migration/output/04-messages-2.1.0.txt @@ -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 diff --git a/ai-21-migration/output/05-refusals-2.0.0.txt b/ai-21-migration/output/05-refusals-2.0.0.txt new file mode 100644 index 0000000..e486d0c --- /dev/null +++ b/ai-21-migration/output/05-refusals-2.0.0.txt @@ -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' diff --git a/ai-21-migration/output/05-refusals-2.0.2.txt b/ai-21-migration/output/05-refusals-2.0.2.txt new file mode 100644 index 0000000..b08cb85 --- /dev/null +++ b/ai-21-migration/output/05-refusals-2.0.2.txt @@ -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' diff --git a/ai-21-migration/output/05-refusals-2.0.3.txt b/ai-21-migration/output/05-refusals-2.0.3.txt new file mode 100644 index 0000000..02fc6a6 --- /dev/null +++ b/ai-21-migration/output/05-refusals-2.0.3.txt @@ -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' diff --git a/ai-21-migration/output/05-refusals-2.1.0.txt b/ai-21-migration/output/05-refusals-2.1.0.txt new file mode 100644 index 0000000..be34d1b --- /dev/null +++ b/ai-21-migration/output/05-refusals-2.1.0.txt @@ -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' diff --git a/ai-21-migration/output/06-legacy-warnings.txt b/ai-21-migration/output/06-legacy-warnings.txt new file mode 100644 index 0000000..6e145ff --- /dev/null +++ b/ai-21-migration/output/06-legacy-warnings.txt @@ -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 diff --git a/ai-21-migration/output/07-compile-breaks.txt b/ai-21-migration/output/07-compile-breaks.txt new file mode 100644 index 0000000..b35a14e --- /dev/null +++ b/ai-21-migration/output/07-compile-breaks.txt @@ -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 cannot be converted to Map +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 diff --git a/ai-21-migration/output/08-session-migration.txt b/ai-21-migration/output/08-session-migration.txt new file mode 100644 index 0000000..3ee5c7d --- /dev/null +++ b/ai-21-migration/output/08-session-migration.txt @@ -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 diff --git a/ai-21-migration/output/09-tool-manager.txt b/ai-21-migration/output/09-tool-manager.txt new file mode 100644 index 0000000..aa966e4 --- /dev/null +++ b/ai-21-migration/output/09-tool-manager.txt @@ -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] diff --git a/ai-21-migration/output/10-openai-api-switch.txt b/ai-21-migration/output/10-openai-api-switch.txt new file mode 100644 index 0000000..29f9da5 --- /dev/null +++ b/ai-21-migration/output/10-openai-api-switch.txt @@ -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) diff --git a/ai-21-migration/output/11-upsert.txt b/ai-21-migration/output/11-upsert.txt new file mode 100644 index 0000000..c5f2efb --- /dev/null +++ b/ai-21-migration/output/11-upsert.txt @@ -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 diff --git a/ai-21-migration/output/12-uncached.txt b/ai-21-migration/output/12-uncached.txt new file mode 100644 index 0000000..40fb773 --- /dev/null +++ b/ai-21-migration/output/12-uncached.txt @@ -0,0 +1,2 @@ +# UncachedTokens.of on the 2.1.0 usage values +promptTokens=2350 cacheRead=2000 cacheWrite=300 -> full-price input = 50 diff --git a/ai-21-migration/output/13-api-diff.txt b/ai-21-migration/output/13-api-diff.txt new file mode 100644 index 0000000..2ff9659 --- /dev/null +++ b/ai-21-migration/output/13-api-diff.txt @@ -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#()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) diff --git a/ai-21-migration/output/14-config-diff.txt b/ai-21-migration/output/14-config-diff.txt new file mode 100644 index 0000000..a71d220 --- /dev/null +++ b/ai-21-migration/output/14-config-diff.txt @@ -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 diff --git a/ai-21-migration/output/15-bom-diff.txt b/ai-21-migration/output/15-bom-diff.txt new file mode 100644 index 0000000..b255a2f --- /dev/null +++ b/ai-21-migration/output/15-bom-diff.txt @@ -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 diff --git a/ai-21-migration/output/16-grep-checklist.txt b/ai-21-migration/output/16-grep-checklist.txt new file mode 100644 index 0000000..9e0bb2e --- /dev/null +++ b/ai-21-migration/output/16-grep-checklist.txt @@ -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: spring-ai-autoconfigure-model-chat-memory-redis + +[ ] 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: 2.0.0 + pom.xml:28: spring-ai-bom + pom.xml:29: ${spring-ai.version} + pom.xml:9: spring-boot-starter-parent + +A hit is a place to read, not proof of a problem. No hit is not proof of safety. diff --git a/ai-21-migration/output/17-openrewrite.txt b/ai-21-migration/output/17-openrewrite.txt new file mode 100644 index 0000000..b9b9ce3 --- /dev/null +++ b/ai-21-migration/output/17-openrewrite.txt @@ -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 @@ + + org.springframework.boot + spring-boot-starter-parent +- 4.1.0 ++ 4.2.0 + + + +@@ -18,7 +18,7 @@ + + + 25 +- 2.0.0 ++ 2.1.0 + + + +@@ -44,7 +44,7 @@ + + + org.springframework.ai +- spring-ai-autoconfigure-model-chat-memory-redis ++ spring-ai-autoconfigure-model-chat-memory-repository-redis + + + +--- 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) diff --git a/ai-21-migration/pom.xml b/ai-21-migration/pom.xml new file mode 100644 index 0000000..15ede9c --- /dev/null +++ b/ai-21-migration/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + ai-21-migration + 1.0.0 + ai-21-migration + Upgrading Spring AI 2.0 to 2.1: the replacement code, tested with scripted and fake models. + + + 25 + 2.1.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + org.springframework.aispring-ai-client-chat + org.springframework.aispring-ai-session + org.springframework.aispring-ai-session-advisor + org.springframework.aispring-ai-starter-model-openai + org.springframework.aispring-ai-pgvector-store + org.springframework.bootspring-boot-starter-jdbc + org.postgresqlpostgresqlruntime + org.springframework.bootspring-boot-starter-testtest + org.testcontainerstestcontainers-postgresqltest + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 + + + + + diff --git a/ai-21-migration/probes/pom.xml b/ai-21-migration/probes/pom.xml new file mode 100644 index 0000000..213de2f --- /dev/null +++ b/ai-21-migration/probes/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + com.ankurm + ai-21-migration-probes + 1.0.0 + One source tree, compiled and run against several Spring AI versions: mvn test -Dspring-ai.version=2.0.3 -Dboot.version=4.1.0 + + + 25 + UTF-8 + 2.1.0 + 4.2.0 + + + + + + org.springframework.boot + spring-boot-dependencies + ${boot.version} + pom + import + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + org.springframework.aispring-ai-client-chat + org.springframework.aispring-ai-anthropic + org.springframework.aispring-ai-google-genai + org.springframework.aispring-ai-deepseek + org.springframework.aispring-ai-bedrock-converse + org.springframework.bootspring-boot-starter-testtest + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.1 + + true + -Xlint:deprecation,removal + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + -Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 + ${spring-ai.version} + + + + + diff --git a/ai-21-migration/probes/src/main/java/com/ankurm/aimigration/probes/LegacyAssistant.java b/ai-21-migration/probes/src/main/java/com/ankurm/aimigration/probes/LegacyAssistant.java new file mode 100644 index 0000000..c1f71d0 --- /dev/null +++ b/ai-21-migration/probes/src/main/java/com/ankurm/aimigration/probes/LegacyAssistant.java @@ -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(); + } +} diff --git a/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/AnthropicProbeTest.java b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/AnthropicProbeTest.java new file mode 100644 index 0000000..181e9c4 --- /dev/null +++ b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/AnthropicProbeTest.java @@ -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 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] + " " : "no Authorization header"; + t.line("header " + auth); + t.line("header " + (seen.headers().containsKey("x-api-key") ? "x-api-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()); + } + } + } +} diff --git a/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/FakeAnthropic.java b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/FakeAnthropic.java new file mode 100644 index 0000000..dd041f2 --- /dev/null +++ b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/FakeAnthropic.java @@ -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 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 = 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 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); + } +} diff --git a/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/MessageAndGuardrailProbeTest.java b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/MessageAndGuardrailProbeTest.java new file mode 100644 index 0000000..fb2420b --- /dev/null +++ b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/MessageAndGuardrailProbeTest.java @@ -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 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() + "'")); + } + } +} diff --git a/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/Transcript.java b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/Transcript.java new file mode 100644 index 0000000..2df9043 --- /dev/null +++ b/ai-21-migration/probes/src/test/java/com/ankurm/aimigration/probes/Transcript.java @@ -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/-.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); + } +} diff --git a/ai-21-migration/rewrite.yml b/ai-21-migration/rewrite.yml new file mode 100644 index 0000000..aea6f5a --- /dev/null +++ b/ai-21-migration/rewrite.yml @@ -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 diff --git a/ai-21-migration/scripts/api-diff.sh b/ai-21-migration/scripts/api-diff.sh new file mode 100755 index 0000000..d0a632d --- /dev/null +++ b/ai-21-migration/scripts/api-diff.sh @@ -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" diff --git a/ai-21-migration/scripts/bom-diff.sh b/ai-21-migration/scripts/bom-diff.sh new file mode 100755 index 0000000..4cb14b2 --- /dev/null +++ b/ai-21-migration/scripts/bom-diff.sh @@ -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:.*\(spring-ai-[^<]*\).*:\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>\([^<]*\).*:\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 diff --git a/ai-21-migration/scripts/compile-breaks.sh b/ai-21-migration/scripts/compile-breaks.sh new file mode 100755 index 0000000..0f52dfe --- /dev/null +++ b/ai-21-migration/scripts/compile-breaks.sh @@ -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" diff --git a/ai-21-migration/scripts/config-diff.py b/ai-21-migration/scripts/config-diff.py new file mode 100755 index 0000000..ac27525 --- /dev/null +++ b/ai-21-migration/scripts/config-diff.py @@ -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}") diff --git a/ai-21-migration/scripts/fetch-jars.sh b/ai-21-migration/scripts/fetch-jars.sh new file mode 100755 index 0000000..88eb5e3 --- /dev/null +++ b/ai-21-migration/scripts/fetch-jars.sh @@ -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/. +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:.*\(spring-ai-[^<]*\).*:\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" diff --git a/ai-21-migration/scripts/grep-checklist.sh b/ai-21-migration/scripts/grep-checklist.sh new file mode 100755 index 0000000..fc4e384 --- /dev/null +++ b/ai-21-migration/scripts/grep-checklist.sh @@ -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 +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" '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." diff --git a/ai-21-migration/scripts/openrewrite.sh b/ai-21-migration/scripts/openrewrite.sh new file mode 100755 index 0000000..7b9cb99 --- /dev/null +++ b/ai-21-migration/scripts/openrewrite.sh @@ -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" diff --git a/ai-21-migration/scripts/run-all.sh b/ai-21-migration/scripts/run-all.sh new file mode 100755 index 0000000..5b650ce --- /dev/null +++ b/ai-21-migration/scripts/run-all.sh @@ -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 diff --git a/ai-21-migration/src/main/java/com/ankurm/aimigration/LoggingToolCallingManager.java b/ai-21-migration/src/main/java/com/ankurm/aimigration/LoggingToolCallingManager.java new file mode 100644 index 0000000..a1f1a07 --- /dev/null +++ b/ai-21-migration/src/main/java/com/ankurm/aimigration/LoggingToolCallingManager.java @@ -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 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); + } +} diff --git a/ai-21-migration/src/main/java/com/ankurm/aimigration/MemoryToSessionCopier.java b/ai-21-migration/src/main/java/com/ankurm/aimigration/MemoryToSessionCopier.java new file mode 100644 index 0000000..40527f0 --- /dev/null +++ b/ai-21-migration/src/main/java/com/ankurm/aimigration/MemoryToSessionCopier.java @@ -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; + } +} diff --git a/ai-21-migration/src/main/java/com/ankurm/aimigration/MigrationApplication.java b/ai-21-migration/src/main/java/com/ankurm/aimigration/MigrationApplication.java new file mode 100644 index 0000000..86bb174 --- /dev/null +++ b/ai-21-migration/src/main/java/com/ankurm/aimigration/MigrationApplication.java @@ -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); + } +} diff --git a/ai-21-migration/src/main/java/com/ankurm/aimigration/SessionAssistant.java b/ai-21-migration/src/main/java/com/ankurm/aimigration/SessionAssistant.java new file mode 100644 index 0000000..d9fef6b --- /dev/null +++ b/ai-21-migration/src/main/java/com/ankurm/aimigration/SessionAssistant.java @@ -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(); + } +} diff --git a/ai-21-migration/src/main/java/com/ankurm/aimigration/UncachedTokens.java b/ai-21-migration/src/main/java/com/ankurm/aimigration/UncachedTokens.java new file mode 100644 index 0000000..e235f4f --- /dev/null +++ b/ai-21-migration/src/main/java/com/ankurm/aimigration/UncachedTokens.java @@ -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; + } +} diff --git a/ai-21-migration/src/main/resources/application.properties b/ai-21-migration/src/main/resources/application.properties new file mode 100644 index 0000000..0a66eb6 --- /dev/null +++ b/ai-21-migration/src/main/resources/application.properties @@ -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 diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/OpenAiApiSwitchTest.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/OpenAiApiSwitchTest.java new file mode 100644 index 0000000..cb23e47 --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/OpenAiApiSwitchTest.java @@ -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 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); + } + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/SessionMigrationTest.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/SessionMigrationTest.java new file mode 100644 index 0000000..f6a1e1b --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/SessionMigrationTest.java @@ -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 messages) { + var parts = new ArrayList(); + 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); + } + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/ToolManagerTest.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/ToolManagerTest.java new file mode 100644 index 0000000..02ef936 --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/ToolManagerTest.java @@ -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 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 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"); + } + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/UncachedTokensTest.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/UncachedTokensTest.java new file mode 100644 index 0000000..23ea8cd --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/UncachedTokensTest.java @@ -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); + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/UpsertTest.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/UpsertTest.java new file mode 100644 index 0000000..508d778 --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/UpsertTest.java @@ -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(); + 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"); + } + } + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/support/ScriptedChatModel.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/support/ScriptedChatModel.java new file mode 100644 index 0000000..be71ced --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/support/ScriptedChatModel.java @@ -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 prompts = new ArrayList<>(); + private final Deque 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(); + } +} diff --git a/ai-21-migration/src/test/java/com/ankurm/aimigration/support/Transcript.java b/ai-21-migration/src/test/java/com/ankurm/aimigration/support/Transcript.java new file mode 100644 index 0000000..bd59162 --- /dev/null +++ b/ai-21-migration/src/test/java/com/ankurm/aimigration/support/Transcript.java @@ -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); + } +} diff --git a/ai-21-migration/tools/ApiDiff.java b/ai-21-migration/tools/ApiDiff.java new file mode 100644 index 0000000..01e7a31 --- /dev/null +++ b/ai-21-migration/tools/ApiDiff.java @@ -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 + * Prints removed public types and members, and what is newly annotated {@code @Deprecated}. + */ +public class ApiDiff { + + record Item(String jar, Set flags, String deprecated) { } + + public static void main(String[] args) throws IOException { + Map before = scan(Path.of(args[0])); + Map 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 scan(Path dir) throws IOException { + Map 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 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(); + }; + } +}