Funzionalità disponibili quando si accede all'API Gemini tramite il framework Foundation Models di Apple


Gli esempi in questa pagina presuppongono che tu abbia completato la sezione Inizia: accedi a Gemini API tramite il framework Foundation Models di Apple.


Questa guida mostra come inviare vari tipi di richieste a Gemini API tramite il framework Foundation Models di Apple utilizzando l'SDK Firebase AI Logic per le piattaforme Apple.

Questa pagina mostra esempi di come inviare i seguenti tipi di richieste:



Genera testo

I modelli Gemini supportano le seguenti funzionalità per la generazione di testo:

Modelli che supportano questa funzionalità

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (e le versioni precedenti gemini-3.7-flash, gemini-3.6-flash e gemini-3.5-flash)
  • gemini-3.5-flash-lite (e la precedente gemini-3.1-flash-lite)

Generare testo da input di solo testo

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Puoi chiedere a un modello Gemini di generare testo fornendo un input solo testuale.

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.8-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)

Visualizzare in streaming la risposta

Puoi ottenere interazioni più rapide senza attendere l'intero risultato della generazione del modello e utilizzare 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
}

Generare testo durante una sessione multi-turno (chat)

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore 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.8-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 multimodali (come le immagini)

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Puoi chiedere a un modello Gemini di generare testo fornendo 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.8-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)

Visualizzare in streaming la risposta

Puoi ottenere interazioni più rapide senza attendere l'intero risultato della generazione del modello e utilizzare 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)



Generare immagini (utilizzando i modelli "Nano Banana")

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Modelli che supportano questa funzionalità

  • gemini-3-pro-image (noto anche come "Nano Banana Pro")
  • gemini-3.1-flash-image (ovvero "Nano Banana 2")

Puoi chiedere a un modello di generazione di immagini Gemini (come 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 immagini possono generare sia immagini che testo.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 image output.
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
      }
    }
  }
}



Generare un output JSON strutturato

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Modelli che supportano questa funzionalità

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-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.

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


Invia feedback sull'accesso a Gemini API tramite il framework Foundation Models di Apple