2024-03-19 15:44:55 +00:00
|
|
|
// Copyright 2023 Google LLC
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
|
//
|
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
//
|
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
2024-03-20 14:11:28 +00:00
|
|
|
import FirebaseAppCheckInterop
|
2024-04-29 16:17:48 -04:00
|
|
|
import FirebaseAuthInterop
|
2024-04-02 17:11:08 +00:00
|
|
|
import FirebaseCore
|
2024-03-19 15:44:55 +00:00
|
|
|
import XCTest
|
|
|
|
|
|
2025-04-23 17:53:11 -04:00
|
|
|
@testable import FirebaseAI
|
2024-03-19 20:59:05 +00:00
|
|
|
|
2024-07-02 17:15:33 -04:00
|
|
|
@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
|
2024-03-19 15:44:55 +00:00
|
|
|
final class GenerativeModelTests: XCTestCase {
|
|
|
|
|
let testPrompt = "What sorts of questions can I ask you?"
|
|
|
|
|
let safetyRatingsNegligible: [SafetyRating] = [
|
2024-10-14 13:36:37 -04:00
|
|
|
.init(
|
|
|
|
|
category: .sexuallyExplicit,
|
|
|
|
|
probability: .negligible,
|
|
|
|
|
probabilityScore: 0.1431877,
|
|
|
|
|
severity: .negligible,
|
|
|
|
|
severityScore: 0.11027937,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
|
|
|
|
.init(
|
|
|
|
|
category: .hateSpeech,
|
|
|
|
|
probability: .negligible,
|
|
|
|
|
probabilityScore: 0.029035643,
|
|
|
|
|
severity: .negligible,
|
|
|
|
|
severityScore: 0.05613278,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
|
|
|
|
.init(
|
|
|
|
|
category: .harassment,
|
|
|
|
|
probability: .negligible,
|
|
|
|
|
probabilityScore: 0.087252244,
|
|
|
|
|
severity: .negligible,
|
|
|
|
|
severityScore: 0.04509957,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
|
|
|
|
.init(
|
|
|
|
|
category: .dangerousContent,
|
|
|
|
|
probability: .negligible,
|
|
|
|
|
probabilityScore: 0.2641685,
|
|
|
|
|
severity: .negligible,
|
|
|
|
|
severityScore: 0.082253955,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
2024-03-22 21:06:39 +00:00
|
|
|
].sorted()
|
2025-04-09 19:14:41 -04:00
|
|
|
let testModelName = "test-model"
|
2024-08-26 15:48:34 -04:00
|
|
|
let testModelResourceName =
|
|
|
|
|
"projects/test-project-id/locations/test-location/publishers/google/models/test-model"
|
2025-04-23 17:53:11 -04:00
|
|
|
let apiConfig = FirebaseAI.defaultVertexAIAPIConfig
|
2024-03-19 15:44:55 +00:00
|
|
|
|
2025-03-17 17:20:27 -04:00
|
|
|
let vertexSubdirectory = "vertexai"
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
var urlSession: URLSession!
|
|
|
|
|
var model: GenerativeModel!
|
|
|
|
|
|
|
|
|
|
override func setUp() async throws {
|
|
|
|
|
let configuration = URLSessionConfiguration.default
|
|
|
|
|
configuration.protocolClasses = [MockURLProtocol.self]
|
|
|
|
|
urlSession = try XCTUnwrap(URLSession(configuration: configuration))
|
2024-03-19 20:59:05 +00:00
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-19 20:59:05 +00:00
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
override func tearDown() {
|
|
|
|
|
MockURLProtocol.requestHandler = nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Generate Content
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_basicReplyLong() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-long",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
let finishReason = try XCTUnwrap(candidate.finishReason)
|
|
|
|
|
XCTAssertEqual(finishReason, .stop)
|
2024-10-14 13:36:37 -04:00
|
|
|
XCTAssertEqual(candidate.safetyRatings.count, 4)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
let partText = try XCTUnwrap(part as? TextPart).text
|
2024-06-19 13:35:17 -04:00
|
|
|
XCTAssertTrue(partText.hasPrefix("1. **Use Freshly Ground Coffee**:"))
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(response.text, partText)
|
2024-04-03 16:12:40 +00:00
|
|
|
XCTAssertEqual(response.functionCalls, [])
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_basicReplyShort() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
let finishReason = try XCTUnwrap(candidate.finishReason)
|
|
|
|
|
XCTAssertEqual(finishReason, .stop)
|
2024-03-22 21:06:39 +00:00
|
|
|
XCTAssertEqual(candidate.safetyRatings.sorted(), safetyRatingsNegligible)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
let textPart = try XCTUnwrap(part as? TextPart)
|
|
|
|
|
XCTAssertEqual(textPart.text, "Mountain View, California")
|
|
|
|
|
XCTAssertEqual(response.text, textPart.text)
|
2024-04-03 16:12:40 +00:00
|
|
|
XCTAssertEqual(response.functionCalls, [])
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
2025-02-11 15:41:25 -05:00
|
|
|
func testGenerateContent_success_basicReplyFullUsageMetadata() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-response-long-usage-metadata",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2025-02-11 15:41:25 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
let finishReason = try XCTUnwrap(candidate.finishReason)
|
|
|
|
|
XCTAssertEqual(finishReason, .stop)
|
|
|
|
|
let usageMetadata = try XCTUnwrap(response.usageMetadata)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails.count, 2)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails[0].modality, .image)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails[0].tokenCount, 1806)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails[1].modality, .text)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails[1].tokenCount, 76)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokensDetails.count, 1)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokensDetails[0].modality, .text)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokensDetails[0].tokenCount, 76)
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testGenerateContent_success_citations() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-citations",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-15 18:45:48 -04:00
|
|
|
let expectedPublicationDate = DateComponents(
|
|
|
|
|
calendar: Calendar(identifier: .gregorian),
|
|
|
|
|
year: 2019,
|
|
|
|
|
month: 5,
|
|
|
|
|
day: 10
|
|
|
|
|
)
|
2024-03-19 15:44:55 +00:00
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
XCTAssertEqual(response.text, "Some information cited from an external source")
|
|
|
|
|
let citationMetadata = try XCTUnwrap(candidate.citationMetadata)
|
2024-09-23 21:27:12 -04:00
|
|
|
XCTAssertEqual(citationMetadata.citations.count, 3)
|
|
|
|
|
let citationSource1 = try XCTUnwrap(citationMetadata.citations[0])
|
2024-04-22 14:54:42 -04:00
|
|
|
XCTAssertEqual(citationSource1.uri, "https://www.example.com/some-citation-1")
|
|
|
|
|
XCTAssertEqual(citationSource1.startIndex, 0)
|
|
|
|
|
XCTAssertEqual(citationSource1.endIndex, 128)
|
2024-08-19 17:33:15 -04:00
|
|
|
XCTAssertNil(citationSource1.title)
|
2024-04-22 14:54:42 -04:00
|
|
|
XCTAssertNil(citationSource1.license)
|
2024-10-15 18:45:48 -04:00
|
|
|
XCTAssertNil(citationSource1.publicationDate)
|
2024-09-23 21:27:12 -04:00
|
|
|
let citationSource2 = try XCTUnwrap(citationMetadata.citations[1])
|
2024-08-19 17:33:15 -04:00
|
|
|
XCTAssertEqual(citationSource2.title, "some-citation-2")
|
2024-10-15 18:45:48 -04:00
|
|
|
XCTAssertEqual(citationSource2.publicationDate, expectedPublicationDate)
|
2024-04-22 14:54:42 -04:00
|
|
|
XCTAssertEqual(citationSource2.startIndex, 130)
|
|
|
|
|
XCTAssertEqual(citationSource2.endIndex, 265)
|
2024-08-19 17:33:15 -04:00
|
|
|
XCTAssertNil(citationSource2.uri)
|
2024-04-22 14:54:42 -04:00
|
|
|
XCTAssertNil(citationSource2.license)
|
2024-09-23 21:27:12 -04:00
|
|
|
let citationSource3 = try XCTUnwrap(citationMetadata.citations[2])
|
2024-04-22 14:54:42 -04:00
|
|
|
XCTAssertEqual(citationSource3.uri, "https://www.example.com/some-citation-3")
|
|
|
|
|
XCTAssertEqual(citationSource3.startIndex, 272)
|
|
|
|
|
XCTAssertEqual(citationSource3.endIndex, 431)
|
|
|
|
|
XCTAssertEqual(citationSource3.license, "mit")
|
2024-08-19 17:33:15 -04:00
|
|
|
XCTAssertNil(citationSource3.title)
|
2024-10-15 18:45:48 -04:00
|
|
|
XCTAssertNil(citationSource3.publicationDate)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_quoteReply() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-quote-reply",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
let finishReason = try XCTUnwrap(candidate.finishReason)
|
|
|
|
|
XCTAssertEqual(finishReason, .stop)
|
2024-10-14 13:36:37 -04:00
|
|
|
XCTAssertEqual(candidate.safetyRatings.count, 4)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
let textPart = try XCTUnwrap(part as? TextPart)
|
|
|
|
|
XCTAssertTrue(textPart.text.hasPrefix("Google"))
|
|
|
|
|
XCTAssertEqual(response.text, textPart.text)
|
2024-03-19 15:44:55 +00:00
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
|
|
|
|
XCTAssertNil(promptFeedback.blockReason)
|
2024-10-14 13:36:37 -04:00
|
|
|
XCTAssertEqual(promptFeedback.safetyRatings.count, 4)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_unknownEnum_safetyRatings() async throws {
|
|
|
|
|
let expectedSafetyRatings = [
|
2024-10-14 13:36:37 -04:00
|
|
|
SafetyRating(
|
|
|
|
|
category: .harassment,
|
|
|
|
|
probability: .medium,
|
|
|
|
|
probabilityScore: 0.0,
|
|
|
|
|
severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
|
|
|
|
|
severityScore: 0.0,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
2024-10-08 20:47:21 -04:00
|
|
|
SafetyRating(
|
|
|
|
|
category: .dangerousContent,
|
2024-10-14 13:36:37 -04:00
|
|
|
probability: SafetyRating.HarmProbability(rawValue: "FAKE_NEW_HARM_PROBABILITY"),
|
|
|
|
|
probabilityScore: 0.0,
|
|
|
|
|
severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
|
|
|
|
|
severityScore: 0.0,
|
|
|
|
|
blocked: false
|
|
|
|
|
),
|
|
|
|
|
SafetyRating(
|
|
|
|
|
category: HarmCategory(rawValue: "FAKE_NEW_HARM_CATEGORY"),
|
|
|
|
|
probability: .high,
|
|
|
|
|
probabilityScore: 0.0,
|
|
|
|
|
severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
|
|
|
|
|
severityScore: 0.0,
|
|
|
|
|
blocked: false
|
2024-10-08 20:47:21 -04:00
|
|
|
),
|
2024-03-19 15:44:55 +00:00
|
|
|
]
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-unknown-enum-safety-ratings",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.text, "Some text")
|
|
|
|
|
XCTAssertEqual(response.candidates.first?.safetyRatings, expectedSafetyRatings)
|
|
|
|
|
XCTAssertEqual(response.promptFeedback?.safetyRatings, expectedSafetyRatings)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_prefixedModelName() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
let model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
|
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-19 20:59:05 +00:00
|
|
|
requestOptions: RequestOptions(),
|
2024-03-19 15:44:55 +00:00
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-27 14:34:49 +00:00
|
|
|
func testGenerateContent_success_functionCall_emptyArguments() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-function-call-empty-arguments",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-27 14:34:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
guard let functionCall = part as? FunctionCallPart else {
|
2024-03-27 14:34:49 +00:00
|
|
|
XCTFail("Part is not a FunctionCall.")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssertEqual(functionCall.name, "current_time")
|
|
|
|
|
XCTAssertTrue(functionCall.args.isEmpty)
|
2024-04-03 16:12:40 +00:00
|
|
|
XCTAssertEqual(response.functionCalls, [functionCall])
|
2024-03-27 14:34:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_functionCall_noArguments() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-function-call-no-arguments",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-27 14:34:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
guard let functionCall = part as? FunctionCallPart else {
|
2024-03-27 14:34:49 +00:00
|
|
|
XCTFail("Part is not a FunctionCall.")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssertEqual(functionCall.name, "current_time")
|
|
|
|
|
XCTAssertTrue(functionCall.args.isEmpty)
|
2024-04-03 16:12:40 +00:00
|
|
|
XCTAssertEqual(response.functionCalls, [functionCall])
|
2024-03-27 14:34:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_functionCall_withArguments() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-function-call-with-arguments",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-27 14:34:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 1)
|
|
|
|
|
let part = try XCTUnwrap(candidate.content.parts.first)
|
2024-10-07 15:37:58 -04:00
|
|
|
guard let functionCall = part as? FunctionCallPart else {
|
2024-03-27 14:34:49 +00:00
|
|
|
XCTFail("Part is not a FunctionCall.")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssertEqual(functionCall.name, "sum")
|
|
|
|
|
XCTAssertEqual(functionCall.args.count, 2)
|
|
|
|
|
let argX = try XCTUnwrap(functionCall.args["x"])
|
|
|
|
|
XCTAssertEqual(argX, .number(4))
|
|
|
|
|
let argY = try XCTUnwrap(functionCall.args["y"])
|
|
|
|
|
XCTAssertEqual(argY, .number(5))
|
2024-04-03 16:12:40 +00:00
|
|
|
XCTAssertEqual(response.functionCalls, [functionCall])
|
2024-03-27 14:34:49 +00:00
|
|
|
}
|
|
|
|
|
|
2024-05-08 16:59:42 -04:00
|
|
|
func testGenerateContent_success_functionCall_parallelCalls() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-function-call-parallel-calls",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-05-08 16:59:42 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 3)
|
|
|
|
|
let functionCalls = response.functionCalls
|
|
|
|
|
XCTAssertEqual(functionCalls.count, 3)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_success_functionCall_mixedContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-function-call-mixed-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-05-08 16:59:42 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.content.parts.count, 4)
|
|
|
|
|
let functionCalls = response.functionCalls
|
|
|
|
|
XCTAssertEqual(functionCalls.count, 2)
|
|
|
|
|
let text = try XCTUnwrap(response.text)
|
|
|
|
|
XCTAssertEqual(text, "The sum of [1, 2, 3] is")
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-20 14:11:28 +00:00
|
|
|
func testGenerateContent_appCheck_validToken() async throws {
|
|
|
|
|
let appCheckToken = "test-valid-token"
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(appCheck: AppCheckInteropFake(token: appCheckToken)),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-20 14:11:28 +00:00
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-20 14:11:28 +00:00
|
|
|
appCheckToken: appCheckToken
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-25 11:54:15 -08:00
|
|
|
func testGenerateContent_dataCollectionOff() async throws {
|
|
|
|
|
let appCheckToken = "test-valid-token"
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(appCheck: AppCheckInteropFake(token: appCheckToken),
|
|
|
|
|
privateAppID: true),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2025-02-25 11:54:15 -08:00
|
|
|
tools: nil,
|
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2025-02-25 11:54:15 -08:00
|
|
|
appCheckToken: appCheckToken,
|
|
|
|
|
dataCollection: false
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-20 14:11:28 +00:00
|
|
|
func testGenerateContent_appCheck_tokenRefreshError() async throws {
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(appCheck: AppCheckInteropFake(error: AppCheckErrorFake())),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-20 14:11:28 +00:00
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-20 14:11:28 +00:00
|
|
|
appCheckToken: AppCheckInteropFake.placeholderTokenValue
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-29 16:17:48 -04:00
|
|
|
func testGenerateContent_auth_validAuthToken() async throws {
|
|
|
|
|
let authToken = "test-valid-token"
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(auth: AuthInteropFake(token: authToken)),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-04-29 16:17:48 -04:00
|
|
|
tools: nil,
|
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-04-29 16:17:48 -04:00
|
|
|
authToken: authToken
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_auth_nilAuthToken() async throws {
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(auth: AuthInteropFake(token: nil)),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-04-29 16:17:48 -04:00
|
|
|
tools: nil,
|
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-04-29 16:17:48 -04:00
|
|
|
authToken: nil
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_auth_authTokenRefreshError() async throws {
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
|
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(auth: AuthInteropFake(error: AuthErrorFake())),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-04-29 16:17:48 -04:00
|
|
|
tools: nil,
|
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-04-29 16:17:48 -04:00
|
|
|
authToken: nil
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw internalError(AuthErrorFake); no error.")
|
|
|
|
|
} catch GenerateContentError.internalError(_ as AuthErrorFake) {
|
|
|
|
|
//
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw internalError(AuthErrorFake); error thrown: \(error)")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-12 17:21:01 -04:00
|
|
|
func testGenerateContent_usageMetadata() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-04-12 17:21:01 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
let usageMetadata = try XCTUnwrap(response.usageMetadata)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokenCount, 6)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokenCount, 7)
|
|
|
|
|
XCTAssertEqual(usageMetadata.totalTokenCount, 13)
|
2025-02-11 15:41:25 -05:00
|
|
|
XCTAssertEqual(usageMetadata.promptTokensDetails.isEmpty, true)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokensDetails.isEmpty, true)
|
2024-04-12 17:21:01 -04:00
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testGenerateContent_failure_invalidAPIKey() async throws {
|
|
|
|
|
let expectedStatusCode = 400
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-api-key",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
statusCode: expectedStatusCode
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(error as BackendError) {
|
2024-03-19 20:59:05 +00:00
|
|
|
XCTAssertEqual(error.httpResponseCode, 400)
|
|
|
|
|
XCTAssertEqual(error.status, .invalidArgument)
|
|
|
|
|
XCTAssertEqual(error.message, "API key not valid. Please pass a valid API key.")
|
2024-11-05 11:12:12 -05:00
|
|
|
XCTAssertTrue(error.localizedDescription.contains(error.message))
|
|
|
|
|
XCTAssertTrue(error.localizedDescription.contains(error.status.rawValue))
|
|
|
|
|
XCTAssertTrue(error.localizedDescription.contains("\(error.httpResponseCode)"))
|
|
|
|
|
let nsError = error as NSError
|
|
|
|
|
XCTAssertEqual(nsError.domain, "\(Constants.baseErrorDomain).\(BackendError.self)")
|
|
|
|
|
XCTAssertEqual(nsError.code, error.httpResponseCode)
|
2024-03-19 20:59:05 +00:00
|
|
|
return
|
2024-03-19 15:44:55 +00:00
|
|
|
} catch {
|
2024-03-19 20:59:05 +00:00
|
|
|
XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-25 18:22:56 -04:00
|
|
|
func testGenerateContent_failure_firebaseVertexAIAPINotEnabled() async throws {
|
|
|
|
|
let expectedStatusCode = 403
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-firebasevertexai-api-not-enabled",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-09-25 18:22:56 -04:00
|
|
|
statusCode: expectedStatusCode
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(error as BackendError) {
|
2024-09-25 18:22:56 -04:00
|
|
|
XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
|
|
|
|
|
XCTAssertEqual(error.status, .permissionDenied)
|
|
|
|
|
XCTAssertTrue(error.message
|
|
|
|
|
.starts(with: "Vertex AI in Firebase API has not been used in project"))
|
|
|
|
|
XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
|
|
|
|
|
return
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testGenerateContent_failure_emptyContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-empty-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
|
|
|
|
|
} catch let GenerateContentError
|
|
|
|
|
.internalError(underlying: invalidCandidateError as InvalidCandidateError) {
|
|
|
|
|
guard case let .emptyContent(decodingError) = invalidCandidateError else {
|
|
|
|
|
XCTFail("Not an InvalidCandidateError.emptyContent error: \(invalidCandidateError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
_ = try XCTUnwrap(decodingError as? DecodingError,
|
|
|
|
|
"Not a DecodingError: \(decodingError)")
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_finishReasonSafety() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-finish-reason-safety",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.responseStoppedEarly(reason, response) {
|
|
|
|
|
XCTAssertEqual(reason, .safety)
|
2024-06-19 13:35:17 -04:00
|
|
|
XCTAssertEqual(response.text, "<redacted>")
|
2024-03-19 15:44:55 +00:00
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a responseStoppedEarly")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_finishReasonSafety_noContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-finish-reason-safety-no-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.responseStoppedEarly(reason, response) {
|
|
|
|
|
XCTAssertEqual(reason, .safety)
|
|
|
|
|
XCTAssertNil(response.text)
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a responseStoppedEarly")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_imageRejected() async throws {
|
|
|
|
|
let expectedStatusCode = 400
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-image-rejected",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
statusCode: 400
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(underlying: rpcError as BackendError) {
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(rpcError.status, .invalidArgument)
|
|
|
|
|
XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
|
|
|
|
|
XCTAssertEqual(rpcError.message, "Request contains an invalid argument.")
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_promptBlockedSafety() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-prompt-blocked-safety",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.promptBlocked(response) {
|
|
|
|
|
XCTAssertNil(response.text)
|
2024-10-14 17:50:24 -04:00
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
|
|
|
|
|
XCTAssertNil(promptFeedback.blockReasonMessage)
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a promptBlocked")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_promptBlockedSafetyWithMessage() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-prompt-blocked-safety-with-message",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-10-14 17:50:24 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.promptBlocked(response) {
|
|
|
|
|
XCTAssertNil(response.text)
|
|
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
|
2024-03-19 15:44:55 +00:00
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a promptBlocked")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_unknownEnum_finishReason() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-unknown-enum-finish-reason",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-09 16:30:43 -04:00
|
|
|
let unknownFinishReason = FinishReason(rawValue: "FAKE_NEW_FINISH_REASON")
|
2024-03-19 15:44:55 +00:00
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.responseStoppedEarly(reason, response) {
|
2024-10-09 16:30:43 -04:00
|
|
|
XCTAssertEqual(reason, unknownFinishReason)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(response.text, "Some text")
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a responseStoppedEarly")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_unknownEnum_promptBlocked() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-unknown-enum-prompt-blocked",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-09 18:53:17 -04:00
|
|
|
let unknownBlockReason = PromptFeedback.BlockReason(rawValue: "FAKE_NEW_BLOCK_REASON")
|
2024-03-19 15:44:55 +00:00
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw")
|
|
|
|
|
} catch let GenerateContentError.promptBlocked(response) {
|
|
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
2024-10-09 18:53:17 -04:00
|
|
|
XCTAssertEqual(promptFeedback.blockReason, unknownBlockReason)
|
2024-03-19 15:44:55 +00:00
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw a promptBlocked")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_unknownModel() async throws {
|
|
|
|
|
let expectedStatusCode = 404
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-unknown-model",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
statusCode: 404
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.generateContent(testPrompt)
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(underlying: rpcError as BackendError) {
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(rpcError.status, .notFound)
|
|
|
|
|
XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
|
|
|
|
|
XCTAssertTrue(rpcError.message.hasPrefix("models/unknown is not found"))
|
|
|
|
|
} catch {
|
|
|
|
|
XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_nonHTTPResponse() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
|
|
|
|
|
|
|
|
|
|
var responseError: Error?
|
|
|
|
|
var content: GenerateContentResponse?
|
|
|
|
|
do {
|
|
|
|
|
content = try await model.generateContent(testPrompt)
|
|
|
|
|
} catch {
|
|
|
|
|
responseError = error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssertNil(content)
|
|
|
|
|
XCTAssertNotNil(responseError)
|
|
|
|
|
let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
|
|
|
|
|
guard case let .internalError(underlyingError) = generateContentError else {
|
|
|
|
|
XCTFail("Not an internal error: \(generateContentError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssertEqual(underlyingError.localizedDescription, "Response was not an HTTP response.")
|
2024-11-05 16:32:47 -05:00
|
|
|
let underlyingNSError = underlyingError as NSError
|
|
|
|
|
XCTAssertEqual(underlyingNSError.domain, NSURLErrorDomain)
|
|
|
|
|
XCTAssertEqual(underlyingNSError.code, URLError.Code.badServerResponse.rawValue)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_invalidResponse() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-invalid-response",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responseError: Error?
|
|
|
|
|
var content: GenerateContentResponse?
|
|
|
|
|
do {
|
|
|
|
|
content = try await model.generateContent(testPrompt)
|
|
|
|
|
} catch {
|
|
|
|
|
responseError = error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssertNil(content)
|
|
|
|
|
XCTAssertNotNil(responseError)
|
|
|
|
|
let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
|
|
|
|
|
guard case let .internalError(underlyingError) = generateContentError else {
|
|
|
|
|
XCTFail("Not an internal error: \(generateContentError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
let decodingError = try XCTUnwrap(underlyingError as? DecodingError)
|
|
|
|
|
guard case let .dataCorrupted(context) = decodingError else {
|
|
|
|
|
XCTFail("Not a data corrupted error: \(decodingError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_failure_malformedContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-malformed-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responseError: Error?
|
|
|
|
|
var content: GenerateContentResponse?
|
|
|
|
|
do {
|
|
|
|
|
content = try await model.generateContent(testPrompt)
|
|
|
|
|
} catch {
|
|
|
|
|
responseError = error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssertNil(content)
|
|
|
|
|
XCTAssertNotNil(responseError)
|
|
|
|
|
let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
|
|
|
|
|
guard case let .internalError(underlyingError) = generateContentError else {
|
|
|
|
|
XCTFail("Not an internal error: \(generateContentError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
let invalidCandidateError = try XCTUnwrap(underlyingError as? InvalidCandidateError)
|
|
|
|
|
guard case let .malformedContent(malformedContentUnderlyingError) = invalidCandidateError else {
|
|
|
|
|
XCTFail("Not a malformed content error: \(invalidCandidateError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
_ = try XCTUnwrap(
|
|
|
|
|
malformedContentUnderlyingError as? DecodingError,
|
|
|
|
|
"Not a decoding error: \(malformedContentUnderlyingError)"
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentMissingSafetyRatings() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-missing-safety-ratings",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let content = try await model.generateContent(testPrompt)
|
|
|
|
|
let promptFeedback = try XCTUnwrap(content.promptFeedback)
|
|
|
|
|
XCTAssertEqual(promptFeedback.safetyRatings.count, 0)
|
|
|
|
|
XCTAssertEqual(content.text, "This is the generated content.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContent_requestOptions_customTimeout() async throws {
|
|
|
|
|
let expectedTimeout = 150.0
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-basic-reply-short",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
timeout: expectedTimeout
|
|
|
|
|
)
|
|
|
|
|
let requestOptions = RequestOptions(timeout: expectedTimeout)
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-19 15:44:55 +00:00
|
|
|
requestOptions: requestOptions,
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.generateContent(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.candidates.count, 1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Generate Content (Streaming)
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_failureInvalidAPIKey() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-api-key",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("No content is there, this shouldn't happen.")
|
|
|
|
|
}
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(error as BackendError) {
|
2024-03-19 20:59:05 +00:00
|
|
|
XCTAssertEqual(error.httpResponseCode, 400)
|
|
|
|
|
XCTAssertEqual(error.status, .invalidArgument)
|
|
|
|
|
XCTAssertEqual(error.message, "API key not valid. Please pass a valid API key.")
|
2024-11-05 11:12:12 -05:00
|
|
|
XCTAssertTrue(error.localizedDescription.contains(error.message))
|
|
|
|
|
XCTAssertTrue(error.localizedDescription.contains(error.status.rawValue))
|
|
|
|
|
XCTAssertTrue(error.localizedDescription.contains("\(error.httpResponseCode)"))
|
|
|
|
|
let nsError = error as NSError
|
|
|
|
|
XCTAssertEqual(nsError.domain, "\(Constants.baseErrorDomain).\(BackendError.self)")
|
|
|
|
|
XCTAssertEqual(nsError.code, error.httpResponseCode)
|
2024-03-19 15:44:55 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-25 18:22:56 -04:00
|
|
|
func testGenerateContentStream_failure_vertexAIInFirebaseAPINotEnabled() async throws {
|
|
|
|
|
let expectedStatusCode = 403
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-failure-firebasevertexai-api-not-enabled",
|
|
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-09-25 18:22:56 -04:00
|
|
|
statusCode: expectedStatusCode
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
|
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("No content is there, this shouldn't happen.")
|
|
|
|
|
}
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(error as BackendError) {
|
2024-09-25 18:22:56 -04:00
|
|
|
XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
|
|
|
|
|
XCTAssertEqual(error.status, .permissionDenied)
|
|
|
|
|
XCTAssertTrue(error.message
|
|
|
|
|
.starts(with: "Vertex AI in Firebase API has not been used in project"))
|
|
|
|
|
XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testGenerateContentStream_failureEmptyContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-empty-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("No content is there, this shouldn't happen.")
|
|
|
|
|
}
|
|
|
|
|
} catch GenerateContentError.internalError(_ as InvalidCandidateError) {
|
|
|
|
|
// Underlying error is as expected, nothing else to check.
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_failureFinishReasonSafety() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-finish-reason-safety",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("Content shouldn't be shown, this shouldn't happen.")
|
|
|
|
|
}
|
2024-10-14 13:36:37 -04:00
|
|
|
} catch let GenerateContentError.responseStoppedEarly(reason, response) {
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(reason, .safety)
|
2024-10-14 13:36:37 -04:00
|
|
|
let candidate = try XCTUnwrap(response.candidates.first)
|
|
|
|
|
XCTAssertEqual(candidate.finishReason, reason)
|
|
|
|
|
XCTAssertTrue(candidate.safetyRatings.contains { $0.blocked })
|
2024-03-19 15:44:55 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_failurePromptBlockedSafety() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-prompt-blocked-safety",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("Content shouldn't be shown, this shouldn't happen.")
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.promptBlocked(response) {
|
2024-10-14 17:50:24 -04:00
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReason, .safety)
|
|
|
|
|
XCTAssertNil(promptFeedback.blockReasonMessage)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_failurePromptBlockedSafetyWithMessage() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-prompt-blocked-safety-with-message",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-10-14 17:50:24 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
let stream = try model.generateContentStream("Hi")
|
|
|
|
|
for try await _ in stream {
|
|
|
|
|
XCTFail("Content shouldn't be shown, this shouldn't happen.")
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.promptBlocked(response) {
|
|
|
|
|
let promptFeedback = try XCTUnwrap(response.promptFeedback)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReason, .safety)
|
|
|
|
|
XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
|
2024-03-19 15:44:55 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_failureUnknownFinishEnum() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-unknown-finish-enum",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-09 16:30:43 -04:00
|
|
|
let unknownFinishReason = FinishReason(rawValue: "FAKE_ENUM")
|
2024-03-19 15:44:55 +00:00
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
do {
|
|
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.responseStoppedEarly(reason, _) {
|
2024-10-09 16:30:43 -04:00
|
|
|
XCTAssertEqual(reason, unknownFinishReason)
|
2024-03-19 15:44:55 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Should have caught an error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_successBasicReplyLong() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-long",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responses = 0
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
responses += 1
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-19 13:35:17 -04:00
|
|
|
XCTAssertEqual(responses, 6)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_successBasicReplyShort() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-short",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responses = 0
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
responses += 1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(responses, 1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_successUnknownSafetyEnum() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-unknown-safety-enum",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-08 18:31:09 -04:00
|
|
|
let unknownSafetyRating = SafetyRating(
|
|
|
|
|
category: HarmCategory(rawValue: "HARM_CATEGORY_DANGEROUS_CONTENT_NEW_ENUM"),
|
2024-10-14 13:36:37 -04:00
|
|
|
probability: SafetyRating.HarmProbability(rawValue: "NEGLIGIBLE_UNKNOWN_ENUM"),
|
|
|
|
|
probabilityScore: 0.0,
|
|
|
|
|
severity: SafetyRating.HarmSeverity(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
|
|
|
|
|
severityScore: 0.0,
|
|
|
|
|
blocked: false
|
2024-10-08 18:31:09 -04:00
|
|
|
)
|
2024-03-19 15:44:55 +00:00
|
|
|
|
2024-10-08 18:31:09 -04:00
|
|
|
var foundUnknownSafetyRating = false
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
if let ratings = content.candidates.first?.safetyRatings,
|
2024-10-08 18:31:09 -04:00
|
|
|
ratings.contains(where: { $0 == unknownSafetyRating }) {
|
|
|
|
|
foundUnknownSafetyRating = true
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-08 18:31:09 -04:00
|
|
|
XCTAssertTrue(foundUnknownSafetyRating)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_successWithCitations() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-citations",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
2024-10-15 18:45:48 -04:00
|
|
|
let expectedPublicationDate = DateComponents(
|
|
|
|
|
calendar: Calendar(identifier: .gregorian),
|
|
|
|
|
year: 2014,
|
|
|
|
|
month: 3,
|
|
|
|
|
day: 30
|
|
|
|
|
)
|
2024-03-19 15:44:55 +00:00
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-25 20:47:37 +00:00
|
|
|
var citations = [Citation]()
|
|
|
|
|
var responses = [GenerateContentResponse]()
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
2024-03-25 20:47:37 +00:00
|
|
|
responses.append(content)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
let candidate = try XCTUnwrap(content.candidates.first)
|
2024-09-23 21:27:12 -04:00
|
|
|
if let sources = candidate.citationMetadata?.citations {
|
2024-03-19 15:44:55 +00:00
|
|
|
citations.append(contentsOf: sources)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-25 20:47:37 +00:00
|
|
|
let lastCandidate = try XCTUnwrap(responses.last?.candidates.first)
|
|
|
|
|
XCTAssertEqual(lastCandidate.finishReason, .stop)
|
2024-06-19 13:35:17 -04:00
|
|
|
XCTAssertEqual(citations.count, 6)
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertTrue(citations
|
2024-08-19 17:33:15 -04:00
|
|
|
.contains {
|
|
|
|
|
$0.startIndex == 0 && $0.endIndex == 128
|
|
|
|
|
&& $0.uri == "https://www.example.com/some-citation-1" && $0.title == nil
|
2024-10-15 18:45:48 -04:00
|
|
|
&& $0.license == nil && $0.publicationDate == nil
|
2024-08-19 17:33:15 -04:00
|
|
|
})
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertTrue(citations
|
2024-08-19 17:33:15 -04:00
|
|
|
.contains {
|
|
|
|
|
$0.startIndex == 130 && $0.endIndex == 265 && $0.uri == nil
|
|
|
|
|
&& $0.title == "some-citation-2" && $0.license == nil
|
2024-10-15 18:45:48 -04:00
|
|
|
&& $0.publicationDate == expectedPublicationDate
|
2024-08-19 17:33:15 -04:00
|
|
|
})
|
|
|
|
|
XCTAssertTrue(citations
|
|
|
|
|
.contains {
|
|
|
|
|
$0.startIndex == 272 && $0.endIndex == 431
|
|
|
|
|
&& $0.uri == "https://www.example.com/some-citation-3" && $0.title == nil
|
2024-10-15 18:45:48 -04:00
|
|
|
&& $0.license == "mit" && $0.publicationDate == nil
|
2024-08-19 17:33:15 -04:00
|
|
|
})
|
|
|
|
|
XCTAssertFalse(citations.contains { $0.uri?.isEmpty ?? false })
|
|
|
|
|
XCTAssertFalse(citations.contains { $0.title?.isEmpty ?? false })
|
|
|
|
|
XCTAssertFalse(citations.contains { $0.license?.isEmpty ?? false })
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
2024-03-20 14:11:28 +00:00
|
|
|
func testGenerateContentStream_appCheck_validToken() async throws {
|
|
|
|
|
let appCheckToken = "test-valid-token"
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(appCheck: AppCheckInteropFake(token: appCheckToken)),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-20 14:11:28 +00:00
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-short",
|
|
|
|
|
withExtension: "txt",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-20 14:11:28 +00:00
|
|
|
appCheckToken: appCheckToken
|
|
|
|
|
)
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-03-20 14:11:28 +00:00
|
|
|
for try await _ in stream {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_appCheck_tokenRefreshError() async throws {
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(appCheck: AppCheckInteropFake(error: AppCheckErrorFake())),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-20 14:11:28 +00:00
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-short",
|
|
|
|
|
withExtension: "txt",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-20 14:11:28 +00:00
|
|
|
appCheckToken: AppCheckInteropFake.placeholderTokenValue
|
|
|
|
|
)
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-03-20 14:11:28 +00:00
|
|
|
for try await _ in stream {}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-12 17:21:01 -04:00
|
|
|
func testGenerateContentStream_usageMetadata() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-short",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-04-12 17:21:01 -04:00
|
|
|
)
|
|
|
|
|
var responses = [GenerateContentResponse]()
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-04-12 17:21:01 -04:00
|
|
|
for try await response in stream {
|
|
|
|
|
responses.append(response)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (index, response) in responses.enumerated() {
|
|
|
|
|
if index == responses.endIndex - 1 {
|
|
|
|
|
let usageMetadata = try XCTUnwrap(response.usageMetadata)
|
|
|
|
|
XCTAssertEqual(usageMetadata.promptTokenCount, 6)
|
|
|
|
|
XCTAssertEqual(usageMetadata.candidatesTokenCount, 4)
|
|
|
|
|
XCTAssertEqual(usageMetadata.totalTokenCount, 10)
|
|
|
|
|
} else {
|
|
|
|
|
// Only the last streamed response contains usage metadata
|
|
|
|
|
XCTAssertNil(response.usageMetadata)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testGenerateContentStream_errorMidStream() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-error-mid-stream",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responseCount = 0
|
|
|
|
|
do {
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
responseCount += 1
|
|
|
|
|
}
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let GenerateContentError.internalError(rpcError as BackendError) {
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(rpcError.httpResponseCode, 499)
|
|
|
|
|
XCTAssertEqual(rpcError.status, .cancelled)
|
|
|
|
|
|
|
|
|
|
// Check the content count is correct.
|
|
|
|
|
XCTAssertEqual(responseCount, 2)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Expected an internalError with an RPCError.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_nonHTTPResponse() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream("Hi")
|
2024-03-19 15:44:55 +00:00
|
|
|
do {
|
|
|
|
|
for try await content in stream {
|
|
|
|
|
XCTFail("Unexpected content in stream: \(content)")
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.internalError(underlying) {
|
|
|
|
|
XCTAssertEqual(underlying.localizedDescription, "Response was not an HTTP response.")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Expected an internal error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_invalidResponse() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-invalid-json",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-03-19 15:44:55 +00:00
|
|
|
do {
|
|
|
|
|
for try await content in stream {
|
|
|
|
|
XCTFail("Unexpected content in stream: \(content)")
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.internalError(underlying as DecodingError) {
|
|
|
|
|
guard case let .dataCorrupted(context) = underlying else {
|
|
|
|
|
XCTFail("Not a data corrupted error: \(underlying)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Expected an internal error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_malformedContent() async throws {
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-failure-malformed-content",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "txt",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-03-19 15:44:55 +00:00
|
|
|
do {
|
|
|
|
|
for try await content in stream {
|
|
|
|
|
XCTFail("Unexpected content in stream: \(content)")
|
|
|
|
|
}
|
|
|
|
|
} catch let GenerateContentError.internalError(underlyingError as InvalidCandidateError) {
|
|
|
|
|
guard case let .malformedContent(contentError) = underlyingError else {
|
|
|
|
|
XCTFail("Not a malformed content error: \(underlyingError)")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssert(contentError is DecodingError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Expected an internal decoding error.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testGenerateContentStream_requestOptions_customTimeout() async throws {
|
|
|
|
|
let expectedTimeout = 150.0
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "streaming-success-basic-reply-short",
|
|
|
|
|
withExtension: "txt",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
timeout: expectedTimeout
|
|
|
|
|
)
|
|
|
|
|
let requestOptions = RequestOptions(timeout: expectedTimeout)
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-19 15:44:55 +00:00
|
|
|
requestOptions: requestOptions,
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var responses = 0
|
2024-09-24 10:50:55 -04:00
|
|
|
let stream = try model.generateContentStream(testPrompt)
|
2024-03-19 15:44:55 +00:00
|
|
|
for try await content in stream {
|
|
|
|
|
XCTAssertNotNil(content.text)
|
|
|
|
|
responses += 1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(responses, 1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Count Tokens
|
|
|
|
|
|
|
|
|
|
func testCountTokens_succeeds() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
2024-06-19 13:35:17 -04:00
|
|
|
forResource: "unary-success-total-tokens",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-03-19 15:44:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.countTokens("Why is the sky blue?")
|
2024-03-27 20:37:29 +00:00
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(response.totalTokens, 6)
|
2024-03-27 20:37:29 +00:00
|
|
|
XCTAssertEqual(response.totalBillableCharacters, 16)
|
2024-03-19 15:44:55 +00:00
|
|
|
}
|
|
|
|
|
|
2025-02-11 15:41:25 -05:00
|
|
|
func testCountTokens_succeeds_detailed() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-detailed-token-response",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2025-02-11 15:41:25 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.countTokens("Why is the sky blue?")
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.totalTokens, 1837)
|
|
|
|
|
XCTAssertEqual(response.totalBillableCharacters, 117)
|
|
|
|
|
XCTAssertEqual(response.promptTokensDetails.count, 2)
|
|
|
|
|
XCTAssertEqual(response.promptTokensDetails[0].modality, .image)
|
|
|
|
|
XCTAssertEqual(response.promptTokensDetails[0].tokenCount, 1806)
|
|
|
|
|
XCTAssertEqual(response.promptTokensDetails[1].modality, .text)
|
|
|
|
|
XCTAssertEqual(response.promptTokensDetails[1].tokenCount, 31)
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-04 17:20:43 -04:00
|
|
|
func testCountTokens_succeeds_allOptions() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
|
|
|
|
forResource: "unary-success-total-tokens",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-10-04 17:20:43 -04:00
|
|
|
)
|
|
|
|
|
let generationConfig = GenerationConfig(
|
|
|
|
|
temperature: 0.5,
|
|
|
|
|
topP: 0.9,
|
|
|
|
|
topK: 3,
|
|
|
|
|
candidateCount: 1,
|
|
|
|
|
maxOutputTokens: 1024,
|
|
|
|
|
stopSequences: ["test-stop"],
|
|
|
|
|
responseMIMEType: "text/plain"
|
|
|
|
|
)
|
|
|
|
|
let sumFunction = FunctionDeclaration(
|
|
|
|
|
name: "sum",
|
|
|
|
|
description: "Add two integers.",
|
|
|
|
|
parameters: ["x": .integer(), "y": .integer()]
|
|
|
|
|
)
|
|
|
|
|
let systemInstruction = ModelContent(
|
|
|
|
|
role: "system",
|
|
|
|
|
parts: "You are a calculator. Use the provided tools."
|
|
|
|
|
)
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-10-04 17:20:43 -04:00
|
|
|
generationConfig: generationConfig,
|
|
|
|
|
tools: [Tool(functionDeclarations: [sumFunction])],
|
|
|
|
|
systemInstruction: systemInstruction,
|
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.countTokens("Why is the sky blue?")
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.totalTokens, 6)
|
|
|
|
|
XCTAssertEqual(response.totalBillableCharacters, 16)
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-10 14:27:48 -04:00
|
|
|
func testCountTokens_succeeds_noBillableCharacters() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
2024-06-19 13:35:17 -04:00
|
|
|
forResource: "unary-success-no-billable-characters",
|
2025-03-17 17:20:27 -04:00
|
|
|
withExtension: "json",
|
|
|
|
|
subdirectory: vertexSubdirectory
|
2024-04-10 14:27:48 -04:00
|
|
|
)
|
|
|
|
|
|
2024-10-07 15:37:58 -04:00
|
|
|
let response = try await model.countTokens(InlineDataPart(data: Data(), mimeType: "image/jpeg"))
|
2024-04-10 14:27:48 -04:00
|
|
|
|
|
|
|
|
XCTAssertEqual(response.totalTokens, 258)
|
2024-09-25 14:43:36 -04:00
|
|
|
XCTAssertNil(response.totalBillableCharacters)
|
2024-04-10 14:27:48 -04:00
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
func testCountTokens_modelNotFound() async throws {
|
|
|
|
|
MockURLProtocol.requestHandler = try httpRequestHandler(
|
2024-06-19 13:35:17 -04:00
|
|
|
forResource: "unary-failure-model-not-found", withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
statusCode: 404
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
_ = try await model.countTokens("Why is the sky blue?")
|
|
|
|
|
XCTFail("Request should not have succeeded.")
|
2024-11-04 19:12:11 -05:00
|
|
|
} catch let rpcError as BackendError {
|
2024-03-19 15:44:55 +00:00
|
|
|
XCTAssertEqual(rpcError.httpResponseCode, 404)
|
|
|
|
|
XCTAssertEqual(rpcError.status, .notFound)
|
|
|
|
|
XCTAssert(rpcError.message.hasPrefix("models/test-model-name is not found"))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
XCTFail("Expected internal RPCError.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func testCountTokens_requestOptions_customTimeout() async throws {
|
|
|
|
|
let expectedTimeout = 150.0
|
|
|
|
|
MockURLProtocol
|
|
|
|
|
.requestHandler = try httpRequestHandler(
|
2024-06-19 13:35:17 -04:00
|
|
|
forResource: "unary-success-total-tokens",
|
2024-03-19 15:44:55 +00:00
|
|
|
withExtension: "json",
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory: vertexSubdirectory,
|
2024-03-19 15:44:55 +00:00
|
|
|
timeout: expectedTimeout
|
|
|
|
|
)
|
|
|
|
|
let requestOptions = RequestOptions(timeout: expectedTimeout)
|
|
|
|
|
model = GenerativeModel(
|
2025-04-09 19:14:41 -04:00
|
|
|
modelName: testModelName,
|
2025-03-28 15:48:41 -04:00
|
|
|
modelResourceName: testModelResourceName,
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseInfo: testFirebaseInfo(),
|
2025-03-05 16:50:54 -05:00
|
|
|
apiConfig: apiConfig,
|
2024-03-27 14:34:49 +00:00
|
|
|
tools: nil,
|
2024-03-19 15:44:55 +00:00
|
|
|
requestOptions: requestOptions,
|
|
|
|
|
urlSession: urlSession
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
let response = try await model.countTokens(testPrompt)
|
|
|
|
|
|
|
|
|
|
XCTAssertEqual(response.totalTokens, 6)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Helpers
|
|
|
|
|
|
2025-02-25 11:54:15 -08:00
|
|
|
private func testFirebaseInfo(appCheck: AppCheckInterop? = nil,
|
|
|
|
|
auth: AuthInterop? = nil,
|
|
|
|
|
privateAppID: Bool = false) -> FirebaseInfo {
|
|
|
|
|
let app = FirebaseApp(instanceWithName: "testApp",
|
|
|
|
|
options: FirebaseOptions(googleAppID: "ignore",
|
|
|
|
|
gcmSenderID: "ignore"))
|
|
|
|
|
app.isDataCollectionDefaultEnabled = !privateAppID
|
|
|
|
|
return FirebaseInfo(
|
|
|
|
|
appCheck: appCheck,
|
|
|
|
|
auth: auth,
|
|
|
|
|
projectID: "my-project-id",
|
|
|
|
|
apiKey: "API_KEY",
|
2025-03-17 09:46:24 -07:00
|
|
|
firebaseAppID: "My app ID",
|
2025-02-25 11:54:15 -08:00
|
|
|
firebaseApp: app
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-19 15:44:55 +00:00
|
|
|
private func nonHTTPRequestHandler() throws -> ((URLRequest) -> (
|
|
|
|
|
URLResponse,
|
|
|
|
|
AsyncLineSequence<URL.AsyncBytes>?
|
|
|
|
|
)) {
|
2024-07-02 17:15:33 -04:00
|
|
|
// Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
|
|
|
|
|
// https://developer.apple.com/documentation/foundation/urlprotocol for details.
|
2024-08-19 17:33:15 -04:00
|
|
|
#if os(watchOS)
|
2024-07-02 17:15:33 -04:00
|
|
|
throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
|
2024-08-19 17:33:15 -04:00
|
|
|
#endif // os(watchOS)
|
2024-03-19 15:44:55 +00:00
|
|
|
return { request in
|
|
|
|
|
// This is *not* an HTTPURLResponse
|
|
|
|
|
let response = URLResponse(
|
|
|
|
|
url: request.url!,
|
|
|
|
|
mimeType: nil,
|
|
|
|
|
expectedContentLength: 0,
|
|
|
|
|
textEncodingName: nil
|
|
|
|
|
)
|
|
|
|
|
return (response, nil)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func httpRequestHandler(forResource name: String,
|
|
|
|
|
withExtension ext: String,
|
2025-03-17 17:20:27 -04:00
|
|
|
subdirectory subpath: String,
|
2024-03-19 15:44:55 +00:00
|
|
|
statusCode: Int = 200,
|
2024-09-26 11:35:04 -04:00
|
|
|
timeout: TimeInterval = RequestOptions().timeout,
|
2024-04-29 16:17:48 -04:00
|
|
|
appCheckToken: String? = nil,
|
2025-02-25 11:54:15 -08:00
|
|
|
authToken: String? = nil,
|
|
|
|
|
dataCollection: Bool = true) throws -> ((URLRequest) throws -> (
|
2024-03-19 15:44:55 +00:00
|
|
|
URLResponse,
|
|
|
|
|
AsyncLineSequence<URL.AsyncBytes>?
|
|
|
|
|
)) {
|
2024-07-02 17:15:33 -04:00
|
|
|
// Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
|
|
|
|
|
// https://developer.apple.com/documentation/foundation/urlprotocol for details.
|
2024-08-19 17:33:15 -04:00
|
|
|
#if os(watchOS)
|
2024-07-02 17:15:33 -04:00
|
|
|
throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
|
2024-08-19 17:33:15 -04:00
|
|
|
#endif // os(watchOS)
|
2024-10-17 16:55:38 -04:00
|
|
|
let bundle = BundleTestUtil.bundle()
|
2025-03-17 17:20:27 -04:00
|
|
|
let fileURL = try XCTUnwrap(
|
|
|
|
|
bundle.url(forResource: name, withExtension: ext, subdirectory: subpath)
|
|
|
|
|
)
|
2024-03-19 15:44:55 +00:00
|
|
|
return { request in
|
|
|
|
|
let requestURL = try XCTUnwrap(request.url)
|
|
|
|
|
XCTAssertEqual(requestURL.path.occurrenceCount(of: "models/"), 1)
|
|
|
|
|
XCTAssertEqual(request.timeoutInterval, timeout)
|
2024-04-02 17:11:08 +00:00
|
|
|
let apiClientTags = try XCTUnwrap(request.value(forHTTPHeaderField: "x-goog-api-client"))
|
|
|
|
|
.components(separatedBy: " ")
|
|
|
|
|
XCTAssert(apiClientTags.contains(GenerativeAIService.languageTag))
|
|
|
|
|
XCTAssert(apiClientTags.contains(GenerativeAIService.firebaseVersionTag))
|
2024-03-20 14:11:28 +00:00
|
|
|
XCTAssertEqual(request.value(forHTTPHeaderField: "X-Firebase-AppCheck"), appCheckToken)
|
2025-03-17 07:46:47 -07:00
|
|
|
|
2025-03-17 09:46:24 -07:00
|
|
|
let firebaseAppID = request.value(forHTTPHeaderField: "X-Firebase-AppId")
|
2025-03-17 07:46:47 -07:00
|
|
|
let appVersion = request.value(forHTTPHeaderField: "X-Firebase-AppVersion")
|
|
|
|
|
let expectedAppVersion =
|
|
|
|
|
try? XCTUnwrap(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)
|
2025-03-17 09:46:24 -07:00
|
|
|
XCTAssertEqual(firebaseAppID, dataCollection ? "My app ID" : nil)
|
2025-03-17 07:46:47 -07:00
|
|
|
XCTAssertEqual(appVersion, dataCollection ? expectedAppVersion : nil)
|
|
|
|
|
|
2024-04-29 16:17:48 -04:00
|
|
|
if let authToken {
|
|
|
|
|
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Firebase \(authToken)")
|
|
|
|
|
} else {
|
|
|
|
|
XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
|
|
|
|
|
}
|
2024-03-19 15:44:55 +00:00
|
|
|
let response = try XCTUnwrap(HTTPURLResponse(
|
|
|
|
|
url: requestURL,
|
|
|
|
|
statusCode: statusCode,
|
|
|
|
|
httpVersion: nil,
|
|
|
|
|
headerFields: nil
|
|
|
|
|
))
|
|
|
|
|
return (response, fileURL.lines)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private extension String {
|
|
|
|
|
/// Returns the number of occurrences of `substring` in the `String`.
|
|
|
|
|
func occurrenceCount(of substring: String) -> Int {
|
|
|
|
|
return components(separatedBy: substring).count - 1
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-02 17:15:33 -04:00
|
|
|
@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
|
2024-03-20 14:11:28 +00:00
|
|
|
class AppCheckInteropFake: NSObject, AppCheckInterop {
|
|
|
|
|
/// The placeholder token value returned when an error occurs
|
|
|
|
|
static let placeholderTokenValue = "placeholder-token"
|
|
|
|
|
|
|
|
|
|
var token: String
|
|
|
|
|
var error: Error?
|
|
|
|
|
|
|
|
|
|
private init(token: String, error: Error?) {
|
|
|
|
|
self.token = token
|
|
|
|
|
self.error = error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
convenience init(token: String) {
|
|
|
|
|
self.init(token: token, error: nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
convenience init(error: Error) {
|
|
|
|
|
self.init(token: AppCheckInteropFake.placeholderTokenValue, error: error)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func getToken(forcingRefresh: Bool) async -> any FIRAppCheckTokenResultInterop {
|
|
|
|
|
return AppCheckTokenResultInteropFake(token: token, error: error)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func tokenDidChangeNotificationName() -> String {
|
|
|
|
|
fatalError("\(#function) not implemented.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func notificationTokenKey() -> String {
|
|
|
|
|
fatalError("\(#function) not implemented.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func notificationAppNameKey() -> String {
|
|
|
|
|
fatalError("\(#function) not implemented.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private class AppCheckTokenResultInteropFake: NSObject, FIRAppCheckTokenResultInterop {
|
|
|
|
|
var token: String
|
|
|
|
|
var error: Error?
|
|
|
|
|
|
|
|
|
|
init(token: String, error: Error?) {
|
|
|
|
|
self.token = token
|
|
|
|
|
self.error = error
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct AppCheckErrorFake: Error {}
|
2024-03-22 21:06:39 +00:00
|
|
|
|
2024-07-02 17:15:33 -04:00
|
|
|
@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
|
2024-09-13 14:56:38 -04:00
|
|
|
extension SafetyRating: Swift.Comparable {
|
2025-04-11 17:07:03 -04:00
|
|
|
public static func < (lhs: SafetyRating, rhs: SafetyRating) -> Bool {
|
2024-03-22 21:06:39 +00:00
|
|
|
return lhs.category.rawValue < rhs.category.rawValue
|
|
|
|
|
}
|
|
|
|
|
}
|