diff --git a/Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift b/Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift index be312ea5..e13dadcc 100644 --- a/Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift +++ b/Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift @@ -1234,23 +1234,29 @@ extension Transcript { } appendAssistant(toolUseBlocks) case .toolOutput(let toolOutput): - // Add user message with tool result - messages.append( - .init( - role: .user, - content: [ - .toolResult( - AnthropicToolResult( - toolUseId: toolOutput.id, - content: try convertSegmentsToAnthropicContent( - toolOutput.segments, - isToolOutput: true - ) - ) - ) - ] + // Coalesce consecutive tool outputs into a single user message so every + // tool_use in a parallel round has its tool_result in the immediately + // following user message, matching in-flight tool continuation. + let result: AnthropicContent = .toolResult( + AnthropicToolResult( + toolUseId: toolOutput.id, + content: try convertSegmentsToAnthropicContent( + toolOutput.segments, + isToolOutput: true + ) ) ) + if let last = messages.last, + last.role == .user, + !last.content.isEmpty, + last.content.allSatisfy({ + if case .toolResult = $0 { true } else { false } + }) + { + messages[messages.count - 1] = .init(role: .user, content: last.content + [result]) + } else { + messages.append(.init(role: .user, content: [result])) + } } } return messages diff --git a/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift b/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift index ea8e997d..62a2b25b 100644 --- a/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift +++ b/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift @@ -55,3 +55,158 @@ import Testing } } #endif + +@Suite("Anthropic tool result replay") +struct AnthropicToolResultReplayTests { + @Test(arguments: [false, true]) + func parallelToolOutputsReplayInOneUserMessage(streaming: Bool) async throws { + let transport = FakeTransport(replies: [ + try Self.parallelToolReply(streaming: streaming), + try Self.textReply("Both sunny.", streaming: streaming), + try Self.textReply("You're welcome.", streaming: streaming), + ]) + let session = LanguageModelSession(model: Self.model(transport), tools: [WeatherTool()]) + + try await Self.ask(session, "Weather in Paris and Tokyo?", streaming: streaming) + try await Self.ask(session, "Thanks", streaming: streaming) + + try #require(transport.bodies.count == 3) + let replayed = try Self.messages(from: transport.bodies[2]) + #expect(replayed.compactMap { $0["role"] as? String } == ["user", "assistant", "user", "assistant", "user"]) + let results = try #require(replayed[2]["content"] as? [[String: Any]]) + #expect(results.compactMap { $0["type"] as? String } == ["tool_result", "tool_result"]) + #expect(results.compactMap { $0["tool_use_id"] as? String } == ["call_1", "call_2"]) + } + + @Test(arguments: [false, true]) + func parallelToolOutputsWithDynamicProfileContinueInOneUserMessage(streaming: Bool) async throws { + let transport = FakeTransport(replies: [ + try Self.parallelToolReply(streaming: streaming), + try Self.textReply("Both sunny.", streaming: streaming), + ]) + let session = LanguageModelSession( + profile: LanguageModelSession.Profile { WeatherTool() } + .model(Self.model(transport)) + .historyTransform { entries in + entries.map { entry in + guard case .toolOutput(var output) = entry, output.id == "call_2" else { + return entry + } + output.segments = [.text(.init(content: "REDACTED"))] + return .toolOutput(output) + } + } + ) + + try await Self.ask(session, "Weather in Paris and Tokyo?", streaming: streaming) + + try #require(transport.bodies.count == 2) + let continuation = try Self.messages(from: transport.bodies[1]) + #expect(continuation.compactMap { $0["role"] as? String } == ["user", "assistant", "user"]) + let results = try #require(continuation[2]["content"] as? [[String: Any]]) + #expect(results.compactMap { $0["type"] as? String } == ["tool_result", "tool_result"]) + #expect(results.compactMap { $0["tool_use_id"] as? String } == ["call_1", "call_2"]) + let texts = results.map { result -> String in + ((result["content"] as? [[String: Any]]) ?? []).compactMap { $0["text"] as? String }.joined() + } + #expect(texts == ["The weather in Paris is sunny and 72°F / 23°C", "REDACTED"]) + } + + @Test func stoppedParallelToolCallsReplayOutputsInOneUserMessage() async throws { + let transport = FakeTransport(replies: [ + try Self.parallelToolReply(streaming: false), + try Self.textReply("Okay.", streaming: false), + ]) + let session = LanguageModelSession(model: Self.model(transport), tools: [WeatherTool()]) + session.toolExecutionDelegate = StopToolExecutionDelegate() + + try await Self.ask(session, "Weather in Paris and Tokyo?", streaming: false) + try await Self.ask(session, "Never mind", streaming: false) + + try #require(transport.bodies.count == 2) + let replayed = try Self.messages(from: transport.bodies[1]) + #expect(replayed.compactMap { $0["role"] as? String } == ["user", "assistant", "user", "user"]) + let results = try #require(replayed[2]["content"] as? [[String: Any]]) + #expect(results.compactMap { $0["type"] as? String } == ["tool_result", "tool_result"]) + #expect(results.compactMap { $0["tool_use_id"] as? String } == ["call_1", "call_2"]) + let followUp = try #require(replayed[3]["content"] as? [[String: Any]]) + #expect(followUp.compactMap { $0["text"] as? String } == ["Never mind"]) + } + + // MARK: - Fixtures + + private static func model(_ transport: FakeTransport) -> AnthropicLanguageModel { + AnthropicLanguageModel(apiKey: "test", model: "test", transport: transport) + } + + private static func ask(_ session: LanguageModelSession, _ prompt: String, streaming: Bool) async throws { + if streaming { + _ = try await session.streamResponse(to: prompt).collect() + } else { + _ = try await session.respond(to: prompt) + } + } + + private static func messages(from body: Data) throws -> [[String: Any]] { + let json = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + return try #require(json["messages"] as? [[String: Any]]) + } + + private static func encode(_ object: [String: Any]) throws -> String { + String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self) + } + + private static func message(_ content: [[String: Any]], stopReason: String) -> [String: Any] { + [ + "id": "m", "type": "message", "role": "assistant", "model": "test", "content": content, + "stop_reason": stopReason, "usage": ["input_tokens": 1, "output_tokens": 1], + ] + } + + private static func textReply(_ text: String, streaming: Bool) throws -> FakeTransport.Reply { + guard streaming else { + return .init(chunks: [try encode(message([["type": "text", "text": text]], stopReason: "end_turn"))]) + } + let events: [[String: Any]] = [ + ["type": "message_start", "message": message([], stopReason: "end_turn")], + ["type": "content_block_start", "index": 0, "content_block": ["type": "text", "text": ""]], + ["type": "content_block_delta", "index": 0, "delta": ["type": "text_delta", "text": text]], + ["type": "content_block_stop", "index": 0], + ["type": "message_stop"], + ] + return .init(chunks: try events.map { "data: \(try encode($0))\n\n" }) + } + + private static func parallelToolReply(streaming: Bool) throws -> FakeTransport.Reply { + let calls: [[String: Any]] = [ + ["type": "tool_use", "id": "call_1", "name": "getWeather", "input": ["city": "Paris"]], + ["type": "tool_use", "id": "call_2", "name": "getWeather", "input": ["city": "Tokyo"]], + ] + guard streaming else { + return .init(chunks: [try encode(message(calls, stopReason: "tool_use"))]) + } + let events: [[String: Any]] = [ + ["type": "message_start", "message": message([], stopReason: "tool_use")], + [ + "type": "content_block_start", "index": 0, + "content_block": ["type": "tool_use", "id": "call_1", "name": "getWeather", "input": [:]], + ], + [ + "type": "content_block_delta", "index": 0, + "delta": ["type": "input_json_delta", "partial_json": #"{"city":"Paris"}"#], + ], + ["type": "content_block_stop", "index": 0], + [ + "type": "content_block_start", "index": 1, + "content_block": ["type": "tool_use", "id": "call_2", "name": "getWeather", "input": [:]], + ], + [ + "type": "content_block_delta", "index": 1, + "delta": ["type": "input_json_delta", "partial_json": #"{"city":"Tokyo"}"#], + ], + ["type": "content_block_stop", "index": 1], + ["type": "message_stop"], + ] + return .init(chunks: try events.map { "data: \(try encode($0))\n\n" }) + } +}