Các chức năng có sẵn khi truy cập vào Gemini API thông qua khung Mô hình cơ bản của Apple


Các ví dụ trên trang này giả định rằng bạn đã hoàn tất hướng dẫn Bắt đầu: Truy cập vào Gemini API thông qua khung Mô hình nền tảng của Apple.


Hướng dẫn này trình bày cách gửi nhiều loại yêu cầu đến Gemini API thông qua khung Mô hình nền tảng của Apple bằng cách sử dụng SDK Firebase AI Logic cho các nền tảng của Apple.

Trang này trình bày các ví dụ về cách gửi các loại yêu cầu sau:



Tạo văn bản

Các mô hình Gemini hỗ trợ những chức năng sau để tạo văn bản do AI tạo:

Các mô hình hỗ trợ tính năng này

  • gemini-4-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • gemini-3.5-flash-lite (và gemini-3.1-flash-lite cũ hơn)

Các mô hình Gemini 3.x Flash đa năng cũ hơn hỗ trợ tính năng này, nhưng bạn không nên sử dụng các mô hình đó nữa do ngày ngừng hoạt động sắp tới và/hoặc việc tự động định tuyến đến các mô hình mới hơn.

Tạo văn bản do AI tạo từ dữ liệu đầu vào chỉ có văn bản

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Bạn có thể yêu cầu mô hình Gemini tạo văn bản do AI tạo bằng cách đặt câu lệnh chỉ có thông tin đầu vào là văn bản.

import FoundationModels
import FirebaseCore
import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Initialize a `geminiLanguageModel` with a Gemini model that supports your use case.
let model = ai.geminiLanguageModel(name: "gemini-4-hydrogen")

// Provide a prompt that contains text.
let prompt = "Write a story about a magic backpack."

// Create a session by injecting the model into Apple's `LanguageModelSession`.
// For a single-turn interaction, create a new session each time you call the model.
let session = LanguageModelSession(model: model)

// Generate a text response to the prompt.
let response = try await session.respond(to: prompt)
print(response.content)

Hiển thị câu trả lời theo thời gian thực

Bạn có thể tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, mà thay vào đó, hãy sử dụng tính năng truyền trực tuyến để xử lý một phần kết quả. Để truyền trực tuyến phản hồi, hãy sử dụng streamResponse(to:) thay vì respond(to:).

// imports
// initialization of Gemini API backend service and a `geminiLanguageModel`

// Provide a prompt that contains text.
let prompt = "Write a story about a magic backpack."

// Create a session by injecting the model into Apple's `LanguageModelSession`.
// For a single-turn interaction, create a new session each time you call the model.
let session = LanguageModelSession(model: model)

// Generate a text response to the prompt.
// To stream the response, use `streamResponse(to:)` instead of `respond(to:)`
let stream = session.streamResponse(to: "Write a story about a magic backpack.")
var response = ""
for try await snapshot in stream {
  // The snapshot contains *all* content generated so far.
  response = snapshot.content
}

Tạo văn bản do AI tạo trong một phiên nhiều lượt (trò chuyện)

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

import FoundationModels
import FirebaseCore
import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Initialize a `geminiLanguageModel` with a Gemini model that supports your use case.
let model = ai.geminiLanguageModel(name: "gemini-4-hydrogen")

// Create a session by injecting the model into Apple's `LanguageModelSession`.
// The session maintains state between each request.
let session = LanguageModelSession(model: model)

// Generate a text response to an initial prompt.
let response = try await session.respond(to: "Hello! I'd like to learn more about Albert Einstein.")
print(response.content)  // Example response from model: "What would you like to know?"

// Continue using the existing session. Each prompt and response is added to the transcript.
let response2 = try await session.respond(to: "When was he born?")
print(response2.content)  // Example response from model: "March 14, 1879"

Tạo văn bản do AI tạo từ dữ liệu đầu vào đa phương thức (như hình ảnh)

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Bạn có thể yêu cầu mô hình Gemini tạo văn bản do AI tạo bằng cách đặt câu lệnh có văn bản và một tệp, chẳng hạn như hình ảnh hoặc tệp PDF.

import FoundationModels
import FirebaseCore
import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Initialize a `geminiLanguageModel` with a Gemini model that supports your use case.
let model = ai.geminiLanguageModel(name: "gemini-4-hydrogen")

// Create a session by injecting the model into Apple's `LanguageModelSession`.
// For a single-turn interaction, create a new session each time you call the model.
let session = LanguageModelSession(model: model)

