From 6856497847413d08f7ee0d146bfec779a187e7bb Mon Sep 17 00:00:00 2001 From: sama Pyb Date: Tue, 1 Dec 2026 22:39:02 +0800 Subject: [PATCH 1/2] Coalesce consecutive Anthropic tool results into one user message --- .../Models/AnthropicLanguageModel.swift | 36 +++-- .../AnthropicToolContinuationTests.swift | 143 ++++++++++++++++++ 2 files changed, 164 insertions(+), 15 deletions(-) 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..dd46de70 100644 --- a/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift +++ b/Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift @@ -55,3 +55,146 @@ 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 { $0 } + ) + + 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"]) + } + + @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" }) + } +} From 2c49d483d5954acd4d6c512f27ec5a6e45729d81 Mon Sep 17 00:00:00 2001 From: sama Pyb Date: Tue, 1 Dec 2026 23:52:27 +0800 Subject: [PATCH 2/2] Join multiple system instructions in Responses API requests --- .../Models/OpenAILanguageModel.swift | 8 +- .../Models/OpenResponsesLanguageModel.swift | 8 +- .../ResponsesSystemInstructionsTests.swift | 115 ++++++++++++++++++ 3 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 Tests/AnyLanguageModelTests/ResponsesSystemInstructionsTests.swift diff --git a/Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift b/Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift index feedb05a..4ad80989 100644 --- a/Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift +++ b/Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift @@ -1329,6 +1329,7 @@ private enum Responses { ] var outputs: [JSONValue] = [] + var instructionParts: [String] = [] for msg in messages { switch msg.role { case .user: @@ -1425,13 +1426,13 @@ private enum Responses { let systemMessage = msg switch systemMessage.content { case .text(let text): - body["instructions"] = .string(text) + if !text.isEmpty { instructionParts.append(text) } case .blocks(let blocks): // Concatenate text blocks for instructions; ignore images let text = blocks.compactMap { if case .text(let t) = $0 { return t } else { return nil } }.joined( separator: "\n" ) - if !text.isEmpty { body["instructions"] = .string(text) } + if !text.isEmpty { instructionParts.append(text) } } case .assistant: @@ -1439,6 +1440,9 @@ private enum Responses { if !text.isEmpty { outputs.append(assistantInputItem(text: text)) } } } + if !instructionParts.isEmpty { + body["instructions"] = .string(instructionParts.joined(separator: "\n")) + } body["input"] = .array(outputs) if let tools { diff --git a/Sources/AnyLanguageModel/Models/OpenResponsesLanguageModel.swift b/Sources/AnyLanguageModel/Models/OpenResponsesLanguageModel.swift index 8a7e933e..a9895ea3 100644 --- a/Sources/AnyLanguageModel/Models/OpenResponsesLanguageModel.swift +++ b/Sources/AnyLanguageModel/Models/OpenResponsesLanguageModel.swift @@ -861,6 +861,7 @@ private enum OpenResponsesAPI { "stream": .bool(stream), ] var input: [JSONValue] = [] + var instructionParts: [String] = [] for msg in messages { switch msg.role { case .user: @@ -897,12 +898,12 @@ private enum OpenResponsesAPI { case .system: switch msg.content { case .text(let t): - body["instructions"] = .string(t) + if !t.isEmpty { instructionParts.append(t) } case .blocks(let blocks): let t = blocks.compactMap { if case .text(let s) = $0 { return s } else { return nil } }.joined( separator: "\n" ) - if !t.isEmpty { body["instructions"] = .string(t) } + if !t.isEmpty { instructionParts.append(t) } } case .assistant(let id): let text = msg.text @@ -927,6 +928,9 @@ private enum OpenResponsesAPI { } } } + if !instructionParts.isEmpty { + body["instructions"] = .string(instructionParts.joined(separator: "\n")) + } body["input"] = .array(input) if let tools { diff --git a/Tests/AnyLanguageModelTests/ResponsesSystemInstructionsTests.swift b/Tests/AnyLanguageModelTests/ResponsesSystemInstructionsTests.swift new file mode 100644 index 00000000..61ea7747 --- /dev/null +++ b/Tests/AnyLanguageModelTests/ResponsesSystemInstructionsTests.swift @@ -0,0 +1,115 @@ +import Foundation +import Testing + +@testable import AnyLanguageModel + +/// Instructions go to the OpenAI Responses and Open Responses APIs in the top-level +/// `instructions` field, with multiple instructions entries joined in order. +@Suite("Responses system instructions") +struct ResponsesSystemInstructionsTests { + enum Provider: CaseIterable, Sendable { + case openAIResponses + case openResponses + } + + @Test(arguments: Provider.allCases, [false, true]) + func instructionsEntriesAreJoinedWithoutImages(provider: Provider, streaming: Bool) async throws { + let transport = FakeTransport(replies: [try Self.reply(text: "Hi", streaming: streaming)]) + let image = Transcript.ImageSegment(data: Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png") + let transcript = Transcript(entries: [ + .instructions( + .init( + segments: [.text(.init(content: "First.")), .image(image), .text(.init(content: "Second."))], + toolDefinitions: [] + ) + ), + .instructions(.init(segments: [.text(.init(content: "Third."))], toolDefinitions: [])), + ]) + let session = LanguageModelSession(model: Self.model(provider, transport: transport), transcript: transcript) + + try await Self.respond(in: session, streaming: streaming) + + let body = try #require(try transport.bodies.map(Self.json).first) + #expect(body["instructions"] as? String == "First.\nSecond.\nThird.") + let input = try #require(body["input"] as? [[String: Any]]) + #expect(input.count == 1) + #expect(input.first?["role"] as? String == "user") + } + + @Test(arguments: Provider.allCases) + func trailingEmptyInstructionsDoesNotClearEarlierInstructions(provider: Provider) async throws { + let transport = FakeTransport(replies: [try Self.reply(text: "Hi", streaming: false)]) + let transcript = Transcript(entries: [ + .instructions(.init(segments: [.text(.init(content: "Keep me."))], toolDefinitions: [])), + .instructions(.init(segments: [.text(.init(content: ""))], toolDefinitions: [])), + ]) + let session = LanguageModelSession(model: Self.model(provider, transport: transport), transcript: transcript) + + try await Self.respond(in: session, streaming: false) + + let body = try #require(try transport.bodies.map(Self.json).first) + #expect(body["instructions"] as? String == "Keep me.") + } + + @Test(arguments: Provider.allCases) + func emptyInstructionsOmitsField(provider: Provider) async throws { + let transport = FakeTransport(replies: [try Self.reply(text: "Hi", streaming: false)]) + let transcript = Transcript(entries: [ + .instructions(.init(segments: [.text(.init(content: ""))], toolDefinitions: [])) + ]) + let session = LanguageModelSession(model: Self.model(provider, transport: transport), transcript: transcript) + + try await Self.respond(in: session, streaming: false) + + let body = try #require(try transport.bodies.map(Self.json).first) + #expect(body["instructions"] == nil) + } + + // MARK: - Fixtures + + private static func model(_ provider: Provider, transport: FakeTransport) -> any LanguageModel { + switch provider { + case .openAIResponses: + OpenAILanguageModel(apiKey: "test", model: "test", apiVariant: .responses, transport: transport) + case .openResponses: + OpenResponsesLanguageModel( + baseURL: URL(string: "https://example.com/v1/")!, + apiKey: "test", + model: "test", + transport: transport + ) + } + } + + private static func respond(in session: LanguageModelSession, streaming: Bool) async throws { + if streaming { + _ = try await session.streamResponse(to: "Hello").collect() + } else { + _ = try await session.respond(to: "Hello") + } + } + + private static func json(_ data: Data) throws -> [String: Any] { + try #require(try JSONSerialization.jsonObject(with: data) 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 reply(text: String, streaming: Bool) throws -> FakeTransport.Reply { + let message: [String: Any] = [ + "type": "message", "id": "msg_1", "role": "assistant", "status": "completed", + "content": [["type": "output_text", "text": text, "annotations": []]], + ] + let response: [String: Any] = ["id": "resp_1", "output": [message]] + guard streaming else { + return .init(chunks: [try encode(response)]) + } + let events: [[String: Any]] = [ + ["type": "response.output_text.delta", "delta": text], + ["type": "response.completed", "response": response], + ] + return .init(chunks: try events.map { "data: \(try encode($0))\n\n" }) + } +}