GenerativeModelTests.swift 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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. #if SWIFT_PACKAGE
  1285. let bundle = Bundle.module
  1286. #else // SWIFT_PACKAGE
  1287. let bundle = Bundle(for: Self.self)
  1288. #endif // SWIFT_PACKAGE
  1289. let fileURL = try XCTUnwrap(bundle.url(forResource: name, withExtension: ext))
  1290. return { request in
  1291. let requestURL = try XCTUnwrap(request.url)
  1292. XCTAssertEqual(requestURL.path.occurrenceCount(of: "models/"), 1)
  1293. XCTAssertEqual(request.timeoutInterval, timeout)
  1294. let apiClientTags = try XCTUnwrap(request.value(forHTTPHeaderField: "x-goog-api-client"))
  1295. .components(separatedBy: " ")
  1296. XCTAssert(apiClientTags.contains(GenerativeAIService.languageTag))
  1297. XCTAssert(apiClientTags.contains(GenerativeAIService.firebaseVersionTag))
  1298. XCTAssertEqual(request.value(forHTTPHeaderField: "X-Firebase-AppCheck"), appCheckToken)
  1299. if let authToken {
  1300. XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Firebase \(authToken)")
  1301. } else {
  1302. XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
  1303. }
  1304. let response = try XCTUnwrap(HTTPURLResponse(
  1305. url: requestURL,
  1306. statusCode: statusCode,
  1307. httpVersion: nil,
  1308. headerFields: nil
  1309. ))
  1310. return (response, fileURL.lines)
  1311. }
  1312. }
  1313. }
  1314. private extension String {
  1315. /// Returns the number of occurrences of `substring` in the `String`.
  1316. func occurrenceCount(of substring: String) -> Int {
  1317. return components(separatedBy: substring).count - 1
  1318. }
  1319. }
  1320. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1321. class AppCheckInteropFake: NSObject, AppCheckInterop {
  1322. /// The placeholder token value returned when an error occurs
  1323. static let placeholderTokenValue = "placeholder-token"
  1324. var token: String
  1325. var error: Error?
  1326. private init(token: String, error: Error?) {
  1327. self.token = token
  1328. self.error = error
  1329. }
  1330. convenience init(token: String) {
  1331. self.init(token: token, error: nil)
  1332. }
  1333. convenience init(error: Error) {
  1334. self.init(token: AppCheckInteropFake.placeholderTokenValue, error: error)
  1335. }
  1336. func getToken(forcingRefresh: Bool) async -> any FIRAppCheckTokenResultInterop {
  1337. return AppCheckTokenResultInteropFake(token: token, error: error)
  1338. }
  1339. func tokenDidChangeNotificationName() -> String {
  1340. fatalError("\(#function) not implemented.")
  1341. }
  1342. func notificationTokenKey() -> String {
  1343. fatalError("\(#function) not implemented.")
  1344. }
  1345. func notificationAppNameKey() -> String {
  1346. fatalError("\(#function) not implemented.")
  1347. }
  1348. private class AppCheckTokenResultInteropFake: NSObject, FIRAppCheckTokenResultInterop {
  1349. var token: String
  1350. var error: Error?
  1351. init(token: String, error: Error?) {
  1352. self.token = token
  1353. self.error = error
  1354. }
  1355. }
  1356. }
  1357. struct AppCheckErrorFake: Error {}
  1358. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1359. extension SafetyRating: Swift.Comparable {
  1360. public static func < (lhs: FirebaseVertexAI.SafetyRating,
  1361. rhs: FirebaseVertexAI.SafetyRating) -> Bool {
  1362. return lhs.category.rawValue < rhs.category.rawValue
  1363. }
  1364. }