פלט מובנה

אתם יכולים להבטיח שהפלט שנוצר על ידי מודל תמיד יתאים לסכימה ספציפית, כדי לקבל תשובות בפורמט עקבי. לדוגמה, יכול להיות שיש לכם סכימת נתונים מוגדרת שבה אתם משתמשים למשימות אחרות. אם תגדירו למודל לפעול לפי אותה סכימה, תוכלו לחלץ נתונים ישירות מהפלט של המודל בלי לבצע עיבוד נוסף.

כדי לציין את המבנה של הפלט של המודל, מגדירים סכימת תשובה, שפועלת כמו תוכנית ליצירת תשובות של המודל. כששולחים הנחיה וכוללים בה את סכימת התגובה, התשובה של המודל תמיד תהיה בהתאם לסכימה שהגדרתם.

אתם יכולים לשלוט בפלט שנוצר כשאתם משתמשים במודלים הבאים:

  • המודלים של Gemini:

לחצו כדי להרחיב את רשימת המודלים הנתמכים

למודלים פתוחים, פועלים לפי המדריך למשתמש.

תרחישים לדוגמה

תרחיש לדוגמה לשימוש בסכימת תגובה הוא כדי לוודא שהתגובה של המודל תהיה בפורמט JSON תקין ותתאים לסכימה שלכם. הפלט של מודלים גנרטיביים יכול להיות מגוון במידה מסוימת, ולכן הכללת סכימת תגובה מבטיחה שתמיד תקבלו JSON תקין. לכן, המשימות הבאות יכולות לצפות באופן מהימן לקלט JSON תקין מהתגובות שנוצרו.

דוגמה נוספת היא הגבלת האופן שבו מודל יכול להשיב. לדוגמה, אפשר להגדיר מודל שיבצע הערות לטקסט באמצעות תוויות שהמשתמש מגדיר, ולא באמצעות תוויות שהמודל יוצר. האילוץ הזה שימושי כשמצפים לקבוצה ספציפית של תוויות, כמו positive או negative, ולא רוצים לקבל שילוב של תוויות אחרות שהמודל עשוי ליצור, כמו good, positive, negative או bad.

לתשומת ליבכם

אם אתם מתכננים להשתמש בסכימת תגובה, כדאי לקרוא את ההגבלות הפוטנציאליות הבאות:

  • חובה להשתמש ב-API כדי להגדיר סכימת תגובה ולהשתמש בה. אין תמיכה בקונסולות.
  • גודל סכימת התגובה נספר במגבלת הטוקנים של הקלט.
  • יש תמיכה רק בפורמטים מסוימים של פלט, כמו application/json או text/x.enum. לגבי פלט JSON:

    • הגדרת response_mime_type ל-application/json בלי לציין response_schema פועלת רק כרמז חזק, ויש סיכון קטן ליצירת JSON פגום.
    • כדי לוודא שאובייקטי ה-JSON תקפים ב-100%, הבקשות צריכות לכלול את הפרמטרים response_schema ו-response_mime_type שמוגדרים לערך application/json.
    • כשיטה מומלצת, אם תרחיש השימוש שלכם מונע מכם להגדיר מראש סכימה, כדאי להטמיע מאמת JSON בצד הלקוח עם מנגנון ניסיון חוזר.
  • הפלט המובנה תומך בקבוצת משנה של הפניה לסכימה של Agent Platform. מידע נוסף זמין במאמר בנושא שדות סכימה נתמכים.

  • סכימה מורכבת עלולה לגרום לשגיאה InvalidArgument: 400. מורכבות יכולה לנבוע משמות מאפיינים ארוכים, ממגבלות אורך ארוכות של מערכים, מ-enums עם הרבה ערכים, מאובייקטים עם הרבה מאפיינים אופציונליים או משילוב של הגורמים האלה.

    אם השגיאה הזו מופיעה בסכימה תקינה, צריך לבצע שינוי אחד או יותר מהשינויים הבאים כדי לפתור את הבעיה:

    • לקצר את שמות הנכסים או את שמות ה-enum.
    • השטחת מערכים מקוננים.
    • צריך לצמצם את מספר הנכסים עם מגבלות, כמו מספרים עם מגבלות מינימום ומקסימום.
    • צריך לצמצם את מספר הנכסים עם אילוצים מורכבים, כמו נכסים עם פורמטים מורכבים כמו date-time.
    • צריך לצמצם את מספר המאפיינים האופציונליים.
    • צריך לצמצם את מספר הערכים החוקיים של סוגי הנתונים המנויים.

