Apple의 파운데이션 모델 프레임워크를 통해 Gemini API에 액세스할 때 사용할 수 있는 기능


이 페이지의 예시에서는 시작하기: Apple의 Foundation Models 프레임워크를 통해 Gemini API에 액세스를 완료했다고 가정합니다.


이 가이드에서는 Apple 플랫폼용 Firebase AI Logic SDK를 사용하여 Apple의 Foundation Models 프레임워크를 통해 Gemini API에 다양한 유형의 요청을 보내는 방법을 보여줍니다.

이 페이지에서는 다음 유형의 요청을 보내는 방법의 예시를 보여줍니다.



텍스트 생성

Gemini 모델은 텍스트 생성을 위해 다음 기능을 지원합니다.

이 기능을 지원하는 모델

  • gemini-4-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • gemini-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 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

텍스트와 파일(예: 이미지 또는 PDF)을 프롬프트로 사용하여 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")

// 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-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • gemini-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 액세스에 관한 의견 보내기