Questa guida si applica a qualsiasi funzionalità che dipende da interazioni a più turni, tra cui:
Conversazione a più turni (chat), inclusa la chat con solo output di testo e la modifica iterativa delle immagini
Panoramica generale
Per le interazioni multi-turno, gli SDK Firebase AI Logic gestiscono lo stato della conversazione. Questo vale anche quando utilizzi i template di prompt del server.
Il flusso di lavoro di base per le interazioni multi-turn e i template di prompt del server è fondamentalmente lo stesso delle richieste single-turn, con alcune importanti differenze:
Crea il template utilizzando la UI guidata nella consoleFirebase.
Per le interazioni multi-turno, devi aggiungere il tag
{{history}}nei contenuti del template, che indica al template dove inserire i turni di conversazione gestiti dall'SDK client.Testa il template in una richiesta reale utilizzando l'esperienza di test nella console Firebase.
Per le interazioni in più passaggi, l'esperienza di test della console può aiutare solo a testare il passaggio iniziale. Puoi testare il modo in cui i turni successivi (la cronologia) vengono gestiti utilizzando il template con la tua app effettiva.
Accedi al template dal codice della tua app utilizzando
templateGenerativeModel.Per le interazioni multi-turn, devi utilizzare
startChatesendMessage(proprio come fai per le interazioni multi-turn quando non utilizzi i template di prompt del server).
Tieni presente che per la chiamata di funzione esistono alcune altre differenze, descritte nella sezione corrispondente più avanti in questa pagina.
Conversazione a più turni (chat)
Se non l'hai ancora fatto, consulta la guida generale per la creazione di conversazioni multi-turno (chat) quando non utilizzi i template di prompt del server.
Formato di base di un template di prompt del server
Per Firebase AI Logic, la consoleFirebase fornisce un'interfaccia utente guidata per specificare il frontmatter e i contenuti del template.
I template di prompt del server utilizzano una sintassi e un formato basati su Dotprompt. Per maggiori dettagli, consulta Formato, sintassi ed esempi dei modelli.
Il modello di esempio riportato di seguito mostra i componenti più importanti per un modello durante la creazione di una conversazione a più turni (chat). Tieni presente l'aggiunta del tag {{history}} nei contenuti del template, che indica al template dove inserire i turni di conversazione gestiti dall'SDK client.
---
model: 'gemini-3.8-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}}
Utilizza il template nel codice
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Il codice client di esempio riportato di seguito mostra come utilizzare il modello nel codice. Tieni presente l'utilizzo di templateGenerativeModel insieme a startChat e sendMessage durante la creazione di interazioni a più turni.
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
// ...
// Initialize the Gemini Developer API backend service
// Create a `TemplateGenerativeModel` instance.
TemplateGenerativeModel templateModel = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.templateGenerativeModel();
// Initialize TemplateChat with history and inputs
TemplateChat templateChat = templateModel.startChat(
// Specify your template ID.
"my-chat-template-v1-0-0",
Map.of(),
Collections.emptyList()
);
TemplateChatFutures chatFutures = TemplateChatFutures.from(templateChat);
// Send messages.
// The template's system instructions and model config apply to every turn automatically.
// The SDK automatically manages the state of the conversation.
Content prompt = new Content.Builder().addText("I need a copy of my invoice.").build();
ListenableFuture responseFuture = chatFutures.sendMessage(prompt);
Futures.addCallback(responseFuture, new FutureCallback() {
@Override
public void onSuccess(GenerateContentResponse result) {
System.out.println("Response: " + result.getText());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
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',
templateVariables: {},
});
// 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.
'my-chat-template-v1-0-0',
inputs: {},
);
// 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}");
}
Chiamata di funzione
Se non l'hai ancora fatto, consulta la guida generale per la chiamata di funzione quando non utilizzi i template di prompt del server. Questa guida sull'utilizzo dei template di prompt del server presuppone che tu comprenda il funzionamento generale delle chiamate di funzione.
Formato di base di un template di prompt del server
Per Firebase AI Logic, la consoleFirebase fornisce un'interfaccia utente guidata per specificare il frontmatter e i contenuti del template.
I template di prompt del server utilizzano una sintassi e un formato basati su Dotprompt. Per maggiori dettagli, consulta Formato, sintassi ed esempi dei modelli.
Il modello di esempio riportato di seguito mostra i componenti più importanti di un modello quando si utilizza la chiamata di funzione. Tieni presente quanto segue:
Nel frontmatter del template, elenca le funzioni a cui il modello ha accesso fornendo le dichiarazioni delle funzioni nell'oggetto
tools.Definisci
name(obbligatorio) edescription(facoltativo) per ogni funzione a cui il modello ha accesso.Definisci lo schema per ogni funzione a cui il modello ha accesso.
Il modello di esempio riportato di seguito presuppone che tu stia definendo gli schemi delle funzioni nel modello. Tuttavia, puoi fornire lo schema della funzione nel codice client. Lo schema definito nel codice client eseguirà l'override di qualsiasi schema definito nel modello. Più avanti in questa pagina, troverai un esempio di un modello e di un codice client per la definizione dello schema nel codice client.
Nel contenuto del template, aggiungi il tag
{{history}}, che indica al template dove inserire i turni di conversazione gestiti dall'SDK client.
Modello di esempio con schema della funzione definito nel modello
---
model: gemini-3.8-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}}
Utilizza il template nel codice
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Il codice client di esempio riportato di seguito mostra come utilizzare il modello nel codice. Tieni presente quanto segue:
Utilizza
templateGenerativeModelinsieme astartChatesendMessagequando utilizzi interazioni a più turni.Durante l'inizializzazione del modello nel codice client, non elencare le funzioni a cui il modello ha accesso. Le funzioni devono invece essere elencate nell'oggetto
toolsdel frontmatter del template (vedi sopra).Il seguente codice client di esempio presuppone che tu stia definendo gli schemi delle funzioni nel template. Se invece decidi di definire lo schema nel codice client, questo eseguirà l'override dello schema definito dal template. Più avanti in questa pagina, troverai un esempio di modello e codice client per la definizione dello schema nel codice client.
Controlla se il modello restituisce una chiamata di funzione nell'ambito dell'evasione di una richiesta. In questo caso, l'app deve eseguire la logica locale e poi inviare il risultato al modello.
Esempio di codice client con schema della funzione definito nel 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
// ...
// Initialize the Gemini Developer API backend service.
// Create a `TemplateGenerativeModel` instance.
TemplateGenerativeModel model = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.templateGenerativeModel();
// Start a chat session with a template that has functions listed as tools.
TemplateChat chatSession = model.startChat(
// Specify your template ID.
"my-function-calling-template-v1-0-0",
Map.of(), // Inputs
List.of() // History
);
TemplateChatFutures chatFutures = TemplateChatFutures.from(chatSession);
// Send a message that might trigger a function call.
Content prompt = new Content.Builder().addText(userMessage).build();
ListenableFuture responseFuture = chatFutures.sendMessage(prompt);
Futures.addCallback(responseFuture, new FutureCallback() {
@Override
public void onSuccess(GenerateContentResponse result) {
// 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.
for (FunctionCallPart callPart : result.getFunctionCalls()) {
if ("fetchWeather".equals(callPart.getName())) {
// Forward the structured input data from the model to the hypothetical external API.
JsonObject location = (JsonObject) callPart.getArgs().get("location");
String city = ((JsonPrimitive) location.get("city")).getContent();
String state = ((JsonPrimitive) location.get("state")).getContent();
String date = ((JsonPrimitive) callPart.getArgs().get("date")).getContent();
Object response = fetchWeather(city, state, date);
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
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',
templateVariables: {},
});
// 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',
inputs: {},
);
// 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}");
}
Chiamata di funzione: definisci lo schema nel codice client
Assicurati di leggere le sezioni precedenti su come funziona la chiamata di funzione con i template di prompt del server (in particolare, l'utilizzo del tag {{history}} nel contenuto del template). Questa sezione fornisce un modello di esempio e un codice client se vuoi definire lo schema della funzione nel codice client (anziché nel modello).
Tieni presente quanto segue sulla definizione dello schema della funzione nel codice client:
Se definisci lo schema di una funzione nel codice client (come mostrato nell'esempio seguente), lo schema lato client eseguirà l'override di qualsiasi schema definito dal template per quella funzione.
Per definire lo schema della funzione nel codice client, scrivi la dichiarazione della funzione e poi fornisci la dichiarazione in
startChat, non durante l'inizializzazione del modello (come fai quando non utilizzi i template di prompt del server).Anche se la dichiarazione della funzione specifica un
name, il template deve comunque elencare le funzioni a cui vuoi che il modello abbia accesso.namenel modello deve corrispondere anamenel codice client.
Modello di esempio con schema di funzione definito nel codice client
---
model: gemini-3.8-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}}
Esempio di codice client con schema della funzione definito nel codice client
(per i dettagli omessi da questo esempio, vedi l'esempio di codice client riportato sopra)
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
TemplateFunctionDeclaration tool = new TemplateFunctionDeclaration(
"fetchWeather", // Name
JsonSchema.obj( // Parameters
Map.of(
"location", JsonSchema.obj(
Map.of(
"city", JsonSchema.string(
"The city of the location."
),
"state", JsonSchema.string(
"The state of the location."
),
"zipCode", JsonSchema.string(
"Optional zip code of the location",
true // Nullable
)
),
List.of("zipCode"),
""
),
"date", JsonSchema.string(
"The date for which to get the weather. Date must be in the format: YY-MM-DD."
),
"unit", JsonSchema.enumeration(
List.of("CELSIUS", "FAHRENHEIT"),
"The temperature unit.",
true // Nullable
)
)
),
JsonSchema.string(
"A description of the current weather."
)
);
// Initialize the Gemini Developer API backend service.
// Create a `TemplateGenerativeModel` instance.
TemplateGenerativeModel templateModel = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.templateGenerativeModel(
new RequestOptions(),
List.of(TemplateTool.functionDeclarations(List.of(tool), List.of()))
);
// In `startChat`, provide the schema for any functions listed in your template.
// This client-side schema will override any schema defined in the template.
TemplateChat chat = templateModel.startChat(
// Specify your template ID.
"my-function-calling-template-with-no-function-schema-v1-0-0",
Map.of(),
List.of()
);
TemplateChatFutures futures = TemplateChatFutures.from(chat);
// 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.
...
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',
templateVariables: {},
// 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: SchemaType.OBJECT,
properties: {
location: {
type: SchemaType.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: SchemaType.STRING,
description: "The city of the location."
},
state: {
type: SchemaType.STRING,
description: "The state of the location."
},
zipCode: {
type: SchemaType.INTEGER,
description: "Optional zip code of the location.",
nullable: true
},
},
required: ["city", "state"],
},
date: {
type: SchemaType.STRING,
description: "The date for which to get the weather. Date must be in the format: YYYY-MM-DD.",
},
unit: {
type: SchemaType.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 chosen 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.
...
}
// ...
Passaggi successivi
Scopri di più sulle best practice e sulle considerazioni per l'utilizzo dei template di prompt del server.
Scopri i dettagli sul formato e sulla sintassi del modello, insieme ad alcuni esempi.
Gestire i modelli, tra cui modifica, blocco e controllo della versione.