تولید خروجی ساختاریافته برای تجربیات ترکیبی در برنامه‌های وب

مدل‌های Gemini به طور پیش‌فرض پاسخ‌ها را به صورت متن بدون ساختار برمی‌گردانند. با این حال، برخی از موارد استفاده به متن ساختاریافته (مانند JSON یا enums) نیاز دارند. به عنوان مثال، ممکن است از این پاسخ برای سایر وظایف پایین‌دستی که به یک طرح داده مشخص نیاز دارند، استفاده کنید.

برای اطمینان از اینکه خروجی تولید شده مدل همیشه از یک طرحواره خاص پیروی می‌کند، می‌توانید یک طرحواره تعریف کنید که مانند یک طرح اولیه برای پاسخ‌های مدل عمل می‌کند. سپس می‌توانید مستقیماً داده‌ها را از خروجی مدل با پردازش کمتر پس از تولید استخراج کنید.

در اینجا چند مورد استفاده به عنوان مثال آورده شده است:

  • اطمینان حاصل کنید که پاسخ مدل، JSON معتبری تولید می‌کند و با طرحواره ارائه شده شما مطابقت دارد.
    برای مثال، این مدل می‌تواند ورودی‌های ساختاریافته‌ای برای دستور پخت‌ها ایجاد کند که همیشه شامل نام دستور پخت، لیست مواد تشکیل‌دهنده و مراحل پخت باشد. سپس می‌توانید این اطلاعات را راحت‌تر تجزیه و در رابط کاربری برنامه خود نمایش دهید.

  • نحوه پاسخگویی یک مدل در طول وظایف طبقه‌بندی را محدود کنید.
    برای مثال، می‌توانید کاری کنید که مدل، متن را با مجموعه‌ای خاص از برچسب‌ها (مثلاً مجموعه‌ای خاص از enumها مانند positive و negative ) حاشیه‌نویسی کند، نه با برچسب‌هایی که مدل تولید می‌کند (که می‌توانند درجه‌ای از تغییرپذیری مانند good ، positive ، negative یا bad داشته باشند).

این صفحه نحوه تولید خروجی ساختاریافته (مانند JSON و enums) را در تجربیات ترکیبی شما برای برنامه‌های وب شرح می‌دهد.

پرش به خروجی JSON به خروجی شمارشی

پیکربندی برای خروجی ساختاریافته

تولید خروجی ساختاریافته (مانند JSON و enums) برای استنتاج با استفاده از مدل‌های میزبانی ابری و روی دستگاه پشتیبانی می‌شود.

  • حالت‌های استنتاج ترکیبی : inCloudParams و onDeviceParams را طوری پیکربندی کنید که مدل صرف نظر از اینکه استنتاج در فضای ابری یا روی دستگاه اجرا می‌شود، با خروجی ساختاریافته پاسخ دهد:

    • برای مدل‌های روی دستگاه : با استفاده از یک طرحواره ایجاد شده با متدهای کمکی Schema یا یک طرحواره JSON ساده، responseConstraint در onDeviceParams مشخص کنید.

    • برای مدل‌های میزبانی‌شده توسط ابر : responseMimeType ) (برای JSON از application/json یا برای enumها از text/x.enum ) و responseSchema در inCloudParams مشخص کنید.

  • حالت‌های استنتاج غیرترکیبی : فقط از پیکربندی قابل اجرا که در بالا توضیح داده شده است استفاده کنید.

قبل از اینکه شروع کنی

برای مشاهده محتوا و کد مخصوص ارائه‌دهنده در این صفحه، روی ارائه‌دهنده API Gemini خود کلیک کنید.

پلتفرم عامل

مطمئن شوید که راهنمای شروع به کار برای ساخت تجربیات ترکیبی را تکمیل کرده‌اید.


پرش به خروجی JSON به خروجی شمارشی

خروجی JSON

مثال‌های زیر، نمونه خروجی عمومی JSON را برای تطبیق با استنتاج ترکیبی (برای مثال، PREFER_ON_DEVICE ) تطبیق می‌دهند.

در سناریوی مربوط به این مثال‌ها، مدل فهرستی از پروفایل‌های شخصیت‌ها را برای یک داستان فانتزی، با ویژگی‌های ساختاریافته‌ای مانند نام، سن، گونه و لوازم جانبی اختیاری تولید می‌کند.

