Kết quả có cấu trúc
Bạn có thể định cấu hình các mô hình Gemini để tạo câu trả lời tuân thủ Giản đồ JSON được cung cấp. Điều này đảm bảo kết quả có thể dự đoán và an toàn về kiểu, đồng thời đơn giản hoá việc trích xuất dữ liệu có cấu trúc từ văn bản không có cấu trúc.
Việc sử dụng kết quả có cấu trúc rất phù hợp cho:
- Trích xuất dữ liệu: Trích xuất thông tin cụ thể như tên và ngày từ văn bản.
- Phân loại có cấu trúc: Phân loại văn bản thành các danh mục được xác định trước.
- Quy trình công việc dựa trên tác nhân: Tạo dữ liệu đầu vào có cấu trúc cho các công cụ hoặc API.
Ngoài việc hỗ trợ Giản đồ JSON trong API REST, SDK AI tạo sinh của Google còn cho phép xác định giản đồ bằng Pydantic (Python) và Zod (JavaScript).
Ví dụ về kết quả có cấu trúc
Trình trích xuất công thức
Ví dụ này minh hoạ cách trích xuất dữ liệu có cấu trúc từ văn bản bằng các loại Giản đồ JSON cơ bản như object, array, string và 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.
"""
interaction = client.interactions.create(
model="gemini-3.5-flash",
input=prompt,
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Recipe.model_json_schema()
},
)
recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const recipeJsonSchema = {
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"]
};
const recipeSchema = z.fromJSONSchema(recipeJsonSchema);
const client = 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 interaction = await client.interactions.create({
model: "gemini-3.5-flash",
input: prompt,
response_format: {
type: 'text',
mime_type: 'application/json',
schema: recipeJsonSchema
},
});
const recipe = recipeSchema.parse(JSON.parse(interaction.output_text));
console.log(recipe);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"input": "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.",
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"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"]
}
}
}
}'
Ví dụ về phản hồi:
{
"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."
]
}
Kiểm duyệt nội dung
Ví dụ này minh hoạ anyOf cho các giản đồ có điều kiện và enum cho việc phân loại, cho phép cấu trúc đầu ra thay đổi dựa trên nội dung.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Union, Literal
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"] = Field(description="The type of spam.")
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
client = genai.Client()
prompt = """
Please moderate the following content and provide a decision.
Content: 'Congratulations! You''ve won a free cruise to the Bahamas. Click here to claim your prize: www.definitely-not-a-scam.com'
"""
interaction = client.interactions.create(
model="gemini-3.5-flash",
input=prompt,
response_format={
"type": "text",
"mime_type": "application/json",
"schema": ModerationResult.model_json_schema()
},
)
result = ModerationResult.model_validate_json(interaction.output_text)
print(result)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const moderationResultJsonSchema = {
type: "object",
properties: {
decision: {
anyOf: [
{
type: "object",
title: "SpamDetails",
description: "Details for content classified as spam.",
properties: {
reason: { type: "string", description: "The reason why the content is considered spam." },
spam_type: { type: "string", enum: ["phishing", "scam", "unsolicited promotion", "other"], description: "The type of spam." }
},
required: ["reason", "spam_type"]
},
{
type: "object",
title: "NotSpamDetails",
description: "Details for content classified as not spam.",
properties: {
summary: { type: "string", description: "A brief summary of the content." },
is_safe: { type: "boolean", description: "Whether the content is safe for all audiences." }
},
required: ["summary", "is_safe"]
}
]
}
},
required: ["decision"]
};
const moderationResultSchema = z.fromJSONSchema(moderationResultJsonSchema);
const client = new GoogleGenAI({});
const prompt = `
Please moderate the following content and provide a decision.
Content: 'Congratulations! You''ve won a free cruise to the Bahamas. Click here to claim your prize: www.definitely-not-a-scam.com'
`;
const interaction = await client.interactions.create({
model: "gemini-3.5-flash",
input: prompt,
response_format: {
type: 'text',
mime_type: 'application/json',
schema: moderationResultJsonSchema
},
});
const result = moderationResultSchema.parse(JSON.parse(interaction.output_text));
console.log(result);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"input": "Please moderate the following content and provide a decision.\nContent: '\''Congratulations! You have won a free cruise to the Bahamas. Click here to claim your prize: www.definitely-not-a-scam.com'\''",
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"decision": {
"anyOf": [
{
"type": "object",
"title": "SpamDetails",
"description": "Details for content classified as spam.",
"properties": {
"reason": { "type": "string", "description": "The reason why the content is considered spam." },
"spam_type": { "type": "string", "enum": ["phishing", "scam", "unsolicited promotion", "other"], "description": "The type of spam." }
},
"required": ["reason", "spam_type"]
},
{
"type": "object",
"title": "NotSpamDetails",
"description": "Details for content classified as not spam.",
"properties": {
"summary": { "type": "string", "description": "A brief summary of the content." },
"is_safe": { "type": "boolean", "description": "Whether the content is safe for all audiences." }
},
"required": ["summary", "is_safe"]
}
]
}
},
"required": ["decision"]
}
}
}
}'
Ví dụ về phản hồi:
{
"decision": {
"reason": "The content is an unsolicited prize notification attempting to trick the user into clicking a suspicious link.",
"spam_type": "scam"
}
}
Cấu trúc đệ quy
Ví dụ này minh hoạ cách xác định một giản đồ đệ quy, chẳng hạn như sơ đồ tổ chức.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List
class Employee(BaseModel):
"""Represents an employee in an organization."""
name: str
employee_id: int
reports: List["Employee"] = Field(
default_factory=list,
description="A list of employees reporting to this employee."
)
client = genai.Client()
prompt = """
Generate an organization chart for a small team.
The manager is Alice, who manages Bob and Charlie. Bob manages David.
"""
interaction = client.interactions.create(
model="gemini-3.5-flash",
input=prompt,
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Employee.model_json_schema()
},
)
employee = Employee.model_validate_json(interaction.output_text)
print(employee)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const employeeJsonSchema = {
type: "object",
properties: {
name: { type: "string" },
employee_id: { type: "integer" },
reports: {
type: "array",
description: "A list of employees reporting to this employee.",
items: {
"$ref": "#"
}
}
},
required: ["name", "employee_id", "reports"]
};
const employeeSchema = z.fromJSONSchema(employeeJsonSchema);
const client = new GoogleGenAI({});
const prompt = `
Generate an organization chart for a small team.
The manager is Alice, who manages Bob and Charlie. Bob manages David.
`;
const interaction = await client.interactions.create({
model: "gemini-3.5-flash",
input: prompt,
response_format: {
type: 'text',
mime_type: 'application/json',
schema: employeeJsonSchema
},
});
const employee = employeeSchema.parse(JSON.parse(interaction.output_text));
console.log(employee);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"input": "Generate an organization chart for a small team.\nThe manager is Alice, who manages Bob and Charlie. Bob manages David.",
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"employee_id": { "type": "integer" },
"reports": {
"type": "array",
"description": "A list of employees reporting to this employee.",
"items": {
"$ref": "#"
}
}
},
"required": ["name", "employee_id", "reports"]
}
}
}
}'
Ví dụ về phản hồi:
{
"name": "Alice",
"employee_id": 101,
"reports": [
{
"name": "Bob",
"employee_id": 102,
"reports": [
{
"name": "David",
"employee_id": 104,
"reports": []
}
]
},
{
"name": "Charlie",
"employee_id": 103,
"reports": []
}
]
}
Truyền trực tuyến kết quả
Bạn có thể truyền trực tuyến kết quả có cấu trúc, cho phép bạn bắt đầu xử lý câu trả lời khi câu trả lời đó đang được tạo. Các khối được truyền trực tuyến là các chuỗi JSON một phần hợp lệ có thể được nối để tạo thành đối tượng JSON cuối cùng.
Python
from google import genai
from pydantic import BaseModel
from typing import Literal
class Feedback(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
summary: str
client = genai.Client()
prompt = "The new UI is incredibly intuitive. Add a very long summary to test streaming!"
stream = client.interactions.create(
model="gemini-3.5-flash",
input=prompt,
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Feedback.model_json_schema()
},
stream=True
)
for event in stream:
if event.event_type == "step.delta" and event.delta.text:
print(event.delta.text, end="")
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const feedbackJsonSchema = {
type: "object",
properties: {
sentiment: { type: "string", enum: ["positive", "neutral", "negative"] },
summary: { type: "string" }
},
required: ["sentiment", "summary"]
};
const feedbackSchema = z.fromJSONSchema(feedbackJsonSchema);
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
model: "gemini-3.5-flash",
input: "The new UI is incredibly intuitive. Add a very long summary!",
response_format: {
type: 'text',
mime_type: 'application/json',
schema: feedbackJsonSchema
},
stream: true,
});
for await (const event of stream) {
if (event.type === "step.delta" && event.delta?.text) {
process.stdout.write(event.delta.text);
}
}
Kết quả có cấu trúc bằng các công cụ
Gemini 3 cho phép bạn kết hợp Kết quả có cấu trúc với các công cụ tích hợp, bao gồm Bám sát nguồn bằng Google Tìm kiếm, Bối cảnh URL, Thực thi mã, Tìm tệp, và Gọi hàm.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List
class MatchResult(BaseModel):
winner: str = Field(description="The name of the winner.")
final_match_score: str = Field(description="The final match score.")
scorers: List[str] = Field(description="The name of the scorer.")
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.1-pro-preview",
input="Search for all details for the latest Euro.",
tools=[{"type": "google_search"}, {"type": "url_context"}],
response_format={
"type": "text",
"mime_type": "application/json",
"schema": MatchResult.model_json_schema()
},
)
result = MatchResult.model_validate_json(interaction.output_text)
print(result)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const matchJsonSchema = {
type: "object",
properties: {
winner: { type: "string" },
final_match_score: { type: "string" },
scorers: { type: "array", items: { type: "string" } }
},
required: ["winner", "final_match_score", "scorers"]
};
const matchSchema = z.fromJSONSchema(matchJsonSchema);
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.1-pro-preview",
input: "Search for all details for the latest Euro.",
tools: [{type: "google_search"}, {type: "url_context"}],
response_format: {
type: 'text',
mime_type: 'application/json',
schema: matchJsonSchema
},
});
const match = matchSchema.parse(JSON.parse(interaction.output_text));
console.log(match);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.1-pro-preview",
"input": "Search for all details for the latest Euro.",
"tools": [{"type": "google_search"}, {"type": "url_context"}],
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"winner": {"type": "string"},
"final_match_score": {"type": "string"},
"scorers": {"type": "array", "items": {"type": "string"}}
},
"required": ["winner", "final_match_score", "scorers"]
}
}
}'
Hỗ trợ giản đồ JSON
Để tạo đối tượng JSON, hãy định cấu hình response_format bằng một đối tượng (hoặc một mảng chứa đối tượng) thuộc loại text và đặt mime_type thành application/json. Bạn nên cung cấp giản đồ trong trường schema.
Chế độ kết quả có cấu trúc của Gemini hỗ trợ một tập hợp con của thông số kỹ thuật Giản đồ JSON.
Các giá trị sau đây của type được hỗ trợ:
string: Dành cho văn bản.number: Dành cho số dấu phẩy động.integer: Dành cho số nguyên.boolean: Dành cho giá trị đúng hoặc sai.object: Dành cho dữ liệu có cấu trúc với các cặp khoá-giá trị.array: Dành cho danh sách các mục.null: Để cho phép một thuộc tính có giá trị rỗng, hãy thêm"null"vào mảng loại (ví dụ:{"type": ["string", "null"]}).
Các thuộc tính mô tả này giúp hướng dẫn mô hình:
title: Nội dung mô tả ngắn về một thuộc tính.description: Nội dung mô tả dài hơn và chi tiết hơn về một thuộc tính.
Thuộc tính cụ thể của từng loại
Đối với các giá
trị object:
properties: Một đối tượng trong đó mỗi khoá là tên thuộc tính và mỗi giá trị là một giản đồ cho thuộc tính đó.required: Một mảng các chuỗi, liệt kê những thuộc tính bắt buộc.additionalProperties: Kiểm soát xem các thuộc tính không có trongpropertiescó được phép hay không. Có thể là một giá trị boolean hoặc một giản đồ.
Đối với các giá
trị string:
enum: Liệt kê một tập hợp cụ thể các chuỗi có thể có cho các tác vụ phân loại.format: Chỉ định cú pháp cho chuỗi, chẳng hạn nhưdate-time,date,time.
Đối với các giá trị number và integer:
enum: Liệt kê một tập hợp cụ thể các giá trị số có thể có.minimum: Giá trị tối thiểu (bao gồm).maximum: Giá trị tối đa (bao gồm).
Đối với các giá trị array:
items: Xác định giản đồ cho tất cả các mục trong mảng.prefixItems: Xác định danh sách giản đồ cho N mục đầu tiên, cho phép các cấu trúc giống như bộ dữ liệu.minItems: Số lượng mục tối thiểu trong mảng.maxItems: Số lượng mục tối đa trong mảng.
So sánh giữa kết quả có cấu trúc và lệnh gọi hàm
| Tính năng | Trường hợp sử dụng chính |
|---|---|
| Kết quả có cấu trúc | Định dạng câu trả lời cuối cùng. Sử dụng khi bạn muốn câu trả lời của mô hình ở một định dạng cụ thể. |
| Lệnh gọi hàm | Thực hiện hành động trong cuộc trò chuyện. Sử dụng khi mô hình cần yêu cầu bạn thực hiện một tác vụ trước khi đưa ra câu trả lời cuối cùng. |
Các phương pháp hay nhất
- Nội dung mô tả rõ ràng: Sử dụng trường
descriptionđể hướng dẫn mô hình. - Kiểu dữ liệu mạnh: Sử dụng các kiểu cụ thể (
integer,string,enum). - Thiết kế câu lệnh: Nêu rõ những gì bạn muốn mô hình thực hiện.
- Xác thực: Mặc dù đầu ra là JSON có cú pháp chính xác, nhưng bạn vẫn nên xác thực các giá trị trong ứng dụng của mình.
- Xử lý lỗi: Triển khai biện pháp xử lý lỗi hữu ích cho các kết quả tuân thủ giản đồ nhưng không chính xác về mặt ngữ nghĩa.
Các điểm hạn chế
- Tập hợp con của giản đồ: Không phải tất cả các tính năng của Giản đồ JSON đều được hỗ trợ.
- Độ phức tạp của giản đồ: Các giản đồ rất lớn hoặc được lồng sâu có thể bị từ chối.