إنشاء نواتج منظَّمة للتجارب المختلطة في تطبيقات الويب

تُعرَض ردود نماذج Gemini كنص غير منظَّم تلقائيًا. ومع ذلك، تتطلّب بعض حالات الاستخدام نصًا منظّمًا (مثل JSON أو التعدادات). على سبيل المثال، قد تستخدم الردّ لمهام أخرى تالية تتطلّب مخطّط بيانات محدّدًا.

لضمان التزام الناتج الذي ينشئه النموذج دائمًا بمخطط معيّن، يمكنك تحديد مخطط يعمل كمخطط لردود النموذج. يمكنك بعد ذلك استخراج البيانات مباشرةً من مخرجات النموذج مع تقليل المعالجة اللاحقة.

في ما يلي بعض الأمثلة على حالات الاستخدام:

  • تأكَّد من أنّ ردّ النموذج ينتج عنه ملف JSON صالح ويتوافق مع المخطط الذي قدّمته.
    على سبيل المثال، يمكن للنموذج إنشاء إدخالات منظَّمة لوصفات تتضمّن دائمًا اسم الوصفة وقائمة المكوّنات والخطوات. ويمكنك بعد ذلك تحليل هذه المعلومات وعرضها بسهولة أكبر في واجهة المستخدم الخاصة بتطبيقك.

  • تقييد طريقة ردّ النموذج أثناء مهام التصنيف
    على سبيل المثال، يمكنك أن تطلب من النموذج إضافة تعليقات توضيحية إلى النص باستخدام مجموعة محدّدة من التصنيفات (على سبيل المثال، مجموعة محدّدة من التعدادات مثل positive وnegative)، بدلاً من التصنيفات التي ينتجها النموذج (والتي قد تتفاوت إلى حدّ ما مثل good أو positive أو negative أو bad).

توضّح هذه الصفحة كيفية إنشاء مخرجات منظَّمة (مثل JSON والتعدادات) في تجاربك المختلطة لتطبيقات الويب.

الانتقال إلى الردّ بتنسيق JSON الانتقال إلى الردّ بتنسيق enum

إعدادات الناتج المنظَّم

يمكن إنشاء مخرجات منظَّمة (مثل JSON والتعدادات) للاستنتاج باستخدام النماذج المستضافة على السحابة الإلكترونية والنماذج على الجهاز فقط.

  • أوضاع الاستنتاج المختلطة: يمكنك ضبط كل من inCloudParams و onDeviceParams ليستجيب النموذج بمخرجات منظَّمة بغض النظر عمّا إذا كان الاستنتاج يتم في السحابة الإلكترونية أو على الجهاز:

    • بالنسبة إلى النماذج على الجهاز فقط: حدِّد responseConstraint في onDeviceParams باستخدام مخطّط تم إنشاؤه باستخدام طرق المساعدة Schema أو مخطّط JSON عادي.

    • بالنسبة إلى النماذج المستضافة على السحابة الإلكترونية: حدِّد responseMimeType (application/json لملفات JSON أو text/x.enum للتعدادات) و responseSchema في inCloudParams.

  • أوضاع الاستنتاج غير المختلطة: استخدِم الإعدادات المناسبة الموضّحة أعلاه فقط.

قبل البدء

انقر على مزوّد خدمة Gemini API لعرض المحتوى والرمز البرمجي الخاصَّين بالمزوّد على هذه الصفحة.

تأكَّد من إكمال دليل البدء لإنشاء تجارب مختلطة.


الانتقال إلى الردّ بتنسيق JSON الانتقال إلى الردّ بتنسيق enum

الردّ بتنسيق JSON

تعدّل الأمثلة التالية مثال الردّ العام بتنسيق JSON لاستيعاب الاستنتاج المختلط (على سبيل المثال، PREFER_ON_DEVICE).

في السيناريو الخاص بهذه الأمثلة، ينشئ النموذج قائمة بملفات تعريف الشخصيات لقصة خيالية، مع سمات منظَّمة مثل الاسم والعمر والنوع والملحقات الاختيارية.

يمكنك تحديد مخططات الردود باستخدام أي من الطريقتين التاليتين:

  • طرق المساعدة في Schema في Firebase (يُنصح بها): يمكنك استخدام طرق المساعدة (مثل Schema.object() وSchema.enumString()) لكتابة مخططات موجزة ومدمجة مباشرةً في الرمز البرمجي بدون الحاجة إلى نماذج إضافية.

  • مخطّط JSON عادي: يمكنك استخدام عنصر مخطط JSON عادي إذا كان لديك تعريفات مخططات حالية، أو إذا كنت تشارك المخططات على مستوى الأنظمة الأساسية أو خدمات الخلفية، أو إذا كنت تستورد المخططات من ملفات JSON.

المثال 1: استخدام طرق المساعدة في Firebase Schema

يستخدم هذا المثال طرق المساعدة Schema (مثل Schema.object وSchema.array وSchema.string وSchema.number) التي توفّرها حزمة تطوير البرامج (SDK) لـ 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()));

المثال 2: استخدام مخطّط 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).

يمكنك تحديد مخططات الردود باستخدام أي من الطريقتين التاليتين:

  • طرق المساعدة في Schema في Firebase (يُنصح بها): يمكنك استخدام طرق المساعدة (مثل Schema.object() وSchema.enumString()) لكتابة مخططات موجزة ومدمجة مباشرةً في الرمز البرمجي بدون الحاجة إلى استخدام رموز نموذجية إضافية.

  • مخطّط JSON عادي: يمكنك استخدام عنصر مخطط JSON عادي إذا كان لديك تعريفات مخططات حالية، أو إذا كنت تشارك المخططات على مستوى الأنظمة الأساسية أو خدمات الخلفية، أو إذا كنت تستورد المخططات من ملفات JSON.

المثال 1: استخدام طرق المساعدة في Firebase Schema

يستخدم هذا المثال طريقة المساعدة Schema.enumString التي توفّرها حزمة تطوير البرامج (SDK) لـ 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());

المثال 2: استخدام مخطّط 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 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"