שדות סכימה נתמכים

אפשר לציין response_schema שמתאר את פורמט הפלט.

המודל ייצור תשובה שתתאים לסכימה שצוינה. כשמשתמשים בפלט מובנה, המודל יפיק פלט באותו סדר של המפתחות בסכימה.

  • השדות הבאים מסכימת ה-Agent Platform נתמכים. אם משתמשים בשדה שלא נתמך, פלטפורמת הסוכנים של Gemini Enterprise עדיין יכולה לטפל בבקשה, אבל היא מתעלמת מהשדה.

  • anyOf

  • enum: נתמכים רק ערכי enum‏ string

  • format

  • items

  • maximum

  • maxItems

  • minimum

  • minItems

  • nullable

  • properties

  • description

  • propertyOrdering*

  • required

* propertyOrdering מיועד במיוחד לפלט מובנה ולא נכלל בסכימה של Agent Platform. בשדה הזה מגדירים את הסדר שבו הנכסים נוצרים. המאפיינים שמופיעים ברשימה צריכים להיות ייחודיים ומפתחות תקינים במילון properties.

כשמגדירים סכימה, המודל לא פועל בדיוק לפי סדר המאפיינים שמגדירים בשדה properties. כדי להגדיר סדר ספציפי ליצירת מאפיינים, משתמשים בשדה propertyOrdering. המאפיינים שמופיעים ב-propertyOrdering נוצרים קודם, בסדר שצוין, ואחריהם נוצרים כל שאר המאפיינים.

אם משתמשים ב-Python SDK, סדר ברירת המחדל של המאפיינים הוא הסדר שמוגדר בסכימה. בכל שאר המקרים, המאפיינים נוצרים בסדר אלפביתי. קודם מוצגים המאפיינים הנדרשים ואחריהם המאפיינים האופציונליים.

בשדה format, Gemini Enterprise Agent Platform תומך בערכים הבאים: date,‏ date-time,‏ duration ו-time. התיאור והפורמט של כל ערך מפורטים במאגר של Open API Initiative

לפני שמתחילים

מגדירים סכימת תגובה כדי לציין את המבנה של הפלט של המודל, את שמות השדות ואת סוג הנתונים הצפוי לכל שדה. צריך להשתמש רק בשדות הנתמכים שמופיעים בקטע שיקולים. המערכת מתעלמת מכל שאר השדות.

צריך לכלול את סכימת התגובה רק בשדה responseSchema. אל תכפילו את הסכימה בהנחיה שלכם. אם תעשו את זה, יכול להיות שהפלט שייווצר יהיה באיכות נמוכה יותר.

דוגמאות לסכימות מופיעות בקטע דוגמאות לסכימות ולתשובות של מודלים.

התנהגות המודל וסכימת התגובה

כשמודל יוצר תגובה, הוא משתמש בשם השדה ובתיאור מתוך הסכימה שסופקה. לכן מומלץ להשתמש במבנה ברור ובשמות שדות חד-משמעיים כדי שהכוונה שלכם תהיה ברורה. מומלץ להשתמש בשדה description בתוך מאפייני הסכימה כדי להגדיר את המטרה של כל שדה.

כברירת מחדל, השדות הם אופציונליים, כלומר המודל יכול למלא את השדות או לדלג עליהם. אתם יכולים להגדיר שדות כחובה כדי לחייב את המודל לספק ערך. אם אין מספיק הקשר בהנחיית הקלט המשויכת, המודל יוצר תשובות שמבוססות בעיקר על הנתונים שעליהם הוא אומן.

אם אתם לא רואים את התוצאות שציפיתם להן, כדאי להתחיל בשיפור התיאורים בסכימה. אם אתם מרגישים שאתם לא יכולים להעביר את כל הניואנסים של הסכימה בתיאור הסכימה, אפשר לדון בסכימה בהנחיה, אבל חשוב:

  1. מציינים את הסכימה רק באובייקט הסכימה. אל תציינו את הסכימה גם בהנחיה. הפעולות האלה עלולות לפגוע בביצועים.

  2. אלא אם יש צורך בכך, לא כדאי לדון בסכימה בהנחיה (מעבר ל "פעל לפי הסכימה שסופקה" או משהו דומה). כך קל יותר לבצע תחזוקה. אם תצטרכו לשנות את הסכימה, תוכלו פשוט לשנות אותה במקום לוודא שההנחיה והסכימה עודכנו בצורה נכונה.

  3. אם אתם חייבים לדון בסכימה בהנחיה (כדי לספק דוגמאות או הוראות מפורטות במיוחד, שאחרת יובילו לערכים מבלבלים של description בסכימה), הקפידו להשתמש באותו סדר שדות exact כמו בסכימה שסיפקתם. אם תערבבו את סדר השדות בסכימה שסיפקתם לעומת ההנחיה, יכול להיות שתקבלו שגיאות בפלט.

