Interaktionen mit mehreren Durchgängen mit Server-Promptvorlagen


Dieser Leitfaden gilt für alle Funktionen, die auf Multi-Turn-Interaktionen basieren, einschließlich:

Gesamtübersicht

Bei Multi-Turn-Interaktionen verwalten die Firebase AI Logic SDKs den Status der Unterhaltung. Das gilt auch für die Verwendung von Server-Promptvorlagen.

Der grundlegende Workflow für Multi-Turn-Interaktionen und Server-Promptvorlagen ist im Wesentlichen derselbe wie für Single-Turn-Anfragen, es gibt jedoch einige wichtige Unterschiede:

  1. Erstellen Sie die Vorlage über die geführte UI in der Firebase Konsole.

    Bei Multi-Turn-Interaktionen müssen Sie das {{history}} Tag in den Inhalt der Vorlage einfügen, wodurch der Vorlage mitgeteilt wird, wo die von dem Client-SDK verwalteten Unterhaltungsrunden eingefügt werden sollen.

  2. Testen Sie die Vorlage in einer echten Anfrage mit der Testfunktion in der Firebase Konsole.

    Bei Multi-Turn-Interaktionen kann die Testfunktion in der Konsole nur zum Testen der ersten Runde verwendet werden. Sie können testen, wie nachfolgende Runden (der Verlauf) verarbeitet werden, indem Sie die Vorlage mit Ihrer tatsächlichen App verwenden.

  3. Greifen Sie über templateGenerativeModel auf die Vorlage im Code Ihrer App zu.

    Bei Multi-Turn-Interaktionen müssen Sie startChat und sendMessage verwenden, genau wie bei Multi-Turn-Interaktionen, wenn Sie keine Server-Promptvorlagen verwenden.

Bei Funktionsaufrufen gibt es einige weitere Unterschiede, die später auf dieser Seite beschrieben werden.



Multi-Turn-Unterhaltung (Chat)

Wenn Sie es noch nicht getan haben, lesen Sie den allgemeinen Leitfaden zum Erstellen von Multi-Turn-Unterhaltungen (Chat) wenn Sie keine Server-Promptvorlagen verwenden.

Grundlegendes Format einer Server-Promptvorlage

Für Firebase AI Logic, die Firebase Konsole bietet eine geführte UI, mit der Sie die Frontmatter und den Inhalt der Vorlage angeben können.

Server-Promptvorlagen verwenden eine auf Dotprompt basierende Syntax und ein entsprechendes Format. Weitere Informationen finden Sie unter Vorlagenformat, -syntax und -beispiele.

Die folgende Beispielvorlage zeigt die wichtigsten Komponenten einer Vorlage zum Erstellen einer Multi-Turn-Unterhaltung (Chat). Beachten Sie das Tag {{history}} im Inhalt der Vorlage, das der Vorlage mitteilt, wo die vom Client-SDK verwalteten Unterhaltungsrunden eingefügt werden sollen.

---
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}}

Vorlage im Code verwenden

Klicken Sie auf Ihren Gemini API Anbieter, um anbieterspezifische Inhalte und Code auf dieser Seite aufzurufen.

Der folgende Beispielcode für den Client zeigt, wie Sie die Vorlage in Ihrem Code verwenden. Beachten Sie die Verwendung von templateGenerativeModel zusammen mit startChat und sendMessage beim Erstellen von Multi-Turn-Interaktionen.

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}");
}



Funktionsaufrufe

Wenn Sie es noch nicht getan haben, lesen Sie den allgemeinen Leitfaden zu Funktionsaufrufen wenn Sie keine Server-Promptvorlagen verwenden. Dieser Leitfaden zur Verwendung von Server-Promptvorlagen setzt voraus, dass Sie die allgemeine Funktionsweise von Funktionsaufrufen verstehen.

Grundlegendes Format einer Server-Promptvorlage

Für Firebase AI Logic, die Firebase Konsole bietet eine geführte UI, mit der Sie die Frontmatter und den Inhalt der Vorlage angeben können.

Server-Promptvorlagen verwenden eine auf Dotprompt basierende Syntax und ein entsprechendes Format. Weitere Informationen finden Sie unter Vorlagenformat, -syntax und -beispiele.

