Esta guía se aplica a cualquier capacidad que dependa de interacciones de varios turnos, incluidas las siguientes:
Conversación de varios turnos (chat), incluido el chat solo de salida de texto y la edición iterativa de imágenes
Descripción general
Para las interacciones de varios turnos, los Firebase AI Logic SDK administran el estado de la conversación. Esto también se aplica cuando se usan plantillas de instrucciones del servidor.
El flujo de trabajo básico para las interacciones de varios turnos y las plantillas de instrucciones del servidor es fundamentalmente el mismo que para las solicitudes de un solo turno, con algunas diferencias importantes:
Crea la plantilla con la IU guiada en la Firebase consola.
Para las interacciones de varios turnos, debes agregar la
{{history}}etiqueta en el contenido de la plantilla, que le indica a la plantilla dónde insertar los turnos de conversación que administra el SDK del cliente.Prueba la plantilla en una solicitud real con la experiencia de prueba en la Firebase consola.
Para las interacciones de varios turnos, la experiencia de prueba de la consola solo puede ayudar a probar el turno inicial. Puedes probar cómo se controlan los turnos posteriores (el historial) usando la plantilla con tu app real.
Accede a la plantilla desde el código de tu app con
templateGenerativeModel.Para las interacciones de varios turnos, debes usar
startChatysendMessage(al igual que para las interacciones de varios turnos cuando no usas plantillas de instrucciones del servidor).
Ten en cuenta que, para las llamadas a funciones, hay algunas diferencias más, que se describen en esa sección más adelante en esta página.
Conversación de varios turnos (chat)
Si aún no lo hiciste, consulta la guía general para crear conversaciones de varios turnos (chat) cuando no usas plantillas de instrucciones del servidor.
Formato básico de una plantilla de instrucciones del servidor
Para Firebase AI Logic, la Firebase consola proporciona una IU guiada para que especifiques el frontmatter y el contenido de la plantilla.
Las plantillas de instrucciones del servidor usan una sintaxis y un formato basados en Dotprompt. Para obtener más detalles, consulta Formato, sintaxis y ejemplos de plantillas.
En la siguiente plantilla de ejemplo, se muestran los componentes más importantes de una plantilla cuando se crea una conversación de varios turnos (chat). Ten en cuenta la adición de la
{{history}} etiqueta en el contenido de la plantilla,
que le indica a la plantilla dónde insertar los turnos de conversación que administra el
SDK del cliente.
---
model: 'gemini-3-flash-preview'
---
{{role "system"}}
You help customers with their invoices, including answering questions or providing their invoices to them.
If an invoice is requested, it must be a clearly structured invoice document that uses a tabular or clearly delineated list format for line items.
{{history}}
Usa tu plantilla en el código
|
Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página. |
En el siguiente código de cliente de ejemplo, se muestra cómo usar la plantilla en tu código. Ten en cuenta el uso de templateGenerativeModel junto con startChat y sendMessage cuando se crean interacciones de varios turnos.
Swift
For Swift, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Kotlin
// ...
// Initialize the Gemini Developer API backend service
// Create a `TemplateGenerativeModel` instance.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.templateGenerativeModel()
// Start a chat session with a template.
val chatSession = model.startChat(
// Specify your template ID
templateId= "my-chat-template-v1-0-0",
inputs = emptyMap()
)
// Send messages.
// The template's system instructions and model config apply to every turn automatically.
// The SDK automatically manages the state of the conversation.
val response = chatSession.sendMessage(
content("user") { text("I need a copy of my invoice.") }
)
val text = response.text
println(text)
Java
For Java, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Web
// ...
// Initialize the Gemini Developer API backend service.
const ai = getAI(app, { backend: new GoogleAIBackend() });
// Create a `TemplateGenerativeModel` instance.
const model = getTemplateGenerativeModel(ai);
// Start a chat session with a template.
const chatSession = model.startChat({
// Specify your template ID.
templateId: 'my-chat-template-v1-0-0',
});
// Send messages.
// The template's system instructions and model config apply to every turn automatically.
// The SDK automatically manages the state of the conversation.
const result = await chatSession.sendMessage("I need a copy of my invoice.");
const text = result.response.text();
console.log(text);
Dart
// ...
// Initialize the Gemini Developer API backend service.
// Create a `TemplateGenerativeModel` instance.
final model = FirebaseAI.googleAI().templateGenerativeModel();
// Start a chat session with a template.
final chatSession = model.startChat(
// Specify your template ID.
templateId: 'my-chat-template-v1-0-0',
);
// Send messages.
// The template's system instructions and model config apply to every turn automatically.
// The SDK automatically manages the state of the conversation.
final response = await chatSession.sendMessage(
Content.text('I need a copy of my invoice.'),
);
final text = response.text;
print(text);
Unity
// ...
// Initialize the Gemini Developer API backend service.
var firebaseAI = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `TemplateGenerativeModel` instance.
var model = firebaseAI.GetTemplateGenerativeModel();
// Start a chat session with a template.
var chatSession = model.StartChat(
// Specify your template ID.
"my-chat-template-v1-0-0"
);
// Send messages.
// The template's system instructions and model config apply to every turn automatically.
// The SDK automatically manages the state of the conversation.
try
{
var response = await chatSession.SendMessageAsync(ModelContent.Text("I need a copy of my invoice."));
Debug.Log($"Response Text: {response.Text}");
}
catch (Exception e) {
Debug.LogError($"An error occurred: {e.Message}");
}
Llamadas a funciones
Si aún no lo hiciste, consulta la guía general para las llamadas a funciones cuando no usas plantillas de instrucciones del servidor. En esta guía sobre el uso de plantillas de instrucciones del servidor, se supone que comprendes cómo funcionan las llamadas a funciones en general.
Formato básico de una plantilla de instrucciones del servidor
Para Firebase AI Logic, la Firebase consola proporciona una IU guiada para que especifiques el frontmatter y el contenido de la plantilla.
Las plantillas de instrucciones del servidor usan una sintaxis y un formato basados en Dotprompt. Para obtener más detalles, consulta Formato, sintaxis y ejemplos de plantillas.
En la siguiente plantilla de ejemplo, se muestran los componentes más importantes de una plantilla cuando se usan llamadas a funciones. Ten en cuenta lo siguiente:
En el frontmatter de la plantilla, enumera las funciones a las que tiene acceso el modelo proporcionando declaraciones de funciones en el objeto
tools.Define el
name(obligatorio) y ladescription(opcional) para cada función a la que tenga acceso el modelo.Define el esquema para cada función a la que tenga acceso el modelo.
En la siguiente plantilla de ejemplo, se supone que defines esquemas de funciones en la plantilla. Sin embargo, puedes proporcionar el esquema de la función en el código del cliente. El esquema definido en el código del cliente anulará cualquier esquema definido en la plantilla. Más adelante en esta página, encontrarás un ejemplo de una plantilla y un código de cliente para definir el esquema en el código del cliente.
En el contenido de la plantilla, agrega la
{{history}}etiqueta, que le indica a la plantilla dónde insertar los turnos de conversación que administra el SDK del cliente.
Plantilla de ejemplo con esquema de función definido en la plantilla
---
model: gemini-3-flash-preview
tools:
- name: fetchWeather
description: Get the weather conditions for a specific city on a specific date.
input:
schema:
location(object, The name of the city and its state for which to get the weather. Only cities in the USA are supported.):
city: string, The city of the location.
state: string, The state of the location.
date: string, The date for which to get the weather. Date must be in the format YYYY-MM-DD.
---
What was the weather like in Boston, Massachusetts on 10/17 in year 2024?
{{history}}
Usa tu plantilla en el código
|
Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página. |
En el siguiente código de cliente de ejemplo, se muestra cómo usar la plantilla en tu código. Ten en cuenta lo siguiente:
Usa
templateGenerativeModeljunto constartChatysendMessagecuando uses interacciones de varios turnos.Durante la inicialización del modelo en el código del cliente, no enumeres las funciones a las que tiene acceso el modelo. En su lugar, las funciones deben aparecer en el objeto
toolsdel frontmatter de la plantilla (consulta más arriba).En el siguiente código de cliente de ejemplo, se supone que defines esquemas de funciones en la plantilla. Si decides definir el esquema en el código del cliente, se anulará el esquema definido en la plantilla. Más adelante en esta página, encontrarás una plantilla de ejemplo y un código de cliente para definir el esquema en el código del cliente.
Verifica si el modelo muestra una llamada a función como parte del cumplimiento de una solicitud. Si lo hace, tu app debe ejecutar la lógica local y, luego, enviar el resultado al modelo.
Código de cliente de ejemplo con esquema de función definido en la plantilla
Swift
For Swift, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Kotlin
// ...
// Initialize the Gemini Developer API backend service.
// Create a `TemplateGenerativeModel` instance.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.templateGenerativeModel()
// Start a chat session with a template that has functions listed as tools.
val chatSession = model.startChat(
// Specify your template ID
templateId = "my-function-calling-template-v1-0-0",
inputs = emptyMap()
)
// Send a message that might trigger a function call.
val response = chatSession.sendMessage(
content("user") { text(userMessage) }
)
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
val functionCalls = response.functionCalls
val fetchWeatherCall = functionCalls.find { it.name == "fetchWeather" }
// Forward the structured input data from the model to the hypothetical external API.
val functionResponse = fetchWeatherCall?.let {
// Alternatively, if your `Location` class is marked as @Serializable, you can use
// val location = Json.decodeFromJsonElement(it.args["location"]!!)
val location = Location(
it.args["location"]!!.jsonObject["city"]!!.jsonPrimitive.content,
it.args["location"]!!.jsonObject["state"]!!.jsonPrimitive.content
)
val date = it.args["date"]!!.jsonPrimitive.content
fetchWeather(location, date)
}
Java
For Java, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Web
// ...
// Initialize the Gemini Developer API backend service.
const ai = getAI(app, { backend: new GoogleAIBackend() });
// Create a `TemplateGenerativeModel` instance.
const model = getTemplateGenerativeModel(ai);
// Start a chat session with a template that has functions listed as tools.
const chatSession = model.startChat({
// Specify your template ID
templateId: 'my-function-calling-template-v1-0-0',
});
// Send a message that might trigger a function call.
const result = await chatSession.sendMessage(userMessage);
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
const functionCalls = result.response.functionCalls();
let functionCall;
let functionResult;
if (functionCalls.length > 0) {
for (const call of functionCalls) {
if (call.name === "fetchWeather") {
// Forward the structured input data prepared by the model
// to the hypothetical external API.
functionResult = await fetchWeather(call.args);
functionCall = call;
}
}
}
Dart
// ...
// Initialize the Gemini Developer API backend service.
// Create a `TemplateGenerativeModel` instance.
final model = FirebaseAI.googleAI().templateGenerativeModel()
// Start a chat session with a template that has functions listed as tools.
var chatSession = model.startChat(
// Specify your template ID
'my-function-calling-template-v1-0-0',
);
// Send a message that might trigger a function call.
var response = await chatSession.sendMessage(
Content.text(userMessage),
);
// Check if the model wants to call a function.
// Note that this is the same as when *not* using server prompt templates.
final functionCalls = response?.functionCalls.toList();
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls != null && functionCalls.isNotEmpty) {
for (final functionCall in functionCalls) {
if (functionCall.name == 'fetchWeather') {
Map<String, dynamic> location =
functionCall.args['location']! as Map<String, dynamic>;
var date = functionCall.args['date']! as String;
var city = location['city'] as String;
var state = location['state'] as String;
final functionResult =
await fetchWeather(Location(city, state), date);
// Send the response to the model so that it can use the result to
// generate text for the user.
response = await chatSession.sendMessage(
Content.functionResponse(functionCall.name, functionResult),
);
}
}
}
Unity
// ...
// Initialize the Gemini Developer API backend service.
var firebaseAI = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `TemplateGenerativeModel` instance.
var model = firebaseAI.GetTemplateGenerativeModel();
// Start a chat session with a template that has functions listed as tools.
var chatSession = model.StartChat(
// Specify your template ID
"my-function-calling-template-v1-0-0"
);
try
{
// Send a message that might trigger a function call.
var response = await chatSession.SendMessageAsync(ModelContent.Text(userMessage));
var functionResponses = new List();
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
foreach (var functionCall in response.FunctionCalls) {
if (functionCall.Name == "fetchWeather") {
// TODO(developer): Handle invalid arguments.
var location = functionCall.Args["location"] as Dictionary<string, object>;
var city = location["city"] as string;
var state = location["state"] as string;
var date = functionCall.Args["date"] as string;
functionResponses.Add(ModelContent.FunctionResponse(
name: functionCall.Name,
// Forward the structured input data prepared by the model
// to the hypothetical external API.
response: FetchWeather(city: city, state: state, date: date)
));
}
// TODO(developer): Handle other potential function calls, if any.
}
// Send the function responses back to the model.
var functionResponseResult = await chatSession.SendMessageAsync(functionResponses);
}
catch (Exception e) {
Debug.LogError($"An error occurred: {e.Message}");
}
Llamadas a funciones: Define el esquema en el código del cliente
Asegúrate de revisar las secciones anteriores sobre cómo funcionan las llamadas a funciones con
plantillas de instrucciones del servidor (en particular, el uso de la
{{history}} etiqueta en el contenido de la
plantilla). En esta sección, se proporciona una plantilla de ejemplo y un código de cliente si deseas definir el esquema de tu función en el código del cliente (en lugar de en la plantilla).
Ten en cuenta lo siguiente sobre la definición del esquema de la función en el código del cliente:
Si defines el esquema de una función en el código del cliente (como se muestra en el siguiente ejemplo), el esquema del cliente anulará cualquier esquema definido en la plantilla para esa función.
Para definir el esquema de la función en el código del cliente, escribe la declaración de la función y, luego, proporciona la declaración en
startChat, no durante la inicialización del modelo (que es lo que haces cuando no usas plantillas de instrucciones del servidor).Aunque la declaración de la función especifica un
name, la plantilla aún debe enumerar las funciones a las que deseas que tenga acceso el modelo. Elnamede la plantilla debe coincidir con elnamedel código del cliente.
Plantilla de ejemplo con esquema de función definido en el código del cliente
---
model: gemini-3-flash-preview
tools:
- name: fetchWeather
description: Get the weather conditions for a specific city on a specific date.
---
What was the weather like in Boston, Massachusetts on 10/17 in year 2024, formatted in CELSIUS?
{{history}}
Código de cliente de ejemplo con esquema de función definido en el código del cliente
(para obtener detalles omitidos en este ejemplo, consulta el
código de cliente de ejemplo anterior)
Swift
For Swift, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Kotlin
// ...
// Initialize your desired Gemini API backend service.
// Create a `TemplateGenerativeModel` instance.
...
// Define the schema for any functions listed in your template.
val fetchWeatherTool = functionDeclarations(
functionDeclarations = listOf(
FunctionDeclaration(
name = "fetchWeather",
description = "Returns the weather for a given location at a given time",
parameters = mapOf(
"location" to Schema.obj(
description = "The name of the city and its state for which to get the weather. Only cities in the USA are supported.",
properties = mapOf(
"city" to Schema.string(
description = "The city of the location."
),
"state" to Schema.string(
description = "The state of the location."
),
"zipCode" to Schema.string(
description = "Optional zip code of the location.",
nullable = true
)
),
optionalProperties = listOf("zipCode")
),
"date" to Schema.string(
description = "The date for which to get the weather. Date must be in the format: YYYY-MM-DD."
),
"unit" to Schema.enumeration(
description = "The temperature unit.",
values = listOf("CELSIUS", "FAHRENHEIT"),
nullable = true
)
),
optionalParameters = listOf("unit"),
)
)
)
// Start a chat session with a template that has functions listed as tools.
var chatSessionWithSchemaOverride = model.startChat(
// Specify your template ID.
templateId = "my-function-calling-template-with-no-function-schema-v1-0-0",
// In `startChat`, provide the schema for any functions listed in your template.
// This client-side schema will override any schema defined in the template.
tools = listOf(fetchWeatherTool)
)
// Send a message that might trigger a function call.
...
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
...
// Forward the structured input data from the model to the hypothetical external API.
...
Java
For Java, using server prompt templates with multi-turn interactions is not yet supported. Check back soon!
Web
// ...
// Initialize your desired Gemini API backend service.
...
// Create a `TemplateGenerativeModel` instance.
...
// Start a chat session with a template that has functions listed as tools.
const chatSessionWithSchemaOverride = model.startChat({
// Specify your template ID.
templateId: 'my-function-calling-template-with-no-function-schema-v1-0-0',
// In `startChat`, provide the schema for any functions listed in your template.
// This client-side schema will override any schema defined in the template.
tools: [
{
functionDeclarations: [
{
name: "fetchWeather",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.OBJECT,
description: "The name of the city and its state for which to get the weather. Only cities in the USA are supported.",
properties: {
city: {
type: Type.STRING,
description: "The city of the location."
},
state: {
type: Type.STRING,
description: "The state of the location."
},
zipCode: {
type: Type.INTEGER,
description: "Optional zip code of the location.",
nullable: true
},
},
required: ["city", "state"],
},
date: {
type: Type.STRING,
description: "The date for which to get the weather. Date must be in the format: YYYY-MM-DD.",
},
unit: {
type: Type.STRING,
description: "The temperature unit.",
enum: ["CELSIUS", "FAHRENHEIT"],
nullable: true,
},
},
required: ["location", "date"],
},
},
],
}
],
});
// Send a message that might trigger a function call.
...
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
...
Dart
// ...
// Initialize your desired Gemini API backend service.
// Create a `TemplateGenerativeModel` instance.
...
// Start a chat session with a template that has functions listed as tools.
final chatSessionWithSchemaOverride = model?.startChat(
// Specify your template ID.
'my-function-calling-template-with-no-function-schema-v1-0-0',
inputs: {},
// In `startChat`, provide the schema for any functions listed in your template.
// This client-side schema will override any schema defined in the template.
tools: [
TemplateTool.functionDeclarations(
[
TemplateFunctionDeclaration(
'fetchWeather',
parameters: {
'location': JSONSchema.object(
description:
'The name of the city and its state for which to get '
'the weather. Only cities in the USA are supported.',
properties: {
'city': JSONSchema.string(
description: 'The city of the location.',
),
'state': JSONSchema.string(
description: 'The state of the location.',
),
'zipCode': JSONSchema.integer(
description: 'Optional zip code of the location.',
nullable: true,
),
},
optionalProperties: ['zipCode'],
),
'date': JSONSchema.string(
description: 'The date for which to get the weather. '
'Date must be in the format: YYYY-MM-DD.',
),
'unit': JSONSchema.enumString(
enumValues: ['CELSIUS', 'FAHRENHEIT'],
description: 'The temperature unit.',
nullable: true,
),
},
optionalParameters: ['unit'],
),
],
),
],
);
// Send a message that might trigger a function call.
...
// Check if the model wants to call a function.
// Note that this is the same as when *not* using server prompt templates.
...
Unity
// ...
// Initialize your desired Gemini API backend service.
...
// Create a `TemplateGenerativeModel` instance.
...
// Define the schema for any functions listed in your template.
var fetchWeatherTool = new TemplateTool.FunctionDeclaration(
name: "fetchWeather",
parameters: new Dictionary<string, JsonSchema>() {
{ "location", JsonSchema.Object(
description: "The name of the city and its state for which to get the weather. Only cities in the USA are supported.",
properties: new Dictionary<string, JsonSchema>() {
{ "city", JsonSchema.String(description: "The city of the location.") },
{ "state", JsonSchema.String(description: "The state of the location.") },
{ "zipCode", JsonSchema.Int(description: "Optional zip code of the location.", nullable: true) }
},
optionalProperties: new[] { "zipCode" })
},
{ "date", JsonSchema.String(description: "The date for which to get the weather. Date must be in the format: YYYY-MM-DD.")},
{ "unit", JsonSchema.Enum(
values: new[] { "CELSIUS", "FAHRENHEIT" },
description: "The temperature unit.",
nullable: true)
}
},
optionalParameters: new[] { "unit" }
);
// Start a chat session with a template that has functions listed as tools.
var chatSessionWithSchemaOverride = model.StartChat(
// Specify your template ID.
templateId: "my-function-calling-template-with-no-function-schema-v1-0-0",
// In `startChat`, provide the schema for any functions listed in your template.
// This client-side schema will override any schema defined in the template.
tools: new[] { fetchWeatherTool }
);
try
{
// Send a message that might trigger a function call.
...
// When the model responds with one or more function calls, invoke the function(s).
// Note that this is the same as when *not* using server prompt templates.
...
}
// ...
Próximos pasos
Obtén información sobre las prácticas recomendadas y las consideraciones para usar plantillas de instrucciones del servidor.
Obtén detalles sobre el formato y la sintaxis de la plantilla, junto con ejemplos.
Administra plantillas, incluida la edición, el bloqueo y el control de versiones.