שליחת הנחיה עם סכימת תגובה

כברירת מחדל, כל השדות הם אופציונליים, כלומר מודל יכול ליצור תגובה לשדה. כדי לחייב את המודל ליצור תגובה לשדה מסוים, צריך להגדיר את השדה כחובה.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import HttpOptions

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "OBJECT",
        "properties": {
            "recipe_name": {"type": "STRING"},
            "ingredients": {"type": "ARRAY", "items": {"type": "STRING"}},
        },
        "required": ["recipe_name", "ingredients"],
    },
}

prompt = """
    List a few popular cookie recipes.
"""

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=prompt,
    config={
        "response_mime_type": "application/json",
        "response_schema": response_schema,
    },
)

print(response.text)
# Example output:
# [
#     {
#         "ingredients": [
#             "2 1/4 cups all-purpose flour",
#             "1 teaspoon baking soda",
#             "1 teaspoon salt",
#             "1 cup (2 sticks) unsalted butter, softened",
#             "3/4 cup granulated sugar",
#             "3/4 cup packed brown sugar",
#             "1 teaspoon vanilla extract",
#             "2 large eggs",
#             "2 cups chocolate chips",
#         ],
#         "recipe_name": "Chocolate Chip Cookies",
#     }
# ]

Go

כך מתקינים או מעדכנים את Go.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithRespSchema shows how to use a response schema to generate output in a specific format.
func generateWithRespSchema(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "application/json",
		// See the OpenAPI specification for more details and examples:
		//   https://spec.openapis.org/oas/v3.0.3.html#schema-object
		ResponseSchema: &genai.Schema{
			Type: "array",
			Items: &genai.Schema{
				Type: "object",
				Properties: map[string]*genai.Schema{
					"recipe_name": {Type: "string"},
					"ingredients": {
						Type:  "array",
						Items: &genai.Schema{Type: "string"},
					},
				},
				Required: []string{"recipe_name", "ingredients"},
			},
		},
	}
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "List a few popular cookie recipes."},
		},
			Role: genai.RoleUser},
	}
	modelName := "gemini-2.5-flash"

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// [
	//   {
	//     "ingredients": [
	//       "2 1/4 cups all-purpose flour",
	//       "1 teaspoon baking soda",
	//       ...
	//     ],
	//     "recipe_name": "Chocolate Chip Cookies"
	//   },
	//   {
	//     ...
	//   },
	//   ...
	// ]

	return nil
}

Node.js

התקנה

npm install @google/genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateResponseSchema(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const prompt = 'List a few popular cookie recipes.';

  const responseSchema = {
    type: 'ARRAY',
    items: {
      type: 'OBJECT',
      properties: {
        recipeName: {type: 'STRING'},
        ingredients: {
          type: 'ARRAY',
          items: {type: 'STRING'},
        },
      },
      required: ['recipeName', 'ingredients'],
    },
  };

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: prompt,
    config: {
      responseMimeType: 'application/json',
      responseSchema: responseSchema,
    },
  });

  console.log(response.text);

  // Example output:
  // [
  //     {
  //         "ingredients": [
  //             "2 1/4 cups all-purpose flour",
  //             "1 teaspoon baking soda",
  //             "1 teaspoon salt",
  //             "1 cup (2 sticks) unsalted butter, softened",
  //             "3/4 cup granulated sugar",
  //             "3/4 cup packed brown sugar",
  //             "1 teaspoon vanilla extract",
  //             "2 large eggs",
  //             "2 cups chocolate chips",
  //         ],
  //         "recipe_name": "Chocolate Chip Cookies",
  //     }
  // ]

  return response.text;
}

Java

כך מתקינים או מעדכנים את Java.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.util.List;
import java.util.Map;

