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:
@@ -0,0 +1,76 @@
|
||||
package com.ankurm.aimigration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.aimigration.support.Transcript;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
|
||||
/** A local server records which OpenAI endpoint and which settings the auto-configured model uses. */
|
||||
class OpenAiApiSwitchTest {
|
||||
|
||||
private static final String CHAT = """
|
||||
{"id":"c1","object":"chat.completion","created":1,"model":"m","choices":[{"index":0,"finish_reason":"stop",
|
||||
"message":{"role":"assistant","content":"hi"}}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}""";
|
||||
|
||||
private static final String RESPONSES = """
|
||||
{"id":"r1","object":"response","created_at":1,"status":"completed","model":"m",
|
||||
"output":[{"id":"msg1","type":"message","status":"completed","role":"assistant",
|
||||
"content":[{"type":"output_text","text":"hi","annotations":[]}]}],
|
||||
"parallel_tool_calls":true,"tool_choice":"auto","tools":[],
|
||||
"usage":{"input_tokens":1,"input_tokens_details":{"cached_tokens":0},"output_tokens":1,
|
||||
"output_tokens_details":{"reasoning_tokens":0},"total_tokens":2}}""";
|
||||
|
||||
private static String field(String body, String name) {
|
||||
var m = Pattern.compile("\"" + name + "\":(\"[^\"]*\"|[0-9.]+)").matcher(body);
|
||||
return name + "=" + (m.find() ? m.group(1) : "(not sent)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameChatPropertiesUnderBothApis() throws IOException {
|
||||
List<String[]> seen = new ArrayList<>();
|
||||
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", x -> {
|
||||
seen.add(new String[] { x.getRequestURI().getPath(), new String(x.getRequestBody().readAllBytes(), StandardCharsets.UTF_8) });
|
||||
byte[] reply = (x.getRequestURI().getPath().endsWith("/responses") ? RESPONSES : CHAT).getBytes(StandardCharsets.UTF_8);
|
||||
x.getResponseHeaders().add("content-type", "application/json");
|
||||
x.sendResponseHeaders(200, reply.length);
|
||||
x.getResponseBody().write(reply);
|
||||
x.close();
|
||||
});
|
||||
server.start();
|
||||
try (var t = new Transcript("10-openai-api-switch.txt", "spring.ai.openai.chat.model=my-model and .temperature=0.1, with and without spring.ai.openai.chat.api (local fake server)")) {
|
||||
for (String api : new String[] { null, "responses" }) {
|
||||
var args = new ArrayList<>(List.of(
|
||||
"--spring.ai.openai.base-url=http://127.0.0.1:" + server.getAddress().getPort() + "/v1",
|
||||
"--spring.ai.openai.api-key=test-key",
|
||||
"--spring.ai.openai.chat.model=my-model",
|
||||
"--spring.ai.openai.chat.temperature=0.1"));
|
||||
if (api != null) {
|
||||
args.add("--spring.ai.openai.chat.api=" + api);
|
||||
}
|
||||
try (var context = new SpringApplicationBuilder(MigrationApplication.class).logStartupInfo(false)
|
||||
.run(args.toArray(String[]::new))) {
|
||||
var model = context.getBean(ChatModel.class);
|
||||
model.call("hello");
|
||||
var request = seen.getLast();
|
||||
t.line("spring.ai.openai.chat.api " + (api == null ? "unset" : "= " + api));
|
||||
t.line(" bean: " + model.getClass().getSimpleName());
|
||||
t.line(" POST " + request[0]);
|
||||
t.line(" body: " + field(request[1], "model") + " " + field(request[1], "temperature"));
|
||||
}
|
||||
}
|
||||
assertThat(seen).hasSize(2);
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ankurm.aimigration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.aimigration.support.ScriptedChatModel;
|
||||
import com.ankurm.aimigration.support.Transcript;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.client.advisor.api.MemoryAdvisor;
|
||||
import org.springframework.ai.chat.memory.ChatMemory;
|
||||
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.SystemMessage;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.session.CreateSessionRequest;
|
||||
import org.springframework.ai.session.DefaultSessionService;
|
||||
import org.springframework.ai.session.InMemorySessionRepository;
|
||||
import org.springframework.ai.session.SessionService;
|
||||
|
||||
@SuppressWarnings("removal")
|
||||
class SessionMigrationTest {
|
||||
|
||||
private static String show(List<? extends Message> messages) {
|
||||
var parts = new ArrayList<String>();
|
||||
messages.forEach(m -> parts.add(m.getMessageType().getValue() + ":" + m.getText()));
|
||||
return String.join(" | ", parts);
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyAWindowIntoASession() {
|
||||
ChatMemory memory = MessageWindowChatMemory.builder()
|
||||
.chatMemoryRepository(new InMemoryChatMemoryRepository()).maxMessages(5).build();
|
||||
memory.add("c1", new SystemMessage("Be brief."));
|
||||
for (int turn = 1; turn <= 4; turn++) {
|
||||
memory.add("c1", List.of(new UserMessage("question " + turn), new AssistantMessage("answer " + turn)));
|
||||
}
|
||||
SessionService sessions = DefaultSessionService.builder()
|
||||
.sessionRepository(InMemorySessionRepository.builder().build()).build();
|
||||
|
||||
try (var t = new Transcript("08-session-migration.txt", "Copying a ChatMemory conversation into a session (scripted model)")) {
|
||||
t.line("added to memory: 1 system message + 4 turns, maxMessages=5");
|
||||
t.line("memory holds: " + show(memory.get("c1")));
|
||||
t.line("copied: " + MemoryToSessionCopier.copy(memory, sessions, "c1") + " messages");
|
||||
t.line("copied again: " + MemoryToSessionCopier.copy(memory, sessions, "c1") + " messages (already has events)");
|
||||
t.line("session holds: " + show(sessions.getMessages("c1")));
|
||||
|
||||
sessions.findOrCreate(CreateSessionRequest.builder().id("c2").build());
|
||||
try {
|
||||
sessions.appendMessage("c2", new SystemMessage("Be brief."));
|
||||
t.line("appendMessage(system): accepted");
|
||||
} catch (RuntimeException e) {
|
||||
t.line("appendMessage(system): " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
var model = new ScriptedChatModel().reply("answer 5");
|
||||
new SessionAssistant(model, sessions).ask("c1", "question 5");
|
||||
t.line("next prompt the model sees: " + show(model.prompts.get(0).getInstructions()));
|
||||
t.line("ChatMemory.CONVERSATION_ID = " + ChatMemory.CONVERSATION_ID);
|
||||
t.line("MemoryAdvisor.CONVERSATION_ID = " + MemoryAdvisor.CONVERSATION_ID);
|
||||
assertThat(model.prompts.get(0).getInstructions()).hasSizeGreaterThan(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.ankurm.aimigration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.aimigration.support.ScriptedChatModel;
|
||||
import com.ankurm.aimigration.support.Transcript;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.ToolCallingAdvisor;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallDecision;
|
||||
import org.springframework.ai.model.tool.ToolCallDecisions;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
import org.springframework.ai.model.tool.ToolCallingManager;
|
||||
import org.springframework.ai.model.tool.ToolExecutionResult;
|
||||
import org.springframework.ai.support.ToolCallbacks;
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.ai.tool.definition.ToolDefinition;
|
||||
|
||||
class ToolManagerTest {
|
||||
|
||||
static class Orders {
|
||||
final List<String> ran = new ArrayList<>();
|
||||
|
||||
@Tool(description = "Refund an order", requiresConfirmation = true)
|
||||
String refund(String orderId) {
|
||||
ran.add(orderId);
|
||||
return "refunded " + orderId;
|
||||
}
|
||||
}
|
||||
|
||||
/** Written for 2.0: both abstract methods delegated, nothing else. It still compiles. */
|
||||
static class Old implements ToolCallingManager {
|
||||
private final ToolCallingManager delegate = ToolCallingManager.builder().build();
|
||||
|
||||
@Override
|
||||
public List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions o) {
|
||||
return delegate.resolveToolDefinitions(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ToolExecutionResult executeToolCalls(Prompt p, ChatResponse r) {
|
||||
return delegate.executeToolCalls(p, r);
|
||||
}
|
||||
}
|
||||
|
||||
private static String run(Transcript t, String label, ToolCallingManager manager) {
|
||||
var orders = new Orders();
|
||||
var model = new ScriptedChatModel().callTool("call_1", "refund", "{\"orderId\":\"A-17\"}");
|
||||
var chat = ChatClient.builder(model)
|
||||
.defaultAdvisors(ToolCallingAdvisor.builder().toolCallingManager(manager).build()).build();
|
||||
ChatResponse paused = chat.prompt().user("Refund A-17").tools(orders).call().chatResponse();
|
||||
t.line(label);
|
||||
t.line(" paused reply, awaiting " + ToolCallDecisions.awaitingDecision(paused) + ", tool ran: " + orders.ran);
|
||||
var prompt = new Prompt(List.of(new UserMessage("Refund A-17")),
|
||||
ToolCallingChatOptions.builder().toolCallbacks(ToolCallbacks.from(orders)).build());
|
||||
String outcome;
|
||||
try {
|
||||
manager.executeToolCalls(prompt, paused, ToolCallDecisions.of(ToolCallDecision.allow("call_1")));
|
||||
outcome = "ok, tool ran: " + orders.ran;
|
||||
} catch (RuntimeException e) {
|
||||
outcome = e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
t.line(" resume: " + outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrappingManagers() {
|
||||
try (var t = new Transcript("09-tool-manager.txt", "A custom ToolCallingManager and a tool that requires confirmation (scripted model)")) {
|
||||
assertThat(run(t, "manager written for 2.0 (two methods)", new Old())).startsWith("Unsupported");
|
||||
assertThat(run(t, "LoggingToolCallingManager (three methods)",
|
||||
new LoggingToolCallingManager(ToolCallingManager.builder().build()))).startsWith("ok");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.aimigration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.aimigration.support.Transcript;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.chat.metadata.Usage;
|
||||
|
||||
class UncachedTokensTest {
|
||||
|
||||
/** The numbers AnthropicChatModel 2.1.0 reported in output/01-usage-2.1.0.txt. */
|
||||
private static final Usage REPORTED = new Usage() {
|
||||
public Integer getPromptTokens() { return 2350; }
|
||||
public Integer getCompletionTokens() { return 100; }
|
||||
public Object getNativeUsage() { return null; }
|
||||
public Long getCacheReadInputTokens() { return 2000L; }
|
||||
public Long getCacheWriteInputTokens() { return 300L; }
|
||||
};
|
||||
|
||||
@Test
|
||||
void subtractDoNotAdd() {
|
||||
try (var t = new Transcript("12-uncached.txt", "UncachedTokens.of on the 2.1.0 usage values")) {
|
||||
t.line("promptTokens=2350 cacheRead=2000 cacheWrite=300 -> full-price input = " + UncachedTokens.of(REPORTED));
|
||||
}
|
||||
assertThat(UncachedTokens.of(REPORTED)).isEqualTo(50);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ankurm.aimigration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.aimigration.support.Transcript;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.embedding.Embedding;
|
||||
import org.springframework.ai.embedding.EmbeddingModel;
|
||||
import org.springframework.ai.embedding.EmbeddingRequest;
|
||||
import org.springframework.ai.embedding.EmbeddingResponse;
|
||||
import org.springframework.ai.vectorstore.EmbeddedDocument;
|
||||
import org.springframework.ai.vectorstore.SearchRequest;
|
||||
import org.springframework.ai.vectorstore.SimpleVectorStore;
|
||||
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
/** VectorStore.upsert against a real pgvector container. The embedding model is a counting fake. */
|
||||
class UpsertTest {
|
||||
|
||||
static class CountingEmbeddingModel implements EmbeddingModel {
|
||||
final AtomicInteger calls = new AtomicInteger();
|
||||
|
||||
@Override
|
||||
public EmbeddingResponse call(EmbeddingRequest request) {
|
||||
calls.incrementAndGet();
|
||||
var out = new ArrayList<Embedding>();
|
||||
for (int i = 0; i < request.getInstructions().size(); i++) {
|
||||
out.add(new Embedding(new float[] { 1, 0, 0 }, i));
|
||||
}
|
||||
return new EmbeddingResponse(out);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float[] embed(Document document) {
|
||||
calls.incrementAndGet();
|
||||
return new float[] { 1, 0, 0 };
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertAndTheDistanceKey() throws Exception {
|
||||
var embeddings = new CountingEmbeddingModel();
|
||||
String id = UUID.nameUUIDFromBytes("doc-1".getBytes(StandardCharsets.UTF_8)).toString();
|
||||
try (var t = new Transcript("11-upsert.txt", "VectorStore.upsert on SimpleVectorStore and on PgVectorStore (pgvector/pgvector:pg17)")) {
|
||||
var simple = SimpleVectorStore.builder(embeddings).build();
|
||||
try {
|
||||
simple.upsert(List.of(new EmbeddedDocument(new Document(id, "text", Map.of()), new float[] { 1, 0, 0 })));
|
||||
t.line("SimpleVectorStore.upsert: ok");
|
||||
} catch (UnsupportedOperationException e) {
|
||||
t.line("SimpleVectorStore.upsert: UnsupportedOperationException: " + e.getMessage());
|
||||
}
|
||||
try (var pg = new PostgreSQLContainer(DockerImageName.parse("pgvector/pgvector:pg17").asCompatibleSubstituteFor("postgres"))) {
|
||||
pg.start();
|
||||
var jdbc = new JdbcTemplate(new DriverManagerDataSource(pg.getJdbcUrl(), pg.getUsername(), pg.getPassword()));
|
||||
var store = PgVectorStore.builder(jdbc, embeddings).dimensions(3).initializeSchema(true).build();
|
||||
store.afterPropertiesSet();
|
||||
int before = embeddings.calls.get();
|
||||
store.upsert(List.of(new EmbeddedDocument(new Document(id, "first version", Map.of("distance", 42)), new float[] { 0, 1, 0 })));
|
||||
store.upsert(List.of(new EmbeddedDocument(new Document(id, "second version", Map.of("distance", 42)), new float[] { 0, 1, 0 })));
|
||||
t.line("PgVectorStore.upsert twice, same id");
|
||||
t.line(" rows in vector_store: " + jdbc.queryForObject("select count(*) from vector_store", Integer.class));
|
||||
t.line(" embedding model calls: " + (embeddings.calls.get() - before));
|
||||
var hit = store.similaritySearch(new float[] { 0, 1, 0 }, SearchRequest.builder().topK(1).build()).get(0);
|
||||
t.line("similaritySearch(float[], request)");
|
||||
t.line(" text: " + hit.getText());
|
||||
t.line(" embedding model calls: " + (embeddings.calls.get() - before));
|
||||
t.line(" stored metadata distance=42 reads back as: " + hit.getMetadata().get("distance"));
|
||||
t.line(" getScore(): " + hit.getScore());
|
||||
try {
|
||||
store.upsert(List.of(new EmbeddedDocument(new Document(UUID.randomUUID().toString(), "short", Map.of()), new float[] { 1, 0 })));
|
||||
t.line("upsert with a 2-wide vector: accepted");
|
||||
} catch (RuntimeException e) {
|
||||
t.line("upsert with a 2-wide vector: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
}
|
||||
assertThat(hit.getText()).isEqualTo("second version");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.aimigration.support;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.model.Generation;
|
||||
import org.springframework.ai.chat.prompt.ChatOptions;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.tool.ToolCallingChatOptions;
|
||||
|
||||
/** Not a language model: replies come from a queue, and every prompt is recorded. */
|
||||
public class ScriptedChatModel implements ChatModel {
|
||||
|
||||
public final List<Prompt> prompts = new ArrayList<>();
|
||||
private final Deque<AssistantMessage> replies = new ArrayDeque<>();
|
||||
|
||||
public ScriptedChatModel reply(String text) {
|
||||
replies.add(new AssistantMessage(text));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ScriptedChatModel callTool(String id, String name, String arguments) {
|
||||
replies.add(AssistantMessage.builder()
|
||||
.toolCalls(List.of(new AssistantMessage.ToolCall(id, "function", name, arguments))).build());
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatResponse call(Prompt prompt) {
|
||||
prompts.add(prompt);
|
||||
return new ChatResponse(List.of(new Generation(replies.remove())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatOptions getOptions() {
|
||||
return ToolCallingChatOptions.builder().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.aimigration.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Writes a numbered transcript under {@code output/}; the article quotes these files verbatim. */
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path path;
|
||||
private final StringBuilder out = new StringBuilder();
|
||||
|
||||
public Transcript(String file, String title) {
|
||||
this.path = Path.of("output", file);
|
||||
line("# " + title);
|
||||
}
|
||||
|
||||
public Transcript line(String text) {
|
||||
out.append(text).append('\n');
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, out.toString());
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
System.out.print(out);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user