GenerativeModelTests.swift 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseCore
  17. import XCTest
  18. @testable import FirebaseVertexAI
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. final class GenerativeModelTests: XCTestCase {
  21. let testPrompt = "What sorts of questions can I ask you?"
  22. let safetyRatingsNegligible: [SafetyRating] = [
  23. .init(
  24. category: .sexuallyExplicit,
  25. probability: .negligible,
  26. probabilityScore: 0.1431877,
  27. severity: .negligible,
  28. severityScore: 0.11027937,
  29. blocked: false
  30. ),
  31. .init(
  32. category: .hateSpeech,
  33. probability: .negligible,
  34. probabilityScore: 0.029035643,
  35. severity: .negligible,
  36. severityScore: 0.05613278,
  37. blocked: false
  38. ),
  39. .init(
  40. category: .harassment,
  41. probability: .negligible,
  42. probabilityScore: 0.087252244,
  43. severity: .negligible,
  44. severityScore: 0.04509957,
  45. blocked: false
  46. ),
  47. .init(
  48. category: .dangerousContent,
  49. probability: .negligible,
  50. probabilityScore: 0.2641685,
  51. severity: .negligible,
  52. severityScore: 0.082253955,
  53. blocked: false
  54. ),
  55. ].sorted()
  56. let testModelResourceName =
  57. "projects/test-project-id/locations/test-location/publishers/google/models/test-model"
  58. var urlSession: URLSession!
  59. var model: GenerativeModel!
  60. override func setUp() async throws {
  61. let configuration = URLSessionConfiguration.default
  62. configuration.protocolClasses = [MockURLProtocol.self]
  63. urlSession = try XCTUnwrap(URLSession(configuration: configuration))
  64. model = GenerativeModel(
  65. name: testModelResourceName,
  66. projectID: "my-project-id",
  67. apiKey: "API_KEY",
  68. tools: nil,
  69. requestOptions: RequestOptions(),
  70. appCheck: nil,
  71. auth: nil,
  72. urlSession: urlSession
  73. )
  74. }
  75. override func tearDown() {
  76. MockURLProtocol.requestHandler = nil
  77. }
  78. // MARK: - Generate Content
  79. func testGenerateContent_success_basicReplyLong() async throws {
  80. MockURLProtocol
  81. .requestHandler = try httpRequestHandler(
  82. forResource: "unary-success-basic-reply-long",
  83. withExtension: "json"
  84. )
  85. let response = try await model.generateContent(testPrompt)
  86. XCTAssertEqual(response.candidates.count, 1)
  87. let candidate = try XCTUnwrap(response.candidates.first)
  88. let finishReason = try XCTUnwrap(candidate.finishReason)
  89. XCTAssertEqual(finishReason, .stop)
  90. XCTAssertEqual(candidate.safetyRatings.count, 4)
  91. XCTAssertEqual(candidate.content.parts.count, 1)
  92. let part = try XCTUnwrap(candidate.content.parts.first)
  93. let partText = try XCTUnwrap(part as? TextPart).text
  94. XCTAssertTrue(partText.hasPrefix("1. **Use Freshly Ground Coffee**:"))
  95. XCTAssertEqual(response.text, partText)
  96. XCTAssertEqual(response.functionCalls, [])
  97. }
  98. func testGenerateContent_success_basicReplyShort() async throws {
  99. MockURLProtocol
  100. .requestHandler = try httpRequestHandler(
  101. forResource: "unary-success-basic-reply-short",
  102. withExtension: "json"
  103. )
  104. let response = try await model.generateContent(testPrompt)
  105. XCTAssertEqual(response.candidates.count, 1)
  106. let candidate = try XCTUnwrap(response.candidates.first)
  107. let finishReason = try XCTUnwrap(candidate.finishReason)
  108. XCTAssertEqual(finishReason, .stop)
  109. XCTAssertEqual(candidate.safetyRatings.sorted(), safetyRatingsNegligible)
  110. XCTAssertEqual(candidate.content.parts.count, 1)
  111. let part = try XCTUnwrap(candidate.content.parts.first)
  112. let textPart = try XCTUnwrap(part as? TextPart)
  113. XCTAssertEqual(textPart.text, "Mountain View, California")
  114. XCTAssertEqual(response.text, textPart.text)
  115. XCTAssertEqual(response.functionCalls, [])
  116. }
  117. func testGenerateContent_success_citations() async throws {
  118. MockURLProtocol
  119. .requestHandler = try httpRequestHandler(
  120. forResource: "unary-success-citations",
  121. withExtension: "json"
  122. )
  123. let expectedPublicationDate = DateComponents(
  124. calendar: Calendar(identifier: .gregorian),
  125. year: 2019,
  126. month: 5,
  127. day: 10
  128. )
  129. let response = try await model.generateContent(testPrompt)
  130. XCTAssertEqual(response.candidates.count, 1)
  131. let candidate = try XCTUnwrap(response.candidates.first)
  132. XCTAssertEqual(candidate.content.parts.count, 1)
  133. XCTAssertEqual(response.text, "Some information cited from an external source")
  134. let citationMetadata = try XCTUnwrap(candidate.citationMetadata)
  135. XCTAssertEqual(citationMetadata.citations.count, 3)
  136. let citationSource1 = try XCTUnwrap(citationMetadata.citations[0])
  137. XCTAssertEqual(citationSource1.uri, "https://www.example.com/some-citation-1")
  138. XCTAssertEqual(citationSource1.startIndex, 0)
  139. XCTAssertEqual(citationSource1.endIndex, 128)
  140. XCTAssertNil(citationSource1.title)
  141. XCTAssertNil(citationSource1.license)
  142. XCTAssertNil(citationSource1.publicationDate)
  143. let citationSource2 = try XCTUnwrap(citationMetadata.citations[1])
  144. XCTAssertEqual(citationSource2.title, "some-citation-2")
  145. XCTAssertEqual(citationSource2.publicationDate, expectedPublicationDate)
  146. XCTAssertEqual(citationSource2.startIndex, 130)
  147. XCTAssertEqual(citationSource2.endIndex, 265)
  148. XCTAssertNil(citationSource2.uri)
  149. XCTAssertNil(citationSource2.license)
  150. let citationSource3 = try XCTUnwrap(citationMetadata.citations[2])
  151. XCTAssertEqual(citationSource3.uri, "https://www.example.com/some-citation-3")
  152. XCTAssertEqual(citationSource3.startIndex, 272)
  153. XCTAssertEqual(citationSource3.endIndex, 431)
  154. XCTAssertEqual(citationSource3.license, "mit")
  155. XCTAssertNil(citationSource3.title)
  156. XCTAssertNil(citationSource3.publicationDate)
  157. }
  158. func testGenerateContent_success_quoteReply() async throws {
  159. MockURLProtocol
  160. .requestHandler = try httpRequestHandler(
  161. forResource: "unary-success-quote-reply",
  162. withExtension: "json"
  163. )
  164. let response = try await model.generateContent(testPrompt)
  165. XCTAssertEqual(response.candidates.count, 1)
  166. let candidate = try XCTUnwrap(response.candidates.first)
  167. let finishReason = try XCTUnwrap(candidate.finishReason)
  168. XCTAssertEqual(finishReason, .stop)
  169. XCTAssertEqual(candidate.safetyRatings.count, 4)
  170. XCTAssertEqual(candidate.content.parts.count, 1)
  171. let part = try XCTUnwrap(candidate.content.parts.first)
  172. let textPart = try XCTUnwrap(part as? TextPart)
  173. XCTAssertTrue(textPart.text.hasPrefix("Google"))
  174. XCTAssertEqual(response.text, textPart.text)
  175. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  176. XCTAssertNil(promptFeedback.blockReason)
  177. XCTAssertEqual(promptFeedback.safetyRatings.count, 4)
  178. }
  179. func testGenerateContent_success_unknownEnum_safetyRatings() async throws {
  180. let expectedSafetyRatings = [
  181. SafetyRating(
  182. category: .harassment,
  183. probability: .medium,
  184. probabilityScore: 0.0,
  185. severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
  186. severityScore: 0.0,
  187. blocked: false
  188. ),
  189. SafetyRating(
  190. category: .dangerousContent,
  191. probability: SafetyRating.HarmProbability(rawValue: "FAKE_NEW_HARM_PROBABILITY"),
  192. probabilityScore: 0.0,
  193. severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
  194. severityScore: 0.0,
  195. blocked: false
  196. ),
  197. SafetyRating(
  198. category: HarmCategory(rawValue: "FAKE_NEW_HARM_CATEGORY"),
  199. probability: .high,
  200. probabilityScore: 0.0,
  201. severity: .init(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
  202. severityScore: 0.0,
  203. blocked: false
  204. ),
  205. ]
  206. MockURLProtocol
  207. .requestHandler = try httpRequestHandler(
  208. forResource: "unary-success-unknown-enum-safety-ratings",
  209. withExtension: "json"
  210. )
  211. let response = try await model.generateContent(testPrompt)
  212. XCTAssertEqual(response.text, "Some text")
  213. XCTAssertEqual(response.candidates.first?.safetyRatings, expectedSafetyRatings)
  214. XCTAssertEqual(response.promptFeedback?.safetyRatings, expectedSafetyRatings)
  215. }
  216. func testGenerateContent_success_prefixedModelName() async throws {
  217. MockURLProtocol
  218. .requestHandler = try httpRequestHandler(
  219. forResource: "unary-success-basic-reply-short",
  220. withExtension: "json"
  221. )
  222. let model = GenerativeModel(
  223. // Model name is prefixed with "models/".
  224. name: "models/test-model",
  225. projectID: "my-project-id",
  226. apiKey: "API_KEY",
  227. tools: nil,
  228. requestOptions: RequestOptions(),
  229. appCheck: nil,
  230. auth: nil,
  231. urlSession: urlSession
  232. )
  233. _ = try await model.generateContent(testPrompt)
  234. }
  235. func testGenerateContent_success_functionCall_emptyArguments() async throws {
  236. MockURLProtocol
  237. .requestHandler = try httpRequestHandler(
  238. forResource: "unary-success-function-call-empty-arguments",
  239. withExtension: "json"
  240. )
  241. let response = try await model.generateContent(testPrompt)
  242. XCTAssertEqual(response.candidates.count, 1)
  243. let candidate = try XCTUnwrap(response.candidates.first)
  244. XCTAssertEqual(candidate.content.parts.count, 1)
  245. let part = try XCTUnwrap(candidate.content.parts.first)
  246. guard let functionCall = part as? FunctionCallPart else {
  247. XCTFail("Part is not a FunctionCall.")
  248. return
  249. }
  250. XCTAssertEqual(functionCall.name, "current_time")
  251. XCTAssertTrue(functionCall.args.isEmpty)
  252. XCTAssertEqual(response.functionCalls, [functionCall])
  253. }
  254. func testGenerateContent_success_functionCall_noArguments() async throws {
  255. MockURLProtocol
  256. .requestHandler = try httpRequestHandler(
  257. forResource: "unary-success-function-call-no-arguments",
  258. withExtension: "json"
  259. )
  260. let response = try await model.generateContent(testPrompt)
  261. XCTAssertEqual(response.candidates.count, 1)
  262. let candidate = try XCTUnwrap(response.candidates.first)
  263. XCTAssertEqual(candidate.content.parts.count, 1)
  264. let part = try XCTUnwrap(candidate.content.parts.first)
  265. guard let functionCall = part as? FunctionCallPart else {
  266. XCTFail("Part is not a FunctionCall.")
  267. return
  268. }
  269. XCTAssertEqual(functionCall.name, "current_time")
  270. XCTAssertTrue(functionCall.args.isEmpty)
  271. XCTAssertEqual(response.functionCalls, [functionCall])
  272. }
  273. func testGenerateContent_success_functionCall_withArguments() async throws {
  274. MockURLProtocol
  275. .requestHandler = try httpRequestHandler(
  276. forResource: "unary-success-function-call-with-arguments",
  277. withExtension: "json"
  278. )
  279. let response = try await model.generateContent(testPrompt)
  280. XCTAssertEqual(response.candidates.count, 1)
  281. let candidate = try XCTUnwrap(response.candidates.first)
  282. XCTAssertEqual(candidate.content.parts.count, 1)
  283. let part = try XCTUnwrap(candidate.content.parts.first)
  284. guard let functionCall = part as? FunctionCallPart else {
  285. XCTFail("Part is not a FunctionCall.")
  286. return
  287. }
  288. XCTAssertEqual(functionCall.name, "sum")
  289. XCTAssertEqual(functionCall.args.count, 2)
  290. let argX = try XCTUnwrap(functionCall.args["x"])
  291. XCTAssertEqual(argX, .number(4))
  292. let argY = try XCTUnwrap(functionCall.args["y"])
  293. XCTAssertEqual(argY, .number(5))
  294. XCTAssertEqual(response.functionCalls, [functionCall])
  295. }
  296. func testGenerateContent_success_functionCall_parallelCalls() async throws {
  297. MockURLProtocol
  298. .requestHandler = try httpRequestHandler(
  299. forResource: "unary-success-function-call-parallel-calls",
  300. withExtension: "json"
  301. )
  302. let response = try await model.generateContent(testPrompt)
  303. XCTAssertEqual(response.candidates.count, 1)
  304. let candidate = try XCTUnwrap(response.candidates.first)
  305. XCTAssertEqual(candidate.content.parts.count, 3)
  306. let functionCalls = response.functionCalls
  307. XCTAssertEqual(functionCalls.count, 3)
  308. }
  309. func testGenerateContent_success_functionCall_mixedContent() async throws {
  310. MockURLProtocol
  311. .requestHandler = try httpRequestHandler(
  312. forResource: "unary-success-function-call-mixed-content",
  313. withExtension: "json"
  314. )
  315. let response = try await model.generateContent(testPrompt)
  316. XCTAssertEqual(response.candidates.count, 1)
  317. let candidate = try XCTUnwrap(response.candidates.first)
  318. XCTAssertEqual(candidate.content.parts.count, 4)
  319. let functionCalls = response.functionCalls
  320. XCTAssertEqual(functionCalls.count, 2)
  321. let text = try XCTUnwrap(response.text)
  322. XCTAssertEqual(text, "The sum of [1, 2, 3] is")
  323. }
  324. func testGenerateContent_appCheck_validToken() async throws {
  325. let appCheckToken = "test-valid-token"
  326. model = GenerativeModel(
  327. name: testModelResourceName,
  328. projectID: "my-project-id",
  329. apiKey: "API_KEY",
  330. tools: nil,
  331. requestOptions: RequestOptions(),
  332. appCheck: AppCheckInteropFake(token: appCheckToken),
  333. auth: nil,
  334. urlSession: urlSession
  335. )
  336. MockURLProtocol
  337. .requestHandler = try httpRequestHandler(
  338. forResource: "unary-success-basic-reply-short",
  339. withExtension: "json",
  340. appCheckToken: appCheckToken
  341. )
  342. _ = try await model.generateContent(testPrompt)
  343. }
  344. func testGenerateContent_appCheck_tokenRefreshError() async throws {
  345. model = GenerativeModel(
  346. name: testModelResourceName,
  347. projectID: "my-project-id",
  348. apiKey: "API_KEY",
  349. tools: nil,
  350. requestOptions: RequestOptions(),
  351. appCheck: AppCheckInteropFake(error: AppCheckErrorFake()),
  352. auth: nil,
  353. urlSession: urlSession
  354. )
  355. MockURLProtocol
  356. .requestHandler = try httpRequestHandler(
  357. forResource: "unary-success-basic-reply-short",
  358. withExtension: "json",
  359. appCheckToken: AppCheckInteropFake.placeholderTokenValue
  360. )
  361. _ = try await model.generateContent(testPrompt)
  362. }
  363. func testGenerateContent_auth_validAuthToken() async throws {
  364. let authToken = "test-valid-token"
  365. model = GenerativeModel(
  366. name: testModelResourceName,
  367. projectID: "my-project-id",
  368. apiKey: "API_KEY",
  369. tools: nil,
  370. requestOptions: RequestOptions(),
  371. appCheck: nil,
  372. auth: AuthInteropFake(token: authToken),
  373. urlSession: urlSession
  374. )
  375. MockURLProtocol
  376. .requestHandler = try httpRequestHandler(
  377. forResource: "unary-success-basic-reply-short",
  378. withExtension: "json",
  379. authToken: authToken
  380. )
  381. _ = try await model.generateContent(testPrompt)
  382. }
  383. func testGenerateContent_auth_nilAuthToken() async throws {
  384. model = GenerativeModel(
  385. name: testModelResourceName,
  386. projectID: "my-project-id",
  387. apiKey: "API_KEY",
  388. tools: nil,
  389. requestOptions: RequestOptions(),
  390. appCheck: nil,
  391. auth: AuthInteropFake(token: nil),
  392. urlSession: urlSession
  393. )
  394. MockURLProtocol
  395. .requestHandler = try httpRequestHandler(
  396. forResource: "unary-success-basic-reply-short",
  397. withExtension: "json",
  398. authToken: nil
  399. )
  400. _ = try await model.generateContent(testPrompt)
  401. }
  402. func testGenerateContent_auth_authTokenRefreshError() async throws {
  403. model = GenerativeModel(
  404. name: "my-model",
  405. projectID: "my-project-id",
  406. apiKey: "API_KEY",
  407. tools: nil,
  408. requestOptions: RequestOptions(),
  409. appCheck: nil,
  410. auth: AuthInteropFake(error: AuthErrorFake()),
  411. urlSession: urlSession
  412. )
  413. MockURLProtocol
  414. .requestHandler = try httpRequestHandler(
  415. forResource: "unary-success-basic-reply-short",
  416. withExtension: "json",
  417. authToken: nil
  418. )
  419. do {
  420. _ = try await model.generateContent(testPrompt)
  421. XCTFail("Should throw internalError(AuthErrorFake); no error.")
  422. } catch GenerateContentError.internalError(_ as AuthErrorFake) {
  423. //
  424. } catch {
  425. XCTFail("Should throw internalError(AuthErrorFake); error thrown: \(error)")
  426. }
  427. }
  428. func testGenerateContent_usageMetadata() async throws {
  429. MockURLProtocol
  430. .requestHandler = try httpRequestHandler(
  431. forResource: "unary-success-basic-reply-short",
  432. withExtension: "json"
  433. )
  434. let response = try await model.generateContent(testPrompt)
  435. let usageMetadata = try XCTUnwrap(response.usageMetadata)
  436. XCTAssertEqual(usageMetadata.promptTokenCount, 6)
  437. XCTAssertEqual(usageMetadata.candidatesTokenCount, 7)
  438. XCTAssertEqual(usageMetadata.totalTokenCount, 13)
  439. }
  440. func testGenerateContent_failure_invalidAPIKey() async throws {
  441. let expectedStatusCode = 400
  442. MockURLProtocol
  443. .requestHandler = try httpRequestHandler(
  444. forResource: "unary-failure-api-key",
  445. withExtension: "json",
  446. statusCode: expectedStatusCode
  447. )
  448. do {
  449. _ = try await model.generateContent(testPrompt)
  450. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  451. } catch let GenerateContentError.internalError(error as RPCError) {
  452. XCTAssertEqual(error.httpResponseCode, 400)
  453. XCTAssertEqual(error.status, .invalidArgument)
  454. XCTAssertEqual(error.message, "API key not valid. Please pass a valid API key.")
  455. return
  456. } catch {
  457. XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
  458. }
  459. }
  460. func testGenerateContent_failure_firebaseVertexAIAPINotEnabled() async throws {
  461. let expectedStatusCode = 403
  462. MockURLProtocol
  463. .requestHandler = try httpRequestHandler(
  464. forResource: "unary-failure-firebasevertexai-api-not-enabled",
  465. withExtension: "json",
  466. statusCode: expectedStatusCode
  467. )
  468. do {
  469. _ = try await model.generateContent(testPrompt)
  470. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  471. } catch let GenerateContentError.internalError(error as RPCError) {
  472. XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
  473. XCTAssertEqual(error.status, .permissionDenied)
  474. XCTAssertTrue(error.message
  475. .starts(with: "Vertex AI in Firebase API has not been used in project"))
  476. XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
  477. return
  478. } catch {
  479. XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
  480. }
  481. }
  482. func testGenerateContent_failure_emptyContent() async throws {
  483. MockURLProtocol
  484. .requestHandler = try httpRequestHandler(
  485. forResource: "unary-failure-empty-content",
  486. withExtension: "json"
  487. )
  488. do {
  489. _ = try await model.generateContent(testPrompt)
  490. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  491. } catch let GenerateContentError
  492. .internalError(underlying: invalidCandidateError as InvalidCandidateError) {
  493. guard case let .emptyContent(decodingError) = invalidCandidateError else {
  494. XCTFail("Not an InvalidCandidateError.emptyContent error: \(invalidCandidateError)")
  495. return
  496. }
  497. _ = try XCTUnwrap(decodingError as? DecodingError,
  498. "Not a DecodingError: \(decodingError)")
  499. } catch {
  500. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  501. }
  502. }
  503. func testGenerateContent_failure_finishReasonSafety() async throws {
  504. MockURLProtocol
  505. .requestHandler = try httpRequestHandler(
  506. forResource: "unary-failure-finish-reason-safety",
  507. withExtension: "json"
  508. )
  509. do {
  510. _ = try await model.generateContent(testPrompt)
  511. XCTFail("Should throw")
  512. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  513. XCTAssertEqual(reason, .safety)
  514. XCTAssertEqual(response.text, "<redacted>")
  515. } catch {
  516. XCTFail("Should throw a responseStoppedEarly")
  517. }
  518. }
  519. func testGenerateContent_failure_finishReasonSafety_noContent() async throws {
  520. MockURLProtocol
  521. .requestHandler = try httpRequestHandler(
  522. forResource: "unary-failure-finish-reason-safety-no-content",
  523. withExtension: "json"
  524. )
  525. do {
  526. _ = try await model.generateContent(testPrompt)
  527. XCTFail("Should throw")
  528. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  529. XCTAssertEqual(reason, .safety)
  530. XCTAssertNil(response.text)
  531. } catch {
  532. XCTFail("Should throw a responseStoppedEarly")
  533. }
  534. }
  535. func testGenerateContent_failure_imageRejected() async throws {
  536. let expectedStatusCode = 400
  537. MockURLProtocol
  538. .requestHandler = try httpRequestHandler(
  539. forResource: "unary-failure-image-rejected",
  540. withExtension: "json",
  541. statusCode: 400
  542. )
  543. do {
  544. _ = try await model.generateContent(testPrompt)
  545. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  546. } catch let GenerateContentError.internalError(underlying: rpcError as RPCError) {
  547. XCTAssertEqual(rpcError.status, .invalidArgument)
  548. XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
  549. XCTAssertEqual(rpcError.message, "Request contains an invalid argument.")
  550. } catch {
  551. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  552. }
  553. }
  554. func testGenerateContent_failure_promptBlockedSafety() async throws {
  555. MockURLProtocol
  556. .requestHandler = try httpRequestHandler(
  557. forResource: "unary-failure-prompt-blocked-safety",
  558. withExtension: "json"
  559. )
  560. do {
  561. _ = try await model.generateContent(testPrompt)
  562. XCTFail("Should throw")
  563. } catch let GenerateContentError.promptBlocked(response) {
  564. XCTAssertNil(response.text)
  565. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  566. XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
  567. XCTAssertNil(promptFeedback.blockReasonMessage)
  568. } catch {
  569. XCTFail("Should throw a promptBlocked")
  570. }
  571. }
  572. func testGenerateContent_failure_promptBlockedSafetyWithMessage() async throws {
  573. MockURLProtocol
  574. .requestHandler = try httpRequestHandler(
  575. forResource: "unary-failure-prompt-blocked-safety-with-message",
  576. withExtension: "json"
  577. )
  578. do {
  579. _ = try await model.generateContent(testPrompt)
  580. XCTFail("Should throw")
  581. } catch let GenerateContentError.promptBlocked(response) {
  582. XCTAssertNil(response.text)
  583. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  584. XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
  585. XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
  586. } catch {
  587. XCTFail("Should throw a promptBlocked")
  588. }
  589. }
  590. func testGenerateContent_failure_unknownEnum_finishReason() async throws {
  591. MockURLProtocol
  592. .requestHandler = try httpRequestHandler(
  593. forResource: "unary-failure-unknown-enum-finish-reason",
  594. withExtension: "json"
  595. )
  596. let unknownFinishReason = FinishReason(rawValue: "FAKE_NEW_FINISH_REASON")
  597. do {
  598. _ = try await model.generateContent(testPrompt)
  599. XCTFail("Should throw")
  600. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  601. XCTAssertEqual(reason, unknownFinishReason)
  602. XCTAssertEqual(response.text, "Some text")
  603. } catch {
  604. XCTFail("Should throw a responseStoppedEarly")
  605. }
  606. }
  607. func testGenerateContent_failure_unknownEnum_promptBlocked() async throws {
  608. MockURLProtocol
  609. .requestHandler = try httpRequestHandler(
  610. forResource: "unary-failure-unknown-enum-prompt-blocked",
  611. withExtension: "json"
  612. )
  613. let unknownBlockReason = PromptFeedback.BlockReason(rawValue: "FAKE_NEW_BLOCK_REASON")
  614. do {
  615. _ = try await model.generateContent(testPrompt)
  616. XCTFail("Should throw")
  617. } catch let GenerateContentError.promptBlocked(response) {
  618. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  619. XCTAssertEqual(promptFeedback.blockReason, unknownBlockReason)
  620. } catch {
  621. XCTFail("Should throw a promptBlocked")
  622. }
  623. }
  624. func testGenerateContent_failure_unknownModel() async throws {
  625. let expectedStatusCode = 404
  626. MockURLProtocol
  627. .requestHandler = try httpRequestHandler(
  628. forResource: "unary-failure-unknown-model",
  629. withExtension: "json",
  630. statusCode: 404
  631. )
  632. do {
  633. _ = try await model.generateContent(testPrompt)
  634. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  635. } catch let GenerateContentError.internalError(underlying: rpcError as RPCError) {
  636. XCTAssertEqual(rpcError.status, .notFound)
  637. XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
  638. XCTAssertTrue(rpcError.message.hasPrefix("models/unknown is not found"))
  639. } catch {
  640. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  641. }
  642. }
  643. func testGenerateContent_failure_nonHTTPResponse() async throws {
  644. MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
  645. var responseError: Error?
  646. var content: GenerateContentResponse?
  647. do {
  648. content = try await model.generateContent(testPrompt)
  649. } catch {
  650. responseError = error
  651. }
  652. XCTAssertNil(content)
  653. XCTAssertNotNil(responseError)
  654. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  655. guard case let .internalError(underlyingError) = generateContentError else {
  656. XCTFail("Not an internal error: \(generateContentError)")
  657. return
  658. }
  659. XCTAssertEqual(underlyingError.localizedDescription, "Response was not an HTTP response.")
  660. }
  661. func testGenerateContent_failure_invalidResponse() async throws {
  662. MockURLProtocol.requestHandler = try httpRequestHandler(
  663. forResource: "unary-failure-invalid-response",
  664. withExtension: "json"
  665. )
  666. var responseError: Error?
  667. var content: GenerateContentResponse?
  668. do {
  669. content = try await model.generateContent(testPrompt)
  670. } catch {
  671. responseError = error
  672. }
  673. XCTAssertNil(content)
  674. XCTAssertNotNil(responseError)
  675. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  676. guard case let .internalError(underlyingError) = generateContentError else {
  677. XCTFail("Not an internal error: \(generateContentError)")
  678. return
  679. }
  680. let decodingError = try XCTUnwrap(underlyingError as? DecodingError)
  681. guard case let .dataCorrupted(context) = decodingError else {
  682. XCTFail("Not a data corrupted error: \(decodingError)")
  683. return
  684. }
  685. XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
  686. }
  687. func testGenerateContent_failure_malformedContent() async throws {
  688. MockURLProtocol
  689. .requestHandler = try httpRequestHandler(
  690. forResource: "unary-failure-malformed-content",
  691. withExtension: "json"
  692. )
  693. var responseError: Error?
  694. var content: GenerateContentResponse?
  695. do {
  696. content = try await model.generateContent(testPrompt)
  697. } catch {
  698. responseError = error
  699. }
  700. XCTAssertNil(content)
  701. XCTAssertNotNil(responseError)
  702. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  703. guard case let .internalError(underlyingError) = generateContentError else {
  704. XCTFail("Not an internal error: \(generateContentError)")
  705. return
  706. }
  707. let invalidCandidateError = try XCTUnwrap(underlyingError as? InvalidCandidateError)
  708. guard case let .malformedContent(malformedContentUnderlyingError) = invalidCandidateError else {
  709. XCTFail("Not a malformed content error: \(invalidCandidateError)")
  710. return
  711. }
  712. _ = try XCTUnwrap(
  713. malformedContentUnderlyingError as? DecodingError,
  714. "Not a decoding error: \(malformedContentUnderlyingError)"
  715. )
  716. }
  717. func testGenerateContentMissingSafetyRatings() async throws {
  718. MockURLProtocol.requestHandler = try httpRequestHandler(
  719. forResource: "unary-success-missing-safety-ratings",
  720. withExtension: "json"
  721. )
  722. let content = try await model.generateContent(testPrompt)
  723. let promptFeedback = try XCTUnwrap(content.promptFeedback)
  724. XCTAssertEqual(promptFeedback.safetyRatings.count, 0)
  725. XCTAssertEqual(content.text, "This is the generated content.")
  726. }
  727. func testGenerateContent_requestOptions_customTimeout() async throws {
  728. let expectedTimeout = 150.0
  729. MockURLProtocol
  730. .requestHandler = try httpRequestHandler(
  731. forResource: "unary-success-basic-reply-short",
  732. withExtension: "json",
  733. timeout: expectedTimeout
  734. )
  735. let requestOptions = RequestOptions(timeout: expectedTimeout)
  736. model = GenerativeModel(
  737. name: testModelResourceName,
  738. projectID: "my-project-id",
  739. apiKey: "API_KEY",
  740. tools: nil,
  741. requestOptions: requestOptions,
  742. appCheck: nil,
  743. auth: nil,
  744. urlSession: urlSession
  745. )
  746. let response = try await model.generateContent(testPrompt)
  747. XCTAssertEqual(response.candidates.count, 1)
  748. }
  749. // MARK: - Generate Content (Streaming)
  750. func testGenerateContentStream_failureInvalidAPIKey() async throws {
  751. MockURLProtocol
  752. .requestHandler = try httpRequestHandler(
  753. forResource: "unary-failure-api-key",
  754. withExtension: "json"
  755. )
  756. do {
  757. let stream = try model.generateContentStream("Hi")
  758. for try await _ in stream {
  759. XCTFail("No content is there, this shouldn't happen.")
  760. }
  761. } catch let GenerateContentError.internalError(error as RPCError) {
  762. XCTAssertEqual(error.httpResponseCode, 400)
  763. XCTAssertEqual(error.status, .invalidArgument)
  764. XCTAssertEqual(error.message, "API key not valid. Please pass a valid API key.")
  765. return
  766. }
  767. XCTFail("Should have caught an error.")
  768. }
  769. func testGenerateContentStream_failure_vertexAIInFirebaseAPINotEnabled() async throws {
  770. let expectedStatusCode = 403
  771. MockURLProtocol
  772. .requestHandler = try httpRequestHandler(
  773. forResource: "unary-failure-firebasevertexai-api-not-enabled",
  774. withExtension: "json",
  775. statusCode: expectedStatusCode
  776. )
  777. do {
  778. let stream = try model.generateContentStream(testPrompt)
  779. for try await _ in stream {
  780. XCTFail("No content is there, this shouldn't happen.")
  781. }
  782. } catch let GenerateContentError.internalError(error as RPCError) {
  783. XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
  784. XCTAssertEqual(error.status, .permissionDenied)
  785. XCTAssertTrue(error.message
  786. .starts(with: "Vertex AI in Firebase API has not been used in project"))
  787. XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
  788. return
  789. }
  790. XCTFail("Should have caught an error.")
  791. }
  792. func testGenerateContentStream_failureEmptyContent() async throws {
  793. MockURLProtocol
  794. .requestHandler = try httpRequestHandler(
  795. forResource: "streaming-failure-empty-content",
  796. withExtension: "txt"
  797. )
  798. do {
  799. let stream = try model.generateContentStream("Hi")
  800. for try await _ in stream {
  801. XCTFail("No content is there, this shouldn't happen.")
  802. }
  803. } catch GenerateContentError.internalError(_ as InvalidCandidateError) {
  804. // Underlying error is as expected, nothing else to check.
  805. return
  806. }
  807. XCTFail("Should have caught an error.")
  808. }
  809. func testGenerateContentStream_failureFinishReasonSafety() async throws {
  810. MockURLProtocol
  811. .requestHandler = try httpRequestHandler(
  812. forResource: "streaming-failure-finish-reason-safety",
  813. withExtension: "txt"
  814. )
  815. do {
  816. let stream = try model.generateContentStream("Hi")
  817. for try await _ in stream {
  818. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  819. }
  820. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  821. XCTAssertEqual(reason, .safety)
  822. let candidate = try XCTUnwrap(response.candidates.first)
  823. XCTAssertEqual(candidate.finishReason, reason)
  824. XCTAssertTrue(candidate.safetyRatings.contains { $0.blocked })
  825. return
  826. }
  827. XCTFail("Should have caught an error.")
  828. }
  829. func testGenerateContentStream_failurePromptBlockedSafety() async throws {
  830. MockURLProtocol
  831. .requestHandler = try httpRequestHandler(
  832. forResource: "streaming-failure-prompt-blocked-safety",
  833. withExtension: "txt"
  834. )
  835. do {
  836. let stream = try model.generateContentStream("Hi")
  837. for try await _ in stream {
  838. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  839. }
  840. } catch let GenerateContentError.promptBlocked(response) {
  841. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  842. XCTAssertEqual(promptFeedback.blockReason, .safety)
  843. XCTAssertNil(promptFeedback.blockReasonMessage)
  844. return
  845. }
  846. XCTFail("Should have caught an error.")
  847. }
  848. func testGenerateContentStream_failurePromptBlockedSafetyWithMessage() async throws {
  849. MockURLProtocol
  850. .requestHandler = try httpRequestHandler(
  851. forResource: "streaming-failure-prompt-blocked-safety-with-message",
  852. withExtension: "txt"
  853. )
  854. do {
  855. let stream = try model.generateContentStream("Hi")
  856. for try await _ in stream {
  857. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  858. }
  859. } catch let GenerateContentError.promptBlocked(response) {
  860. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  861. XCTAssertEqual(promptFeedback.blockReason, .safety)
  862. XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
  863. return
  864. }
  865. XCTFail("Should have caught an error.")
  866. }
  867. func testGenerateContentStream_failureUnknownFinishEnum() async throws {
  868. MockURLProtocol
  869. .requestHandler = try httpRequestHandler(
  870. forResource: "streaming-failure-unknown-finish-enum",
  871. withExtension: "txt"
  872. )
  873. let unknownFinishReason = FinishReason(rawValue: "FAKE_ENUM")
  874. let stream = try model.generateContentStream("Hi")
  875. do {
  876. for try await content in stream {
  877. XCTAssertNotNil(content.text)
  878. }
  879. } catch let GenerateContentError.responseStoppedEarly(reason, _) {
  880. XCTAssertEqual(reason, unknownFinishReason)
  881. return
  882. }
  883. XCTFail("Should have caught an error.")
  884. }
  885. func testGenerateContentStream_successBasicReplyLong() async throws {
  886. MockURLProtocol
  887. .requestHandler = try httpRequestHandler(
  888. forResource: "streaming-success-basic-reply-long",
  889. withExtension: "txt"
  890. )
  891. var responses = 0
  892. let stream = try model.generateContentStream("Hi")
  893. for try await content in stream {
  894. XCTAssertNotNil(content.text)
  895. responses += 1
  896. }
  897. XCTAssertEqual(responses, 6)
  898. }
  899. func testGenerateContentStream_successBasicReplyShort() async throws {
  900. MockURLProtocol
  901. .requestHandler = try httpRequestHandler(
  902. forResource: "streaming-success-basic-reply-short",
  903. withExtension: "txt"
  904. )
  905. var responses = 0
  906. let stream = try model.generateContentStream("Hi")
  907. for try await content in stream {
  908. XCTAssertNotNil(content.text)
  909. responses += 1
  910. }
  911. XCTAssertEqual(responses, 1)
  912. }
  913. func testGenerateContentStream_successUnknownSafetyEnum() async throws {
  914. MockURLProtocol
  915. .requestHandler = try httpRequestHandler(
  916. forResource: "streaming-success-unknown-safety-enum",
  917. withExtension: "txt"
  918. )
  919. let unknownSafetyRating = SafetyRating(
  920. category: HarmCategory(rawValue: "HARM_CATEGORY_DANGEROUS_CONTENT_NEW_ENUM"),
  921. probability: SafetyRating.HarmProbability(rawValue: "NEGLIGIBLE_UNKNOWN_ENUM"),
  922. probabilityScore: 0.0,
  923. severity: SafetyRating.HarmSeverity(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
  924. severityScore: 0.0,
  925. blocked: false
  926. )
  927. var foundUnknownSafetyRating = false
  928. let stream = try model.generateContentStream("Hi")
  929. for try await content in stream {
  930. XCTAssertNotNil(content.text)
  931. if let ratings = content.candidates.first?.safetyRatings,
  932. ratings.contains(where: { $0 == unknownSafetyRating }) {
  933. foundUnknownSafetyRating = true
  934. }
  935. }
  936. XCTAssertTrue(foundUnknownSafetyRating)
  937. }
  938. func testGenerateContentStream_successWithCitations() async throws {
  939. MockURLProtocol
  940. .requestHandler = try httpRequestHandler(
  941. forResource: "streaming-success-citations",
  942. withExtension: "txt"
  943. )
  944. let expectedPublicationDate = DateComponents(
  945. calendar: Calendar(identifier: .gregorian),
  946. year: 2014,
  947. month: 3,
  948. day: 30
  949. )
  950. let stream = try model.generateContentStream("Hi")
  951. var citations = [Citation]()
  952. var responses = [GenerateContentResponse]()
  953. for try await content in stream {
  954. responses.append(content)
  955. XCTAssertNotNil(content.text)
  956. let candidate = try XCTUnwrap(content.candidates.first)
  957. if let sources = candidate.citationMetadata?.citations {
  958. citations.append(contentsOf: sources)
  959. }
  960. }
  961. let lastCandidate = try XCTUnwrap(responses.last?.candidates.first)
  962. XCTAssertEqual(lastCandidate.finishReason, .stop)
  963. XCTAssertEqual(citations.count, 6)
  964. XCTAssertTrue(citations
  965. .contains {
  966. $0.startIndex == 0 && $0.endIndex == 128
  967. && $0.uri == "https://www.example.com/some-citation-1" && $0.title == nil
  968. && $0.license == nil && $0.publicationDate == nil
  969. })
  970. XCTAssertTrue(citations
  971. .contains {
  972. $0.startIndex == 130 && $0.endIndex == 265 && $0.uri == nil
  973. && $0.title == "some-citation-2" && $0.license == nil
  974. && $0.publicationDate == expectedPublicationDate
  975. })
  976. XCTAssertTrue(citations
  977. .contains {
  978. $0.startIndex == 272 && $0.endIndex == 431
  979. && $0.uri == "https://www.example.com/some-citation-3" && $0.title == nil
  980. && $0.license == "mit" && $0.publicationDate == nil
  981. })
  982. XCTAssertFalse(citations.contains { $0.uri?.isEmpty ?? false })
  983. XCTAssertFalse(citations.contains { $0.title?.isEmpty ?? false })
  984. XCTAssertFalse(citations.contains { $0.license?.isEmpty ?? false })
  985. }
  986. func testGenerateContentStream_appCheck_validToken() async throws {
  987. let appCheckToken = "test-valid-token"
  988. model = GenerativeModel(
  989. name: testModelResourceName,
  990. projectID: "my-project-id",
  991. apiKey: "API_KEY",
  992. tools: nil,
  993. requestOptions: RequestOptions(),
  994. appCheck: AppCheckInteropFake(token: appCheckToken),
  995. auth: nil,
  996. urlSession: urlSession
  997. )
  998. MockURLProtocol
  999. .requestHandler = try httpRequestHandler(
  1000. forResource: "streaming-success-basic-reply-short",
  1001. withExtension: "txt",
  1002. appCheckToken: appCheckToken
  1003. )
  1004. let stream = try model.generateContentStream(testPrompt)
  1005. for try await _ in stream {}
  1006. }
  1007. func testGenerateContentStream_appCheck_tokenRefreshError() async throws {
  1008. model = GenerativeModel(
  1009. name: testModelResourceName,
  1010. projectID: "my-project-id",
  1011. apiKey: "API_KEY",
  1012. tools: nil,
  1013. requestOptions: RequestOptions(),
  1014. appCheck: AppCheckInteropFake(error: AppCheckErrorFake()),
  1015. auth: nil,
  1016. urlSession: urlSession
  1017. )
  1018. MockURLProtocol
  1019. .requestHandler = try httpRequestHandler(
  1020. forResource: "streaming-success-basic-reply-short",
  1021. withExtension: "txt",
  1022. appCheckToken: AppCheckInteropFake.placeholderTokenValue
  1023. )
  1024. let stream = try model.generateContentStream(testPrompt)
  1025. for try await _ in stream {}
  1026. }
  1027. func testGenerateContentStream_usageMetadata() async throws {
  1028. MockURLProtocol
  1029. .requestHandler = try httpRequestHandler(
  1030. forResource: "streaming-success-basic-reply-short",
  1031. withExtension: "txt"
  1032. )
  1033. var responses = [GenerateContentResponse]()
  1034. let stream = try model.generateContentStream(testPrompt)
  1035. for try await response in stream {
  1036. responses.append(response)
  1037. }
  1038. for (index, response) in responses.enumerated() {
  1039. if index == responses.endIndex - 1 {
  1040. let usageMetadata = try XCTUnwrap(response.usageMetadata)
  1041. XCTAssertEqual(usageMetadata.promptTokenCount, 6)
  1042. XCTAssertEqual(usageMetadata.candidatesTokenCount, 4)
  1043. XCTAssertEqual(usageMetadata.totalTokenCount, 10)
  1044. } else {
  1045. // Only the last streamed response contains usage metadata
  1046. XCTAssertNil(response.usageMetadata)
  1047. }
  1048. }
  1049. }
  1050. func testGenerateContentStream_errorMidStream() async throws {
  1051. MockURLProtocol.requestHandler = try httpRequestHandler(
  1052. forResource: "streaming-failure-error-mid-stream",
  1053. withExtension: "txt"
  1054. )
  1055. var responseCount = 0
  1056. do {
  1057. let stream = try model.generateContentStream("Hi")
  1058. for try await content in stream {
  1059. XCTAssertNotNil(content.text)
  1060. responseCount += 1
  1061. }
  1062. } catch let GenerateContentError.internalError(rpcError as RPCError) {
  1063. XCTAssertEqual(rpcError.httpResponseCode, 499)
  1064. XCTAssertEqual(rpcError.status, .cancelled)
  1065. // Check the content count is correct.
  1066. XCTAssertEqual(responseCount, 2)
  1067. return
  1068. }
  1069. XCTFail("Expected an internalError with an RPCError.")
  1070. }
  1071. func testGenerateContentStream_nonHTTPResponse() async throws {
  1072. MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
  1073. let stream = try model.generateContentStream("Hi")
  1074. do {
  1075. for try await content in stream {
  1076. XCTFail("Unexpected content in stream: \(content)")
  1077. }
  1078. } catch let GenerateContentError.internalError(underlying) {
  1079. XCTAssertEqual(underlying.localizedDescription, "Response was not an HTTP response.")
  1080. return
  1081. }
  1082. XCTFail("Expected an internal error.")
  1083. }
  1084. func testGenerateContentStream_invalidResponse() async throws {
  1085. MockURLProtocol
  1086. .requestHandler = try httpRequestHandler(
  1087. forResource: "streaming-failure-invalid-json",
  1088. withExtension: "txt"
  1089. )
  1090. let stream = try model.generateContentStream(testPrompt)
  1091. do {
  1092. for try await content in stream {
  1093. XCTFail("Unexpected content in stream: \(content)")
  1094. }
  1095. } catch let GenerateContentError.internalError(underlying as DecodingError) {
  1096. guard case let .dataCorrupted(context) = underlying else {
  1097. XCTFail("Not a data corrupted error: \(underlying)")
  1098. return
  1099. }
  1100. XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
  1101. return
  1102. }
  1103. XCTFail("Expected an internal error.")
  1104. }
  1105. func testGenerateContentStream_malformedContent() async throws {
  1106. MockURLProtocol
  1107. .requestHandler = try httpRequestHandler(
  1108. forResource: "streaming-failure-malformed-content",
  1109. withExtension: "txt"
  1110. )
  1111. let stream = try model.generateContentStream(testPrompt)
  1112. do {
  1113. for try await content in stream {
  1114. XCTFail("Unexpected content in stream: \(content)")
  1115. }
  1116. } catch let GenerateContentError.internalError(underlyingError as InvalidCandidateError) {
  1117. guard case let .malformedContent(contentError) = underlyingError else {
  1118. XCTFail("Not a malformed content error: \(underlyingError)")
  1119. return
  1120. }
  1121. XCTAssert(contentError is DecodingError)
  1122. return
  1123. }
  1124. XCTFail("Expected an internal decoding error.")
  1125. }
  1126. func testGenerateContentStream_requestOptions_customTimeout() async throws {
  1127. let expectedTimeout = 150.0
  1128. MockURLProtocol
  1129. .requestHandler = try httpRequestHandler(
  1130. forResource: "streaming-success-basic-reply-short",
  1131. withExtension: "txt",
  1132. timeout: expectedTimeout
  1133. )
  1134. let requestOptions = RequestOptions(timeout: expectedTimeout)
  1135. model = GenerativeModel(
  1136. name: testModelResourceName,
  1137. projectID: "my-project-id",
  1138. apiKey: "API_KEY",
  1139. tools: nil,
  1140. requestOptions: requestOptions,
  1141. appCheck: nil,
  1142. auth: nil,
  1143. urlSession: urlSession
  1144. )
  1145. var responses = 0
  1146. let stream = try model.generateContentStream(testPrompt)
  1147. for try await content in stream {
  1148. XCTAssertNotNil(content.text)
  1149. responses += 1
  1150. }
  1151. XCTAssertEqual(responses, 1)
  1152. }
  1153. // MARK: - Count Tokens
  1154. func testCountTokens_succeeds() async throws {
  1155. MockURLProtocol.requestHandler = try httpRequestHandler(
  1156. forResource: "unary-success-total-tokens",
  1157. withExtension: "json"
  1158. )
  1159. let response = try await model.countTokens("Why is the sky blue?")
  1160. XCTAssertEqual(response.totalTokens, 6)
  1161. XCTAssertEqual(response.totalBillableCharacters, 16)
  1162. }
  1163. func testCountTokens_succeeds_allOptions() async throws {
  1164. MockURLProtocol.requestHandler = try httpRequestHandler(
  1165. forResource: "unary-success-total-tokens",
  1166. withExtension: "json"
  1167. )
  1168. let generationConfig = GenerationConfig(
  1169. temperature: 0.5,
  1170. topP: 0.9,
  1171. topK: 3,
  1172. candidateCount: 1,
  1173. maxOutputTokens: 1024,
  1174. stopSequences: ["test-stop"],
  1175. responseMIMEType: "text/plain"
  1176. )
  1177. let sumFunction = FunctionDeclaration(
  1178. name: "sum",
  1179. description: "Add two integers.",
  1180. parameters: ["x": .integer(), "y": .integer()]
  1181. )
  1182. let systemInstruction = ModelContent(
  1183. role: "system",
  1184. parts: "You are a calculator. Use the provided tools."
  1185. )
  1186. model = GenerativeModel(
  1187. name: testModelResourceName,
  1188. projectID: "my-project-id",
  1189. apiKey: "API_KEY",
  1190. generationConfig: generationConfig,
  1191. tools: [Tool(functionDeclarations: [sumFunction])],
  1192. systemInstruction: systemInstruction,
  1193. requestOptions: RequestOptions(),
  1194. appCheck: nil,
  1195. auth: nil,
  1196. urlSession: urlSession
  1197. )
  1198. let response = try await model.countTokens("Why is the sky blue?")
  1199. XCTAssertEqual(response.totalTokens, 6)
  1200. XCTAssertEqual(response.totalBillableCharacters, 16)
  1201. }
  1202. func testCountTokens_succeeds_noBillableCharacters() async throws {
  1203. MockURLProtocol.requestHandler = try httpRequestHandler(
  1204. forResource: "unary-success-no-billable-characters",
  1205. withExtension: "json"
  1206. )
  1207. let response = try await model.countTokens(InlineDataPart(data: Data(), mimeType: "image/jpeg"))
  1208. XCTAssertEqual(response.totalTokens, 258)
  1209. XCTAssertNil(response.totalBillableCharacters)
  1210. }
  1211. func testCountTokens_modelNotFound() async throws {
  1212. MockURLProtocol.requestHandler = try httpRequestHandler(
  1213. forResource: "unary-failure-model-not-found", withExtension: "json",
  1214. statusCode: 404
  1215. )
  1216. do {
  1217. _ = try await model.countTokens("Why is the sky blue?")
  1218. XCTFail("Request should not have succeeded.")
  1219. } catch let rpcError as RPCError {
  1220. XCTAssertEqual(rpcError.httpResponseCode, 404)
  1221. XCTAssertEqual(rpcError.status, .notFound)
  1222. XCTAssert(rpcError.message.hasPrefix("models/test-model-name is not found"))
  1223. return
  1224. }
  1225. XCTFail("Expected internal RPCError.")
  1226. }
  1227. func testCountTokens_requestOptions_customTimeout() async throws {
  1228. let expectedTimeout = 150.0
  1229. MockURLProtocol
  1230. .requestHandler = try httpRequestHandler(
  1231. forResource: "unary-success-total-tokens",
  1232. withExtension: "json",
  1233. timeout: expectedTimeout
  1234. )
  1235. let requestOptions = RequestOptions(timeout: expectedTimeout)
  1236. model = GenerativeModel(
  1237. name: testModelResourceName,
  1238. projectID: "my-project-id",
  1239. apiKey: "API_KEY",
  1240. tools: nil,
  1241. requestOptions: requestOptions,
  1242. appCheck: nil,
  1243. auth: nil,
  1244. urlSession: urlSession
  1245. )
  1246. let response = try await model.countTokens(testPrompt)
  1247. XCTAssertEqual(response.totalTokens, 6)
  1248. }
  1249. // MARK: - Helpers
  1250. private func nonHTTPRequestHandler() throws -> ((URLRequest) -> (
  1251. URLResponse,
  1252. AsyncLineSequence<URL.AsyncBytes>?
  1253. )) {
  1254. // Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
  1255. // https://developer.apple.com/documentation/foundation/urlprotocol for details.
  1256. #if os(watchOS)
  1257. throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
  1258. #endif // os(watchOS)
  1259. return { request in
  1260. // This is *not* an HTTPURLResponse
  1261. let response = URLResponse(
  1262. url: request.url!,
  1263. mimeType: nil,
  1264. expectedContentLength: 0,
  1265. textEncodingName: nil
  1266. )
  1267. return (response, nil)
  1268. }
  1269. }
  1270. private func httpRequestHandler(forResource name: String,
  1271. withExtension ext: String,
  1272. statusCode: Int = 200,
  1273. timeout: TimeInterval = RequestOptions().timeout,
  1274. appCheckToken: String? = nil,
  1275. authToken: String? = nil) throws -> ((URLRequest) throws -> (
  1276. URLResponse,
  1277. AsyncLineSequence<URL.AsyncBytes>?
  1278. )) {
  1279. // Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
  1280. // https://developer.apple.com/documentation/foundation/urlprotocol for details.
  1281. #if os(watchOS)
  1282. throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
  1283. #endif // os(watchOS)
  1284. let bundle = BundleTestUtil.bundle()
  1285. let fileURL = try XCTUnwrap(bundle.url(forResource: name, withExtension: ext))
  1286. return { request in
  1287. let requestURL = try XCTUnwrap(request.url)
  1288. XCTAssertEqual(requestURL.path.occurrenceCount(of: "models/"), 1)
  1289. XCTAssertEqual(request.timeoutInterval, timeout)
  1290. let apiClientTags = try XCTUnwrap(request.value(forHTTPHeaderField: "x-goog-api-client"))
  1291. .components(separatedBy: " ")
  1292. XCTAssert(apiClientTags.contains(GenerativeAIService.languageTag))
  1293. XCTAssert(apiClientTags.contains(GenerativeAIService.firebaseVersionTag))
  1294. XCTAssertEqual(request.value(forHTTPHeaderField: "X-Firebase-AppCheck"), appCheckToken)
  1295. if let authToken {
  1296. XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Firebase \(authToken)")
  1297. } else {
  1298. XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
  1299. }
  1300. let response = try XCTUnwrap(HTTPURLResponse(
  1301. url: requestURL,
  1302. statusCode: statusCode,
  1303. httpVersion: nil,
  1304. headerFields: nil
  1305. ))
  1306. return (response, fileURL.lines)
  1307. }
  1308. }
  1309. }
  1310. private extension String {
  1311. /// Returns the number of occurrences of `substring` in the `String`.
  1312. func occurrenceCount(of substring: String) -> Int {
  1313. return components(separatedBy: substring).count - 1
  1314. }
  1315. }
  1316. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1317. class AppCheckInteropFake: NSObject, AppCheckInterop {
  1318. /// The placeholder token value returned when an error occurs
  1319. static let placeholderTokenValue = "placeholder-token"
  1320. var token: String
  1321. var error: Error?
  1322. private init(token: String, error: Error?) {
  1323. self.token = token
  1324. self.error = error
  1325. }
  1326. convenience init(token: String) {
  1327. self.init(token: token, error: nil)
  1328. }
  1329. convenience init(error: Error) {
  1330. self.init(token: AppCheckInteropFake.placeholderTokenValue, error: error)
  1331. }
  1332. func getToken(forcingRefresh: Bool) async -> any FIRAppCheckTokenResultInterop {
  1333. return AppCheckTokenResultInteropFake(token: token, error: error)
  1334. }
  1335. func tokenDidChangeNotificationName() -> String {
  1336. fatalError("\(#function) not implemented.")
  1337. }
  1338. func notificationTokenKey() -> String {
  1339. fatalError("\(#function) not implemented.")
  1340. }
  1341. func notificationAppNameKey() -> String {
  1342. fatalError("\(#function) not implemented.")
  1343. }
  1344. private class AppCheckTokenResultInteropFake: NSObject, FIRAppCheckTokenResultInterop {
  1345. var token: String
  1346. var error: Error?
  1347. init(token: String, error: Error?) {
  1348. self.token = token
  1349. self.error = error
  1350. }
  1351. }
  1352. }
  1353. struct AppCheckErrorFake: Error {}
  1354. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1355. extension SafetyRating: Swift.Comparable {
  1356. public static func < (lhs: FirebaseVertexAI.SafetyRating,
  1357. rhs: FirebaseVertexAI.SafetyRating) -> Bool {
  1358. return lhs.category.rawValue < rhs.category.rawValue
  1359. }
  1360. }