פלט מובנה למודלים של Grok

פלט מובנה מאפשר למודל ליצור פלט שתמיד תואם לסכימה ספציפית. לדוגמה, אפשר לספק למודל סכֵימת תשובה כדי לוודא שהתשובה תהיה בפורמט JSON תקין. המודלים של Grok שזמינים ב-Gemini Enterprise Agent Platform Model as a Service (MaaS) תומכים בפלט מובנה.

מידע נוסף על היכולת של פלט מובנה מופיע במאמר מבוא לפלט מובנה.

שימוש בפלט מובנה עם Responses API

ערך ברירת המחדל של store הוא false, כך שהבקשות הן בלי שמירת מצב, אלא אם מגדירים את store ל-true (או ל-True ב-Python). כדי לשמור תשובות, קראו את המאמר שליחת קריאה עם שמירת מצב ל-Responses API.

התבניות הבאות מראות איך להשתמש בפלט מובנה עם Responses API:

Python

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

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="MODEL", input="INPUT", text={ "format": { "type": "json_schema", "name": "SCHEMA_NAME", "strict": True, "schema": JSON_SCHEMA } }, stream=False, ) print(response)

  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.20-reasoning.
  • ‫INPUT: ההנחיה או הקלט למודל.
  • ‫SCHEMA_NAME: שם לסכֵימת התשובה.
  • ‫JSON_SCHEMA: מילון שמגדיר את סכימת ה-JSON, לדוגמה:
    {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"], "additionalProperties": False}

REST

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

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.20-reasoning.
  • ‫INPUT: ההנחיה או הקלט למודל.
  • ‫SCHEMA_NAME: שם לסכֵימת התשובה.
  • ‫JSON_SCHEMA: אובייקט סכימת JSON שמגדיר את מבנה הפלט.

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

POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses

גוף בקשת JSON:

{
  "model": "MODEL",
  "input": "INPUT",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "SCHEMA_NAME",
      "strict": true,
      "schema": JSON_SCHEMA
    }
  },
  "stream": false
}

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

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://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses"

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://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses" | Select-Object -Expand Content
 

דוגמה

הדוגמאות הבאות מציגות דוגמה פתורה מלאה של שימוש בפלט מובנה עם Responses API:

Python

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

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="xai/grok-4.7", input="Extract: John Doe is 30.", text={ "format": { "type": "json_schema", "name": "person_info", "strict": True, "schema": { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} }, "required": ["name", "age"], "additionalProperties": False } } }, stream=False, ) print(response)

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses -d \
'{
  "model": "xai/grok-4.7",
  "input": "Extract: John Doe is 30.",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person_info",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "age": {
            "type": "integer"
          }
        },
        "required": [
          "name",
          "age"
        ],
        "additionalProperties": false
      }
    }
  },
  "stream": false
}'
  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .

תגובה לדוגמה

הנה דוגמה לפלט מהמודל:

{
  "background": false,
  "completed_at": 1793837914,
  "created_at": 1793837914,
  "error": null,
  "frequency_penalty": 0,
  "id": "d18533b9-ecdc-447d-9bbd-f061359c89e9",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": "fp_grok47_0"
  },
  "model": "xai/grok-4.7",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "{\"age\":30,\"name\":\"John Doe\"}",
          "type": "output_text"
        }
      ],
      "id": "msg_d18533b9-ecdc-447d-9bbd-f061359c89e9",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "high",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 0.7,
  "text": {
    "format": {
      "schema": {
        "additionalProperties": false,
        "properties": {
          "age": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "age"
        ],
        "type": "object"
      },
      "type": "json_schema"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "context_details": {
      "input_tokens": 276,
      "output_tokens": 70
    },
    "extra_properties": {
      "google": {
        "traffic_type": "ON_DEMAND"
      }
    },
    "input_tokens": 276,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 70,
    "output_tokens_details": {
      "reasoning_tokens": 59
    },
    "total_tokens": 346
  },
  "user": null
}

שימוש בפלט מובנה עם Chat Completions API