public class ControlledGenerationWithResponseSchema {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";

    String contents = "List a few popular cookie recipes.";

    generateContent(modelId, contents);
  }

  // Generates content with a response schema
  public static String generateContent(String modelId, String contents) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Schema for each item in array
      Schema recipeSchema =
          Schema.builder()
              .type(Type.Known.OBJECT)
              .properties(
                  Map.of(
                      "recipe_name", Schema.builder().type(Type.Known.STRING).build(),
                      "ingredients",
                          Schema.builder()
                              .type(Type.Known.ARRAY)
                              .items(Schema.builder().type(Type.Known.STRING).build())
                              .build()))
              .required(List.of("recipe_name", "ingredients"))
              .build();

      // Full root schema (array)
      Schema responseSchema = Schema.builder().type(Type.Known.ARRAY).items(recipeSchema).build();

      GenerateContentConfig config =
          GenerateContentConfig.builder()
              .responseMimeType("application/json")
              .responseSchema(responseSchema)
              .build();

      GenerateContentResponse response = client.models.generateContent(modelId, contents, config);

      System.out.println(response.text());
      // Example response:
      // [
      //    {
      //        "ingredients": [
      //            "2 1/4 cups all-purpose flour",
      //            "1 teaspoon baking soda",
      //            "1 teaspoon salt",
      //            "1 cup (2 sticks) unsalted butter, softened",
      //            "3/4 cup granulated sugar",
      //            "3/4 cup packed brown sugar",
      //            "1 teaspoon vanilla extract",
      //            "2 large eggs",
      //            "2 cups chocolate chips",
      //        ],
      //        "recipe_name": "Chocolate Chip Cookies",
      //    }
      // ]
      return response.text();
    }
  }
}

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • GENERATE_RESPONSE_METHOD: סוג התשובה שרוצים שהמודל ייצור. בוחרים שיטה ליצירת התשובה של המודל:
    • streamGenerateContent: התשובה מועברת בסטרימינג בזמן שהיא נוצרת, כדי לצמצם את תפיסת זמן האחזור בקרב קהל אנושי.
    • generateContent: התשובה מוחזרת אחרי שהיא נוצרת במלואה.
  • LOCATION: האזור שבו הבקשה תעובד.
  • PROJECT_ID: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
  • MODEL_ID: מזהה המודל של המודל הרב-אופני שרוצים להשתמש בו.
  • ROLE: התפקיד בשיחה שמשויך לתוכן. חובה לציין תפקיד גם בתרחישי שימוש של תור אחד. הערכים הקבילים כוללים את האפשרויות הבאות:
    • USER: מציין תוכן שנשלח על ידכם.
  • TEXT: ההנחיות לטקסט שצריך לכלול בהנחיה.
  • RESPONSE_MIME_TYPE: סוג הפורמט של הטקסט המוצע שנוצר. רשימה של הערכים הנתמכים זמינה בפרמטר responseMimeType ב-Gemini API.
  • RESPONSE_SCHEMA: סכימה של המודל שצריך לפעול לפיה כשיוצרים תשובות. מומלץ להשתמש בשדה description כדי לתאר את מטרת הסכימה ואת המאפיינים שלה. מידע נוסף זמין במאמר בנושא סכימה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD

גוף בקשת JSON:

{
  "contents": {
    "role": "ROLE",
    "parts": {
      "text": "TEXT"
    }
  },
  "generation_config": {
    "responseMimeType": "RESPONSE_MIME_TYPE",
    "responseSchema": RESPONSE_SCHEMA,
  }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

דוגמה לפקודת curl

LOCATION="us-central1"
MODEL_ID="gemini-3.5-flash"
PROJECT_ID="test-project"
GENERATE_RESPONSE_METHOD="generateContent"

cat << EOF > request.json
{
  "contents": {
    "role": "user",
    "parts": {
      "text": "List a few popular cookie recipes."
    }
  },
  "generation_config": {
    "maxOutputTokens": 2048,
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "recipe_name": {
            "type": "string",
            "description": "The name of the cookie recipe."
          },
        },
        "required": ["recipe_name"],
      },
    }
  }
}
EOF

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:${GENERATE_RESPONSE_METHOD} \
-d '@request.json'

דוגמאות לסכימות של פלט JSON

בקטעים הבאים מוצגות מגוון הנחיות לדוגמה וסכימות של תגובות. אחרי כל דוגמת קוד מופיעה גם דוגמה לתשובה של המודל.

