Tạo đầu ra có cấu trúc (như JSON và enum) bằng API Gemini

Theo mặc định, Gemini API sẽ trả về các câu trả lời dưới dạng văn bản không có cấu trúc. Tuy nhiên, một số trường hợp sử dụng yêu cầu văn bản có cấu trúc, chẳng hạn như JSON. Ví dụ: bạn có thể đang sử dụng phản hồi cho các tác vụ khác ở hạ nguồn đòi hỏi một lược đồ dữ liệu đã thiết lập.

Để đảm bảo rằng đầu ra do mô hình tạo luôn tuân thủ một giản đồ cụ thể, bạn có thể xác định một giản đồ phản hồi hoạt động như một bản thiết kế cho các phản hồi của mô hình. Sau đó, bạn có thể trực tiếp trích xuất dữ liệu từ đầu ra của mô hình mà không cần xử lý hậu kỳ nhiều.

Sau đây là một số ví dụ:

  • Đảm bảo rằng phản hồi của mô hình tạo ra JSON hợp lệ và tuân thủ giản đồ mà bạn cung cấp.
    Ví dụ: mô hình này có thể tạo các mục có cấu trúc cho công thức nấu ăn, trong đó luôn có tên công thức, danh sách nguyên liệu và các bước. Sau đó, bạn có thể phân tích cú pháp và hiển thị thông tin này dễ dàng hơn trong giao diện người dùng của ứng dụng.

  • Hạn chế cách mô hình có thể phản hồi trong các tác vụ phân loại.
    Ví dụ: bạn có thể yêu cầu mô hình chú thích văn bản bằng một bộ nhãn cụ thể (ví dụ: một bộ enum cụ thể như positivenegative), thay vì các nhãn mà mô hình tạo ra (có thể có mức độ biến đổi như good, positive, negative hoặc bad).

Hướng dẫn này cho biết cách tạo đầu ra JSON bằng cách cung cấp một responseSchema trong lệnh gọi đến generateContent. Gemini tập trung vào dữ liệu đầu vào chỉ có văn bản, nhưng cũng có thể tạo ra các câu trả lời có cấu trúc cho các yêu cầu đa phương thức bao gồm hình ảnh, video và âm thanh làm dữ liệu đầu vào.

Ở cuối trang này có nhiều ví dụ khác, chẳng hạn như cách tạo các giá trị enum dưới dạng đầu ra.

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 thực hiện, hãy hoàn tất 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 động 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, thậm chí nhận được một đoạn mã được tạo, bạn nên sử dụng Google AI Studio.

Bước 1: Xác định giản đồ phản hồi

Xác định giản đồ phản hồi để chỉ định cấu trúc của đầu ra của mô hình, tên trường và loại dữ liệu dự kiến cho từng trường.

Khi tạo câu trả lời, mô hình sẽ sử dụng tên trường và ngữ cảnh trong câu lệnh của bạn. Để đảm bảo ý định của bạn rõ ràng, bạn nên sử dụng cấu trúc rõ ràng, tên trường không mơ hồ và thậm chí cả nội dung mô tả nếu cần.

Những điểm cần cân nhắc đối với giản đồ phản hồi

