สร้างเอาต์พุตที่มีโครงสร้าง (เช่น JSON และลิสต์แบบจำกัด) โดยใช้ Gemini API

Gemini API จะแสดงผลการตอบสนองเป็นข้อความที่ไม่มีโครงสร้างโดยค่าเริ่มต้น อย่างไรก็ตาม บางกรณีการใช้งานจำเป็นต้องใช้ข้อความที่มีโครงสร้าง เช่น JSON ตัวอย่างเช่น คุณอาจใช้การตอบสนองสำหรับงานอื่นๆ ที่ต้องทำต่อจากนี้ซึ่งต้องใช้สคีมาข้อมูลที่กำหนดไว้

หากต้องการให้เอาต์พุตที่สร้างขึ้นของโมเดลเป็นไปตามสคีมาที่เฉพาะเจาะจงเสมอ คุณสามารถกำหนด สคีมาการตอบสนอง ซึ่งทำงานเหมือนพิมพ์เขียวสำหรับการตอบสนองของโมเดล จากนั้นคุณจะดึงข้อมูลจากเอาต์พุตของโมเดลได้โดยตรงโดยไม่ต้องประมวลผลภายหลังมากนัก

ตัวอย่างเช่น

  • ตรวจสอบว่าการตอบสนองของโมเดลสร้าง JSON ที่ถูกต้องและเป็นไปตามสคีมาที่คุณ ระบุ
    ตัวอย่างเช่น โมเดลสามารถสร้างรายการที่มีโครงสร้างสำหรับสูตรอาหารซึ่งรวมถึงชื่อสูตร รายการส่วนผสม และขั้นตอนต่างๆ เสมอ จากนั้นคุณจะแยกวิเคราะห์และแสดงข้อมูลนี้ใน UI ของแอปได้ง่ายขึ้น

  • จำกัดวิธีที่โมเดลจะตอบสนองระหว่างงานการจัดประเภท
    ตัวอย่างเช่น คุณสามารถให้โมเดลใส่คำอธิบายประกอบข้อความด้วยชุดป้ายกำกับที่เฉพาะเจาะจง (เช่น ชุด enum ที่เฉพาะเจาะจง เช่น positive และ negative) แทนที่จะใช้ป้ายกำกับที่โมเดลสร้างขึ้น (ซึ่งอาจมีความหลากหลาย เช่น good, positive, negative หรือ bad)

คู่มือนี้จะแสดงวิธีสร้างเอาต์พุต JSON โดยระบุ responseSchema ในการเรียก generateContent โดยจะเน้นที่อินพุตที่เป็นข้อความเท่านั้น แต่ Gemini ยังสร้างการตอบสนองที่มีโครงสร้างสำหรับคำขอแบบมัลติโมดัลที่รวมรูปภาพ วิดีโอ และเสียงเป็นอินพุตได้ด้วย

ที่ด้านล่างของหน้านี้มีตัวอย่างเพิ่มเติม เช่น วิธี สร้างค่า enum เป็นเอาต์พุต

ก่อนเริ่มต้น

คลิกผู้ให้บริการ Gemini API เพื่อดูเนื้อหาที่เฉพาะเจาะจงของผู้ให้บริการ และโค้ดในหน้านี้

หากยังไม่ได้ดำเนินการ โปรดทำตาม คู่มือเริ่มต้นใช้งาน ซึ่งอธิบายวิธี ตั้งค่าโปรเจ็กต์ Firebase, เชื่อมต่อแอปกับ Firebase, เพิ่ม SDK, เริ่มต้นบริการแบ็กเอนด์สำหรับผู้ให้บริการ Gemini API ที่คุณเลือก และ สร้างอินสแตนซ์ GenerativeModel

เราขอแนะนำให้ใช้ สำหรับการทดสอบและทำซ้ำพรอมต์Google AI Studio

ขั้นตอนที่ 1: กำหนดสคีมาการตอบสนอง

