Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,7 @@ private enum Responses {
]

var outputs: [JSONValue] = []
var instructionParts: [String] = []
for msg in messages {
switch msg.role {
case .user:
Expand Down Expand Up @@ -1425,20 +1426,23 @@ 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:
let text = msg.responsesAssistantText
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -927,6 +928,9 @@ private enum OpenResponsesAPI {
}
}
}
if !instructionParts.isEmpty {
body["instructions"] = .string(instructionParts.joined(separator: "\n"))
}
body["input"] = .array(input)

if let tools {
Expand Down
143 changes: 143 additions & 0 deletions Tests/AnyLanguageModelTests/AnthropicToolContinuationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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" })
}
}
115 changes: 115 additions & 0 deletions Tests/AnyLanguageModelTests/ResponsesSystemInstructionsTests.swift
Original file line number Diff line number Diff line change
@@ -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" })
}
}
Loading