תחזית מזג האוויר לכל יום בשבוע

בדוגמה הבאה מוצג אובייקט forecast לכל יום בשבוע, שכולל מערך של מאפיינים כמו הטמפרטורה הצפויה ורמת הלחות לאותו יום. חלק מהמאפיינים מוגדרים כמאפיינים שניתן להגדיר להם ערך null, כדי שהמודל יוכל להחזיר ערך null כשאין לו מספיק הקשר כדי ליצור תגובה משמעותית. האסטרטגיה הזו עוזרת להפחית הזיות.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

response_schema = {
    "type": "OBJECT",
    "properties": {
        "forecast": {
            "type": "ARRAY",
            "items": {
                "type": "OBJECT",
                "properties": {
                    "Day": {"type": "STRING", "nullable": True},
                    "Forecast": {"type": "STRING", "nullable": True},
                    "Temperature": {"type": "INTEGER", "nullable": True},
                    "Humidity": {"type": "STRING", "nullable": True},
                    "Wind Speed": {"type": "INTEGER", "nullable": True},
                },
                "required": ["Day", "Temperature", "Forecast", "Wind Speed"],
            },
        }
    },
}

prompt = """
    The week ahead brings a mix of weather conditions.
    Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
    Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and the winds will pick up slightly to around 15 km/h.
    Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%.
    Wednesday may see thunderstorms, with a temperature of 68°F.
    Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.
    Friday returns to partly cloudy conditions, with a temperature of 73°F and the Winds will be light at 12 km/h.
    Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
"""

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=prompt,
    config=GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=response_schema,
    ),
)

print(response.text)
# Example output:
# {"forecast": [{"Day": "Sunday", "Forecast": "sunny", "Temperature": 77, "Wind Speed": 10, "Humidity": "50%"},
#   {"Day": "Monday", "Forecast": "partly cloudy", "Temperature": 72, "Wind Speed": 15},
#   {"Day": "Tuesday", "Forecast": "rain showers", "Temperature": 64, "Wind Speed": null, "Humidity": "70%"},
#   {"Day": "Wednesday", "Forecast": "thunderstorms", "Temperature": 68, "Wind Speed": null},
#   {"Day": "Thursday", "Forecast": "cloudy", "Temperature": 66, "Wind Speed": null, "Humidity": "60%"},
#   {"Day": "Friday", "Forecast": "partly cloudy", "Temperature": 73, "Wind Speed": 12},
#   {"Day": "Saturday", "Forecast": "sunny", "Temperature": 80, "Wind Speed": 8, "Humidity": "40%"}]}

Go

כך מתקינים או מעדכנים את Go.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithNullables shows how to use the response schema with nullable values.
func generateWithNullables(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.5-flash"
	prompt := `
The week ahead brings a mix of weather conditions.
Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and the winds will pick up slightly to around 15 km/h.
Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%.
Wednesday may see thunderstorms, with a temperature of 68°F.
Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.
Friday returns to partly cloudy conditions, with a temperature of 73°F and the Winds will be light at 12 km/h.
Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
`
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: prompt},
		},
			Role: genai.RoleUser},
	}
	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "application/json",
		// See the OpenAPI specification for more details and examples:
		//   https://spec.openapis.org/oas/v3.0.3.html#schema-object
		ResponseSchema: &genai.Schema{
			Type: "object",
			Properties: map[string]*genai.Schema{
				"forecast": {
					Type: "array",
					Items: &genai.Schema{
						Type: "object",
						Properties: map[string]*genai.Schema{
							"Day":         {Type: "string", Nullable: genai.Ptr(true)},
							"Forecast":    {Type: "string", Nullable: genai.Ptr(true)},
							"Temperature": {Type: "integer", Nullable: genai.Ptr(true)},
							"Humidity":    {Type: "string", Nullable: genai.Ptr(true)},
							"Wind Speed":  {Type: "integer", Nullable: genai.Ptr(true)},
						},
						Required: []string{"Day", "Temperature", "Forecast", "Wind Speed"},
					},
				},
			},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// {
	// 	"forecast": [
	// 		{"Day": "Sunday", "Forecast": "Sunny", "Temperature": 77, "Wind Speed": 10, "Humidity": "50%"},
	// 		{"Day": "Monday", "Forecast": "Partly Cloudy", "Temperature": 72, "Wind Speed": 15},
	// 		{"Day": "Tuesday", "Forecast": "Rain Showers", "Temperature": 64, "Wind Speed": null, "Humidity": "70%"},
	// 		{"Day": "Wednesday", "Forecast": "Thunderstorms", "Temperature": 68, "Wind Speed": null},
	// 		{"Day": "Thursday", "Forecast": "Cloudy", "Temperature": 66, "Wind Speed": null, "Humidity": "60%"},
	// 		{"Day": "Friday", "Forecast": "Partly Cloudy", "Temperature": 73, "Wind Speed": 12},
	// 		{"Day": "Saturday", "Forecast": "Sunny", "Temperature": 80, "Wind Speed": 8, "Humidity": "40%"}
	// 	]
	// }

	return nil
}