בתרחיש לדוגמה הבא מוגדרת סכימת תשובה שמוודאת שהפלט מהמודל הוא אובייקט JSON עם המאפיינים הבאים: name,‏ date ו-participants. קוד Python משתמש ב-OpenAI SDK ובאובייקטים של Pydantic כדי ליצור את סכימת ה-JSON.

from pydantic import BaseModel
from openai import OpenAI

client = OpenAI()

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

completion = client.beta.chat.completions.parse(
    model="MODEL_NAME",
    messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    response_format=CalendarEvent,
)

print(completion.choices[0].message.parsed)

הפלט מהמודל יתאים לסכימת ה-JSON הבאה:

{ "name": STRING, "date": STRING, "participants": [STRING] }

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

{
  "name": "science fair",
  "date": "Friday",
  "participants": [
    "Alice",
    "Bob"
  ]
}

דוגמה מפורטת

הקוד הבא הוא דוגמה לסכימה רקורסיבית. הכיתה UI מכילה רשימה של children, שיכולה להיות גם מהכיתה UI.

from pydantic import BaseModel
from openai import OpenAI
from enum import Enum
from typing import List

client = OpenAI()

class UIType(str, Enum):
  div = "div"
  button = "button"
  header = "header"
  section = "section"
  field = "field"
  form = "form"

class Attribute(BaseModel):
  name: str
  value: str

class UI(BaseModel):
  type: UIType
  label: str
  children: List["UI"]
  attributes: List[Attribute]

UI.model_rebuild() # This is required to enable recursive types

class Response(BaseModel):
  ui: UI

completion = client.beta.chat.completions.parse(
  model="MODEL_NAME",
  messages=[
    {"role": "system", "content": "You are a UI generator AI. Convert the user input into a UI."},
    {"role": "user", "content": "Make a User Profile Form"}
  ],
  response_format=Response,
)

print(completion.choices[0].message.parsed)

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

Form
  Input
    Name
    Email
    Age

התגובה עשויה להיראות כך:

ui = UI(
    type=UIType.div,
    label='Form',
    children=[
        UI(
            type=UIType.div,
            label='Input',
            children=[],
            attributes=[
                Attribute(name='label', value='Name')
            ]
        ),
        UI(
            type=UIType.div,
            label='Input',
            children=[],
            attributes=[
                Attribute(name='label', value='Email')
            ]
        ),
        UI(
            type=UIType.div,
            label='Input',
            children=[],
            attributes=[
                Attribute(name='label', value='Age')
            ]
        )
    ],
    attributes=[
        Attribute(name='name', value='John Doe'),
        Attribute(name='email', value='john.doe@example.com'),
        Attribute(name='age', value='30')
    ]
)

קבלת תשובות של אובייקטים בפורמט JSON

כדי להגביל את המודל כך שיפיק רק אובייקטים של JSON עם תחביר תקין, מגדירים את השדה response_format לערך { "type": "json_object" }. היכולת הזו נקראת לעיתים קרובות מצב JSON. מצב JSON שימושי כשיוצרים JSON לשימוש עם קריאה להפעלת פונקציות או משימות אחרות בהמשך שדורשות קלט JSON.

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

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

Python

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

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create( model="MODEL", response_format={ "type": "json_object" }, messages=[ {"role": "user", "content": "List 5 rivers in South America. Your response must be a JSON object with a single key "rivers", which has a list of strings as its value."}, ] ) print(response.choices[0].message.content)

מחליפים את MODEL בשם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.6.

REST

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

  • PROJECT_ID: מזהה הפרויקט ב-Google Cloud.
  • ‫LOCATION: אזור שתומך במודלים של Grok.
  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.6.

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

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions

גוף בקשת JSON:

{
  "model": "MODEL",
  "response_format": {
    "type": "json_object"
  },
  "messages": [
    {
      "role": "user",
      "content": "List 5 rivers in South America. Your response must be a JSON object with a single key \"rivers\", which has a list of strings as its value."
    }
  ]
}

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

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/endpoints/openapi/chat/completions"

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/endpoints/openapi/chat/completions" | Select-Object -Expand Content

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

המאמרים הבאים