| Gli esempi riportati in questa pagina presuppongono che tu abbia completato la sezione Inizia: accedi all'Gemini API tramite il framework Foundation Models di Apple. |
Questa guida mostra come inviare vari tipi di richieste al Gemini API tramite il framework Foundation Models di Apple utilizzando l' Firebase AI Logic SDK per le piattaforme Apple.
Questa pagina mostra esempi di come inviare i seguenti tipi di richieste:
- Genera testo da input di solo testo
- Genera testo durante una sessione multi-turn (chat)
- Genera testo da input multimodale (come le immagini)
- Genera immagini da input di solo testo
Genera testo
Gemini modelli supportano le seguenti funzionalità per la generazione di testo:
- Genera testo da input di solo testo
- Genera testo durante una sessione multi-turn (chat)
- Genera testo da input multimodale (come le immagini)
Modelli che supportano questa funzionalità
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-lite
Genera testo da input di solo testo
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
Puoi chiedere a un Gemini modello di generare testo utilizzando un prompt con input di solo testo.
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)
Trasmetti in streaming la risposta
Puoi ottenere interazioni più rapide senza attendere l'intero risultato della generazione del modello e utilizzando invece lo streaming per gestire i risultati parziali. Per trasmettere in streaming la risposta, utilizza streamResponse(to:) anziché 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
}
Genera testo durante una sessione multi-turn (chat)
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
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"
Genera testo da input multimodale (come le immagini)
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
Puoi chiedere a un modello Gemini di generare testo utilizzando un prompt con testo e un file, ad esempio un'immagine o un 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)
Trasmetti in streaming la risposta
Puoi ottenere interazioni più rapide senza attendere l'intero risultato della generazione del modello e utilizzando invece lo streaming per gestire i risultati parziali. Per trasmettere in streaming la risposta, utilizza streamResponse anziché 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)
Genera immagini (utilizzando i modelli "Nano Banana")
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
Modelli che supportano questa funzionalità
gemini-3-pro-image(noto anche come "Nano Banana Pro")gemini-3.1-flash-image(noto anche come "Nano Banana 2")
Puoi chiedere a un modello di generazione di immagini Gemini (ad esempio un modello "Nano Banana" ) di generare un'immagine utilizzando un prompt con input di solo testo.
L'esempio seguente mostra come generare solo un'immagine, ma i modelli di generazione di Gemini immagini possono generare sia immagini che testo.
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
}
}
}
}
Genera output JSON strutturato
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
Modelli che supportano questa funzionalità
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-litegemini-3-pro-image
Per impostazione predefinita, i modelli Gemini restituiscono le risposte come testo non strutturato. Tuttavia, alcuni casi d'uso richiedono testo strutturato, come JSON. Ad esempio, potresti utilizzare la risposta per altre attività downstream che richiedono uno schema di dati stabilito.
Puoi configurare il modello in modo che formatti la risposta in base a uno schema JSON che fornisci. Per dettagli, best practice e casi d'uso per la generazione di output JSON strutturato, consulta la guida generale Generare output strutturato guide.
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
Fornisci feedback sull'accesso a Gemini API tramite il framework Foundation Models di Apple