Node.js

התקנה

npm install @google/genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateNullableSchema(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const prompt = `
  The week ahead brings a mix of weather conditions.
  Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
  Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and the winds will pick up slightly to around 15 km/h.
  Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%.
  Wednesday may see thunderstorms, with a temperature of 68°F.
  Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.
  Friday returns to partly cloudy conditions, with a temperature of 73°F and the Winds will be light at 12 km/h.
  Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
`;

  const responseSchema = {
    type: 'object',
    properties: {
      forecast: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            Day: {type: 'string', nullable: true},
            Forecast: {type: 'string', nullable: true},
            Temperature: {type: 'integer', nullable: true},
            Humidity: {type: 'string', nullable: true},
            WindSpeed: {type: 'integer', nullable: true},
          },
          required: ['Day', 'Temperature', 'Forecast', 'WindSpeed'],
        },
      },
    },
  };

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: prompt,
    config: {
      responseMimeType: 'application/json',
      responseSchema: responseSchema,
    },
  });
  console.log(response.text);

  // Example output:
  //  {"forecast": [{"Day": "Sunday", "Forecast": "sunny", "Temperature": 77, "Wind Speed": 10, "Humidity": "50%"},
  //   {"Day": "Monday", "Forecast": "partly cloudy", "Temperature": 72, "Wind Speed": 15},
  //   {"Day": "Tuesday", "Forecast": "rain showers", "Temperature": 64, "Wind Speed": null, "Humidity": "70%"},
  //   {"Day": "Wednesday", "Forecast": "thunderstorms", "Temperature": 68, "Wind Speed": null},
  //   {"Day": "Thursday", "Forecast": "cloudy", "Temperature": 66, "Wind Speed": null, "Humidity": "60%"},
  //   {"Day": "Friday", "Forecast": "partly cloudy", "Temperature": 73, "Wind Speed": 12},
  //   {"Day": "Saturday", "Forecast": "sunny", "Temperature": 80, "Wind Speed": 8, "Humidity": "40%"}]}

  return response.text;
}

Java

כך מתקינים או מעדכנים את Java.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.util.List;
import java.util.Map;

public class ControlledGenerationWithNullableSchema {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";

    String prompt =
        "The week ahead brings a mix of weather conditions.\n"
            + "Sunday is expected to be sunny with a temperature "
            + "of 77°F and a humidity level of 50%. "
            + "Winds will be light at around 10 km/h.\n"
            + "Monday will see partly cloudy skies with "
            + "a slightly cooler temperature of 72°F and the winds "
            + "will pick up slightly to around 15 km/h.\n"
            + "Tuesday brings rain showers, with temperatures dropping "
            + "to 64°F and humidity rising to 70%.\n"
            + "Wednesday may see thunderstorms, with a temperature of 68°F.\n"
            + "Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.\n"
            + "Friday returns to partly cloudy conditions, with "
            + "a temperature of 73°F and the Winds will be "
            + "light at 12 km/h.\n"
            + "Finally, Saturday rounds off the week with sunny skies, a "
            + "temperature of 80°F, and a humidity "
            + "level of 40%. Winds will be gentle at 8 km/h.\n";

