API Gemini по умолчанию возвращает ответы в виде неструктурированного текста. Однако в некоторых случаях использования требуется структурированный текст, например JSON. Например, вы можете использовать ответ для других последующих задач, требующих установленной схемы данных.
Чтобы гарантировать, что выходные данные модели всегда соответствуют определенной схеме, вы можете определить схему ответа , которая работает как образец ответов модели. Затем вы можете напрямую извлекать данные из выходных данных модели с меньшими затратами на постобработку.
Вот несколько примеров:
Убедитесь, что ответ модели создает действительный JSON и соответствует предоставленной вами схеме.
Например, модель может генерировать структурированные записи для рецептов, которые всегда включают название рецепта, список ингредиентов и этапы. После этого вам будет проще анализировать и отображать эту информацию в пользовательском интерфейсе вашего приложения.Ограничьте реакцию модели на выполнение задач классификации.
Например, вы можете аннотировать текст модели определенным набором меток (например, определенным набором перечислений, таких какpositive
иnegative
), а не метками, которые создает модель (которые могут иметь определенную степень изменчивости, например,good
,positive
,negative
илиbad
).
В этом руководстве показано, как генерировать выходные данные JSON, предоставляя responseSchema
при вызове generateContent
. Он ориентирован на ввод только текста, но Gemini также может выдавать структурированные ответы на мультимодальные запросы, которые включают в себя изображения, видео и аудио в качестве входных данных.
Внизу этой страницы приведены дополнительные примеры, например, как генерировать значения перечисления в качестве вывода . Чтобы просмотреть дополнительные примеры того, как можно генерировать структурированный вывод, ознакомьтесь со списком примеров схем и ответов моделей в документации Google Cloud .
При желании поэкспериментируйте с альтернативной версией API Gemini « Google AI ».
Получите бесплатный доступ (в пределах ограничений и там, где это возможно) с помощью Google AI Studio и клиентских SDK Google AI . Эти SDK следует использовать для прототипирования только в мобильных и веб-приложениях.После того, как вы ознакомитесь с тем, как работает API Gemini , перейдите на наши Vertex AI в Firebase SDK (эта документация), которые имеют множество дополнительных функций, важных для мобильных и веб-приложений, таких как защита API от злоупотреблений с помощью Firebase App Check и поддержка больших медиафайлов в запросах .
При необходимости вызовите серверный API Vertex AI Gemini (например, с помощью Python, Node.js или Go).
Используйте серверные Vertex AI SDK , Genkit или Firebase Extensions для Gemini API .
Прежде чем начать
Если вы еще этого не сделали, прочтите руководство по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать службу Vertex AI и создать экземпляр GenerativeModel
.
Шаг 1. Определите схему ответа.
Определите схему ответа, чтобы указать структуру выходных данных модели, имена полей и ожидаемый тип данных для каждого поля.
Когда модель генерирует ответ, она использует имя поля и контекст из вашего приглашения. Чтобы убедиться в ясности ваших намерений, мы рекомендуем использовать четкую структуру, однозначные названия полей и даже описания, если это необходимо.
Рекомендации по схемам ответов
При написании схемы ответа помните следующее:
Размер схемы ответа учитывается при расчете лимита входного токена.
Функция схемы ответа поддерживает следующие типы MIME ответов:
application/json
: выводит JSON, как определено в схеме ответа (полезно для требований структурированного вывода)text/x.enum
: вывести значение перечисления, как определено в схеме ответа (полезно для задач классификации)
Функция схемы ответа поддерживает следующие поля схемы:
enum
items
maxItems
nullable
properties
required
Если вы используете неподдерживаемое поле, модель все равно сможет обработать ваш запрос, но игнорирует это поле. Обратите внимание, что приведенный выше список является подмножеством объекта схемы OpenAPI 3.0 (см. справочник по схеме Vertex AI ).
По умолчанию для Vertex AI в Firebase SDK все поля считаются обязательными , если вы не укажете их как необязательные в массиве
optionalProperties
. Для этих необязательных полей модель может заполнять поля или пропускать их.Обратите внимание, что это противоположно поведению по умолчанию для API Vertex AI Gemini .
Шаг 2. Отправьте запрос со схемой ответа для создания JSON.
В следующем примере показано, как создать структурированный вывод JSON.
При создании экземпляра GenerativeModel
укажите соответствующий responseMimeType
(в данном примере — application/json
), а также responseSchema
, которую вы хотите использовать в модели.
Быстрый
import FirebaseVertexAI
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let jsonSchema = Schema.object(
properties: [
"characters": Schema.array(
items: .object(
properties: [
"name": .string(),
"age": .integer(),
"species": .string(),
"accessory": .enumeration(values: ["hat", "belt", "shoes"]),
],
optionalProperties: ["accessory"]
)
),
]
)
// Initialize the Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "application/json",
responseSchema: jsonSchema
)
)
let prompt = "For use in a children's card game, generate 10 animal-based characters."
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
Для Kotlin методы в этом SDK являются функциями приостановки, и их необходимо вызывать из области Coroutine .// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val jsonSchema = Schema.obj(
mapOf("characters" to Schema.array(
Schema.obj(
mapOf(
"name" to Schema.string(),
"age" to Schema.integer(),
"species" to Schema.string(),
"accessory" to Schema.enumeration(listOf("hat", "belt", "shoes")),
),
optionalProperties = listOf("accessory")
)
))
)
// Initialize the Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = jsonSchema
})
val prompt = "For use in a children's card game, generate 10 animal-based characters."
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
Для Java методы потоковой передачи в этом SDK возвращают типPublisher
из библиотеки Reactive Streams . // Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema jsonSchema = Schema.obj(
/* properties */
Map.of(
"characters", Schema.array(
/* items */ Schema.obj(
/* properties */
Map.of("name", Schema.str(),
"age", Schema.numInt(),
"species", Schema.str(),
"accessory",
Schema.enumeration(
List.of("hat", "belt", "shoes")))
))),
List.of("accessory"));
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = jsonSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
Content content = new Content.Builder()
.addText("For use in a children's card game, generate 10 animal-based characters.")
.build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
Web
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// TODO(developer) Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const jsonSchema = Schema.object({
properties: {
characters: Schema.array({
items: Schema.object({
properties: {
name: Schema.string(),
accessory: Schema.string(),
age: Schema.number(),
species: Schema.string(),
},
optionalProperties: ["accessory"],
}),
}),
}
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
},
});
let prompt = "For use in a children's card game, generate 10 animal-based characters.";
let result = await model.generateContent(prompt)
console.log(result.response.text());
Dart
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final jsonSchema = Schema.object(
properties: {
'characters': Schema.array(
items: Schema.object(
properties: {
'name': Schema.string(),
'age': Schema.integer(),
'species': Schema.string(),
'accessory':
Schema.enumString(enumValues: ['hat', 'belt', 'shoes']),
},
),
),
},
optionalProperties: ['accessory'],
);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'application/json', responseSchema: jsonSchema));
final prompt = "For use in a children's card game, generate 10 animal-based characters.";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Узнайте, как выбрать модель и, при необходимости, местоположение, подходящее для вашего варианта использования и приложения.
Дополнительные примеры
Чтобы просмотреть дополнительные примеры того, как вы можете использовать и генерировать структурированный вывод, ознакомьтесь со списком примеров схем и ответов моделей в документации Google Cloud .
Генерация значений перечисления в качестве вывода
В следующем примере показано, как использовать схему ответа для задачи классификации. Модель просят определить жанр фильма на основе его описания. Выходные данные представляют собой одно значение перечисления в виде обычного текста, которое модель выбирает из списка значений, определенных в предоставленной схеме ответа.
Чтобы выполнить эту задачу структурированной классификации, во время инициализации модели вам необходимо указать соответствующий тип responseMimeType
(в данном примере text/x.enum
), а также responseSchema
, который вы хотите, чтобы модель использовала.
Быстрый
import FirebaseVertexAI
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let enumSchema = Schema.enumeration(values: ["drama", "comedy", "documentary"])
// Initialize the Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "text/x.enum",
responseSchema: enumSchema
)
)
let prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
Для Kotlin методы в этом SDK являются функциями приостановки, и их необходимо вызывать из области Coroutine .// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val enumSchema = Schema.enumeration(listOf("drama", "comedy", "documentary"))
// Initialize the Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "text/x.enum"
responseSchema = enumSchema
})
val prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
Для Java методы потоковой передачи в этом SDK возвращают типPublisher
из библиотеки Reactive Streams . // Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema enumSchema = Schema.enumeration(List.of("drama", "comedy", "documentary"));
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "text/x.enum";
configBuilder.responseSchema = enumSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
String prompt = "The film aims to educate and inform viewers about real-life subjects," +
" events, or people. It offers a factual record of a particular topic by" +
" combining interviews, historical footage, and narration. The primary purpose" +
" of a film is to present information and provide insights into various aspects" +
" of reality.";
Content content = new Content.Builder().addText(prompt).build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
Web
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// TODO(developer) Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const enumSchema = Schema.enumString({
enum: ["drama", "comedy", "documentary"],
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema,
},
});
let prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;
let result = await model.generateContent(prompt);
console.log(result.response.text());
Dart
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final enumSchema = Schema.enumString(enumValues: ['drama', 'comedy', 'documentary']);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'text/x.enum', responseSchema: enumSchema));
final prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
""";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Узнайте, как выбрать модель и, при необходимости, местоположение, подходящее для вашего варианта использования и приложения.
Другие варианты управления созданием контента
- Узнайте больше о разработке подсказок , чтобы вы могли влиять на модель и генерировать выходные данные, соответствующие вашим потребностям.
- Настройте параметры модели , чтобы контролировать, как модель генерирует ответ. Для моделей Gemini эти параметры включают максимальное количество токенов вывода, температуру, topK и topP. Для моделей Imagen к ним относятся соотношение сторон, генерация людей, водяные знаки и т. д.
- Используйте настройки безопасности , чтобы настроить вероятность получения ответов, которые могут быть расценены как вредные, включая разжигание ненависти и контент откровенно сексуального характера.
- Установите системные инструкции для управления поведением модели. Эта функция похожа на «преамбулу», которую вы добавляете перед тем, как модель будет подвергнута дальнейшим инструкциям от конечного пользователя.
Оставьте отзыв о своем опыте использования Vertex AI в Firebase.