| Các ví dụ trên trang này giả định rằng bạn đã hoàn tất phần Bắt đầu: Truy cập vào Gemini API thông qua khung Foundation Models của Apple. |
Hướng dẫn này cho bạn biết cách gửi nhiều loại yêu cầu đến Gemini API thông qua khung Foundation Models của Apple bằng SDK Firebase AI Logic cho các nền tảng của Apple.
Trang này trình bày ví dụ về cách gửi các loại yêu cầu sau:
- Tạo văn bản từ dữ liệu đầu vào chỉ có văn bản
- Tạo văn bản trong phiên trò chuyện nhiều lượt
- Tạo văn bản từ dữ liệu đầu vào đa phương thức (chẳng hạn như hình ảnh)
- Tạo hình ảnh từ dữ liệu đầu vào chỉ có văn bản
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:
- Tạo văn bản từ dữ liệu đầu vào chỉ có văn bản
- Tạo văn bản trong phiên trò chuyện nhiều lượt
- Tạo văn bản từ dữ liệu đầu vào đa phương thức (chẳng hạn như hình ảnh)
Các mô hình hỗ trợ tính năng này
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-lite
Tạo văn bản từ dữ liệu đầu vào chỉ có văn bản
|
Nhấp vào nhà cung cấp Gemini API để 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 bằng cách đưa ra câu lệnh chỉ có 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-3.5-flash")
// 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 câu trả lời theo thời gian thực
Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không đợi 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 phát trực tiếp để xử lý kết quả một phần. Để 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 trong phiên trò chuyện nhiều lượt (chat)
|
Nhấp vào nhà cung cấp Gemini API để 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-3.5-flash")
// 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 từ dữ liệu đầu vào đa phương thức (chẳng hạn như hình ảnh)
|
Nhấp vào nhà cung cấp Gemini API để 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 bằng cách đưa ra câu lệnh kèm theo văn bản và một tệp, chẳng hạn như hình ảnh hoặc 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-3.5-flash")
// 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 câu trả lời theo thời gian thực
Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không đợi 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 phát trực tiếp để xử lý kết quả một phần. Để 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 các mô hình "Nano Banana")
|
Nhấp vào nhà cung cấp Gemini API để 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-3-pro-image(còn gọi là "Nano Banana Pro")gemini-3.1-flash-image(còn gọi là "Nano Banana 2")
Bạn có thể yêu cầu một mô hình tạo hình ảnh Gemini (chẳng hạn như mô hình "Nano Banana") tạo hình ảnh bằng cách đưa ra câu lệnh chỉ bằng văn bản.
Ví dụ sau đây cho thấy cách chỉ tạo một hình ảnh, nhưng các mô hình tạo hình ảnh Gemini 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 image-generating model that supports your use case.
let model = ai.geminiLanguageModel(name: "gemini-3.1-flash-image"
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 đầu ra JSON có cấu trúc
|
Nhấp vào nhà cung cấp Gemini API để 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-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-litegemini-3-pro-image
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ụ khác ở hạ nguồn 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 một 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 đầu ra JSON có cấu trúc, hãy xem hướng dẫn chung về Tạo đầu ra 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-3.5-flash")
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 cơ bản của Apple