GenerativeModelTests.swift 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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 BackendError) {
  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. XCTAssertTrue(error.localizedDescription.contains(error.message))
  456. XCTAssertTrue(error.localizedDescription.contains(error.status.rawValue))
  457. XCTAssertTrue(error.localizedDescription.contains("\(error.httpResponseCode)"))
  458. let nsError = error as NSError
  459. XCTAssertEqual(nsError.domain, "\(Constants.baseErrorDomain).\(BackendError.self)")
  460. XCTAssertEqual(nsError.code, error.httpResponseCode)
  461. return
  462. } catch {
  463. XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
  464. }
  465. }
  466. func testGenerateContent_failure_firebaseVertexAIAPINotEnabled() async throws {
  467. let expectedStatusCode = 403
  468. MockURLProtocol
  469. .requestHandler = try httpRequestHandler(
  470. forResource: "unary-failure-firebasevertexai-api-not-enabled",
  471. withExtension: "json",
  472. statusCode: expectedStatusCode
  473. )
  474. do {
  475. _ = try await model.generateContent(testPrompt)
  476. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  477. } catch let GenerateContentError.internalError(error as BackendError) {
  478. XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
  479. XCTAssertEqual(error.status, .permissionDenied)
  480. XCTAssertTrue(error.message
  481. .starts(with: "Vertex AI in Firebase API has not been used in project"))
  482. XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
  483. return
  484. } catch {
  485. XCTFail("Should throw GenerateContentError.internalError(RPCError); error thrown: \(error)")
  486. }
  487. }
  488. func testGenerateContent_failure_emptyContent() async throws {
  489. MockURLProtocol
  490. .requestHandler = try httpRequestHandler(
  491. forResource: "unary-failure-empty-content",
  492. withExtension: "json"
  493. )
  494. do {
  495. _ = try await model.generateContent(testPrompt)
  496. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  497. } catch let GenerateContentError
  498. .internalError(underlying: invalidCandidateError as InvalidCandidateError) {
  499. guard case let .emptyContent(decodingError) = invalidCandidateError else {
  500. XCTFail("Not an InvalidCandidateError.emptyContent error: \(invalidCandidateError)")
  501. return
  502. }
  503. _ = try XCTUnwrap(decodingError as? DecodingError,
  504. "Not a DecodingError: \(decodingError)")
  505. } catch {
  506. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  507. }
  508. }
  509. func testGenerateContent_failure_finishReasonSafety() async throws {
  510. MockURLProtocol
  511. .requestHandler = try httpRequestHandler(
  512. forResource: "unary-failure-finish-reason-safety",
  513. withExtension: "json"
  514. )
  515. do {
  516. _ = try await model.generateContent(testPrompt)
  517. XCTFail("Should throw")
  518. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  519. XCTAssertEqual(reason, .safety)
  520. XCTAssertEqual(response.text, "<redacted>")
  521. } catch {
  522. XCTFail("Should throw a responseStoppedEarly")
  523. }
  524. }
  525. func testGenerateContent_failure_finishReasonSafety_noContent() async throws {
  526. MockURLProtocol
  527. .requestHandler = try httpRequestHandler(
  528. forResource: "unary-failure-finish-reason-safety-no-content",
  529. withExtension: "json"
  530. )
  531. do {
  532. _ = try await model.generateContent(testPrompt)
  533. XCTFail("Should throw")
  534. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  535. XCTAssertEqual(reason, .safety)
  536. XCTAssertNil(response.text)
  537. } catch {
  538. XCTFail("Should throw a responseStoppedEarly")
  539. }
  540. }
  541. func testGenerateContent_failure_imageRejected() async throws {
  542. let expectedStatusCode = 400
  543. MockURLProtocol
  544. .requestHandler = try httpRequestHandler(
  545. forResource: "unary-failure-image-rejected",
  546. withExtension: "json",
  547. statusCode: 400
  548. )
  549. do {
  550. _ = try await model.generateContent(testPrompt)
  551. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  552. } catch let GenerateContentError.internalError(underlying: rpcError as BackendError) {
  553. XCTAssertEqual(rpcError.status, .invalidArgument)
  554. XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
  555. XCTAssertEqual(rpcError.message, "Request contains an invalid argument.")
  556. } catch {
  557. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  558. }
  559. }
  560. func testGenerateContent_failure_promptBlockedSafety() async throws {
  561. MockURLProtocol
  562. .requestHandler = try httpRequestHandler(
  563. forResource: "unary-failure-prompt-blocked-safety",
  564. withExtension: "json"
  565. )
  566. do {
  567. _ = try await model.generateContent(testPrompt)
  568. XCTFail("Should throw")
  569. } catch let GenerateContentError.promptBlocked(response) {
  570. XCTAssertNil(response.text)
  571. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  572. XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
  573. XCTAssertNil(promptFeedback.blockReasonMessage)
  574. } catch {
  575. XCTFail("Should throw a promptBlocked")
  576. }
  577. }
  578. func testGenerateContent_failure_promptBlockedSafetyWithMessage() async throws {
  579. MockURLProtocol
  580. .requestHandler = try httpRequestHandler(
  581. forResource: "unary-failure-prompt-blocked-safety-with-message",
  582. withExtension: "json"
  583. )
  584. do {
  585. _ = try await model.generateContent(testPrompt)
  586. XCTFail("Should throw")
  587. } catch let GenerateContentError.promptBlocked(response) {
  588. XCTAssertNil(response.text)
  589. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  590. XCTAssertEqual(promptFeedback.blockReason, PromptFeedback.BlockReason.safety)
  591. XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
  592. } catch {
  593. XCTFail("Should throw a promptBlocked")
  594. }
  595. }
  596. func testGenerateContent_failure_unknownEnum_finishReason() async throws {
  597. MockURLProtocol
  598. .requestHandler = try httpRequestHandler(
  599. forResource: "unary-failure-unknown-enum-finish-reason",
  600. withExtension: "json"
  601. )
  602. let unknownFinishReason = FinishReason(rawValue: "FAKE_NEW_FINISH_REASON")
  603. do {
  604. _ = try await model.generateContent(testPrompt)
  605. XCTFail("Should throw")
  606. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  607. XCTAssertEqual(reason, unknownFinishReason)
  608. XCTAssertEqual(response.text, "Some text")
  609. } catch {
  610. XCTFail("Should throw a responseStoppedEarly")
  611. }
  612. }
  613. func testGenerateContent_failure_unknownEnum_promptBlocked() async throws {
  614. MockURLProtocol
  615. .requestHandler = try httpRequestHandler(
  616. forResource: "unary-failure-unknown-enum-prompt-blocked",
  617. withExtension: "json"
  618. )
  619. let unknownBlockReason = PromptFeedback.BlockReason(rawValue: "FAKE_NEW_BLOCK_REASON")
  620. do {
  621. _ = try await model.generateContent(testPrompt)
  622. XCTFail("Should throw")
  623. } catch let GenerateContentError.promptBlocked(response) {
  624. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  625. XCTAssertEqual(promptFeedback.blockReason, unknownBlockReason)
  626. } catch {
  627. XCTFail("Should throw a promptBlocked")
  628. }
  629. }
  630. func testGenerateContent_failure_unknownModel() async throws {
  631. let expectedStatusCode = 404
  632. MockURLProtocol
  633. .requestHandler = try httpRequestHandler(
  634. forResource: "unary-failure-unknown-model",
  635. withExtension: "json",
  636. statusCode: 404
  637. )
  638. do {
  639. _ = try await model.generateContent(testPrompt)
  640. XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
  641. } catch let GenerateContentError.internalError(underlying: rpcError as BackendError) {
  642. XCTAssertEqual(rpcError.status, .notFound)
  643. XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
  644. XCTAssertTrue(rpcError.message.hasPrefix("models/unknown is not found"))
  645. } catch {
  646. XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
  647. }
  648. }
  649. func testGenerateContent_failure_nonHTTPResponse() async throws {
  650. MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
  651. var responseError: Error?
  652. var content: GenerateContentResponse?
  653. do {
  654. content = try await model.generateContent(testPrompt)
  655. } catch {
  656. responseError = error
  657. }
  658. XCTAssertNil(content)
  659. XCTAssertNotNil(responseError)
  660. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  661. guard case let .internalError(underlyingError) = generateContentError else {
  662. XCTFail("Not an internal error: \(generateContentError)")
  663. return
  664. }
  665. XCTAssertEqual(underlyingError.localizedDescription, "Response was not an HTTP response.")
  666. let underlyingNSError = underlyingError as NSError
  667. XCTAssertEqual(underlyingNSError.domain, NSURLErrorDomain)
  668. XCTAssertEqual(underlyingNSError.code, URLError.Code.badServerResponse.rawValue)
  669. }
  670. func testGenerateContent_failure_invalidResponse() async throws {
  671. MockURLProtocol.requestHandler = try httpRequestHandler(
  672. forResource: "unary-failure-invalid-response",
  673. withExtension: "json"
  674. )
  675. var responseError: Error?
  676. var content: GenerateContentResponse?
  677. do {
  678. content = try await model.generateContent(testPrompt)
  679. } catch {
  680. responseError = error
  681. }
  682. XCTAssertNil(content)
  683. XCTAssertNotNil(responseError)
  684. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  685. guard case let .internalError(underlyingError) = generateContentError else {
  686. XCTFail("Not an internal error: \(generateContentError)")
  687. return
  688. }
  689. let decodingError = try XCTUnwrap(underlyingError as? DecodingError)
  690. guard case let .dataCorrupted(context) = decodingError else {
  691. XCTFail("Not a data corrupted error: \(decodingError)")
  692. return
  693. }
  694. XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
  695. }
  696. func testGenerateContent_failure_malformedContent() async throws {
  697. MockURLProtocol
  698. .requestHandler = try httpRequestHandler(
  699. forResource: "unary-failure-malformed-content",
  700. withExtension: "json"
  701. )
  702. var responseError: Error?
  703. var content: GenerateContentResponse?
  704. do {
  705. content = try await model.generateContent(testPrompt)
  706. } catch {
  707. responseError = error
  708. }
  709. XCTAssertNil(content)
  710. XCTAssertNotNil(responseError)
  711. let generateContentError = try XCTUnwrap(responseError as? GenerateContentError)
  712. guard case let .internalError(underlyingError) = generateContentError else {
  713. XCTFail("Not an internal error: \(generateContentError)")
  714. return
  715. }
  716. let invalidCandidateError = try XCTUnwrap(underlyingError as? InvalidCandidateError)
  717. guard case let .malformedContent(malformedContentUnderlyingError) = invalidCandidateError else {
  718. XCTFail("Not a malformed content error: \(invalidCandidateError)")
  719. return
  720. }
  721. _ = try XCTUnwrap(
  722. malformedContentUnderlyingError as? DecodingError,
  723. "Not a decoding error: \(malformedContentUnderlyingError)"
  724. )
  725. }
  726. func testGenerateContentMissingSafetyRatings() async throws {
  727. MockURLProtocol.requestHandler = try httpRequestHandler(
  728. forResource: "unary-success-missing-safety-ratings",
  729. withExtension: "json"
  730. )
  731. let content = try await model.generateContent(testPrompt)
  732. let promptFeedback = try XCTUnwrap(content.promptFeedback)
  733. XCTAssertEqual(promptFeedback.safetyRatings.count, 0)
  734. XCTAssertEqual(content.text, "This is the generated content.")
  735. }
  736. func testGenerateContent_requestOptions_customTimeout() async throws {
  737. let expectedTimeout = 150.0
  738. MockURLProtocol
  739. .requestHandler = try httpRequestHandler(
  740. forResource: "unary-success-basic-reply-short",
  741. withExtension: "json",
  742. timeout: expectedTimeout
  743. )
  744. let requestOptions = RequestOptions(timeout: expectedTimeout)
  745. model = GenerativeModel(
  746. name: testModelResourceName,
  747. projectID: "my-project-id",
  748. apiKey: "API_KEY",
  749. tools: nil,
  750. requestOptions: requestOptions,
  751. appCheck: nil,
  752. auth: nil,
  753. urlSession: urlSession
  754. )
  755. let response = try await model.generateContent(testPrompt)
  756. XCTAssertEqual(response.candidates.count, 1)
  757. }
  758. // MARK: - Generate Content (Streaming)
  759. func testGenerateContentStream_failureInvalidAPIKey() async throws {
  760. MockURLProtocol
  761. .requestHandler = try httpRequestHandler(
  762. forResource: "unary-failure-api-key",
  763. withExtension: "json"
  764. )
  765. do {
  766. let stream = try model.generateContentStream("Hi")
  767. for try await _ in stream {
  768. XCTFail("No content is there, this shouldn't happen.")
  769. }
  770. } catch let GenerateContentError.internalError(error as BackendError) {
  771. XCTAssertEqual(error.httpResponseCode, 400)
  772. XCTAssertEqual(error.status, .invalidArgument)
  773. XCTAssertEqual(error.message, "API key not valid. Please pass a valid API key.")
  774. XCTAssertTrue(error.localizedDescription.contains(error.message))
  775. XCTAssertTrue(error.localizedDescription.contains(error.status.rawValue))
  776. XCTAssertTrue(error.localizedDescription.contains("\(error.httpResponseCode)"))
  777. let nsError = error as NSError
  778. XCTAssertEqual(nsError.domain, "\(Constants.baseErrorDomain).\(BackendError.self)")
  779. XCTAssertEqual(nsError.code, error.httpResponseCode)
  780. return
  781. }
  782. XCTFail("Should have caught an error.")
  783. }
  784. func testGenerateContentStream_failure_vertexAIInFirebaseAPINotEnabled() async throws {
  785. let expectedStatusCode = 403
  786. MockURLProtocol
  787. .requestHandler = try httpRequestHandler(
  788. forResource: "unary-failure-firebasevertexai-api-not-enabled",
  789. withExtension: "json",
  790. statusCode: expectedStatusCode
  791. )
  792. do {
  793. let stream = try model.generateContentStream(testPrompt)
  794. for try await _ in stream {
  795. XCTFail("No content is there, this shouldn't happen.")
  796. }
  797. } catch let GenerateContentError.internalError(error as BackendError) {
  798. XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
  799. XCTAssertEqual(error.status, .permissionDenied)
  800. XCTAssertTrue(error.message
  801. .starts(with: "Vertex AI in Firebase API has not been used in project"))
  802. XCTAssertTrue(error.isVertexAIInFirebaseServiceDisabledError())
  803. return
  804. }
  805. XCTFail("Should have caught an error.")
  806. }
  807. func testGenerateContentStream_failureEmptyContent() async throws {
  808. MockURLProtocol
  809. .requestHandler = try httpRequestHandler(
  810. forResource: "streaming-failure-empty-content",
  811. withExtension: "txt"
  812. )
  813. do {
  814. let stream = try model.generateContentStream("Hi")
  815. for try await _ in stream {
  816. XCTFail("No content is there, this shouldn't happen.")
  817. }
  818. } catch GenerateContentError.internalError(_ as InvalidCandidateError) {
  819. // Underlying error is as expected, nothing else to check.
  820. return
  821. }
  822. XCTFail("Should have caught an error.")
  823. }
  824. func testGenerateContentStream_failureFinishReasonSafety() async throws {
  825. MockURLProtocol
  826. .requestHandler = try httpRequestHandler(
  827. forResource: "streaming-failure-finish-reason-safety",
  828. withExtension: "txt"
  829. )
  830. do {
  831. let stream = try model.generateContentStream("Hi")
  832. for try await _ in stream {
  833. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  834. }
  835. } catch let GenerateContentError.responseStoppedEarly(reason, response) {
  836. XCTAssertEqual(reason, .safety)
  837. let candidate = try XCTUnwrap(response.candidates.first)
  838. XCTAssertEqual(candidate.finishReason, reason)
  839. XCTAssertTrue(candidate.safetyRatings.contains { $0.blocked })
  840. return
  841. }
  842. XCTFail("Should have caught an error.")
  843. }
  844. func testGenerateContentStream_failurePromptBlockedSafety() async throws {
  845. MockURLProtocol
  846. .requestHandler = try httpRequestHandler(
  847. forResource: "streaming-failure-prompt-blocked-safety",
  848. withExtension: "txt"
  849. )
  850. do {
  851. let stream = try model.generateContentStream("Hi")
  852. for try await _ in stream {
  853. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  854. }
  855. } catch let GenerateContentError.promptBlocked(response) {
  856. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  857. XCTAssertEqual(promptFeedback.blockReason, .safety)
  858. XCTAssertNil(promptFeedback.blockReasonMessage)
  859. return
  860. }
  861. XCTFail("Should have caught an error.")
  862. }
  863. func testGenerateContentStream_failurePromptBlockedSafetyWithMessage() async throws {
  864. MockURLProtocol
  865. .requestHandler = try httpRequestHandler(
  866. forResource: "streaming-failure-prompt-blocked-safety-with-message",
  867. withExtension: "txt"
  868. )
  869. do {
  870. let stream = try model.generateContentStream("Hi")
  871. for try await _ in stream {
  872. XCTFail("Content shouldn't be shown, this shouldn't happen.")
  873. }
  874. } catch let GenerateContentError.promptBlocked(response) {
  875. let promptFeedback = try XCTUnwrap(response.promptFeedback)
  876. XCTAssertEqual(promptFeedback.blockReason, .safety)
  877. XCTAssertEqual(promptFeedback.blockReasonMessage, "Reasons")
  878. return
  879. }
  880. XCTFail("Should have caught an error.")
  881. }
  882. func testGenerateContentStream_failureUnknownFinishEnum() async throws {
  883. MockURLProtocol
  884. .requestHandler = try httpRequestHandler(
  885. forResource: "streaming-failure-unknown-finish-enum",
  886. withExtension: "txt"
  887. )
  888. let unknownFinishReason = FinishReason(rawValue: "FAKE_ENUM")
  889. let stream = try model.generateContentStream("Hi")
  890. do {
  891. for try await content in stream {
  892. XCTAssertNotNil(content.text)
  893. }
  894. } catch let GenerateContentError.responseStoppedEarly(reason, _) {
  895. XCTAssertEqual(reason, unknownFinishReason)
  896. return
  897. }
  898. XCTFail("Should have caught an error.")
  899. }
  900. func testGenerateContentStream_successBasicReplyLong() async throws {
  901. MockURLProtocol
  902. .requestHandler = try httpRequestHandler(
  903. forResource: "streaming-success-basic-reply-long",
  904. withExtension: "txt"
  905. )
  906. var responses = 0
  907. let stream = try model.generateContentStream("Hi")
  908. for try await content in stream {
  909. XCTAssertNotNil(content.text)
  910. responses += 1
  911. }
  912. XCTAssertEqual(responses, 6)
  913. }
  914. func testGenerateContentStream_successBasicReplyShort() async throws {
  915. MockURLProtocol
  916. .requestHandler = try httpRequestHandler(
  917. forResource: "streaming-success-basic-reply-short",
  918. withExtension: "txt"
  919. )
  920. var responses = 0
  921. let stream = try model.generateContentStream("Hi")
  922. for try await content in stream {
  923. XCTAssertNotNil(content.text)
  924. responses += 1
  925. }
  926. XCTAssertEqual(responses, 1)
  927. }
  928. func testGenerateContentStream_successUnknownSafetyEnum() async throws {
  929. MockURLProtocol
  930. .requestHandler = try httpRequestHandler(
  931. forResource: "streaming-success-unknown-safety-enum",
  932. withExtension: "txt"
  933. )
  934. let unknownSafetyRating = SafetyRating(
  935. category: HarmCategory(rawValue: "HARM_CATEGORY_DANGEROUS_CONTENT_NEW_ENUM"),
  936. probability: SafetyRating.HarmProbability(rawValue: "NEGLIGIBLE_UNKNOWN_ENUM"),
  937. probabilityScore: 0.0,
  938. severity: SafetyRating.HarmSeverity(rawValue: "HARM_SEVERITY_UNSPECIFIED"),
  939. severityScore: 0.0,
  940. blocked: false
  941. )
  942. var foundUnknownSafetyRating = false
  943. let stream = try model.generateContentStream("Hi")
  944. for try await content in stream {
  945. XCTAssertNotNil(content.text)
  946. if let ratings = content.candidates.first?.safetyRatings,
  947. ratings.contains(where: { $0 == unknownSafetyRating }) {
  948. foundUnknownSafetyRating = true
  949. }
  950. }
  951. XCTAssertTrue(foundUnknownSafetyRating)
  952. }
  953. func testGenerateContentStream_successWithCitations() async throws {
  954. MockURLProtocol
  955. .requestHandler = try httpRequestHandler(
  956. forResource: "streaming-success-citations",
  957. withExtension: "txt"
  958. )
  959. let expectedPublicationDate = DateComponents(
  960. calendar: Calendar(identifier: .gregorian),
  961. year: 2014,
  962. month: 3,
  963. day: 30
  964. )
  965. let stream = try model.generateContentStream("Hi")
  966. var citations = [Citation]()
  967. var responses = [GenerateContentResponse]()
  968. for try await content in stream {
  969. responses.append(content)
  970. XCTAssertNotNil(content.text)
  971. let candidate = try XCTUnwrap(content.candidates.first)
  972. if let sources = candidate.citationMetadata?.citations {
  973. citations.append(contentsOf: sources)
  974. }
  975. }
  976. let lastCandidate = try XCTUnwrap(responses.last?.candidates.first)
  977. XCTAssertEqual(lastCandidate.finishReason, .stop)
  978. XCTAssertEqual(citations.count, 6)
  979. XCTAssertTrue(citations
  980. .contains {
  981. $0.startIndex == 0 && $0.endIndex == 128
  982. && $0.uri == "https://www.example.com/some-citation-1" && $0.title == nil
  983. && $0.license == nil && $0.publicationDate == nil
  984. })
  985. XCTAssertTrue(citations
  986. .contains {
  987. $0.startIndex == 130 && $0.endIndex == 265 && $0.uri == nil
  988. && $0.title == "some-citation-2" && $0.license == nil
  989. && $0.publicationDate == expectedPublicationDate
  990. })
  991. XCTAssertTrue(citations
  992. .contains {
  993. $0.startIndex == 272 && $0.endIndex == 431
  994. && $0.uri == "https://www.example.com/some-citation-3" && $0.title == nil
  995. && $0.license == "mit" && $0.publicationDate == nil
  996. })
  997. XCTAssertFalse(citations.contains { $0.uri?.isEmpty ?? false })
  998. XCTAssertFalse(citations.contains { $0.title?.isEmpty ?? false })
  999. XCTAssertFalse(citations.contains { $0.license?.isEmpty ?? false })
  1000. }
  1001. func testGenerateContentStream_appCheck_validToken() async throws {
  1002. let appCheckToken = "test-valid-token"
  1003. model = GenerativeModel(
  1004. name: testModelResourceName,
  1005. projectID: "my-project-id",
  1006. apiKey: "API_KEY",
  1007. tools: nil,
  1008. requestOptions: RequestOptions(),
  1009. appCheck: AppCheckInteropFake(token: appCheckToken),
  1010. auth: nil,
  1011. urlSession: urlSession
  1012. )
  1013. MockURLProtocol
  1014. .requestHandler = try httpRequestHandler(
  1015. forResource: "streaming-success-basic-reply-short",
  1016. withExtension: "txt",
  1017. appCheckToken: appCheckToken
  1018. )
  1019. let stream = try model.generateContentStream(testPrompt)
  1020. for try await _ in stream {}
  1021. }
  1022. func testGenerateContentStream_appCheck_tokenRefreshError() async throws {
  1023. model = GenerativeModel(
  1024. name: testModelResourceName,
  1025. projectID: "my-project-id",
  1026. apiKey: "API_KEY",
  1027. tools: nil,
  1028. requestOptions: RequestOptions(),
  1029. appCheck: AppCheckInteropFake(error: AppCheckErrorFake()),
  1030. auth: nil,
  1031. urlSession: urlSession
  1032. )
  1033. MockURLProtocol
  1034. .requestHandler = try httpRequestHandler(
  1035. forResource: "streaming-success-basic-reply-short",
  1036. withExtension: "txt",
  1037. appCheckToken: AppCheckInteropFake.placeholderTokenValue
  1038. )
  1039. let stream = try model.generateContentStream(testPrompt)
  1040. for try await _ in stream {}
  1041. }
  1042. func testGenerateContentStream_usageMetadata() async throws {
  1043. MockURLProtocol
  1044. .requestHandler = try httpRequestHandler(
  1045. forResource: "streaming-success-basic-reply-short",
  1046. withExtension: "txt"
  1047. )
  1048. var responses = [GenerateContentResponse]()
  1049. let stream = try model.generateContentStream(testPrompt)
  1050. for try await response in stream {
  1051. responses.append(response)
  1052. }
  1053. for (index, response) in responses.enumerated() {
  1054. if index == responses.endIndex - 1 {
  1055. let usageMetadata = try XCTUnwrap(response.usageMetadata)
  1056. XCTAssertEqual(usageMetadata.promptTokenCount, 6)
  1057. XCTAssertEqual(usageMetadata.candidatesTokenCount, 4)
  1058. XCTAssertEqual(usageMetadata.totalTokenCount, 10)
  1059. } else {
  1060. // Only the last streamed response contains usage metadata
  1061. XCTAssertNil(response.usageMetadata)
  1062. }
  1063. }
  1064. }
  1065. func testGenerateContentStream_errorMidStream() async throws {
  1066. MockURLProtocol.requestHandler = try httpRequestHandler(
  1067. forResource: "streaming-failure-error-mid-stream",
  1068. withExtension: "txt"
  1069. )
  1070. var responseCount = 0
  1071. do {
  1072. let stream = try model.generateContentStream("Hi")
  1073. for try await content in stream {
  1074. XCTAssertNotNil(content.text)
  1075. responseCount += 1
  1076. }
  1077. } catch let GenerateContentError.internalError(rpcError as BackendError) {
  1078. XCTAssertEqual(rpcError.httpResponseCode, 499)
  1079. XCTAssertEqual(rpcError.status, .cancelled)
  1080. // Check the content count is correct.
  1081. XCTAssertEqual(responseCount, 2)
  1082. return
  1083. }
  1084. XCTFail("Expected an internalError with an RPCError.")
  1085. }
  1086. func testGenerateContentStream_nonHTTPResponse() async throws {
  1087. MockURLProtocol.requestHandler = try nonHTTPRequestHandler()
  1088. let stream = try model.generateContentStream("Hi")
  1089. do {
  1090. for try await content in stream {
  1091. XCTFail("Unexpected content in stream: \(content)")
  1092. }
  1093. } catch let GenerateContentError.internalError(underlying) {
  1094. XCTAssertEqual(underlying.localizedDescription, "Response was not an HTTP response.")
  1095. return
  1096. }
  1097. XCTFail("Expected an internal error.")
  1098. }
  1099. func testGenerateContentStream_invalidResponse() async throws {
  1100. MockURLProtocol
  1101. .requestHandler = try httpRequestHandler(
  1102. forResource: "streaming-failure-invalid-json",
  1103. withExtension: "txt"
  1104. )
  1105. let stream = try model.generateContentStream(testPrompt)
  1106. do {
  1107. for try await content in stream {
  1108. XCTFail("Unexpected content in stream: \(content)")
  1109. }
  1110. } catch let GenerateContentError.internalError(underlying as DecodingError) {
  1111. guard case let .dataCorrupted(context) = underlying else {
  1112. XCTFail("Not a data corrupted error: \(underlying)")
  1113. return
  1114. }
  1115. XCTAssert(context.debugDescription.hasPrefix("Failed to decode GenerateContentResponse"))
  1116. return
  1117. }
  1118. XCTFail("Expected an internal error.")
  1119. }
  1120. func testGenerateContentStream_malformedContent() async throws {
  1121. MockURLProtocol
  1122. .requestHandler = try httpRequestHandler(
  1123. forResource: "streaming-failure-malformed-content",
  1124. withExtension: "txt"
  1125. )
  1126. let stream = try model.generateContentStream(testPrompt)
  1127. do {
  1128. for try await content in stream {
  1129. XCTFail("Unexpected content in stream: \(content)")
  1130. }
  1131. } catch let GenerateContentError.internalError(underlyingError as InvalidCandidateError) {
  1132. guard case let .malformedContent(contentError) = underlyingError else {
  1133. XCTFail("Not a malformed content error: \(underlyingError)")
  1134. return
  1135. }
  1136. XCTAssert(contentError is DecodingError)
  1137. return
  1138. }
  1139. XCTFail("Expected an internal decoding error.")
  1140. }
  1141. func testGenerateContentStream_requestOptions_customTimeout() async throws {
  1142. let expectedTimeout = 150.0
  1143. MockURLProtocol
  1144. .requestHandler = try httpRequestHandler(
  1145. forResource: "streaming-success-basic-reply-short",
  1146. withExtension: "txt",
  1147. timeout: expectedTimeout
  1148. )
  1149. let requestOptions = RequestOptions(timeout: expectedTimeout)
  1150. model = GenerativeModel(
  1151. name: testModelResourceName,
  1152. projectID: "my-project-id",
  1153. apiKey: "API_KEY",
  1154. tools: nil,
  1155. requestOptions: requestOptions,
  1156. appCheck: nil,
  1157. auth: nil,
  1158. urlSession: urlSession
  1159. )
  1160. var responses = 0
  1161. let stream = try model.generateContentStream(testPrompt)
  1162. for try await content in stream {
  1163. XCTAssertNotNil(content.text)
  1164. responses += 1
  1165. }
  1166. XCTAssertEqual(responses, 1)
  1167. }
  1168. // MARK: - Count Tokens
  1169. func testCountTokens_succeeds() async throws {
  1170. MockURLProtocol.requestHandler = try httpRequestHandler(
  1171. forResource: "unary-success-total-tokens",
  1172. withExtension: "json"
  1173. )
  1174. let response = try await model.countTokens("Why is the sky blue?")
  1175. XCTAssertEqual(response.totalTokens, 6)
  1176. XCTAssertEqual(response.totalBillableCharacters, 16)
  1177. }
  1178. func testCountTokens_succeeds_allOptions() async throws {
  1179. MockURLProtocol.requestHandler = try httpRequestHandler(
  1180. forResource: "unary-success-total-tokens",
  1181. withExtension: "json"
  1182. )
  1183. let generationConfig = GenerationConfig(
  1184. temperature: 0.5,
  1185. topP: 0.9,
  1186. topK: 3,
  1187. candidateCount: 1,
  1188. maxOutputTokens: 1024,
  1189. stopSequences: ["test-stop"],
  1190. responseMIMEType: "text/plain"
  1191. )
  1192. let sumFunction = FunctionDeclaration(
  1193. name: "sum",
  1194. description: "Add two integers.",
  1195. parameters: ["x": .integer(), "y": .integer()]
  1196. )
  1197. let systemInstruction = ModelContent(
  1198. role: "system",
  1199. parts: "You are a calculator. Use the provided tools."
  1200. )
  1201. model = GenerativeModel(
  1202. name: testModelResourceName,
  1203. projectID: "my-project-id",
  1204. apiKey: "API_KEY",
  1205. generationConfig: generationConfig,
  1206. tools: [Tool(functionDeclarations: [sumFunction])],
  1207. systemInstruction: systemInstruction,
  1208. requestOptions: RequestOptions(),
  1209. appCheck: nil,
  1210. auth: nil,
  1211. urlSession: urlSession
  1212. )
  1213. let response = try await model.countTokens("Why is the sky blue?")
  1214. XCTAssertEqual(response.totalTokens, 6)
  1215. XCTAssertEqual(response.totalBillableCharacters, 16)
  1216. }
  1217. func testCountTokens_succeeds_noBillableCharacters() async throws {
  1218. MockURLProtocol.requestHandler = try httpRequestHandler(
  1219. forResource: "unary-success-no-billable-characters",
  1220. withExtension: "json"
  1221. )
  1222. let response = try await model.countTokens(InlineDataPart(data: Data(), mimeType: "image/jpeg"))
  1223. XCTAssertEqual(response.totalTokens, 258)
  1224. XCTAssertNil(response.totalBillableCharacters)
  1225. }
  1226. func testCountTokens_modelNotFound() async throws {
  1227. MockURLProtocol.requestHandler = try httpRequestHandler(
  1228. forResource: "unary-failure-model-not-found", withExtension: "json",
  1229. statusCode: 404
  1230. )
  1231. do {
  1232. _ = try await model.countTokens("Why is the sky blue?")
  1233. XCTFail("Request should not have succeeded.")
  1234. } catch let rpcError as BackendError {
  1235. XCTAssertEqual(rpcError.httpResponseCode, 404)
  1236. XCTAssertEqual(rpcError.status, .notFound)
  1237. XCTAssert(rpcError.message.hasPrefix("models/test-model-name is not found"))
  1238. return
  1239. }
  1240. XCTFail("Expected internal RPCError.")
  1241. }
  1242. func testCountTokens_requestOptions_customTimeout() async throws {
  1243. let expectedTimeout = 150.0
  1244. MockURLProtocol
  1245. .requestHandler = try httpRequestHandler(
  1246. forResource: "unary-success-total-tokens",
  1247. withExtension: "json",
  1248. timeout: expectedTimeout
  1249. )
  1250. let requestOptions = RequestOptions(timeout: expectedTimeout)
  1251. model = GenerativeModel(
  1252. name: testModelResourceName,
  1253. projectID: "my-project-id",
  1254. apiKey: "API_KEY",
  1255. tools: nil,
  1256. requestOptions: requestOptions,
  1257. appCheck: nil,
  1258. auth: nil,
  1259. urlSession: urlSession
  1260. )
  1261. let response = try await model.countTokens(testPrompt)
  1262. XCTAssertEqual(response.totalTokens, 6)
  1263. }
  1264. // MARK: - Helpers
  1265. private func nonHTTPRequestHandler() throws -> ((URLRequest) -> (
  1266. URLResponse,
  1267. AsyncLineSequence<URL.AsyncBytes>?
  1268. )) {
  1269. // Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
  1270. // https://developer.apple.com/documentation/foundation/urlprotocol for details.
  1271. #if os(watchOS)
  1272. throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
  1273. #endif // os(watchOS)
  1274. return { request in
  1275. // This is *not* an HTTPURLResponse
  1276. let response = URLResponse(
  1277. url: request.url!,
  1278. mimeType: nil,
  1279. expectedContentLength: 0,
  1280. textEncodingName: nil
  1281. )
  1282. return (response, nil)
  1283. }
  1284. }
  1285. private func httpRequestHandler(forResource name: String,
  1286. withExtension ext: String,
  1287. statusCode: Int = 200,
  1288. timeout: TimeInterval = RequestOptions().timeout,
  1289. appCheckToken: String? = nil,
  1290. authToken: String? = nil) throws -> ((URLRequest) throws -> (
  1291. URLResponse,
  1292. AsyncLineSequence<URL.AsyncBytes>?
  1293. )) {
  1294. // Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
  1295. // https://developer.apple.com/documentation/foundation/urlprotocol for details.
  1296. #if os(watchOS)
  1297. throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
  1298. #endif // os(watchOS)
  1299. let bundle = BundleTestUtil.bundle()
  1300. let fileURL = try XCTUnwrap(bundle.url(forResource: name, withExtension: ext))
  1301. return { request in
  1302. let requestURL = try XCTUnwrap(request.url)
  1303. XCTAssertEqual(requestURL.path.occurrenceCount(of: "models/"), 1)
  1304. XCTAssertEqual(request.timeoutInterval, timeout)
  1305. let apiClientTags = try XCTUnwrap(request.value(forHTTPHeaderField: "x-goog-api-client"))
  1306. .components(separatedBy: " ")
  1307. XCTAssert(apiClientTags.contains(GenerativeAIService.languageTag))
  1308. XCTAssert(apiClientTags.contains(GenerativeAIService.firebaseVersionTag))
  1309. XCTAssertEqual(request.value(forHTTPHeaderField: "X-Firebase-AppCheck"), appCheckToken)
  1310. if let authToken {
  1311. XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Firebase \(authToken)")
  1312. } else {
  1313. XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
  1314. }
  1315. let response = try XCTUnwrap(HTTPURLResponse(
  1316. url: requestURL,
  1317. statusCode: statusCode,
  1318. httpVersion: nil,
  1319. headerFields: nil
  1320. ))
  1321. return (response, fileURL.lines)
  1322. }
  1323. }
  1324. }
  1325. private extension String {
  1326. /// Returns the number of occurrences of `substring` in the `String`.
  1327. func occurrenceCount(of substring: String) -> Int {
  1328. return components(separatedBy: substring).count - 1
  1329. }
  1330. }
  1331. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1332. class AppCheckInteropFake: NSObject, AppCheckInterop {
  1333. /// The placeholder token value returned when an error occurs
  1334. static let placeholderTokenValue = "placeholder-token"
  1335. var token: String
  1336. var error: Error?
  1337. private init(token: String, error: Error?) {
  1338. self.token = token
  1339. self.error = error
  1340. }
  1341. convenience init(token: String) {
  1342. self.init(token: token, error: nil)
  1343. }
  1344. convenience init(error: Error) {
  1345. self.init(token: AppCheckInteropFake.placeholderTokenValue, error: error)
  1346. }
  1347. func getToken(forcingRefresh: Bool) async -> any FIRAppCheckTokenResultInterop {
  1348. return AppCheckTokenResultInteropFake(token: token, error: error)
  1349. }
  1350. func tokenDidChangeNotificationName() -> String {
  1351. fatalError("\(#function) not implemented.")
  1352. }
  1353. func notificationTokenKey() -> String {
  1354. fatalError("\(#function) not implemented.")
  1355. }
  1356. func notificationAppNameKey() -> String {
  1357. fatalError("\(#function) not implemented.")
  1358. }
  1359. private class AppCheckTokenResultInteropFake: NSObject, FIRAppCheckTokenResultInterop {
  1360. var token: String
  1361. var error: Error?
  1362. init(token: String, error: Error?) {
  1363. self.token = token
  1364. self.error = error
  1365. }
  1366. }
  1367. }
  1368. struct AppCheckErrorFake: Error {}
  1369. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  1370. extension SafetyRating: Swift.Comparable {
  1371. public static func < (lhs: FirebaseVertexAI.SafetyRating,
  1372. rhs: FirebaseVertexAI.SafetyRating) -> Bool {
  1373. return lhs.category.rawValue < rhs.category.rawValue
  1374. }
  1375. }