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

تعرض نماذج 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).

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

يمكنك تحديد مخططات الاستجابة باستخدام إحدى الطريقتَين التاليتَين:

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

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

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

يستخدم هذا المثال طرقًا مساعِدة خاصة بـ 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).

يمكنك تحديد مخططات الاستجابة باستخدام إحدى الطريقتَين التاليتَين:

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

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

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

يستخدم هذا المثال طريقة المساعدة 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());

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