Khi viết giản đồ phản hồi, hãy lưu ý những điều sau:

  • Kích thước của giản đồ phản hồi được tính vào giới hạn mã thông báo đầu vào.

  • Tính năng giản đồ phản hồi hỗ trợ các loại MIME phản hồi sau:

    • application/json: xuất JSON như được xác định trong giản đồ phản hồi (hữu ích cho các yêu cầu về đầu ra có cấu trúc)

    • text/x.enum: xuất một giá trị enum như được xác định trong giản đồ phản hồi (hữu ích cho các tác vụ phân loại)

  • Tính năng giản đồ phản hồi hỗ trợ các trường giản đồ sau:

    enum
    items
    maxItems
    nullable
    properties
    required

    Nếu bạn sử dụng một trường không được hỗ trợ, mô hình vẫn có thể xử lý yêu cầu của bạn, nhưng sẽ bỏ qua trường đó. Xin lưu ý rằng danh sách trên là một nhóm nhỏ của đối tượng lược đồ OpenAPI 3.0.

  • Theo mặc định, đối với các SDK Firebase AI Logic, tất cả các trường đều được coi là bắt buộc, trừ phi bạn chỉ định chúng là không bắt buộc trong một mảng optionalProperties. Đối với các trường không bắt buộc này, mô hình có thể điền sẵn hoặc bỏ qua các trường. Xin lưu ý rằng điều này ngược lại với hành vi mặc định của hai nhà cung cấp Gemini API nếu bạn sử dụng SDK máy chủ hoặc API của họ một cách trực tiếp.

Bước 2: Tạo đầu ra JSON bằng giản đồ phản hồi

Trước khi dùng 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 của bạn.
Trong phần đó, bạn cũng sẽ nhấp vào một nút cho 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.

Ví dụ sau đây cho thấy cách tạo đầu ra JSON có cấu trúc.

Khi bạn tạo phiên bản GenerativeModel, hãy chỉ định responseMimeType thích hợp (trong ví dụ này là application/json) cũng như responseSchema mà bạn muốn mô hình sử dụng.

Swift


import FirebaseAI

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let jsonSchema = Schema.object(
  properties: [
    "characters": Schema.array(
      items: .object(
        properties: [
          "name": .string(),
          "age": .integer(),
          "species": .string(),
          "accessory": .enumeration(values: ["hat", "belt", "shoes"]),
        ],
        optionalProperties: ["accessory"]
      )
    ),
  ]
)

// 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.5-flash",
  // In the generation config, set the `responseMimeType` to `application/json`
  // and pass the JSON schema object into `responseSchema`.
  generationConfig: GenerationConfig(
    responseMIMEType: "application/json",
    responseSchema: jsonSchema
  )
)

let prompt = "For use in a children's card game, generate 10 animal-based characters."

let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

Kotlin

Đố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 qua Phạm vi Coroutine.

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val jsonSchema = Schema.obj(
    mapOf("characters" to Schema.array(
        Schema.obj(
            mapOf(
                "name" to Schema.string(),
                "age" to Schema.integer(),
                "species" to Schema.string(),
                "accessory" to Schema.enumeration(listOf("hat", "belt", "shoes")),
            ),
            optionalProperties = listOf("accessory")
        )
    ))
)

// 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(
    modelName = "gemini-2.5-flash",
    // In the generation config, set the `responseMimeType` to `application/json`
    // and pass the JSON schema object into `responseSchema`.
    generationConfig = generationConfig {
        responseMimeType = "application/json"
        responseSchema = jsonSchema
    })

val prompt = "For use in a children's card game, generate 10 animal-based characters."
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

Đối với Java, các phương thức truyền phát trực tiếp trong SDK này sẽ trả về một loại Publisher từ thư viện Reactive Streams.

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema jsonSchema = Schema.obj(
        /* properties */
        Map.of(
                "characters", Schema.array(
                        /* items */ Schema.obj(
                                /* properties */
                                Map.of("name", Schema.str(),
                                        "age", Schema.numInt(),
                                        "species", Schema.str(),
                                        "accessory",
                                        Schema.enumeration(
                                                List.of("hat", "belt", "shoes")))
                        ))),
        List.of("accessory"));

// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = jsonSchema;

GenerationConfig generationConfig = configBuilder.build();

