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
22 changes: 15 additions & 7 deletions Sources/AnyLanguageModel/Models/GeminiLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -911,12 +911,21 @@ extension Transcript {

fileprivate func toGeminiContent() throws -> [GeminiContent] {
var messages = [GeminiContent]()
var pendingFunctionResponses = [GeminiPart]()

func flushFunctionResponses() {
guard !pendingFunctionResponses.isEmpty else { return }
messages.append(.init(role: .user, parts: pendingFunctionResponses))
pendingFunctionResponses.removeAll(keepingCapacity: true)
}

for item in geminiReplayEntries {
switch item {
case .instructions:
// Sent in the request's `systemInstruction` field; see `geminiSystemInstruction`.
continue
case .prompt(let prompt):
flushFunctionResponses()
messages.append(
.init(
role: .user,
Expand All @@ -927,6 +936,7 @@ extension Transcript {
// Keep display history in the transcript without sending unsupported replay state.
continue
case .response(let response):
flushFunctionResponses()
messages.append(
.init(
role: .model,
Expand All @@ -935,6 +945,7 @@ extension Transcript {
)
)
case .toolCalls(let toolCalls):
flushFunctionResponses()
// Add model's response with function calls
let functionCallParts: [GeminiPart] = toolCalls.map { call in
let args = call.arguments.jsonValue.objectValue ?? [:]
Expand All @@ -954,16 +965,13 @@ extension Transcript {
)
)
case .toolOutput(let toolOutput):
// Add function response as a user message (Gemini API expects function responses from user role)
// Coalesce consecutive function responses into one user message (Gemini requires
// one turn carrying a functionResponse part for each parallel functionCall).
let functionResponse = try toGeminiFunctionResponse(toolOutput)
messages.append(
.init(
role: .user,
parts: [.functionResponse(functionResponse)]
)
)
pendingFunctionResponses.append(.functionResponse(functionResponse))
}
}
flushFunctionResponses()
return messages
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ import Testing

let bodies = StubURLProtocol.recordedBodies
try #require(bodies.count == 3)
#expect(try bodies.map { try contentCount(in: $0) } == [1, 4, 6])
#expect(try bodies.map { try contentCount(in: $0) } == [1, 3, 5])
for body in bodies.dropFirst() {
try expectParts(parts, in: contents(in: body)[1])
}
Expand Down
189 changes: 189 additions & 0 deletions Tests/AnyLanguageModelTests/GeminiToolResponseTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import Foundation
import Testing

@testable import AnyLanguageModel

/// Parallel function calls in Gemini must be answered by one `user` content
/// carrying a `functionResponse` part for each call in order.
@Suite("Gemini tool responses")
struct GeminiToolResponseTests {
private static func model(_ transport: FakeTransport) -> any LanguageModel {
GeminiLanguageModel(apiKey: "test", model: "test", transport: transport)
}

private static func json(_ object: [String: Any]) throws -> String {
String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self)
}

private static func reply(parts: [[String: Any]], streaming: Bool) throws -> FakeTransport.Reply {
let body = try json(["candidates": [["content": ["role": "model", "parts": parts], "finishReason": "STOP"]]])
return .init(chunks: [streaming ? "data: \(body)\n\n" : body])
}

private static func call(_ name: String, city: String) -> [String: Any] {
["functionCall": ["name": name, "args": ["city": city]]]
}

private static func text(_ text: String) -> [String: Any] {
["text": text]
}

private static func ask(_ session: LanguageModelSession, _ prompt: String, streaming: Bool) async throws -> String {
try await streaming ? session.streamResponse(to: prompt).collect().content : session.respond(to: prompt).content
}

private static func contents(in body: Data) throws -> [[String: Any]] {
let json = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any])
return try #require(json["contents"] as? [[String: Any]])
}

private static func functionResponses(in content: [String: Any]) throws -> [(name: String, result: String)] {
let parts = try #require(content["parts"] as? [[String: Any]])
return try parts.map { part in
let response = try #require(part["functionResponse"] as? [String: Any])
let name = try #require(response["name"] as? String)
let payload = try #require(response["response"] as? [String: Any])
let result = try #require(payload["result"] as? String)
return (name: name, result: result)
}
}

@Test(arguments: [false, true])
func parallelFunctionCallsContinueAndReplayInOneUserContent(streaming: Bool) async throws {
let transport = FakeTransport(replies: [
try Self.reply(
parts: [Self.call("getWeather", city: "Paris"), Self.call("getTime", city: "Tokyo")],
streaming: streaming
),
try Self.reply(parts: [Self.text("Paris is sunny and it's noon in Tokyo.")], streaming: streaming),
try Self.reply(parts: [Self.text("You're welcome.")], streaming: streaming),
])
let session = LanguageModelSession(model: Self.model(transport), tools: [WeatherTool(), ClockTool()])
_ = try await Self.ask(session, "Weather in Paris and time in Tokyo?", streaming: streaming)
_ = try await Self.ask(session, "Thanks", streaming: streaming)

try #require(transport.bodies.count == 3)

// Continuation request after parallel tool execution.
let continuation = try Self.contents(in: transport.bodies[1])
#expect(continuation.map { $0["role"] as? String } == ["user", "model", "user"])
let continuationResponses = try Self.functionResponses(in: continuation[2])
#expect(continuationResponses.map(\.name) == ["getWeather", "getTime"])
#expect(
continuationResponses.map(\.result) == [
"The weather in Paris is sunny and 72°F / 23°C",
"It's noon in Tokyo",
]
)

// Subsequent turn replay keeps both function responses in one user content.
let replay = try Self.contents(in: transport.bodies[2])
#expect(replay.map { $0["role"] as? String } == ["user", "model", "user", "model", "user"])
let replayResponses = try Self.functionResponses(in: replay[2])
#expect(replayResponses.map(\.name) == ["getWeather", "getTime"])
#expect(
replayResponses.map(\.result) == [
"The weather in Paris is sunny and 72°F / 23°C",
"It's noon in Tokyo",
]
)
}

@Test(arguments: [false, true])
func parallelFunctionOutputsWithDynamicProfileContinueInOneUserContent(streaming: Bool) async throws {
let transport = FakeTransport(replies: [
try Self.reply(
parts: [Self.call("getWeather", city: "Paris"), Self.call("getTime", city: "Tokyo")],
streaming: streaming
),
try Self.reply(parts: [Self.text("Done.")], streaming: streaming),
])
let session = LanguageModelSession(
profile: LanguageModelSession.Profile {
WeatherTool()
ClockTool()
}
.model(Self.model(transport))
.historyTransform { entries in
entries.map { entry in
guard case .toolOutput(var output) = entry, output.toolName == "getTime" else {
return entry
}
output.segments = [.text(.init(content: "REDACTED"))]
return .toolOutput(output)
}
}
)
_ = try await Self.ask(session, "Weather in Paris and time in Tokyo?", streaming: streaming)

try #require(transport.bodies.count == 2)
let continuation = try Self.contents(in: transport.bodies[1])
#expect(continuation.map { $0["role"] as? String } == ["user", "model", "user"])
let responses = try Self.functionResponses(in: continuation[2])
#expect(responses.map(\.name) == ["getWeather", "getTime"])
#expect(
responses.map(\.result) == [
"The weather in Paris is sunny and 72°F / 23°C",
"REDACTED",
]
)
}

@Test(arguments: [false, true])
func stoppedParallelFunctionCallsReplayInOneUserContentBeforeNextPrompt(streaming: Bool) async throws {
let transport = FakeTransport(replies: [
try Self.reply(
parts: [Self.call("getWeather", city: "Paris"), Self.call("getTime", city: "Tokyo")],
streaming: streaming
),
try Self.reply(parts: [Self.text("Okay.")], streaming: streaming),
])
let session = LanguageModelSession(model: Self.model(transport), tools: [WeatherTool(), ClockTool()])
session.toolExecutionDelegate = StopToolExecutionDelegate()
_ = try await Self.ask(session, "Weather in Paris and time in Tokyo?", streaming: streaming)
_ = try await Self.ask(session, "Never mind", streaming: streaming)

try #require(transport.bodies.count == 2)
let replay = try Self.contents(in: transport.bodies[1])
#expect(replay.map { $0["role"] as? String } == ["user", "model", "user", "user"])
let responses = try Self.functionResponses(in: replay[2])
#expect(responses.map(\.name) == ["getWeather", "getTime"])
#expect(responses.allSatisfy { $0.result.contains("not executed") })
let followUpParts = try #require(replay[3]["parts"] as? [[String: Any]])
#expect(followUpParts.compactMap { $0["text"] as? String } == ["Never mind"])
}

@Test(arguments: [false, true])
func pendingPromptAfterParallelFunctionCallsStaysInSeparateUserContent(streaming: Bool) async throws {
let transport = FakeTransport(replies: [
try Self.reply(
parts: [Self.call("getWeather", city: "Paris"), Self.call("getTime", city: "Tokyo")],
streaming: streaming
),
try Self.reply(parts: [Self.text("Brief answer.")], streaming: streaming),
])
let session = LanguageModelSession(model: Self.model(transport), tools: [WeatherTool(), ClockTool()])
session.toolExecutionDelegate = SteeringToolDelegate()
_ = try await Self.ask(session, "Weather in Paris and time in Tokyo?", streaming: streaming)

try #require(transport.bodies.count == 2)
let continuation = try Self.contents(in: transport.bodies[1])
#expect(continuation.map { $0["role"] as? String } == ["user", "model", "user", "user"])
let responses = try Self.functionResponses(in: continuation[2])
#expect(responses.map(\.name) == ["getWeather", "getTime"])
let steeringParts = try #require(continuation[3]["parts"] as? [[String: Any]])
#expect(steeringParts.compactMap { $0["text"] as? String } == ["Be brief."])
}
}

private final class SteeringToolDelegate: ToolExecutionDelegate, @unchecked Sendable {
private let lock = NSLock()
private var pending = [AnyLanguageModel.Prompt("Be brief.")]

func pendingMessages(in session: LanguageModelSession) async -> [AnyLanguageModel.Prompt] {
lock.withLock {
defer { pending = [] }
return pending
}
}
}