Capacidades disponibles cuando se accede a la API de Gemini a través del framework de modelos de base de Apple


En los ejemplos de esta página, se supone que completaste la sección Introducción: Accede a la Gemini API a través del framework de Foundation Models de Apple.


En esta guía, se muestra cómo enviar varios tipos de solicitudes a la Gemini API a través del framework de Foundation Models de Apple con el Firebase AI Logic SDK para plataformas de Apple.

En esta página, se muestran ejemplos para enviar los siguientes tipos de solicitudes:



Generar texto

Gemini modelos admiten las siguientes capacidades para generar texto:

Modelos que admiten esta capacidad

  • gemini-3.1-pro-preview
  • gemini-3.6-flash (y el gemini-3.5-flash más antiguo)
  • gemini-3.5-flash-lite (y el gemini-3.1-flash-lite más antiguo)

Generar texto a partir de una entrada de solo texto

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

Puedes pedirle a un Gemini modelo que genere texto con una instrucción de entrada de solo texto.

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

Transmite la respuesta

Puedes lograr interacciones más rápidas si no esperas el resultado completo de la generación del modelo y, en su lugar, usas la transmisión para controlar los resultados parciales. Para transmitir la respuesta, usa streamResponse(to:) en lugar de 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
}

Generar texto durante una sesión de varios turnos (chat)

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

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.6-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"

Generar texto a partir de una entrada multimodal (como imágenes)

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

Puedes pedirle a un Gemini modelo que genere texto con una instrucción de texto y un archivo, como una imagen 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.6-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)

Transmite la respuesta

Puedes lograr interacciones más rápidas si no esperas el resultado completo de la generación del modelo y, en su lugar, usas la transmisión para controlar los resultados parciales. Para transmitir la respuesta, usa streamResponse en lugar de 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)



Generar imágenes (con modelos "Nano Banana")

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

Modelos que admiten esta capacidad

  • gemini-3-pro-image (también conocido como "Nano Banana Pro")
  • gemini-3.1-flash-image (también conocido como "Nano Banana 2")

Puedes pedirle a un modelo que genere imágenes Gemini (como un modelo "Nano Banana" ) que genere una imagen con una instrucción de entrada de solo texto.

En el siguiente ejemplo, se muestra cómo generar solo una imagen, pero los modelos Gemini que generan imágenes pueden generar imágenes y texto.

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
      }
    }
  }
}



Generar un resultado JSON estructurado

Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página.

Modelos que admiten esta capacidad

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-3-pro-image

De forma predeterminada, los modelos de Gemini muestran respuestas como texto no estructurado. Sin embargo, algunos casos de uso requieren texto estructurado, como JSON. Por ejemplo, es posible que uses la respuesta para otras tareas posteriores que requieran un esquema de datos establecido.

Puedes configurar el modelo para que formatee su respuesta según un esquema JSON que proporciones. Para obtener detalles, prácticas recomendadas y casos de uso para generar resultados JSON estructurados, consulta la guía general Genera resultados estructurados

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


Envía comentarios sobre el acceso a la Gemini API a través del framework de Foundation Models de Apple.