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

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

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

در اینجا چند نمونه از موارد استفاده آورده شده است:

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

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

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

رفتن به برونداد JSON رفتن به برونداد شمارشی

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

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

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

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

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

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

قبل از شروع

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

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


رفتن به برونداد JSON رفتن به برونداد شمارشی

برونداد JSON

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

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

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

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

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

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

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

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

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 تعریف می‌کند.

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

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()));

برونداد شمارشی

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

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

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

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

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

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

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

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

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 تعریف می‌کند.

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

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