Add ai-21-migration module: upgrading Spring AI 2.0.x to 2.1.0, measured. One probe source tree run on 2.0.0, 2.0.2, 2.0.3 and 2.1.0 (Anthropic prompt tokens with caching, auth header, discarded temperature, thinking parts, message mutability, entity() on refusals), three compile breaks, API and configuration diffs from the jars, ChatMemory to session copy, a wrapping ToolCallingManager under tool confirmation, the OpenAI Responses switch, VectorStore.upsert on real pgvector, a grep checklist and an OpenRewrite recipe. Scripted and local fake models; no provider called. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7N4ZDbUtA3ofqAqRV
This commit is contained in:
Claude
2026-12-03 09:46:46 +05:30
parent 8f69e7bf50
commit c8fa0912f7
71 changed files with 1990 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm</groupId>
<artifactId>ai-21-migration-probes</artifactId>
<version>1.0.0</version>
<description>One source tree, compiled and run against several Spring AI versions: mvn test -Dspring-ai.version=2.0.3 -Dboot.version=4.1.0</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-ai.version>2.1.0</spring-ai.version>
<boot.version>4.2.0</boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-client-chat</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-anthropic</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-google-genai</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-deepseek</artifactId></dependency>
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bedrock-converse</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<showDeprecation>true</showDeprecation>
<compilerArgs><arg>-Xlint:deprecation,removal</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<argLine>-Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
<systemPropertyVariables><probe.version>${spring-ai.version}</probe.version></systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,43 @@
package com.ankurm.aimigration.probes;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
/**
* Ordinary 2.0-style code. It compiles on 2.0.3 with no warnings from these lines and on 2.1.0
* with removal warnings. See output/06-legacy-warnings.txt.
*/
public class LegacyAssistant {
private final ChatClient chat;
public LegacyAssistant(ChatModel model) {
ChatMemory memory = MessageWindowChatMemory.builder()
.chatMemoryRepository(new InMemoryChatMemoryRepository())
.maxMessages(20)
.build();
this.chat = ChatClient.builder(model)
.defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
.build();
}
public String ask(String conversationId, String question) {
return chat.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();
}
public static AnthropicChatOptions options() {
return AnthropicChatOptions.builder()
.model("claude-sonnet-4-5")
.temperature(0.2)
.build();
}
}
@@ -0,0 +1,86 @@
package com.ankurm.aimigration.probes;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.ai.anthropic.AnthropicChatModel;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
/** The same calls against the real AnthropicChatModel of whatever version is on the class path. */
@ExtendWith(OutputCaptureExtension.class)
class AnthropicProbeTest {
private static AnthropicChatModel model(FakeAnthropic fake, boolean sampling) {
var options = AnthropicChatOptions.builder().baseUrl(fake.url()).apiKey("test-key")
.model("claude-sonnet-4-5").maxTokens(1024).maxRetries(0);
if (sampling) {
options.temperature(0.2);
}
return AnthropicChatModel.builder().options(options.build()).build();
}
@Test
void promptTokensWithCaching() throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("01-usage", "Anthropic usage with cache tokens")) {
t.line("server reports: input_tokens=" + FakeAnthropic.INPUT + " cache_creation=" + FakeAnthropic.CACHE_WRITE
+ " cache_read=" + FakeAnthropic.CACHE_READ + " output=" + FakeAnthropic.OUTPUT);
var model = model(fake, false);
print(t, "call() ", model.call(new Prompt("hi")).getMetadata().getUsage());
List<ChatResponse> chunks = model.stream(new Prompt("hi")).collectList().block();
Usage streamed = chunks.stream().map(r -> r.getMetadata().getUsage())
.filter(u -> u.getTotalTokens() != null && u.getTotalTokens() > 0).reduce((a, b) -> b).orElseThrow();
print(t, "stream()", streamed);
}
}
private static void print(Transcript t, String label, Usage u) {
t.line(label + " promptTokens=" + u.getPromptTokens() + " completionTokens=" + u.getCompletionTokens()
+ " totalTokens=" + u.getTotalTokens() + " cacheRead=" + u.getCacheReadInputTokens()
+ " cacheWrite=" + u.getCacheWriteInputTokens());
// The workaround many 2.0.x dashboards carry: add the cache counters to the prompt count.
long adjusted = u.getPromptTokens() + orZero(u.getCacheReadInputTokens()) + orZero(u.getCacheWriteInputTokens());
t.line(label + " prompt + cacheRead + cacheWrite (the old workaround) = " + adjusted);
}
private static long orZero(Long value) {
return value == null ? 0 : value;
}
@Test
void requestAndSampling(CapturedOutput log) throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("02-request", "What AnthropicChatModel sends, temperature=0.2 set")) {
model(fake, true).call(new Prompt("hi"));
var seen = fake.seen.get(0);
String auth = seen.headers().containsKey("authorization")
? "Authorization: " + seen.headers().get("authorization").split(" ")[0] + " <key>" : "no Authorization header";
t.line("header " + auth);
t.line("header " + (seen.headers().containsKey("x-api-key") ? "x-api-key: <key>" : "no x-api-key header"));
t.line("header anthropic-version: " + seen.headers().get("anthropic-version"));
var temperature = Pattern.compile("\"temperature\":[0-9.]+").matcher(seen.body());
t.line("body " + (temperature.find() ? temperature.group() : "no temperature field"));
log.getOut().lines().filter(l -> l.contains("WARN") && l.toLowerCase().contains("temperature"))
.map(l -> l.substring(l.indexOf("WARN"))).forEach(t::line);
}
}
@Test
void thinkingBlocks() throws Exception {
try (var fake = new FakeAnthropic(); var t = new Transcript("03-thinking", "A reply with one thinking block and one text block")) {
ChatResponse r = model(fake, false).call(new Prompt("hi"));
t.line("getResults().size() = " + r.getResults().size());
t.line("getResult().getOutput().getText() = " + r.getResult().getOutput().getText());
int i = 0;
for (Generation g : r.getResults()) {
t.line("generation " + i++ + ": text=" + g.getOutput().getText()
+ " metadata keys=" + g.getOutput().getMetadata().keySet().stream().sorted().toList());
}
}
}
}
@@ -0,0 +1,84 @@
package com.ankurm.aimigration.probes;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* A local stand-in for the Anthropic Messages API. No vendor is called. It always answers with
* the same thinking block, text block and usage numbers, and records what it received.
*/
final class FakeAnthropic implements AutoCloseable {
record Seen(Map<String, String> headers, String body) { }
static final int INPUT = 50;
static final int CACHE_WRITE = 300;
static final int CACHE_READ = 2000;
static final int OUTPUT = 100;
final List<Seen> seen = new ArrayList<>();
private final HttpServer server;
FakeAnthropic() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> headers = exchange.getRequestHeaders().entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toLowerCase(), e -> String.join(",", e.getValue())));
seen.add(new Seen(headers, body));
boolean stream = body.contains("\"stream\":true");
byte[] reply = (stream ? sse() : json()).getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("content-type", stream ? "text/event-stream" : "application/json");
exchange.sendResponseHeaders(200, reply.length);
exchange.getResponseBody().write(reply);
exchange.close();
});
server.start();
}
String url() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
private static String usage(int output) {
return """
{"input_tokens":%d,"cache_creation_input_tokens":%d,"cache_read_input_tokens":%d,"output_tokens":%d}"""
.formatted(INPUT, CACHE_WRITE, CACHE_READ, output);
}
private static String json() {
return """
{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-5",
"content":[{"type":"thinking","thinking":"The user greets me.","signature":"sig-abc"},
{"type":"text","text":"Hello there."}],
"stop_reason":"end_turn","stop_sequence":null,"usage":%s}""".formatted(usage(OUTPUT));
}
private static String sse() {
StringBuilder s = new StringBuilder();
event(s, "message_start", """
{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":%s}}"""
.formatted(usage(1)));
event(s, "content_block_start", "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}");
event(s, "content_block_delta", "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello there.\"}}");
event(s, "content_block_stop", "{\"type\":\"content_block_stop\",\"index\":0}");
event(s, "message_delta", "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":" + OUTPUT + "}}");
event(s, "message_stop", "{\"type\":\"message_stop\"}");
return s.toString();
}
private static void event(StringBuilder s, String name, String data) {
s.append("event: ").append(name).append('\n').append("data: ").append(data).append("\n\n");
}
@Override
public void close() {
server.stop(0);
}
}
@@ -0,0 +1,73 @@
package com.ankurm.aimigration.probes;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.MimeTypeUtils;
/** Behaviour that changes without a compile error. The model is a lambda; nothing is called. */
class MessageAndGuardrailProbeTest {
record Answer(String city) { }
private static Media image(byte b) {
return new Media(MimeTypeUtils.IMAGE_PNG, new ByteArrayResource(new byte[] { b }));
}
private static String attempt(java.util.concurrent.Callable<Object> c) {
try {
return "returns " + c.call();
} catch (Exception e) {
return "throws " + e.getClass().getSimpleName();
}
}
@Test
void messages() {
try (var t = new Transcript("04-messages", "Message mutability and equality")) {
var user = UserMessage.builder().text("look").media(image((byte) 1)).build();
t.line("userMessage.getMedia().add(..) " + attempt(() -> user.getMedia().add(image((byte) 2))));
var reply = AssistantMessage.builder().content("ok")
.toolCalls(List.of(new AssistantMessage.ToolCall("1", "function", "f", "{}"))).build();
t.line("assistant.getToolCalls().clear() " + attempt(() -> { reply.getToolCalls().clear(); return "cleared"; }));
var a = UserMessage.builder().text("look").media(image((byte) 1)).build();
var b = UserMessage.builder().text("look").media(image((byte) 2)).build();
t.line("same text, different image: equals() = " + a.equals(b));
}
}
/** A custom or scripted model that finished because a content filter stopped it. */
private static final ChatModel FILTERED = prompt -> new ChatResponse(List.of(new Generation(
new AssistantMessage(""), ChatGenerationMetadata.builder().finishReason("content_filter").build())));
private static final ChatModel NEVER_CALLED = prompt -> {
throw new AssertionError("the guard should have blocked this");
};
@Test
void refusals() {
try (var t = new Transcript("05-refusals", "entity() on a filtered reply and on a SafeGuardAdvisor refusal")) {
var filtered = ChatClient.create(FILTERED);
t.line("finishReason=content_filter, empty text");
t.line(" entity(Answer.class) " + attempt(() -> filtered.prompt().user("q").call().entity(Answer.class)));
t.line(" responseEntity(..).entity() " + attempt(() -> filtered.prompt().user("q").call().responseEntity(Answer.class).entity()));
t.line(" content() " + attempt(() -> "'" + filtered.prompt().user("q").call().content() + "'"));
var guarded = ChatClient.builder(NEVER_CALLED)
.defaultAdvisors(SafeGuardAdvisor.builder().sensitiveWords(List.of("password")).build()).build();
t.line("SafeGuardAdvisor blocks the word 'password'");
t.line(" entity(Answer.class) " + attempt(() -> guarded.prompt().user("the password?").call().entity(Answer.class)));
t.line(" finishReason " + attempt(() -> "'" + guarded.prompt().user("the password?").call()
.chatResponse().getResult().getMetadata().getFinishReason() + "'"));
}
}
}
@@ -0,0 +1,35 @@
package com.ankurm.aimigration.probes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Writes {@code ../output/<name>-<spring-ai version>.txt}; the article quotes these files verbatim. */
final class Transcript implements AutoCloseable {
static final String VERSION = System.getProperty("probe.version", "unknown");
private final Path path;
private final StringBuilder out = new StringBuilder();
Transcript(String name, String title) {
this.path = Path.of("..", "output", name + "-" + VERSION + ".txt");
line("# " + title + " (Spring AI " + VERSION + ")");
}
Transcript line(String text) {
out.append(text).append('\n');
return this;
}
@Override
public void close() {
try {
Files.createDirectories(path.getParent());
Files.writeString(path, out.toString());
} catch (IOException e) {
throw new IllegalStateException(e);
}
System.out.print(out);
}
}