Wieloetapowe interakcje z szablonami promptów serwera


Ten przewodnik dotyczy wszystkich funkcji, które zależą od interakcji wieloetapowych, w tym:

Ogólne omówienie

W przypadku interakcji wieloetapowych pakiety Firebase AI Logic SDK zarządzają stanem rozmowy. Dotyczy to również korzystania z szablonów promptów serwera.

Podstawowy przepływ pracy w przypadku interakcji wieloetapowych i szablonów promptów serwera jest zasadniczo taki sam jak w przypadku żądań jednoetapowych, ale występują pewne istotne różnice:

  1. Utwórz szablon za pomocą interfejsu użytkownika z przewodnikiem w Firebase konsoli.

    W przypadku interakcji wieloetapowych musisz dodać tag {{history}} do treści szablonu, który informuje szablon, gdzie należy wstawić etapy rozmowy zarządzane przez pakiet SDK klienta.

  2. Przetestuj szablon w rzeczywistym żądaniu za pomocą funkcji testowania w konsoli Firebase.

    W przypadku interakcji wieloetapowych funkcja testowania w konsoli może pomóc tylko w testowaniu etapu początkowego. Możesz sprawdzić, jak kolejne etapy (historia) są obsługiwane przez szablon, używając szablonu w rzeczywistej aplikacji.

  3. Uzyskaj dostęp do szablonu z kodu aplikacji za pomocą templateGenerativeModel.

    W przypadku interakcji wieloetapowych musisz używać funkcji startChat i sendMessage (tak samo jak w przypadku interakcji wieloetapowych, gdy nie używasz szablonów promptów serwera).

Pamiętaj, że w przypadku wywoływania funkcji występuje kilka dodatkowych różnic, które zostały opisane w dalszej części tej strony.



Rozmowa wieloetapowa (czat)

Jeśli jeszcze tego nie zrobisz, zapoznaj się z ogólnym przewodnikiem dotyczącym tworzenia rozmów wieloetapowych (czatów) gdy nie używasz szablonów promptów serwera.

Podstawowy format szablonu promptu serwera

W przypadku Firebase AI Logic konsola Firebase udostępnia interfejs użytkownika z przewodnikiem, który umożliwia określenie nagłówka i treści szablonu.

Szablony promptów serwera używają składni i formatu opartego na Dotprompt. Więcej informacji znajdziesz w artykule Format, składnia i przykłady szablonów.

W przykładowym szablonie poniżej widać najważniejsze komponenty szablonu podczas tworzenia rozmowy wieloetapowej (czatu). Zwróć uwagę na dodanie tagu {{history}} do treści szablonu. Informuje on szablon, gdzie należy wstawić etapy rozmowy zarządzane przez pakiet SDK klienta.

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

Używanie szablonu w kodzie

Kliknij swojego dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod specyficzne dla dostawcy.

W przykładowym kodzie klienta poniżej pokazujemy, jak używać szablonu w kodzie. Zwróć uwagę na użycie templateGenerativeModel wraz z startChat i sendMessage podczas tworzenia interakcji wieloetapowych.

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



Wywoływanie funkcji

Jeśli jeszcze tego nie zrobisz, zapoznaj się z ogólnym przewodnikiem dotyczącym wywoływania funkcji gdy nie używasz szablonów promptów serwera. Ten przewodnik dotyczący używania szablonów promptów serwera zakłada, że rozumiesz, jak działa wywoływanie funkcji.

Podstawowy format szablonu promptu serwera

W przypadku Firebase AI Logic konsola Firebase udostępnia interfejs użytkownika z przewodnikiem, który umożliwia określenie nagłówka i treści szablonu.

Szablony promptów serwera używają składni i formatu opartego na Dotprompt. Więcej informacji znajdziesz w artykule Format, składnia i przykłady szablonów.

W przykładowym szablonie poniżej widać najważniejsze komponenty szablonu podczas używania wywoływania funkcji. Pamiętaj:

  • W nagłówku szablonu wymień funkcje, do których model ma dostęp, podając deklaracje funkcji w obiekcie tools.

    • Określ name (wymagane) i description (opcjonalne) dla każdej funkcji, do której model ma dostęp.

    • Określ schemat każdej funkcji, do której model ma dostęp.

      W przykładowym szablonie poniżej założono, że definiujesz schematy funkcji w szablonie. Możesz jednak podać schemat funkcji w kodzie klienta. Schemat zdefiniowany w kodzie klienta zastąpi każdy schemat zdefiniowany w szablonie. W dalszej części tej strony znajdziesz przykład a szablonu i kodu klienta do definiowania schematu w kodzie klienta.

  • W treści szablonu dodaj tag {{history}}. Informuje on szablon gdzie należy wstawić etapy rozmowy zarządzane przez pakiet SDK klienta.

Przykładowy szablon ze schematem funkcji zdefiniowanym w szablonie

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

Używanie szablonu w kodzie

Kliknij swojego dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod specyficzne dla dostawcy.

W przykładowym kodzie klienta poniżej pokazujemy, jak używać szablonu w kodzie. Pamiętaj:

  • Podczas korzystania z interakcji wieloetapowych używaj templateGenerativeModel wraz z startChat i sendMessage.

  • Podczas inicjowania modelu w kodzie klienta nie wymieniaj funkcji, do których model ma dostęp. Zamiast tego funkcje muszą być wymienione w obiekcie tools w nagłówku szablonu (patrz wyżej).

  • W przykładowym kodzie klienta poniżej założono, że definiujesz schematy funkcji w szablonie. Jeśli zamiast tego zdecydujesz się zdefiniować schemat w kodzie klienta, zastąpi on schemat zdefiniowany w szablonie. W dalszej części tej strony znajdziesz przykładowy szablon i kod klienta do definiowania schematu w kodzie klienta.

  • Sprawdź, czy model zwraca wywołanie funkcji w ramach realizacji żądania. Jeśli tak, aplikacja musi wykonać logikę lokalną, a następnie wysłać wynik z powrotem do modelu.

Przykładowy kod klienta ze schematem funkcji zdefiniowanym w szablonie

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


Wywoływanie funkcji – definiowanie schematu w kodzie klienta

Zapoznaj się z sekcjami powyżej, aby dowiedzieć się, jak działa wywoływanie funkcji z szablonami promptów serwera (w szczególności z użyciem tagu {{history}} w treści szablonu). W tej sekcji znajdziesz przykładowy szablon i kod klienta, jeśli chcesz zdefiniować schemat funkcji w kodzie klienta (zamiast w szablonie).

Pamiętaj o tych kwestiach dotyczących definiowania schematu funkcji w kodzie klienta:

  • Jeśli zdefiniujesz schemat funkcji w kodzie klienta (jak pokazano w przykładzie poniżej), schemat po stronie klienta zastąpi każdy schemat zdefiniowany w szablonie dla tej funkcji.

  • Aby zdefiniować schemat funkcji w kodzie klienta, napisz deklarację funkcji a następnie podaj deklarację w startChat, nie podczas inicjowania modelu (tak jak to robisz, gdy nie używasz szablonów promptów serwera).

  • Nawet jeśli deklaracja funkcji określa name, szablon musi nadal zawierać listę funkcji, do których model ma mieć dostęp. name w szablonie musi być zgodne z name w kodzie klienta.

Przykładowy szablon ze schematem funkcji zdefiniowanym w kodzie klienta

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

Przykładowy kod klienta ze schematem funkcji zdefiniowanym w kodzie klienta
(szczegóły pominięte w tym przykładzie znajdziesz w przykładowym kodzie klienta powyżej)

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

// ...



Co dalej?