Tạo cuộc trò chuyện (trò chuyện) nhiều lượt bằng API Gemini

Khi sử dụng Gemini API, bạn có thể tạo các cuộc trò chuyện ở dạng tự do qua nhiều lượt. SDK Firebase AI Logic đơn giản hoá quy trình này bằng cách quản lý trạng thái của cuộc trò chuyện. Vì vậy, không giống như với generateContent() (hoặc generateContentStream()), bạn không phải tự lưu trữ nhật ký trò chuyện.

Trước khi bắt đầu

Nhấp vào nhà cung cấp Gemini API để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Nếu bạn chưa hoàn tất, hãy hoàn thành hướng dẫn bắt đầu sử dụng. Hướng dẫn này mô tả cách thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK, khởi chạy dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn đã chọn và tạo một thực thể GenerativeModel.

Để kiểm thử và lặp lại các câu lệnh của bạn, thậm chí là nhận một đoạn mã đã tạo, bạn nên sử dụng Google AI Studio.

Gửi yêu cầu câu lệnh trò chuyện

Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng.
Trong phần đó, bạn cũng sẽ nhấp vào nút của nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này.

Để tạo một cuộc trò chuyện nhiều lượt (như cuộc trò chuyện), hãy bắt đầu bằng cách khởi chạy cuộc trò chuyện bằng cách gọi startChat(). Sau đó, hãy sử dụng sendMessage() để gửi tin nhắn mới của người dùng. Thao tác này cũng sẽ thêm tin nhắn và phản hồi vào nhật ký trò chuyện.

Có hai tuỳ chọn có thể dùng cho role liên kết với nội dung trong một cuộc trò chuyện:

  • user: vai trò cung cấp lời nhắc. Giá trị này là giá trị mặc định cho các lệnh gọi đến sendMessage() và hàm sẽ gửi một ngoại lệ nếu một vai trò khác được truyền.

  • model: vai trò cung cấp phản hồi. Bạn có thể sử dụng vai trò này khi gọi startChat() bằng history hiện có.

Swift

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:


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

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:

Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.

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

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:

Đối với Java, các phương thức trong SDK này trả về một 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

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:


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

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:


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

Bạn có thể gọi startChat()sendMessage() để gửi tin nhắn cho người dùng mới:


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.");

Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Truyền trực tuyến phản hồi

Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng.
Trong phần đó, bạn cũng sẽ nhấp vào nút của nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này.

Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, mà thay vào đó, hãy sử dụng tính năng truyền trực tuyến để xử lý một phần kết quả. Để truyền trực tuyến phản hồi, hãy gọi sendMessageStream().



Bạn có thể làm gì khác?

Thử các tính năng khác

Tìm hiểu cách kiểm soát việc tạo nội dung

Bạn cũng có thể thử nghiệm với các lời nhắc và cấu hình mô hình, thậm chí nhận được một đoạn mã được tạo bằng Google AI Studio.

Tìm hiểu thêm về các mẫu được hỗ trợ

Tìm hiểu về các mô hình có sẵn cho nhiều trường hợp sử dụng, cũng như hạn mứcgiá của các mô hình đó.


Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic