Gemini API를 사용하여 멀티턴 대화 (채팅) 빌드

Gemini API를 사용하면 여러 차례에 걸쳐 자유 형식의 대화를 빌드할 수 있습니다. Firebase AI Logic SDK는 대화 상태를 관리하여 프로세스를 간소화하므로 generateContent()(또는 generateContentStream())와 달리 대화 기록을 직접 저장하지 않아도 됩니다.

시작하기 전에

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, GenerativeModel 인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료하세요.

프롬프트를 테스트하고 반복하며 생성된 코드 스니펫을 가져오려면 Google AI Studio를 사용하는 것이 좋습니다.

채팅 프롬프트 요청 보내기

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다.

멀티턴 대화 (예: 채팅)를 빌드하려면 먼저 startChat()를 호출하여 채팅을 초기화합니다. 그런 다음 sendMessage()를 사용하여 새 사용자 메시지를 전송합니다. 그러면 메시지와 응답이 채팅 기록에 추가됩니다.

대화의 콘텐츠와 연결된 role에는 두 가지 옵션이 있습니다.

  • user: 프롬프트를 제공하는 역할입니다. 이 값은 sendMessage() 호출의 기본값이며 다른 역할이 전달되면 함수가 예외를 발생시킵니다.

  • model: 응답을 제공하는 역할입니다. 이 역할은 기존 historystartChat()를 호출할 때 사용할 수 있습니다.

Swift

startChat()sendMessage()를 호출하여 신규 사용자 메시지를 보낼 수 있습니다.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Optionally specify existing chat history
let history = [
  ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]

// Initialize the chat with optional chat history
let chat = model.startChat(history: history)

// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
print(response.text ?? "No text in response.")

Kotlin

startChat()sendMessage()를 호출하여 새 사용자 메시지를 보낼 수 있습니다.

Kotlin의 경우 이 SDK의 메서드는 정지 함수이므로 코루틴 범위에서 호출해야 합니다.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


// Initialize the chat
val chat = generativeModel.startChat(
  history = listOf(
    content(role = "user") { text("Hello, I have 2 dogs in my house.") },
    content(role = "model") { text("Great to meet you. What would you like to know?") }
  )
)

val response = chat.sendMessage("How many paws are in my house?")
print(response.text)

Java

startChat()sendMessage()를 호출하여 신규 사용자 메시지를 보낼 수 있습니다.

Java의 경우 이 SDK의 메서드는 ListenableFuture를 반환합니다.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");

Content message = messageBuilder.build();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

startChat()sendMessage()를 호출하여 신규 사용자 메시지를 보낼 수 있습니다.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


async function run() {
  const chat = model.startChat({
    history: [
      {
        role: "user",
        parts: [{ text: "Hello, I have 2 dogs in my house." }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
    generationConfig: {
      maxOutputTokens: 100,
    },
  });

  const msg = "How many paws are in my house?";

  const result = await chat.sendMessage(msg);

  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

startChat()sendMessage()를 호출하여 신규 사용자 메시지를 보낼 수 있습니다.


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


final chat = model.startChat();
// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

final response = await chat.sendMessage(prompt);
print(response.text);

Unity

StartChat()SendMessageAsync()를 호출하여 신규 사용자 메시지를 보낼 수 있습니다.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Optionally specify existing chat history
var history = new [] {
  ModelContent.Text("Hello, I have 2 dogs in my house."),
  new ModelContent("model", new ModelContent.TextPart("Great to meet you. What would you like to know?")),
};

// Initialize the chat with optional chat history
var chat = model.StartChat(history);

// To generate text output, call SendMessageAsync and pass in the message
var response = await chat.SendMessageAsync("How many paws are in my house?");
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

사용 사례 및 앱에 적합한 모델을 선택하는 방법을 알아보세요.

대답 스트리밍

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다.

모델 생성의 전체 결과를 기다리지 않고 대신 스트리밍을 사용하여 부분 결과를 처리하면 더 빠른 상호작용을 얻을 수 있습니다. 응답을 스트리밍하려면 sendMessageStream()를 호출합니다.



또 뭘 할 수 있니?

  • 모델에 긴 프롬프트를 보내기 전에 토큰 수를 집계하는 방법을 알아보세요.
  • Cloud Storage for Firebase를 설정하여 다중 모드 요청에 대용량 파일을 포함하고 프롬프트에서 파일을 제공하는 더 관리된 솔루션을 사용할 수 있습니다. 파일에는 이미지, PDF, 동영상, 오디오가 포함될 수 있습니다.
  • 다음을 포함하여 프로덕션 준비 (프로덕션 체크리스트 참고)에 대해 생각해 보세요.

다른 기능 사용해 보기

콘텐츠 생성을 제어하는 방법 알아보기

프롬프트와 모델 구성을 실험하고 Google AI Studio를 사용하여 생성된 코드 스니펫을 가져올 수도 있습니다.

지원되는 모델 자세히 알아보기

다양한 사용 사례에 사용할 수 있는 모델할당량, 가격에 대해 알아보세요.


Firebase AI Logic 사용 경험에 관한 의견 보내기