Die folgende Beispielvorlage zeigt die wichtigsten Komponenten einer Vorlage bei Verwendung von Funktionsaufrufen. Beachten Sie Folgendes:

  • Listen Sie in der Frontmatter der Vorlage die Funktionen auf, auf die das Modell Zugriff hat, indem Sie Funktionsdeklarationen im Objekt tools angeben.

    • Definieren Sie name (erforderlich) und description (optional) für jede Funktion, auf die das Modell Zugriff hat.

    • Definieren Sie das Schema für jede Funktion, auf die das Modell Zugriff hat.

      In dieser Beispielvorlage wird davon ausgegangen, dass Sie Funktionsschemas in der Vorlage definieren. Sie können das Schema der Funktion aber auch im Clientcode angeben. Im Clientcode definierte Schemas überschreiben alle in der Vorlage definierten Schemas. Weiter unten auf dieser Seite finden Sie ein Beispiel für eine Vorlage und Clientcode zum Definieren eines Schemas im Clientcode.

  • Fügen Sie im Inhalt der Vorlage das {{history}} Tag ein. Dadurch wird der Vorlage mitgeteilt, wo die vom Client-SDK verwalteten Unterhaltungsrunden eingefügt werden sollen.

Beispielvorlage mit in der Vorlage definiertem Funktionsschema

---
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}}

Vorlage im Code verwenden

Klicken Sie auf Ihren Gemini API Anbieter, um anbieterspezifische Inhalte und Code auf dieser Seite aufzurufen.

Der folgende Beispielcode für den Client zeigt, wie Sie die Vorlage in Ihrem Code verwenden. Beachten Sie Folgendes:

  • Verwenden Sie templateGenerativeModel zusammen mit startChat und sendMessage bei Multi-Turn-Interaktionen.

  • Listen Sie bei der Initialisierung des Modells in Ihrem Clientcode nicht die Funktionen auf, auf die das Modell Zugriff hat. Stattdessen müssen Funktionen im Objekt tools der Frontmatter der Vorlage aufgeführt werden (siehe oben).

  • In diesem Beispielcode für den Client wird davon ausgegangen, dass Sie Funktionsschemas in der Vorlage definieren. Wenn Sie stattdessen ein Schema in Ihrem Clientcode definieren, überschreibt es das in der Vorlage definierte Schema. Weiter unten auf dieser Seite finden Sie eine Beispielvorlage und Clientcode zum Definieren eines Schemas im Clientcode.

  • Prüfen Sie, ob das Modell einen Funktionsaufruf als Teil der Erfüllung einer Anfrage zurückgibt. Wenn dies der Fall ist, muss Ihre App die lokale Logik ausführen und das Ergebnis dann an das Modell zurücksenden.

Beispielcode für den Client mit in der Vorlage definiertem Funktionsschema

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}");
}


Funktionsaufrufe – Schema im Clientcode definieren

Lesen Sie die obigen Abschnitte zur Funktionsweise von Funktionsaufrufen mit Server-Promptvorlagen (insbesondere zur Verwendung des {{history}} Tags im Inhalt der Vorlage). In diesem Abschnitt finden Sie eine Beispielvorlage und Clientcode, wenn Sie Ihr Funktionsschema im Clientcode (anstatt in der Vorlage) definieren möchten.

Beachten Sie Folgendes zum Definieren eines Funktionsschemas im Clientcode:

  • Wenn Sie das Schema einer Funktion in Ihrem Clientcode definieren (wie im folgenden Beispiel gezeigt), überschreibt das clientseitige Schema alle in der Vorlage definierten Schemas für diese Funktion.

  • Um das Funktionsschema im Clientcode zu definieren, schreiben Sie die Funktionsdeklaration und dann geben Sie die Deklaration in startChatan, nicht während der Modellinitialisierung (wie Sie es tun, wenn Sie keine Server-Promptvorlagen verwenden).

  • Obwohl die Funktionsdeklaration einen name angibt, müssen in der Vorlage trotzdem die Funktionen aufgeführt sein, auf die das Modell Zugriff haben soll. Der name in der Vorlage muss mit dem name im Clientcode übereinstimmen.

Beispielvorlage mit im Clientcode definiertem Funktionsschema

---
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}}

Beispielcode für den Client mit im Clientcode definiertem Funktionsschema
(Details, die in diesem Beispiel ausgelassen wurden, finden Sie im Beispielcode für den Client oben)

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.
  ...
}

// ...



Nächste Schritte