Skip to content

Commit

Permalink
Add functionCalls accessor to GenerateContentResponse (google-gemini#123
Browse files Browse the repository at this point in the history
)
  • Loading branch information
andrewheard authored and G.Dev.Ssomsak committed Jun 21, 2024
1 parent 62a13f1 commit ab4f33c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Sources/GoogleAI/GenerateContentResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ public struct GenerateContentResponse {
return text
}

/// Returns function calls found in any `Part`s of the first candidate of the response, if any.
public var functionCalls: [FunctionCall] {
guard let candidate = candidates.first else {
return []
}
return candidate.content.parts.compactMap { part in
guard case let .functionCall(functionCall) = part else {
return nil
}
return functionCall
}
}

/// Initializer for SwiftUI previews or tests.
public init(candidates: [CandidateResponse], promptFeedback: PromptFeedback?) {
self.candidates = candidates
Expand Down
5 changes: 5 additions & 0 deletions Tests/GoogleAITests/GenerativeModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ final class GenerativeModelTests: XCTestCase {
let promptFeedback = try XCTUnwrap(response.promptFeedback)
XCTAssertNil(promptFeedback.blockReason)
XCTAssertEqual(promptFeedback.safetyRatings, safetyRatingsNegligible)
XCTAssertEqual(response.functionCalls, [])
}

func testGenerateContent_success_basicReplyShort() async throws {
Expand All @@ -86,6 +87,7 @@ final class GenerativeModelTests: XCTestCase {
let promptFeedback = try XCTUnwrap(response.promptFeedback)
XCTAssertNil(promptFeedback.blockReason)
XCTAssertEqual(promptFeedback.safetyRatings, safetyRatingsNegligible)
XCTAssertEqual(response.functionCalls, [])
}

func testGenerateContent_success_citations() async throws {
Expand Down Expand Up @@ -188,6 +190,7 @@ final class GenerativeModelTests: XCTestCase {
}
XCTAssertEqual(functionCall.name, "current_time")
XCTAssertTrue(functionCall.args.isEmpty)
XCTAssertEqual(response.functionCalls, [functionCall])
}

func testGenerateContent_success_functionCall_noArguments() async throws {
Expand All @@ -209,6 +212,7 @@ final class GenerativeModelTests: XCTestCase {
}
XCTAssertEqual(functionCall.name, "current_time")
XCTAssertTrue(functionCall.args.isEmpty)
XCTAssertEqual(response.functionCalls, [functionCall])
}

func testGenerateContent_success_functionCall_withArguments() async throws {
Expand All @@ -234,6 +238,7 @@ final class GenerativeModelTests: XCTestCase {
XCTAssertEqual(argX, .number(4))
let argY = try XCTUnwrap(functionCall.args["y"])
XCTAssertEqual(argY, .number(5))
XCTAssertEqual(response.functionCalls, [functionCall])
}

func testGenerateContent_failure_invalidAPIKey() async throws {
Expand Down

0 comments on commit ab4f33c

Please sign in to comment.