Ju mund të konfiguroni modelet Gemini për të gjeneruar përgjigje që i përmbahen një Skeme JSON të dhënë. Kjo aftësi garanton rezultate të parashikueshme dhe të analizueshme, siguron sigurinë e formatit dhe llojit, mundëson zbulimin programatik të refuzimeve dhe thjeshton nxitjen.
Përdorimi i rezultateve të strukturuara është ideal për një gamë të gjerë aplikimesh:
- Nxjerrja e të dhënave: Nxirrni informacione specifike nga teksti i pastrukturuar, si p.sh. nxjerrja e emrave, datave dhe shumave nga një faturë.
- Klasifikimi i strukturuar: Klasifikoni tekstin në kategori të paracaktuara dhe caktoni etiketa të strukturuara, siç është kategorizimi i reagimeve të klientëve sipas ndjenjës dhe temës.
- Flukset e punës agjentike: Gjeneroni të dhëna të strukturuara që mund të përdoren për të thirrur mjete ose API të tjera, si krijimi i një flete karakteresh për një lojë ose plotësimi i një formulari.
Përveç mbështetjes së Skemës JSON në API-n REST, SDK-të e Google GenAI për Python dhe JavaScript e bëjnë të lehtë përcaktimin e skemave të objekteve duke përdorur përkatësisht Pydantic dhe Zod . Shembulli më poshtë tregon se si të nxirret informacion nga teksti i pastrukturuar që përputhet me një skemë të përcaktuar në kod.
Ky shembull demonstron se si të nxirren të dhëna të strukturuara nga teksti duke përdorur llojet themelore të skemës JSON si object , array , string dhe integer .
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional
class Ingredient(BaseModel):
name: str = Field(description="Name of the ingredient.")
quantity: str = Field(description="Quantity of the ingredient, including units.")
class Recipe(BaseModel):
recipe_name: str = Field(description="The name of the recipe.")
prep_time_minutes: Optional[int] = Field(description="Optional time in minutes to prepare the recipe.")
ingredients: List[Ingredient]
instructions: List[str]
client = genai.Client()
prompt = """
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
"""
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Recipe.model_json_schema(),
},
)
recipe = Recipe.model_validate_json(response.text)
print(recipe)
JavaScript
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ingredientSchema = z.object({
name: z.string().describe("Name of the ingredient."),
quantity: z.string().describe("Quantity of the ingredient, including units."),
});
const recipeSchema = z.object({
recipe_name: z.string().describe("The name of the recipe."),
prep_time_minutes: z.number().optional().describe("Optional time in minutes to prepare the recipe."),
ingredients: z.array(ingredientSchema),
instructions: z.array(z.string()),
});
const ai = new GoogleGenAI({});
const prompt = `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(recipeSchema),
},
});
const recipe = recipeSchema.parse(JSON.parse(response.text));
console.log(recipe);
Shko
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`
config := &genai.GenerateContentConfig{
ResponseMIMEType: "application/json",
ResponseJsonSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"recipe_name": map[string]any{
"type": "string",
"description": "The name of the recipe.",
},
"prep_time_minutes": map[string]any{
"type": "integer",
"description": "Optional time in minutes to prepare the recipe.",
},
"ingredients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{
"type": "string",
"description": "Name of the ingredient.",
},
"quantity": map[string]any{
"type": "string",
"description": "Quantity of the ingredient, including units.",
},
},
"required": []string{"name", "quantity"},
},
},
"instructions": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
},
},
"required": []string{"recipe_name", "ingredients", "instructions"},
},
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text(prompt),
config,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
PUSHTIM
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{ "text": "Please extract the recipe from the following text.\nThe user wants to make delicious chocolate chip cookies.\nThey need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,\n1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,\n3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.\nFor the best part, they will need 2 cups of semisweet chocolate chips.\nFirst, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,\nbaking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar\nuntil light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry\ningredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons\nonto ungreased baking sheets and bake for 9 to 11 minutes." }
]
}],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"recipe_name": {
"type": "string",
"description": "The name of the recipe."
},
"prep_time_minutes": {
"type": "integer",
"description": "Optional time in minutes to prepare the recipe."
},
"ingredients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name of the ingredient."},
"quantity": { "type": "string", "description": "Quantity of the ingredient, including units."}
},
"required": ["name", "quantity"]
}
},
"instructions": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["recipe_name", "ingredients", "instructions"]
}
}
}'
Shembull Përgjigjeje:
{
"recipe_name": "Delicious Chocolate Chip Cookies",
"ingredients": [
{
"name": "all-purpose flour",
"quantity": "2 and 1/4 cups"
},
{
"name": "baking soda",
"quantity": "1 teaspoon"
},
{
"name": "salt",
"quantity": "1 teaspoon"
},
{
"name": "unsalted butter (softened)",
"quantity": "1 cup"
},
{
"name": "granulated sugar",
"quantity": "3/4 cup"
},
{
"name": "packed brown sugar",
"quantity": "3/4 cup"
},
{
"name": "vanilla extract",
"quantity": "1 teaspoon"
},
{
"name": "large eggs",
"quantity": "2"
},
{
"name": "semisweet chocolate chips",
"quantity": "2 cups"
}
],
"instructions": [
"Preheat the oven to 375°F (190°C).",
"In a small bowl, whisk together the flour, baking soda, and salt.",
"In a large bowl, cream together the butter, granulated sugar, and brown sugar until light and fluffy.",
"Beat in the vanilla and eggs, one at a time.",
"Gradually beat in the dry ingredients until just combined.",
"Stir in the chocolate chips.",
"Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
]
}
Transmetim
Mund të transmetoni rezultate të strukturuara, gjë që ju lejon të filloni përpunimin e përgjigjes ndërsa ajo gjenerohet, pa pasur nevojë të prisni që të përfundojë i gjithë rezultati. Kjo mund të përmirësojë performancën e perceptuar të aplikacionit tuaj.
Pjesët e transmetuara do të jenë vargje të pjesshme JSON të vlefshme, të cilat mund të bashkohen për të formuar objektin përfundimtar dhe të plotë JSON.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal
class Feedback(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
summary: str
client = genai.Client()
prompt = "The new UI is incredibly intuitive and visually appealing. Great job. Add a very long summary to test streaming!"
response_stream = client.models.generate_content_stream(
model="gemini-2.5-flash",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Feedback.model_json_schema(),
},
)
for chunk in response_stream:
print(chunk.candidates[0].content.parts[0].text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ai = new GoogleGenAI({});
const prompt = "The new UI is incredibly intuitive and visually appealing. Great job! Add a very long summary to test streaming!";
const feedbackSchema = z.object({
sentiment: z.enum(["positive", "neutral", "negative"]),
summary: z.string(),
});
const stream = await ai.models.generateContentStream({
model: "gemini-2.5-flash",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(feedbackSchema),
},
});
for await (const chunk of stream) {
console.log(chunk.candidates[0].content.parts[0].text)
}
Mbështetje për skemën JSON
Për të gjeneruar një objekt JSON, vendosni response_mime_type në konfigurimin e gjenerimit në application/json dhe jepni një response_json_schema . Skema duhet të jetë një Skemë JSON e vlefshme që përshkruan formatin e dëshiruar të daljes.
Modeli më pas do të gjenerojë një përgjigje që është një varg JSON i vlefshëm sintaksorisht që përputhet me skemën e dhënë. Kur përdoren dalje të strukturuara, modeli do të prodhojë dalje në të njëjtën renditje si çelësat në skemë.
Modaliteti i strukturuar i daljes së Gemini mbështet një nëngrup të specifikimit të Skemës JSON .
Vlerat e mëposhtme të type mbështeten:
-
string: Për tekstin. -
number: Për numra me pikë lundruese. -
integer: Për numra të plotë. -
boolean: Për vlerat e vërteta/të gabuara. -
object: Për të dhëna të strukturuara me çifte çelës-vlerë. -
array: Për listat e artikujve. -
null: Për të lejuar që një veti të jetë null, përfshi"null"në vargun e tipit (p.sh.,{"type": ["string", "null"]}).
Këto veti përshkruese ndihmojnë në udhëzimin e modelit:
-
title: Një përshkrim i shkurtër i një prone. -
description: Një përshkrim më i gjatë dhe më i detajuar i një prone.
Vetitë specifike të tipit
Për vlerat object :
-
properties: Një objekt ku çdo çelës është një emër prone dhe çdo vlerë është një skemë për atë veti. -
required: Një varg vargjesh, që rendit cilat veti janë të detyrueshme. -
additionalProperties: Kontrollon nëse lejohen vetitë që nuk janë të listuara nëproperties. Mund të jetë një vlerë booleane ose një skemë.
Për vlerat string :
-
enum: Liston një grup specifik vargjesh të mundshme për detyrat e klasifikimit. -
format: Specifikon një sintaksë për vargun, siç ështëdate-time,date,time.
Për vlerat number dhe integer :
-
enum: Liston një grup specifik vlerash numerike të mundshme. -
minimum: Vlera minimale gjithëpërfshirëse. -
maximum: Vlera maksimale gjithëpërfshirëse.
Për vlerat array :
-
items: Përcakton skemën për të gjitha elementet në varg. -
prefixItems: Përcakton një listë skemash për N artikujt e parë, duke lejuar struktura të ngjashme me tuple. -
minItems: Numri minimal i artikujve në varg. -
maxItems: Numri maksimal i artikujve në varg.
Mbështetje për modelin
Modelet e mëposhtme mbështesin prodhimin e strukturuar:
| Model | Rezultatet e strukturuara |
|---|---|
| Gemini 2.5 Pro | ✔️ |
| Binjakët 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
| Binjakët 2.0 Flash | ✔️* |
| Gemini 2.0 Flash-Lite | ✔️* |
* Vini re se Gemini 2.0 kërkon një listë të qartë propertyOrdering brenda inputit JSON për të përcaktuar strukturën e preferuar. Mund të gjeni një shembull në këtë libër gatimi .
Daljet e strukturuara kundrejt thirrjes së funksioneve
Si rezultatet e strukturuara ashtu edhe thirrja e funksioneve përdorin skema JSON, por ato shërbejnë për qëllime të ndryshme:
| Karakteristikë | Rasti i Përdorimit Kryesor |
|---|---|
| Rezultatet e strukturuara | Formatimi i përgjigjes përfundimtare për përdoruesin. Përdoreni këtë kur dëshironi që përgjigjja e modelit të jetë në një format specifik (p.sh., nxjerrja e të dhënave nga një dokument për t'i ruajtur në një bazë të dhënash). |
| Thirrja e funksionit | Ndërmarrja e veprimeve gjatë bisedës. Përdoreni këtë kur modeli duhet t'ju kërkojë të kryeni një detyrë (p.sh., "të merrni të dhënat aktuale të motit") përpara se të japë një përgjigje përfundimtare. |
Praktikat më të mira
- Përshkrime të qarta: Përdorni fushën e
descriptionnë skemën tuaj për t'i dhënë modelit udhëzime të qarta rreth asaj që përfaqëson secila veti. Kjo është thelbësore për të udhëhequr rezultatin e modelit. - Tipizim i fortë: Përdorni lloje specifike (
integer,string,enum) sa herë që është e mundur. Nëse një parametër ka një grup të kufizuar vlerash të vlefshme, përdorni njëenum. - Inxhinieri e shpejtë: Shpjegoni qartë në kërkesën tuaj se çfarë dëshironi të bëjë modeli. Për shembull, "Nxirrni informacionin e mëposhtëm nga teksti..." ose "Klasifikoni këtë reagim sipas skemës së dhënë...".
- Validimi: Ndërsa rezultati i strukturuar garanton JSON të saktë nga ana sintaksore, ai nuk garanton që vlerat janë semantikisht të sakta. Gjithmonë validoni rezultatin përfundimtar në kodin e aplikacionit tuaj përpara se ta përdorni.
- Trajtimi i gabimeve: Implementoni trajtim të fuqishëm të gabimeve në aplikacionin tuaj për të menaxhuar me elegancë rastet kur rezultati i modelit, ndërsa është në përputhje me skemën, mund të mos i përmbushë kërkesat e logjikës së biznesit tuaj.
Kufizime
- Nënbashkësia e skemës: Jo të gjitha veçoritë e specifikimit të skemës JSON mbështeten. Modeli injoron vetitë e pambështetura.
- Kompleksiteti i skemës: API-ja mund të refuzojë skema shumë të mëdha ose të ndërthurura thellë. Nëse hasni gabime, provoni ta thjeshtoni skemën tuaj duke shkurtuar emrat e vetive, duke zvogëluar ndërthurjen ose duke kufizuar numrin e kufizimeve.