diff --git a/Sources/LLMProviderKitAnthropic/AnthropicProvider.swift b/Sources/LLMProviderKitAnthropic/AnthropicProvider.swift index 9c62783..b9d917e 100644 --- a/Sources/LLMProviderKitAnthropic/AnthropicProvider.swift +++ b/Sources/LLMProviderKitAnthropic/AnthropicProvider.swift @@ -137,8 +137,11 @@ public struct AnthropicProvider: LLMProvider { // Observed 2026-09-06: without this, cache_read_input_tokens was // never reported for any Naseem call. // Runs of one role are merged first (see mergingConsecutiveRoles), so - // the breakpoint lands on the last block of the merged final entry. - bodyDict["messages"] = Self.markingLastBlockForCache(Self.mergingConsecutiveRoles(messages)) + // both message breakpoints land on merged entries: the last block of + // the final entry, and the last block of the entry right before the + // newest assistant turn (where the previous request ended). + bodyDict["messages"] = Self.markingLastBlockForCache( + Self.markingPreviousTurnForCache(Self.mergingConsecutiveRoles(messages))) if let sys = systemText { bodyDict["system"] = [["type": "text", "text": sys, "cache_control": Self.ephemeral]] @@ -222,6 +225,34 @@ public struct AnthropicProvider: LLMProvider { return out } + /// A breakpoint on the last block of the message right before the newest + /// assistant turn — where the previous request of this conversation + /// ended. The lookup from the newest breakpoint walks back only about 20 + /// blocks, and one step with many parallel tool calls adds more than + /// that; this breakpoint matches the previous request's entry exactly. + /// With tools, system and the last message that is four, Anthropic's + /// limit. Runs on merged entries (after mergingConsecutiveRoles), so the + /// target is never the final message. String content becomes one text + /// block, as for the last message. + static func markingPreviousTurnForCache(_ messages: [[String: Any]]) -> [[String: Any]] { + guard let newestAssistant = messages.lastIndex(where: { $0["role"] as? String == "assistant" }), + newestAssistant > 0 else { return messages } + let target = newestAssistant - 1 + var message = messages[target] + if let text = message["content"] as? String { + guard !text.isEmpty else { return messages } + message["content"] = [["type": "text", "text": text, "cache_control": ephemeral]] + } else if var blocks = message["content"] as? [[String: Any]], !blocks.isEmpty { + blocks[blocks.count - 1]["cache_control"] = ephemeral + message["content"] = blocks + } else { + return messages + } + var out = messages + out[target] = message + return out + } + public func parseStreamLine(_ line: String, request: LLMRequest) throws -> [LLMStreamChunk] { if line.isEmpty || line.hasPrefix(":") { return [] } if line.hasPrefix("event: ") { return [] } diff --git a/Tests/LLMProviderKitTests/AnthropicCacheBreakpointTests.swift b/Tests/LLMProviderKitTests/AnthropicCacheBreakpointTests.swift new file mode 100644 index 0000000..4fa7aa3 --- /dev/null +++ b/Tests/LLMProviderKitTests/AnthropicCacheBreakpointTests.swift @@ -0,0 +1,99 @@ +import Testing +import Foundation +@testable import LLMProviderKit +@testable import LLMProviderKitAnthropic + +/// Anthropic looks a cached prefix up from each breakpoint, walking back +/// about 20 blocks. One step with many parallel tool calls adds more than +/// that, so the single moving breakpoint on the last message could miss the +/// previous request's entry. A fourth breakpoint sits exactly where the +/// previous request ended: the last block of the message right before the +/// newest assistant turn. +struct AnthropicCacheBreakpointTests { + static let tool = LLMToolDefinition(name: "read_file", description: "Read.", + parameters: ["type": "object", "properties": [:] as [String: Any]]) + + private func body(_ messages: [LLMMessage], tools: [LLMToolDefinition] = []) throws -> (json: [String: Any], text: String) { + let provider = AnthropicProvider(configuration: AnthropicProvider.anthropic(apiKey: "k", model: "claude-sonnet-4-6")) + let request = LLMRequest(model: "claude-sonnet-4-6", messages: messages, tools: tools) + let data = try #require(try provider.prepareRequest(request, stream: false).httpBody) + let json = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + return (json, String(decoding: data, as: UTF8.self)) + } + + private func marks(_ text: String) -> Int { text.components(separatedBy: #""cache_control""#).count - 1 } + + private func isMarked(_ message: [String: Any]) -> Bool { + (message["content"] as? [[String: Any]])?.last?["cache_control"] != nil + } + + private func step(_ id: String) -> [LLMMessage] { + var call = LLMMessage(role: .assistant, content: "") + call.toolCalls = [LLMToolCall(id: id, name: "read_file", arguments: "{}")] + var result = LLMMessage(role: .tool, content: "text of \(id)") + result.toolCallId = id + return [call, result] + } + + /// Mid-run: the previous request ended at the tool result before the + /// newest step. + @Test func thePreviousRequestsLastBlockIsMarked() throws { + let (json, text) = try body([.system("sys"), .user("go")] + step("a") + step("b"), tools: [Self.tool]) + let messages = try #require(json["messages"] as? [[String: Any]]) + // user, assistant(a), user(result a), assistant(b), user(result b) + #expect(messages.count == 5) + #expect(isMarked(messages[2])) // where the previous request ended + #expect(isMarked(messages[4])) // the newest message + #expect(!isMarked(messages[0]) && !isMarked(messages[1]) && !isMarked(messages[3])) + #expect(marks(text) == 4) // tools, system, previous turn, last message + } + + /// A new user turn: the previous request ended at the last tool result + /// before the final answer. + @Test func aNewTurnMarksWhereThePreviousRunEnded() throws { + let (json, _) = try body([.system("sys"), .user("go")] + step("a") + [.assistant("done"), .user("again")], + tools: [Self.tool]) + let messages = try #require(json["messages"] as? [[String: Any]]) + // user, assistant(a), user(result a), assistant(done), user(again) + #expect(isMarked(messages[2])) + #expect(isMarked(messages[4])) + #expect(!isMarked(messages[3])) + } + + @Test func aFirstMessageHasNoPreviousTurn() throws { + let (_, text) = try body([.system("sys"), .user("hi")]) + #expect(marks(text) == 2) // system, last message + } + + @Test func neverMoreThanFour() throws { + var messages: [LLMMessage] = [.system("sys"), .user("go")] + for i in 0..<12 { messages += step("s\(i)") } + let (_, text) = try body(messages, tools: [Self.tool]) + #expect(marks(text) == 4) + } + + /// Parallel tool results merge into one user entry first; the previous + /// turn's breakpoint lands on that entry's last block only. + @Test func parallelResultsAreMarkedOnTheMergedEntry() throws { + var call = LLMMessage(role: .assistant, content: "") + call.toolCalls = (0..<3).map { LLMToolCall(id: "p\($0)", name: "read_file", arguments: "{}") } + let results: [LLMMessage] = (0..<3).map { + var r = LLMMessage(role: .tool, content: "text of p\($0)"); r.toolCallId = "p\($0)"; return r + } + let (json, text) = try body([.system("sys"), .user("go"), call] + results + step("b"), tools: [Self.tool]) + let messages = try #require(json["messages"] as? [[String: Any]]) + // user, assistant(p0..p2), user(results p0..p2), assistant(b), user(result b) + #expect(messages.count == 5) + let merged = try #require(messages[2]["content"] as? [[String: Any]]) + #expect(merged.count == 3) + #expect(merged[2]["cache_control"] != nil) + #expect(merged[0]["cache_control"] == nil && merged[1]["cache_control"] == nil) + #expect(marks(text) == 4) + } + + /// Same conversation, same body, call after call. + @Test func placementIsDeterministic() throws { + let messages: [LLMMessage] = [.system("sys"), .user("go")] + step("a") + step("b") + #expect(try body(messages, tools: [Self.tool]).text == body(messages, tools: [Self.tool]).text) + } +} diff --git a/Tests/LLMProviderKitTests/LLMKitTests.swift b/Tests/LLMProviderKitTests/LLMKitTests.swift index cbbed4d..6d2f521 100644 --- a/Tests/LLMProviderKitTests/LLMKitTests.swift +++ b/Tests/LLMProviderKitTests/LLMKitTests.swift @@ -1197,8 +1197,13 @@ struct InProcessProviderTests { #expect((tools.last?["cache_control"] as? [String: String])?["type"] == "ephemeral") let messages = try #require(body["messages"] as? [[String: Any]]) - // Only the final message carries a breakpoint; earlier ones stay byte-stable. - #expect(messages.dropLast().allSatisfy { $0["content"] is String }) + // The final message and the one right before the newest assistant turn + // (where the previous request ended) carry breakpoints; the rest stay + // byte-stable. + #expect(messages[1]["content"] is String) + let previousBlocks = try #require(messages[0]["content"] as? [[String: Any]]) + #expect(previousBlocks.last?["text"] as? String == "Hi") + #expect((previousBlocks.last?["cache_control"] as? [String: String])?["type"] == "ephemeral") let lastBlocks = try #require(messages.last?["content"] as? [[String: Any]]) #expect(lastBlocks.last?["text"] as? String == "Read x") #expect((lastBlocks.last?["cache_control"] as? [String: String])?["type"] == "ephemeral")