let cgImage: CGImage = // ... fetch CGImage from your datasource.
let response = try await session.respond {
  "What are the dominant colors of this image, in order?"
  Attachment(cgImage)
}
print(response.content)

Hiển thị câu trả lời theo thời gian thực

Bạn có thể tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, mà thay vào đó, hãy sử dụng tính năng truyền trực tuyến để xử lý một phần kết quả. Để truyền trực tuyến phản hồi, hãy sử dụng streamResponse thay vì respond.

// imports
// initialization of Gemini API backend service and a `geminiLanguageModel`

// Create a session by injecting the model into Apple's `LanguageModelSession`.
// For a single-turn interaction, create a new session each time you call the model.
let session = LanguageModelSession(model: model)

let cgImage: CGImage = // ... fetch CGImage from your datasource.
let stream = session.streamResponse {
  "What are the dominant colors of this image, in order?"
  Attachment(cgImage)
}

var response = ""
for try await snapshot in stream {
  // The snapshot contains *all* content generated so far.
  response = snapshot.content
}
print(response)



Tạo hình ảnh (bằng mô hình Nano Banana)

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Các mô hình hỗ trợ tính năng này

  • gemini-nano-banana-2.1 (Nano Banana 2.1)
  • gemini-3.1-flash-image (Nano Banana 2)
  • gemini-3.1-flash-lite-image (Nano Banana 2 Lite)
  • gemini-3-pro-image (Nano Banana Pro)

Bạn có thể yêu cầu mô hình Gemini Nano Banana tạo hình ảnh bằng cách đưa ra câu lệnh chỉ có văn bản.

Ví dụ sau đây cho thấy cách tạo chỉ một hình ảnh, nhưng các mô hình Nano Banana có thể tạo cả hình ảnh và văn bản.

import FoundationModels
import FirebaseCore
import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Initialize a `geminiLanguageModel` with a Gemini model that supports image output.
let model = ai.geminiLanguageModel(name: "gemini-nano-banana-2.1"
    options:
      GeminiGenerationOptions(responseModalities: .image)
)

let session = LanguageModelSession(model: model)
let response = try await session.respond(
          to: "Generate an image of the Eiffel tower with fireworks in the background."
        )

var generatedImage: CIImage?
// Find the image in the transcriptEntries.
for entry in response.transcriptEntries {
  if case let .response(response) = entry {
    for segment in response.segments {
      if case let .attachment(attachment) = segment,
          case let .image(image) = attachment.content {
        generatedImage = image.ciImage
      }
    }
  }
}



Tạo kết quả JSON có cấu trúc

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Các mô hình hỗ trợ tính năng này

  • gemini-4-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • gemini-3.5-flash-lite (và gemini-3.1-flash-lite cũ hơn)
  • gemini-3-pro-image (Nano Banana Pro)

Các mô hình Gemini 3.x Flash đa năng cũ hơn hỗ trợ tính năng này, nhưng bạn không nên sử dụng các mô hình đó nữa do ngày ngừng hoạt động sắp tới và/hoặc việc tự động định tuyến đến các mô hình mới hơn.

Theo mặc định, các mô hình Gemini sẽ trả về câu trả lời dưới dạng văn bản không có cấu trúc. Tuy nhiên, một số trường hợp sử dụng yêu cầu văn bản có cấu trúc, chẳng hạn như JSON. Ví dụ: bạn có thể đang sử dụng phản hồi cho các tác vụ hạ nguồn khác yêu cầu một giản đồ dữ liệu đã thiết lập.

Bạn có thể định cấu hình mô hình để định dạng phản hồi theo giản đồ JSON mà bạn cung cấp. Để biết thông tin chi tiết, các phương pháp hay nhất và trường hợp sử dụng để tạo kết quả JSON có cấu trúc, hãy xem hướng dẫn chung về cách Tạo kết quả có cấu trúc.

import FoundationModels
import FirebaseCore
import FirebaseAILogic

@Generable(description: "Basic profile information about a cat")
struct CatProfile {
  var name: String
  @Guide(description: "The age of the cat", .range(0 ... 20))
  var age: Int
  @Guide(description: "A one sentence profile about the cat's personality")
  var profile: String
}

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Initialize a `geminiLanguageModel` with a Gemini model that supports your use case.
let model = ai.geminiLanguageModel(name: "GEMINI_MODEL_NAME")
let session = LanguageModelSession(model: model)

let response = try await session.respond(
  to: "Generate a cute rescue cat profile with an Elvish theme",
  generating: CatProfile.self
)
let cat = response.content


Gửi ý kiến phản hồi về việc truy cập vào Gemini API thông qua khung Mô hình nền tảng của Apple