Skip to content

Commit 7e8029e

Browse files
andrewheardG.Dev.Ssomsak
authored and
G.Dev.Ssomsak
committed
Make text computed property handle mixed-parts responses (google-gemini#165)
1 parent 440a2e2 commit 7e8029e

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

Sources/GoogleAI/GenerateContentResponse.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,17 @@ public struct GenerateContentResponse {
4545
Logging.default.error("Could not get text from a response that had no candidates.")
4646
return nil
4747
}
48-
guard let text = candidate.content.parts.first?.text else {
48+
let textValues: [String] = candidate.content.parts.compactMap { part in
49+
guard case let .text(text) = part else {
50+
return nil
51+
}
52+
return text
53+
}
54+
guard textValues.count > 0 else {
4955
Logging.default.error("Could not get a text part from the first candidate.")
5056
return nil
5157
}
52-
return text
58+
return textValues.joined(separator: " ")
5359
}
5460

5561
/// Returns function calls found in any `Part`s of the first candidate of the response, if any.

Tests/GoogleAITests/GenerativeModelTests.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,40 @@ final class GenerativeModelTests: XCTestCase {
254254
XCTAssertEqual(response.functionCalls, [functionCall])
255255
}
256256

257+
func testGenerateContent_success_functionCall_parallelCalls() async throws {
258+
MockURLProtocol
259+
.requestHandler = try httpRequestHandler(
260+
forResource: "unary-success-function-call-parallel-calls",
261+
withExtension: "json"
262+
)
263+
264+
let response = try await model.generateContent(testPrompt)
265+
266+
XCTAssertEqual(response.candidates.count, 1)
267+
let candidate = try XCTUnwrap(response.candidates.first)
268+
XCTAssertEqual(candidate.content.parts.count, 3)
269+
let functionCalls = response.functionCalls
270+
XCTAssertEqual(functionCalls.count, 3)
271+
}
272+
273+
func testGenerateContent_success_functionCall_mixedContent() async throws {
274+
MockURLProtocol
275+
.requestHandler = try httpRequestHandler(
276+
forResource: "unary-success-function-call-mixed-content",
277+
withExtension: "json"
278+
)
279+
280+
let response = try await model.generateContent(testPrompt)
281+
282+
XCTAssertEqual(response.candidates.count, 1)
283+
let candidate = try XCTUnwrap(response.candidates.first)
284+
XCTAssertEqual(candidate.content.parts.count, 4)
285+
let functionCalls = response.functionCalls
286+
XCTAssertEqual(functionCalls.count, 2)
287+
let text = try XCTUnwrap(response.text)
288+
XCTAssertEqual(text, "The sum of [1, 2, 3] is")
289+
}
290+
257291
func testGenerateContent_usageMetadata() async throws {
258292
MockURLProtocol
259293
.requestHandler = try httpRequestHandler(

0 commit comments

Comments
 (0)