    generateContent(modelId, prompt);
  }

  // Generates content with a nullable response schema
  public static String generateContent(String modelId, String contents) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Define schema for array items (each weather entry object)
      Schema dayForecastSchema =
          Schema.builder()
              .type(Type.Known.OBJECT)
              .properties(
                  Map.of(
                      "Day", Schema.builder().type(Type.Known.STRING).nullable(true).build(),
                      "Forecast", Schema.builder().type(Type.Known.STRING).nullable(true).build(),
                      "Temperature",
                          Schema.builder().type(Type.Known.INTEGER).nullable(true).build(),
                      "Humidity", Schema.builder().type(Type.Known.STRING).nullable(true).build(),
                      "Wind Speed",
                          Schema.builder().type(Type.Known.INTEGER).nullable(true).build()))
              .required(List.of("Day", "Temperature", "Forecast", "Wind Speed"))
              .build();

      // Full response schema
      Schema responseSchema =
          Schema.builder()
              .type(Type.Known.OBJECT)
              .properties(
                  Map.of(
                      "forecast",
                      Schema.builder().type(Type.Known.ARRAY).items(dayForecastSchema).build()))
              .build();

      GenerateContentConfig config =
          GenerateContentConfig.builder()
              .responseMimeType("application/json")
              .responseSchema(responseSchema)
              .build();

      GenerateContentResponse response = client.models.generateContent(modelId, contents, config);

      System.out.println(response.text());
      // Example response:
      // {"forecast": [{"Day": "Sunday", "Forecast": "sunny", "Temperature": 77, "Wind Speed": 10,
      // "Humidity": "50%"},
      //  {"Day": "Monday", "Forecast": "partly cloudy", "Temperature": 72, "Wind Speed": 15},
      //  {"Day": "Tuesday", "Forecast": "rain showers", "Temperature": 64, "Wind Speed": null,
      // "Humidity": "70%"},
      //  {"Day": "Wednesday", "Forecast": "thunderstorms", "Temperature": 68, "Wind Speed": null},
      //  {"Day": "Thursday", "Forecast": "cloudy", "Temperature": 66, "Wind Speed": null,
      // "Humidity": "60%"},
      //  {"Day": "Friday", "Forecast": "partly cloudy", "Temperature": 73, "Wind Speed": 12},
      //  {"Day": "Saturday", "Forecast": "sunny", "Temperature": 80, "Wind Speed": 8, "Humidity":
      // "40%"}]}
      return response.text();
    }
  }
}

סיווג מוצר

בדוגמה הבאה יש סוגי enum שבהם המודל צריך לסווג את הסוג והמצב של אובייקט מתוך רשימה של ערכים נתונים.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="What type of instrument is an oboe?",
    config=GenerateContentConfig(
        response_mime_type="text/x.enum",
        response_schema={
            "type": "STRING",
            "enum": ["Percussion", "String", "Woodwind", "Brass", "Keyboard"],
        },
    ),
)

print(response.text)
# Example output:
# Woodwind

Go

כך מתקינים או מעדכנים את Go.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithEnumSchema shows how to use enum schema to generate output.
func generateWithEnumSchema(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What type of instrument is an oboe?"},
		}, Role: genai.RoleUser},
	}
	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "text/x.enum",
		ResponseSchema: &genai.Schema{
			Type: "STRING",
			Enum: []string{"Percussion", "String", "Woodwind", "Brass", "Keyboard"},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// Woodwind

	return nil
}

Node.js

התקנה

npm install @google/genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI, Type} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const responseSchema = {
    type: Type.STRING,
    enum: ['Percussion', 'String', 'Woodwind', 'Brass', 'Keyboard'],
  };

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'What type of instrument is an oboe?',
    config: {
      responseMimeType: 'text/x.enum',
      responseSchema: responseSchema,
    },
  });

  console.log(response.text);
  // Example output:
  //  Woodwind
  return response.text;
}

Java

כך מתקינים או מעדכנים את Java.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.util.List;

public class ControlledGenerationWithEnumSchema {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String contents = "What type of instrument is an oboe?";
    String modelId = "gemini-2.5-flash";
    generateContent(modelId, contents);
  }

  // Generates content with an enum response schema
  public static String generateContent(String modelId, String contents) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Define the response schema with an enum.
      Schema responseSchema =
          Schema.builder()
              .type(Type.Known.STRING)
              .enum_(List.of("Percussion", "String", "Woodwind", "Brass", "Keyboard"))
              .build();

      GenerateContentConfig config =
          GenerateContentConfig.builder()
              .responseMimeType("text/x.enum")
              .responseSchema(responseSchema)
              .build();

      GenerateContentResponse response = client.models.generateContent(modelId, contents, config);

      System.out.print(response.text());
      // Example response:
      // Woodwind
      return response.text();
    }
  }
}