// 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(
            /* modelName */ "gemini-2.5-flash",
            /* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

Content content = new Content.Builder()
    .addText("For use in a children's card game, generate 10 animal-based characters.")
    .build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
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


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, Schema } 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() });

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const jsonSchema = Schema.object({
 properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          accessory: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
        },
        optionalProperties: ["accessory"],
      }),
    }),
  }
});

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
  model: "gemini-2.5-flash",
  // In the generation config, set the `responseMimeType` to `application/json`
  // and pass the JSON schema object into `responseSchema`.
  generationConfig: {
    responseMimeType: "application/json",
    responseSchema: jsonSchema
  },
});


let prompt = "For use in a children's card game, generate 10 animal-based characters.";

let result = await model.generateContent(prompt)
console.log(result.response.text());

Dart


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

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final jsonSchema = Schema.object(
        properties: {
          'characters': Schema.array(
            items: Schema.object(
              properties: {
                'name': Schema.string(),
                'age': Schema.integer(),
                'species': Schema.string(),
                'accessory':
                    Schema.enumString(enumValues: ['hat', 'belt', 'shoes']),
              },
            ),
          ),
        },
        optionalProperties: ['accessory'],
      );


// 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.5-flash',
        // In the generation config, set the `responseMimeType` to `application/json`
        // and pass the JSON schema object into `responseSchema`.
        generationConfig: GenerationConfig(
            responseMimeType: 'application/json', responseSchema: jsonSchema));

final prompt = "For use in a children's card game, generate 10 animal-based characters.";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Unity


using Firebase;
using Firebase.AI;

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var jsonSchema = Schema.Object(
  properties: new System.Collections.Generic.Dictionary<string, Schema> {
    { "characters", Schema.Array(
      items: Schema.Object(
        properties: new System.Collections.Generic.Dictionary<string, Schema> {
          { "name", Schema.String() },
          { "age", Schema.Int() },
          { "species", Schema.String() },
          { "accessory", Schema.Enum(new string[] { "hat", "belt", "shoes" }) },
        },
        optionalProperties: new string[] { "accessory" }
      )
    ) },
  }
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
  modelName: "gemini-2.5-flash",
  // In the generation config, set the `responseMimeType` to `application/json`
  // and pass the JSON schema object into `responseSchema`.
  generationConfig: new GenerationConfig(
    responseMimeType: "application/json",
    responseSchema: jsonSchema
  )
);

var prompt = "For use in a children's card game, generate 10 animal-based characters.";

var response = await model.GenerateContentAsync(prompt);
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.

Các ví dụ khác

Sau đây là một số ví dụ khác về cách bạn có thể sử dụng và tạo đầu ra có cấu trúc.

Tạo các giá trị enum làm đầu ra

Trước khi dùng 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 của bạn.
Trong phần đó, bạn cũng sẽ nhấp vào một nút cho 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.

Ví dụ sau đây cho biết cách sử dụng một giản đồ phản hồi cho tác vụ phân loại. Mô hình được yêu cầu xác định thể loại của một bộ phim dựa trên nội dung mô tả của bộ phim đó. Đầu ra là một giá trị enum văn bản thuần tuý mà mô hình chọn trong danh sách các giá trị được xác định trong giản đồ phản hồi được cung cấp.

Để thực hiện nhiệm vụ phân loại có cấu trúc này, bạn cần chỉ định responseMimeType thích hợp (trong ví dụ này là text/x.enum) cũng như responseSchema mà bạn muốn mô hình sử dụng trong quá trình khởi tạo mô hình.

Swift


import FirebaseAI

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let enumSchema = Schema.enumeration(values: ["drama", "comedy", "documentary"])

// 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.5-flash",
  // In the generation config, set the `responseMimeType` to `text/x.enum`
  // and pass the enum schema object into `responseSchema`.
  generationConfig: GenerationConfig(
    responseMIMEType: "text/x.enum",
    responseSchema: enumSchema
  )
)

let prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""

let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

Kotlin

Đố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 qua Phạm vi Coroutine.

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val enumSchema = Schema.enumeration(listOf("drama", "comedy", "documentary"))

// 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(
    modelName = "gemini-2.5-flash",
    // In the generation config, set the `responseMimeType` to `text/x.enum`
    // and pass the enum schema object into `responseSchema`.
    generationConfig = generationConfig {
        responseMimeType = "text/x.enum"
        responseSchema = enumSchema
    })

val prompt = """
    The film aims to educate and inform viewers about real-life subjects, events, or people.
    It offers a factual record of a particular topic by combining interviews, historical footage,
    and narration. The primary purpose of a film is to present information and provide insights
    into various aspects of reality.
    """
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

Đối với Java, các phương thức truyền phát trực tiếp trong SDK này sẽ trả về một loại Publisher từ thư viện Reactive Streams.

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema enumSchema = Schema.enumeration(List.of("drama", "comedy", "documentary"));

// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "text/x.enum";
configBuilder.responseSchema = enumSchema;

GenerationConfig generationConfig = configBuilder.build();

// 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(
            /* modelName */ "gemini-2.5-flash",
            /* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

String prompt = "The film aims to educate and inform viewers about real-life subjects," +
                " events, or people. It offers a factual record of a particular topic by" +
                " combining interviews, historical footage, and narration. The primary purpose" +
                " of a film is to present information and provide insights into various aspects" +
                " of reality.";

Content content = new Content.Builder().addText(prompt).build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
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


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, Schema } 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() });

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"],
});

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
  model: "gemini-2.5-flash",
  // In the generation config, set the `responseMimeType` to `text/x.enum`
  // and pass the JSON schema object into `responseSchema`.
  generationConfig: {
    responseMimeType: "text/x.enum",
    responseSchema: enumSchema,
  },
});

let prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;

let result = await model.generateContent(prompt);
console.log(result.response.text());

Dart


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

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final enumSchema = Schema.enumString(enumValues: ['drama', 'comedy', 'documentary']);

// 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.5-flash',
        // In the generation config, set the `responseMimeType` to `text/x.enum`
        // and pass the enum schema object into `responseSchema`.
        generationConfig: GenerationConfig(
            responseMimeType: 'text/x.enum', responseSchema: enumSchema));

final prompt = """
      The film aims to educate and inform viewers about real-life subjects, events, or people.
      It offers a factual record of a particular topic by combining interviews, historical footage, 
      and narration. The primary purpose of a film is to present information and provide insights
      into various aspects of reality.
      """;
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Unity


using Firebase;
using Firebase.AI;

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var enumSchema = Schema.Enum(new string[] { "drama", "comedy", "documentary" });

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
  modelName: "gemini-2.5-flash",
  // In the generation config, set the `responseMimeType` to `text/x.enum`
  // and pass the enum schema object into `responseSchema`.
  generationConfig: new GenerationConfig(
    responseMimeType: "text/x.enum",
    responseSchema: enumSchema
  )
);

var prompt = @"
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
";

var response = await model.GenerateContentAsync(prompt);
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.

Các lựa chọn khác để kiểm soát việc tạo nội dung

  • Tìm hiểu thêm về cách thiết kế câu lệnh để bạn có thể tác động đến mô hình nhằm tạo ra kết quả phù hợp với nhu cầu của mình.
  • Định cấu hình các thông số mô hình để kiểm soát cách mô hình tạo ra câu trả lời. Đối với các mô hình Gemini, các tham số này bao gồm số lượng mã thông báo đầu ra tối đa, nhiệt độ, topK và topP. Đối với các mô hình Imagen, những yếu tố này bao gồm tỷ lệ khung hình, tạo người, đóng dấu bản quyền, v.v.
  • Sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được những câu trả lời có thể bị coi là gây hại, bao gồm cả lời nói hận thù và nội dung khiêu dâm.
  • Đặt chỉ dẫn hệ thống để định hướng hành vi của mô hình. Tính năng này giống như một phần mở đầu mà bạn thêm trước khi mô hình tiếp xúc với bất kỳ hướng dẫn nào khác của người dùng cuối.


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