กำหนดสคีมาการตอบสนองเพื่อระบุโครงสร้างของเอาต์พุตของโมเดล ชื่อฟิลด์ และประเภทข้อมูลที่คาดไว้สำหรับแต่ละฟิลด์

เมื่อโมเดลสร้างการตอบสนอง โมเดลจะใช้ชื่อฟิลด์และบริบทจากพรอมต์ เราขอแนะนำให้ใช้โครงสร้างที่ชัดเจน ชื่อฟิลด์ที่ไม่กำกวม และคำอธิบาย (หากจำเป็น) เพื่อให้แน่ใจว่าความตั้งใจของคุณชัดเจน

ข้อควรพิจารณาสำหรับสคีมาการตอบสนอง

โปรดคำนึงถึงสิ่งต่อไปนี้เมื่อเขียนสคีมาการตอบสนอง

  • ขนาดของสคีมาการตอบสนองจะนับรวมในขีดจำกัดโทเค็นอินพุต

  • ฟีเจอร์สคีมาการตอบสนองรองรับ MIME ประเภทการตอบสนองต่อไปนี้

    • application/json: แสดงผล JSON ตามที่กำหนดไว้ในสคีมาการตอบสนอง (มีประโยชน์สำหรับข้อกำหนดเอาต์พุตที่มีโครงสร้าง)

    • text/x.enum: แสดงผลค่า enum ตามที่กำหนดไว้ในสคีมาการตอบสนอง (มีประโยชน์สำหรับงานการจัดประเภท)

  • ฟีเจอร์สคีมาการตอบสนองรองรับฟิลด์สคีมาต่อไปนี้

    enum
    items
    maxItems
    nullable
    properties
    required

    หากคุณใช้ฟิลด์ที่ไม่รองรับ โมเดลจะยังจัดการคำขอของคุณได้ แต่จะละเว้นฟิลด์ดังกล่าว โปรดทราบว่ารายการด้านบนเป็นส่วนหนึ่งของออบเจ็กต์สคีมา OpenAPI 3.0

  • โดยค่าเริ่มต้น สำหรับ Firebase AI Logic SDK ระบบจะถือว่าฟิลด์ทั้งหมดเป็น ฟิลด์ที่ต้องกรอก เว้นแต่คุณจะระบุว่าเป็นฟิลด์ที่ไม่บังคับในoptionalProperties อาร์เรย์ สำหรับฟิลด์ที่ไม่บังคับเหล่านี้ โมเดลสามารถป้อนข้อมูลในฟิลด์หรือข้ามฟิลด์ได้ โปรดทราบว่าลักษณะการทำงานนี้จะตรงข้ามกับลักษณะการทำงานเริ่มต้นของผู้ให้บริการทั้งสองราย Gemini API หากคุณใช้ SDK ของเซิร์ฟเวอร์หรือ API ของผู้ให้บริการโดยตรง

ขั้นตอนที่ 2: สร้างเอาต์พุต JSON โดยใช้สคีมาการตอบสนอง

ก่อนที่จะลองใช้ตัวอย่างนี้ โปรดทำตามส่วน ก่อนเริ่มต้น ของคู่มือนี้ เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่คุณเลือกด้วย เพื่อให้เห็นเนื้อหาที่เฉพาะเจาะจงของผู้ให้บริการ ในหน้านี้

ตัวอย่างต่อไปนี้แสดงวิธีสร้างเอาต์พุต JSON ที่มีโครงสร้าง

เมื่อสร้างอินสแตนซ์ GenerativeModel ให้ระบุ responseMimeType ที่เหมาะสม (ในตัวอย่างนี้คือ application/json) รวมถึง responseSchema ที่ต้องการให้โมเดลใช้

Swift


import FirebaseAILogic

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

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียก จาก ขอบเขตโครูทีน

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

