| このページの例は、スタートガイド: Apple の Foundation Models フレームワークを介して Gemini API にアクセスするを完了していることを前提としています。 |
このガイドでは、Apple プラットフォーム用の Firebase AI Logic SDK を使用して、Apple の Foundation Models フレームワークを介して Gemini API にさまざまなタイプのリクエストを送信する方法について説明します。
このページでは、次のタイプのリクエストを送信する方法の例を示します。
テキストを生成
Gemini モデルは、テキストを生成する次の機能をサポートしています。
この機能をサポートするモデル
gemini-4-hydrogengemini-4-argongemini-4-carbongemini-3.8-flashgemini-3.5-flash-lite(および以前のgemini-3.1-flash-lite)
古い一般用途の Gemini 3.x Flash モデルはこの機能をサポートしていますが、今後のシャットダウン日や新しいモデルへの自動ルーティングにより、使用は推奨されなくなりました。
テキストのみの入力からテキストを生成する
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
テキストのみの入力でプロンプトを送信することで、Gemini モデルにテキストを生成するようリクエストできます。
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)
レスポンスをストリーミングする
モデル生成から完全な結果を待つのではなく、ストリーミングを使用して部分的な結果を処理することで、より迅速なインタラクションを実現できます。レスポンスをストリーミングするには、respond(to:) ではなく streamResponse(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
}
マルチターン セッション(チャット)中にテキストを生成する
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
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"
マルチモーダル入力(画像など)からテキストを生成する
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
Gemini モデルにテキストとファイル(画像や 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)
レスポンスをストリーミングする
モデル生成から完全な結果を待つのではなく、ストリーミングを使用して部分的な結果を処理することで、より迅速なインタラクションを実現できます。レスポンスをストリーミングするには、respond ではなく streamResponse を使用します。
// 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)
画像を生成する(Nano Banana モデルを使用)
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
この機能をサポートするモデル
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)
テキストのみの入力でプロンプトを表示することで、Gemini Nano Banana モデルに画像を生成するようリクエストできます。
次の例は、画像のみを生成する方法を示していますが、Nano Banana モデルは画像とテキストの両方を生成できます。
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
}
}
}
}
構造化された JSON 出力を生成する
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
この機能をサポートするモデル
gemini-4-hydrogengemini-4-argongemini-4-carbongemini-3.8-flashgemini-3.5-flash-lite(および以前のgemini-3.1-flash-lite)gemini-3-pro-image(Nano Banana Pro)
古い一般用途の Gemini 3.x Flash モデルはこの機能をサポートしていますが、今後のシャットダウン日や新しいモデルへの自動ルーティングにより、使用は推奨されなくなりました。
Gemini モデルは、デフォルトで非構造化テキストとしてレスポンスを返します。ただし、ユースケースによっては、JSON などの構造化テキストが必要になることがあります。たとえば、確立されたデータ スキーマを必要とする他のダウンストリーム タスクにレスポンスを使用している場合があります。
指定した JSON スキーマに従ってレスポンスをフォーマットするようにモデルを構成できます。構造化 JSON 出力を生成するための詳細、ベスト プラクティス、ユースケースについては、一般的な構造化出力を生成するガイドをご覧ください。
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
Apple の Foundation Models フレームワークを介した Gemini API へのアクセスについてフィードバックをお寄せください