Ce guide s'applique à toutes les fonctionnalités qui dépendent des interactions multitours, y compris :
Conversation multitour (chat), y compris le chat avec sortie de texte uniquement et la retouche d'images itérative
Vue d'ensemble
Pour les interactions multitours, les SDK Firebase AI Logic gèrent l'état de la conversation. Cela s'applique également lorsque vous utilisez des modèles de prompts côté serveur.
Le workflow de base pour les interactions multitours et les modèles d'invite de serveur est fondamentalement le même que pour les requêtes monotours, avec quelques différences importantes :
Créez le modèle à l'aide de l'UI guidée dans la console Firebase.
Pour les interactions multitours, vous devez ajouter la balise
{{history}}dans le contenu du modèle. Elle indique au modèle où insérer les tours de conversation gérés par le SDK client.Testez le modèle dans une requête réelle à l'aide de l'outil de test de la console Firebase.
Pour les interactions multitours, l'expérience de test de la console ne peut vous aider qu'à tester le premier tour. Vous pouvez tester la façon dont les tours suivants (l'historique) sont gérés en utilisant le modèle avec votre application.
Accédez au modèle à partir du code de votre application à l'aide de
templateGenerativeModel.Pour les interactions multitours, vous devez utiliser
startChatetsendMessage(comme vous le faites pour les interactions multitours lorsque vous n'utilisez pas de modèles d'invite de serveur).
Notez que pour l'appel de fonction, il existe quelques différences supplémentaires, qui sont décrites dans cette section plus loin sur cette page.
Conversation multitour (chat)
Si vous ne l'avez pas déjà fait, consultez le guide général pour créer des conversations multitours (chat) lorsque vous n'utilisez pas de modèles de prompts côté serveur.
Format de base d'un modèle de prompt côté serveur
Pour Firebase AI Logic, la console Firebase fournit une interface utilisateur guidée qui vous permet de spécifier le contenu et le frontmatter du modèle.
Les modèles de prompts côté serveur utilisent une syntaxe et un format basés sur Dotprompt. Pour en savoir plus, consultez Format, syntaxe et exemples de modèles.
L'exemple de modèle ci-dessous montre les composants les plus importants d'un modèle lors de la création d'une conversation multitour (chat). Notez l'ajout de la balise {{history}} dans le contenu du modèle, qui indique au modèle où insérer les tours de conversation gérés par le SDK client.
---
model: 'gemini-3.5-flash'
---
{{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}}
Utiliser votre modèle dans le code
|
Cliquez sur votre fournisseur Gemini API pour afficher le contenu et le code spécifiques à ce fournisseur sur cette page. |
L'exemple de code client ci-dessous montre comment utiliser le modèle dans votre code. Notez l'utilisation de templateGenerativeModel avec startChat et sendMessage lors de la création d'interactions multitours.
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}");
}
Appel de fonction
Si vous ne l'avez pas déjà fait, consultez le guide général sur l'appel de fonctions lorsque vous n'utilisez pas de modèles de prompts côté serveur. Ce guide sur l'utilisation des modèles d'invite de serveur suppose que vous comprenez le fonctionnement général de l'appel de fonction.
Format de base d'un modèle de prompt côté serveur
Pour Firebase AI Logic, la console Firebase fournit une interface utilisateur guidée qui vous permet de spécifier le contenu et le frontmatter du modèle.
Les modèles de prompts côté serveur utilisent une syntaxe et un format basés sur Dotprompt. Pour en savoir plus, consultez Format, syntaxe et exemples de modèles.
L'exemple de modèle ci-dessous montre les composants les plus importants d'un modèle lors de l'utilisation de l'appel de fonction. Veuillez noter les points suivants :
Dans le frontmatter du modèle, listez les fonctions auxquelles le modèle a accès en fournissant des déclarations de fonctions dans l'objet
tools.Définissez
name(obligatoire) etdescription(facultatif) pour chaque fonction à laquelle le modèle a accès.Définissez le schéma de chaque fonction à laquelle le modèle a accès.
L'exemple de modèle ci-dessous suppose que vous définissez des schémas de fonctions dans le modèle. Toutefois, vous pouvez fournir le schéma de la fonction dans le code client. Le schéma défini dans le code client remplacera tout schéma défini dans le modèle. Plus loin sur cette page, vous trouverez un exemple de code de modèle et de client pour définir un schéma dans le code client.
Dans le contenu du modèle, ajoutez la balise
{{history}}, qui indique au modèle où insérer les tours de conversation gérés par le SDK client.
Exemple de modèle avec un schéma de fonction défini dans le modèle
---
model: gemini-3.5-flash
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}}
Utiliser votre modèle dans le code
|
Cliquez sur votre fournisseur Gemini API pour afficher le contenu et le code spécifiques à ce fournisseur sur cette page. |
L'exemple de code client ci-dessous montre comment utiliser le modèle dans votre code. Veuillez noter les points suivants :
Utilisez
templateGenerativeModelavecstartChatetsendMessagelorsque vous utilisez des interactions multitours.Lors de l'initialisation du modèle dans votre code client, ne listez pas les fonctions auxquelles le modèle a accès. Les fonctions doivent plutôt être listées dans l'objet
toolsde la section "frontmatter" du modèle (voir ci-dessus).L'exemple de code client ci-dessous suppose que vous définissez des schémas de fonction dans le modèle. Si vous décidez de définir le schéma dans votre code client, il remplacera le schéma défini dans le modèle. Plus loin sur cette page, vous trouverez un exemple de modèle et de code client pour définir un schéma dans le code client.
Vérifiez si le modèle renvoie un appel de fonction pour répondre à une requête. Si c'est le cas, votre application doit exécuter la logique locale, puis renvoyer le résultat au modèle.
Exemple de code client avec un schéma de fonction défini dans le modèle
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}");
}
Appel de fonction : définir le schéma dans le code client
Assurez-vous de consulter les sections ci-dessus sur le fonctionnement des appels de fonction avec les modèles de requêtes serveur (en particulier l'utilisation de la balise {{history}} dans le contenu du modèle). Cette section fournit un exemple de modèle et de code client si vous souhaitez définir le schéma de votre fonction dans le code client (au lieu de le faire dans le modèle).
Notez les points suivants concernant la définition du schéma de fonction dans le code client :
Si vous définissez le schéma d'une fonction dans votre code client (comme indiqué dans l'exemple ci-dessous), le schéma côté client remplacera tout schéma défini par le modèle pour cette fonction.
Pour définir le schéma de la fonction dans le code client, écrivez la déclaration de la fonction, puis fournissez la déclaration dans
startChat, et non lors de l'initialisation du modèle (ce que vous faites lorsque vous n'utilisez pas de modèles d'invite de serveur).Même si la déclaration de fonction spécifie un
name, le modèle doit toujours lister les fonctions auxquelles vous souhaitez que le modèle ait accès. Lenamedu modèle doit correspondre aunamedu code client.
Exemple de modèle avec un schéma de fonction défini dans le code client
---
model: gemini-3.5-flash
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}}
Exemple de code client avec un schéma de fonction défini dans le code client
(pour en savoir plus sur les détails omis dans cet exemple, consultez l'exemple de code client ci-dessus)
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.
...
}
// ...
Étape suivante
Découvrez les bonnes pratiques et les points à prendre en compte pour utiliser les modèles de prompts côté serveur.
Découvrez en détail le format et la syntaxe des modèles, ainsi que des exemples.
Gérer les modèles, y compris les modifier, les verrouiller et contrôler les versions