Panduan ini berlaku untuk semua kemampuan yang bergantung pada interaksi multi-turn, termasuk:
Percakapan multi-giliran (chat), termasuk chat khusus output teks dan pengeditan gambar secara berulang
Ringkasan umum
Untuk interaksi multi-giliran, SDK Firebase AI Logic mengelola status percakapan. Hal ini juga berlaku saat menggunakan template perintah server.
Alur kerja dasar untuk interaksi multi-turn dan template prompt server pada dasarnya sama dengan permintaan single-turn, dengan beberapa perbedaan penting:
Buat template menggunakan UI terpandu di konsol Firebase.
Untuk interaksi multi-giliran, Anda harus menambahkan tag
{{history}}dalam konten template, yang memberi tahu template tempat untuk menyisipkan giliran percakapan yang dikelola oleh SDK klien.Uji template dalam permintaan sebenarnya menggunakan pengalaman pengujian di konsol Firebase.
Untuk interaksi multi-giliran, pengalaman pengujian konsol hanya dapat membantu menguji giliran awal. Anda dapat menguji cara penanganan giliran berikutnya (histori) dengan menggunakan template dengan aplikasi sebenarnya.
Akses template dari kode aplikasi Anda menggunakan
templateGenerativeModel.Untuk interaksi multi-turn, Anda harus menggunakan
startChatdansendMessage(seperti yang Anda lakukan untuk interaksi multi-turn saat tidak menggunakan template prompt server).
Perhatikan bahwa untuk panggilan fungsi, ada beberapa perbedaan lagi, yang dijelaskan di bagian tersebut nanti di halaman ini.
Percakapan multi-giliran (chat)
Jika belum, tinjau panduan umum untuk membangun percakapan multi-giliran (chat) saat tidak menggunakan template perintah server.
Format dasar template perintah server
Untuk Firebase AI Logic, konsol Firebase menyediakan UI terpandu bagi Anda untuk menentukan frontmatter dan konten template.
Template perintah server menggunakan sintaksis dan format berbasis Dotprompt. Untuk mengetahui detail selengkapnya, lihat Format, sintaksis, dan contoh template.
Template contoh di bawah menunjukkan komponen terpenting untuk template
saat membangun percakapan multi-turn (chat). Perhatikan penambahan tag
{{history}} dalam konten template,
yang memberi tahu template tempat untuk menyisipkan giliran percakapan yang dikelola oleh
SDK klien.
---
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}}
Menggunakan template dalam kode
|
Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini. |
Contoh kode klien di bawah menunjukkan cara menggunakan template dalam kode Anda. Perhatikan
penggunaan templateGenerativeModel bersama dengan startChat dan sendMessage
saat membuat interaksi multi-giliran.
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}");
}
Panggilan fungsi
Jika belum, tinjau panduan umum untuk panggilan fungsi saat tidak menggunakan template perintah server. Panduan tentang penggunaan template perintah server ini mengasumsikan bahwa Anda memahami cara kerja panggilan fungsi secara umum.
Format dasar template perintah server
Untuk Firebase AI Logic, konsol Firebase menyediakan UI terpandu bagi Anda untuk menentukan frontmatter dan konten template.
Template perintah server menggunakan sintaksis dan format berbasis Dotprompt. Untuk mengetahui detail selengkapnya, lihat Format, sintaksis, dan contoh template.
Template contoh di bawah menunjukkan komponen terpenting untuk template saat menggunakan panggilan fungsi. Perhatikan hal berikut:
Di frontmatter template, cantumkan fungsi yang dapat diakses model dengan memberikan deklarasi fungsi dalam objek
tools.Tentukan
name(wajib) dandescription(opsional) untuk setiap fungsi yang dapat diakses model.Tentukan skema untuk setiap fungsi yang dapat diakses model.
Contoh template di bawah ini mengasumsikan bahwa Anda menentukan skema fungsi dalam template. Namun, Anda dapat memberikan skema fungsi di kode klien. Skema yang ditentukan dalam kode klien akan menggantikan skema apa pun yang ditentukan dalam template. Di bagian selanjutnya dalam halaman ini, temukan contoh template dan kode klien untuk menentukan skema dalam kode klien.
Di konten template, tambahkan tag
{{history}}, yang memberi tahu template tempat untuk menyisipkan giliran percakapan yang dikelola oleh SDK klien.
Contoh template dengan skema fungsi yang ditentukan dalam template
---
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}}
Menggunakan template dalam kode
|
Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini. |
Contoh kode klien di bawah menunjukkan cara menggunakan template dalam kode Anda. Perhatikan hal berikut:
Gunakan
templateGenerativeModelbersama denganstartChatdansendMessagesaat menggunakan interaksi multi-turn.Selama inisialisasi model dalam kode klien, jangan mencantumkan fungsi yang dapat diakses model. Sebagai gantinya, fungsi harus dicantumkan dalam objek
toolsfrontmatter template (lihat di atas).Contoh kode klien di bawah ini mengasumsikan bahwa Anda menentukan skema fungsi dalam template. Jika Anda memutuskan untuk menentukan skema dalam kode klien, skema tersebut akan menggantikan skema yang ditentukan template. Di bagian selanjutnya dalam halaman ini, lihat contoh template dan kode klien untuk menentukan skema dalam kode klien.
Periksa apakah model menampilkan panggilan fungsi sebagai bagian dari pemenuhan permintaan. Jika ya, aplikasi Anda perlu menjalankan logika lokal, lalu mengirimkan hasilnya kembali ke model.
Contoh kode klien dengan skema fungsi yang ditentukan dalam template
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}");
}
Panggilan fungsi - menentukan skema dalam kode klien
Pastikan untuk meninjau bagian di atas tentang cara kerja panggilan fungsi dengan
template perintah server (khususnya, penggunaan tag
{{history}} dalam konten
template). Bagian ini memberikan contoh template dan kode klien jika Anda ingin menentukan skema fungsi dalam kode klien (bukan dalam template).
Perhatikan hal-hal berikut tentang menentukan skema fungsi dalam kode klien:
Jika Anda menentukan skema fungsi dalam kode klien (seperti yang ditunjukkan dalam contoh di bawah), skema sisi klien akan menggantikan skema yang ditentukan template untuk fungsi tersebut.
Untuk menentukan skema fungsi dalam kode klien, tulis deklarasi fungsi lalu berikan deklarasi dalam
startChat, bukan selama inisialisasi model (yang Anda lakukan saat tidak menggunakan template perintah server).Meskipun deklarasi fungsi menentukan
name, template tetap harus mencantumkan fungsi yang ingin Anda akses oleh model.namedalam template harus cocok dengannamedalam kode klien.
Contoh template dengan skema fungsi yang ditentukan dalam kode klien
---
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}}
Contoh kode klien dengan skema fungsi yang ditentukan dalam kode klien
(untuk detail yang tidak disertakan dalam contoh ini, lihat
contoh kode klien di atas)
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.
...
}
// ...
Apa langkah selanjutnya?
Pelajari praktik terbaik dan pertimbangan untuk menggunakan template perintah server.
Pelajari detail tentang format dan sintaksis template, beserta contohnya.
Mengelola template, termasuk mengedit, mengunci, dan kontrol versi.