สำหรับ Java เมธอดการสตรีมใน SDK นี้จะแสดงผลประเภท Publisher จาก ไลบรารี 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-3.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-3.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-3.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-3.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.");

ดูวิธีเลือกโมเดล (ไม่บังคับ) ที่เหมาะสมกับกรณีการใช้งานและแอปของคุณ

ตัวอย่างเพิ่มเติม

ตัวอย่างเพิ่มเติมเกี่ยวกับวิธีใช้และสร้างเอาต์พุตที่มีโครงสร้างมีดังนี้

สร้างค่า enum เป็นเอาต์พุต

ก่อนที่จะลองใช้ตัวอย่างนี้ โปรดทำตามส่วน ก่อนเริ่มต้น ของคู่มือนี้ เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่คุณเลือกด้วย เพื่อให้เห็นเนื้อหาที่เฉพาะเจาะจงของผู้ให้บริการ ในหน้านี้

ตัวอย่างต่อไปนี้แสดงวิธีใช้สคีมาการตอบสนองสำหรับงานการจัดประเภท ระบบจะขอให้โมเดลระบุประเภทของภาพยนตร์ตามคำอธิบาย เอาต์พุตจะเป็นค่า enum แบบข้อความธรรมดา 1 ค่าที่โมเดลเลือกจากรายการค่าที่กำหนดไว้ในสคีมาการตอบสนองที่ระบุ

หากต้องการทำงานการจัดประเภทที่มีโครงสร้างนี้ คุณต้องระบุ responseMimeType ที่เหมาะสม (ในตัวอย่างนี้คือ text/x.enum) รวมถึง responseSchema ที่ต้องการให้โมเดลใช้ระหว่างการเริ่มต้นโมเดล

Swift


import FirebaseAILogic

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

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียก จาก ขอบเขตโครูทีน

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

สำหรับ Java เมธอดการสตรีมใน SDK นี้จะแสดงผลประเภท Publisher จาก ไลบรารี 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-3.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-3.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-3.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-3.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.");

ดูวิธีเลือกโมเดล (ไม่บังคับ) ที่เหมาะสมกับกรณีการใช้งานและแอปของคุณ

ตัวเลือกอื่นๆ ในการควบคุมการสร้างเนื้อหา

  • ดูข้อมูลเพิ่มเติมเกี่ยวกับการออกแบบพรอมต์ เพื่อให้คุณมีอิทธิพลต่อโมเดลในการสร้างเอาต์พุตที่เฉพาะเจาะจงตามความต้องการของคุณ
  • กำหนดค่า พารามิเตอร์ของโมเดล เพื่อควบคุมวิธีที่โมเดลสร้างการตอบสนอง สำหรับ Gemini โมเดล พารามิเตอร์เหล่านี้รวมถึงโทเค็นเอาต์พุตสูงสุด ความน่าจะเป็นของโทเค็นเอาต์พุตที่ซ้ำกัน โทเค็น เป็นต้น สำหรับ Imagen โมเดล พารามิเตอร์เหล่านี้รวมถึงอัตราส่วนกว้างยาว การสร้างบุคคล การใส่ลายน้ำ เป็นต้น
  • ใช้การตั้งค่าความปลอดภัย เพื่อปรับความน่าจะเป็นที่จะได้รับคำตอบที่อาจถือว่าเป็น อันตราย ซึ่งรวมถึงวาจาสร้างความเกลียดชังและเนื้อหาเกี่ยวกับเรื่องเพศอย่างโจ่งแจ้ง
  • ตั้งค่าวิธีการของระบบ เพื่อกำหนดลักษณะการทำงานของโมเดล ฟีเจอร์นี้จะเหมือนคำนำที่คุณ เพิ่มก่อนที่โมเดลจะได้รับวิธีการเพิ่มเติมจากผู้ใช้ปลายทาง


แสดงความคิดเห็น เกี่ยวกับประสบการณ์การใช้งาน Firebase AI Logic