Respostas estruturadas

É possível configurar os modelos do Gemini para gerar respostas que sigam um esquema JSON fornecido. Esse recurso garante resultados previsíveis e analisáveis, segurança de formato e tipo, detecção programática de recusas e simplifica os comandos.

Usar saídas estruturadas é ideal para uma ampla variedade de aplicativos:

  • Extração de dados:extrai informações específicas de textos não estruturados, como nomes, datas e valores de uma fatura.
  • Classificação estruturada:classifique textos em categorias predefinidas e atribua rótulos estruturados, como categorizar o feedback dos clientes por sentimento e assunto.
  • Fluxos de trabalho com agentes:gere dados estruturados que podem ser usados para chamar outras ferramentas ou APIs, como criar uma ficha de personagem para um jogo ou preencher um formulário.

Além de oferecer suporte ao esquema JSON na API REST, os SDKs da GenAI do Google para Python e JavaScript também facilitam a definição de esquemas de objetos usando Pydantic e Zod, respectivamente. O exemplo abaixo demonstra como extrair informações de texto não estruturado que está de acordo com um esquema definido em código.

Este exemplo demonstra como extrair dados estruturados de texto usando tipos básicos de esquema JSON, como object, array, string e 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);

Go

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())
}

REST

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"]
        }
      }
    }'

Exemplo de resposta:

{
  "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."
  ]
}

Streaming

Você pode transmitir saídas estruturadas, o que permite começar a processar a resposta à medida que ela é gerada, sem precisar esperar que toda a saída seja concluída. Isso pode melhorar o desempenho percebido do aplicativo.

Os blocos transmitidos serão strings JSON parciais válidas, que podem ser concatenadas para formar o objeto JSON final e completo.

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)
}

Suporte a esquemas JSON

Para gerar um objeto JSON, defina o response_mime_type na configuração de geração como application/json e forneça um response_json_schema. O esquema precisa ser um esquema JSON válido que descreve o formato de saída desejado.

Em seguida, o modelo vai gerar uma resposta que é uma string JSON sintaticamente válida e que corresponde ao esquema fornecido. Ao usar saídas estruturadas, o modelo vai gerar saídas na mesma ordem das chaves no esquema.

O modo de saída estruturada do Gemini é compatível com um subconjunto da especificação JSON Schema.

Os seguintes valores de type são aceitos:

  • string: para texto.
  • number: para números de ponto flutuante.
  • integer: para números inteiros.
  • boolean: para valores verdadeiro/falso.
  • object: para dados estruturados com pares de chave-valor.
  • array: para listas de itens.
  • null: para permitir que uma propriedade seja nula, inclua "null" na matriz de tipos (por exemplo, {"type": ["string", "null"]}).

Essas propriedades descritivas ajudam a orientar o modelo:

  • title: uma breve descrição de uma propriedade.
  • description: uma descrição mais longa e detalhada de uma propriedade.

Propriedades específicas do tipo

Para valores object:

  • properties: um objeto em que cada chave é um nome de propriedade e cada valor é um esquema para essa propriedade.
  • required: uma matriz de strings que lista quais propriedades são obrigatórias.
  • additionalProperties: controla se as propriedades não listadas em properties são permitidas. Pode ser um booleano ou um esquema.

Para valores string:

  • enum: lista um conjunto específico de strings possíveis para tarefas de classificação.
  • format: especifica uma sintaxe para a string, como date-time, date e time.

Para valores number e integer:

  • enum: lista um conjunto específico de valores numéricos possíveis.
  • minimum: o valor mínimo inclusivo.
  • maximum: o valor máximo inclusivo.

Para valores array:

  • items: define o esquema de todos os itens na matriz.
  • prefixItems: define uma lista de esquemas para os primeiros N itens, permitindo estruturas semelhantes a tuplas.
  • minItems: o número mínimo de itens na matriz.
  • maxItems: o número máximo de itens na matriz.

Suporte a modelos

Os seguintes modelos são compatíveis com saída estruturada:

Modelo Respostas estruturadas
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash-Lite ✔️
Gemini 2.0 Flash ✔️*
Gemini 2.0 Flash-Lite ✔️*

* O Gemini 2.0 exige uma lista propertyOrdering explícita na entrada JSON para definir a estrutura preferida. Confira um exemplo neste manual.

Saídas estruturadas x chamada de função

As saídas estruturadas e a chamada de função usam esquemas JSON, mas têm finalidades diferentes:

Recurso Caso de uso principal
Saídas estruturadas Formatar a resposta final para o usuário. Use isso quando quiser que a resposta do modelo esteja em um formato específico (por exemplo, extrair dados de um documento para salvar em um banco de dados).
Chamada de função Tomar medidas durante a conversa. Use isso quando o modelo precisar pedir que você execute uma tarefa (por exemplo, "qual é a previsão do tempo") antes de fornecer uma resposta final.

Práticas recomendadas

  • Descrições claras:use o campo description no esquema para dar instruções claras ao modelo sobre o que cada propriedade representa. Isso é essencial para orientar a saída do modelo.
  • Tipagem forte:use tipos específicos (integer, string, enum) sempre que possível. Se um parâmetro tiver um conjunto limitado de valores válidos, use um enum.
  • Engenharia de comando:deixe claro no comando o que você quer que o modelo faça. Por exemplo, "Extraia as seguintes informações do texto..." ou "Classifique este feedback de acordo com o esquema fornecido...".
  • Validação:embora a saída estruturada garanta um JSON sintaticamente correto, ela não garante que os valores estejam semanticamente corretos. Sempre valide a saída final no código do aplicativo antes de usá-la.
  • Tratamento de erros:implemente um tratamento de erros robusto no seu aplicativo para gerenciar de forma adequada casos em que a saída do modelo, embora esteja em conformidade com o esquema, não atenda aos requisitos da sua lógica de negócios.

Limitações

  • Subconjunto de esquema:nem todos os recursos da especificação do esquema JSON são compatíveis. O modelo ignora propriedades sem suporte.
  • Complexidade do esquema:a API pode rejeitar esquemas muito grandes ou profundamente aninhados. Se você encontrar erros, tente simplificar o esquema encurtando os nomes das propriedades, reduzindo o aninhamento ou limitando o número de restrições.