شما می‌توانید طرحواره‌های پاسخ خود را با استفاده از هر یک از رویکردهای زیر تعریف کنید:

  • متدهای کمکی Firebase Schema (توصیه می‌شود) : از متدهای کمکی (مانند Schema.object() و Schema.enumString() ) برای نوشتن طرحواره‌های مختصر و جمع‌وجور مستقیماً در کد خود بدون استفاده از کدهای تکراری اضافی استفاده کنید.

  • طرحواره JSON ساده : اگر از قبل تعاریف طرحواره دارید، طرحواره‌ها را در پلتفرم‌ها یا سرویس‌های بک‌اند به اشتراک بگذارید یا طرحواره‌ها را از فایل‌های JSON وارد کنید، از یک شیء استاندارد JSON Schema استفاده کنید.

مثال ۱: استفاده از متدهای کمکی Firebase Schema

این مثال از متدهای کمکی Schema (مانند Schema.object ، Schema.array ، Schema.string و Schema.number ) که توسط Firebase AI Logic SDK ارائه شده‌اند، برای تعریف طرحواره شیء استفاده می‌کند.

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

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

// Define a schema using the `Schema` helper methods.
// Optional properties are specified in optionalProperties.
const jsonSchema = Schema.object({
  properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
          accessory: Schema.string()
        },
        optionalProperties: ["accessory"]
      })
    })
  }
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

مثال ۲: استفاده از یک طرحواره JSON ساده

این مثال، طرحواره را فقط با استفاده از JSON تعریف می‌کند.

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

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

// Define the schema as a plain JSON object.
// Properties are required by default unless omitted from the required array.
const jsonSchema = {
  type: "object",
  properties: {
    characters: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: {
            type: "string",
            nullable: false
          },
          age: {
            type: "number",
            nullable: false
          },
          species: {
            type: "string",
            nullable: false
          },
          accessory: {
            type: "string",
            nullable: true
          }
        },
        nullable: false,
        required: [
          "name",
          "age",
          "species"
        ]
      },
      nullable: false
    }
  },
  nullable: false,
  required: [
    "characters"
  ]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

خروجی شمارشی

مثال‌های زیر، نمونه خروجی عمومی enum را برای تطبیق با استنتاج ترکیبی (برای مثال، PREFER_ON_DEVICE ) تطبیق می‌دهند.

در سناریوی مربوط به این مثال‌ها، مدل با انتخاب یک ژانر واحد از یک لیست از پیش تعریف‌شده از گزینه‌های مجاز ( drama ، comedy یا documentary )، توصیف یک فیلم را طبقه‌بندی می‌کند.

شما می‌توانید طرحواره‌های پاسخ خود را با استفاده از هر یک از رویکردهای زیر تعریف کنید:

  • متدهای کمکی Firebase Schema (توصیه می‌شود) : از متدهای کمکی (مانند Schema.object() و Schema.enumString() ) برای نوشتن طرحواره‌های مختصر و جمع‌وجور مستقیماً در کد خود بدون استفاده از کدهای تکراری اضافی استفاده کنید.

  • طرحواره JSON ساده : اگر از قبل تعاریف طرحواره دارید، طرحواره‌ها را در پلتفرم‌ها یا سرویس‌های بک‌اند به اشتراک بگذارید یا طرحواره‌ها را از فایل‌های JSON وارد کنید، از یک شیء استاندارد JSON Schema استفاده کنید.

مثال ۱: استفاده از متدهای کمکی Firebase Schema

این مثال از متد کمکی Schema.enumString که توسط Firebase AI Logic SDK ارائه شده است، برای تعریف مقادیر enum مجاز استفاده می‌کند.

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

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

// Define an enum schema using the `Schema` helper method with allowed string values.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"]
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const 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.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());

مثال ۲: استفاده از یک طرحواره JSON ساده

این مثال، طرحواره enum را فقط با استفاده از JSON تعریف می‌کند.

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

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

// Define the enum schema as a plain JSON object.
const enumSchema = {
  type: "string",
  enum: ["drama", "comedy", "documentary"]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const 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.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());


درباره تجربه خود با Firebase AI Logic بازخورد دهید