ChatSnippets.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2024 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 FirebaseAI
  15. import FirebaseCore
  16. import XCTest
  17. // These snippet tests are intentionally skipped in CI jobs; see the README file in this directory
  18. // for instructions on running them manually.
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. final class ChatSnippets: XCTestCase {
  21. lazy var model = FirebaseAI.firebaseAI().generativeModel(modelName: "gemini-2.0-flash")
  22. override func setUpWithError() throws {
  23. try FirebaseApp.configureDefaultAppForSnippets()
  24. }
  25. override func tearDown() async throws {
  26. await FirebaseApp.deleteDefaultAppForSnippets()
  27. }
  28. func testChatNonStreaming() async throws {
  29. // Optionally specify existing chat history
  30. let history = [
  31. ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  32. ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
  33. ]
  34. // Initialize the chat with optional chat history
  35. let chat = model.startChat(history: history)
  36. // To generate text output, call sendMessage and pass in the message
  37. let response = try await chat.sendMessage("How many paws are in my house?")
  38. print(response.text ?? "No text in response.")
  39. }
  40. func testChatStreaming() async throws {
  41. // Optionally specify existing chat history
  42. let history = [
  43. ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  44. ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
  45. ]
  46. // Initialize the chat with optional chat history
  47. let chat = model.startChat(history: history)
  48. // To stream generated text output, call sendMessageStream and pass in the message
  49. let contentStream = try chat.sendMessageStream("How many paws are in my house?")
  50. for try await chunk in contentStream {
  51. if let text = chunk.text {
  52. print(text)
  53. }
  54. }
  55. }
  56. }