Introdução às chamadas de funções

A chamada de funções, também conhecida como utilização de ferramentas, fornece ao GML definições de ferramentas externas (por exemplo, uma função get_current_weather). Ao processar um comando, o modelo determina de forma inteligente se é necessária uma ferramenta e, se for, produz dados estruturados que especificam a ferramenta a chamar e os respetivos parâmetros (por exemplo, get_current_weather(location='Boston')). Em seguida, a sua aplicação executa esta ferramenta, envia o resultado de volta para o modelo, o que lhe permite concluir a resposta com informações dinâmicas do mundo real ou o resultado de uma ação. Isto faz a ponte entre o MDG e os seus sistemas, e expande as respetivas capacidades.

Interação de chamadas de funções 

As chamadas de funções permitem dois exemplos de utilização principais:

  • Obter dados: obtenha informações atualizadas para respostas de modelos, como o estado do tempo atual, a conversão de moeda ou dados específicos de bases de conhecimentos e APIs (RAG).

  • Tomar medidas: realizar operações externas, como enviar formulários, atualizar o estado da aplicação ou orquestrar fluxos de trabalho de agentes (por exemplo, transferências de conversas).

Para ver mais exemplos de utilização e exemplos baseados na Chamada de funções, consulte Exemplos de utilização.

Funcionalidades e limitações

Como criar uma aplicação de chamadas de funções

Para usar a chamada de funções, realize as seguintes tarefas:

  1. Enviar declarações de funções e comandos para o modelo.
  2. Forneça a saída da API ao modelo.

Passo 1: envie o comando e as declarações de funções ao modelo

Declare um Tool num formato de esquema compatível com o esquema OpenAPI. Para mais informações, consulte os exemplos de esquemas.

Os exemplos seguintes enviam um comando e uma declaração de função aos modelos Gemini.

REST

PROJECT_ID=myproject
LOCATION=us-central1
MODEL_ID=gemini-2.0-flash-001

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "functionDeclarations": [
        {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city name of the location for which to get the weather.",
                "default": {
                  "string_value": "Boston, MA"
                }
              }
            },
            "required": [
              "location"
            ]
          }
        }
      ]
    }]
  }'

Python

Pode especificar o esquema manualmente através de um dicionário Python ou automaticamente com a função auxiliar from_func. O exemplo seguinte demonstra como declarar uma função manualmente.

import vertexai
from vertexai.generative_models import (
    Content,
    FunctionDeclaration,
    GenerationConfig,
    GenerativeModel,
    Part,
    Tool,
    ToolConfig
)

# Initialize Vertex AI
# TODO(developer): Update the project
vertexai.init(project="PROJECT_ID", location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.0-flash")

# Manual function declaration
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "location": {
              "type": "string",
              "description": "The city name of the location for which to get the weather.",
              "default": {
                "string_value": "Boston, MA"
              }
           }
        },
    },
)

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)

Em alternativa, pode declarar a função automaticamente com a função auxiliar from_func, conforme mostrado no exemplo seguinte:

def get_current_weather(location: str = "Boston, MA"):
  """
  Get the current weather in a given location

  Args:
      location: The city name of the location for which to get the weather.

  """
  # This example uses a mock implementation.
  # You can define a local function or import the requests library to call an API
  return {
    "location": "Boston, MA",
    "temperature": 38,
    "description": "Partly Cloudy",
    "icon": "partly-cloudy",
    "humidity": 65,
    "wind": {
        "speed": 10,
        "direction": "NW"
    }
  }
get_current_weather_func = FunctionDeclaration.from_func(get_current_weather)

Node.js

Este exemplo demonstra um cenário de texto com uma função e um comando.

Node.js

Antes de experimentar este exemplo, siga as Node.jsinstruções de configuração no início rápido do Vertex AI com bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Node.js Vertex AI.

Para se autenticar no Vertex AI, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.0-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {role: 'user', parts: [{text: 'What is the weather in Boston?'}]},
      {
        role: 'ASSISTANT',
        parts: [
          {
            functionCall: {
              name: 'get_current_weather',
              args: {location: 'Boston'},
            },
          },
        ],
      },
      {role: 'USER', parts: functionResponseParts},
    ],
    tools: functionDeclarations,
  };
  const streamingResp = await generativeModel.generateContentStream(request);
  for await (const item of streamingResp.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

Ir

Este exemplo demonstra um cenário de texto com uma função e um comando.

Saiba como instalar ou atualizar o Go.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA gen com o Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithFuncCall shows how to submit a prompt and a function declaration to the model,
// allowing it to suggest a call to the function to fetch external data. Returning this data
// enables the model to generate a text response that incorporates the data.
func generateWithFuncCall(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	weatherFunc := &genai.FunctionDeclaration{
		Description: "Returns the current weather in a location.",
		Name:        "getCurrentWeather",
		Parameters: &genai.Schema{
			Type: "object",
			Properties: map[string]*genai.Schema{
				"location": {Type: "string"},
			},
			Required: []string{"location"},
		},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{FunctionDeclarations: []*genai.FunctionDeclaration{weatherFunc}},
		},
		Temperature: genai.Ptr(float32(0.0)),
	}

	modelName := "gemini-2.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What is the weather like in Boston?"},
		},
			Role: "user"},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	var funcCall *genai.FunctionCall
	for _, p := range resp.Candidates[0].Content.Parts {
		if p.FunctionCall != nil {
			funcCall = p.FunctionCall
			fmt.Fprint(w, "The model suggests to call the function ")
			fmt.Fprintf(w, "%q with args: %v\n", funcCall.Name, funcCall.Args)
			// Example response:
			// The model suggests to call the function "getCurrentWeather" with args: map[location:Boston]
		}
	}
	if funcCall == nil {
		return fmt.Errorf("model did not suggest a function call")
	}

	// Use synthetic data to simulate a response from the external API.
	// In a real application, this would come from an actual weather API.
	funcResp := &genai.FunctionResponse{
		Name: "getCurrentWeather",
		Response: map[string]any{
			"location":         "Boston",
			"temperature":      "38",
			"temperature_unit": "F",
			"description":      "Cold and cloudy",
			"humidity":         "65",
			"wind":             `{"speed": "10", "direction": "NW"}`,
		},
	}

	// Return conversation turns and API response to complete the model's response.
	contents = []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What is the weather like in Boston?"},
		},
			Role: "user"},
		{Parts: []*genai.Part{
			{FunctionCall: funcCall},
		}},
		{Parts: []*genai.Part{
			{FunctionResponse: funcResp},
		}},
	}

	resp, err = client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// The weather in Boston is cold and cloudy with a temperature of 38 degrees Fahrenheit. The humidity is ...

	return nil
}

C#

Este exemplo demonstra um cenário de texto com uma função e um comando.

C#

Antes de experimentar este exemplo, siga as C#instruções de configuração no início rápido do Vertex AI com bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API C# Vertex AI.

Para se autenticar no Vertex AI, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.


using Google.Cloud.AIPlatform.V1;
using System;
using System.Threading.Tasks;
using Type = Google.Cloud.AIPlatform.V1.Type;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class FunctionCalling
{
    public async Task<string> GenerateFunctionCall(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-2.0-flash-001")
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Define the user's prompt in a Content object that we can reuse in
        // model calls
        var userPromptContent = new Content
        {
            Role = "USER",
            Parts =
            {
                new Part { Text = "What is the weather like in Boston?" }
            }
        };

        // Specify a function declaration and parameters for an API request
        var functionName = "get_current_weather";
        var getCurrentWeatherFunc = new FunctionDeclaration
        {
            Name = functionName,
            Description = "Get the current weather in a given location",
            Parameters = new OpenApiSchema
            {
                Type = Type.Object,
                Properties =
                {
                    ["location"] = new()
                    {
                        Type = Type.String,
                        Description = "Get the current weather in a given location"
                    },
                    ["unit"] = new()
                    {
                        Type = Type.String,
                        Description = "The unit of measurement for the temperature",
                        Enum = {"celsius", "fahrenheit"}
                    }
                },
                Required = { "location" }
            }
        };

        // Send the prompt and instruct the model to generate content using the tool that you just created
        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0f
            },
            Contents =
            {
                userPromptContent
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        var functionCall = response.Candidates[0].Content.Parts[0].FunctionCall;
        Console.WriteLine(functionCall);

        string apiResponse = "";

        // Check the function name that the model responded with, and make an API call to an external system
        if (functionCall.Name == functionName)
        {
            // Extract the arguments to use in your API call
            string locationCity = functionCall.Args.Fields["location"].StringValue;

            // Here you can use your preferred method to make an API request to
            // fetch the current weather

            // In this example, we'll use synthetic data to simulate a response
            // payload from an external API
            apiResponse = @"{ ""location"": ""Boston, MA"",
                    ""temperature"": 38, ""description"": ""Partly Cloudy""}";
        }

        // Return the API response to Gemini so it can generate a model response or request another function call
        generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                userPromptContent, // User prompt
                response.Candidates[0].Content, // Function call response,
                new Content
                {
                    Parts =
                    {
                        new Part
                        {
                            FunctionResponse = new()
                            {
                                Name = functionName,
                                Response = new()
                                {
                                    Fields =
                                    {
                                        { "content", new Value { StringValue = apiResponse } }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);

        return responseText;
    }
}

Java

Java

Antes de experimentar este exemplo, siga as Javainstruções de configuração no início rápido do Vertex AI com bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Java Vertex AI.

Para se autenticar no Vertex AI, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.FunctionDeclaration;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.Schema;
import com.google.cloud.vertexai.api.Tool;
import com.google.cloud.vertexai.api.Type;
import com.google.cloud.vertexai.generativeai.ChatSession;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class FunctionCalling {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-2.0-flash-001";

    String promptText = "What's the weather like in Paris?";

    whatsTheWeatherLike(projectId, location, modelName, promptText);
  }

  // A request involving the interaction with an external tool
  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (VertexAI vertexAI = new VertexAI(projectId, location)) {

      FunctionDeclaration functionDeclaration = FunctionDeclaration.newBuilder()
          .setName("getCurrentWeather")
          .setDescription("Get the current weather in a given location")
          .setParameters(
              Schema.newBuilder()
                  .setType(Type.OBJECT)
                  .putProperties("location", Schema.newBuilder()
                      .setType(Type.STRING)
                      .setDescription("location")
                      .build()
                  )
                  .addRequired("location")
                  .build()
          )
          .build();

      System.out.println("Function declaration:");
      System.out.println(functionDeclaration);

      // Add the function to a "tool"
      Tool tool = Tool.newBuilder()
          .addFunctionDeclarations(functionDeclaration)
          .build();

      // Start a chat session from a model, with the use of the declared function.
      GenerativeModel model = new GenerativeModel(modelName, vertexAI)
          .withTools(Arrays.asList(tool));
      ChatSession chat = model.startChat();

      System.out.println(String.format("Ask the question: %s", promptText));
      GenerateContentResponse response = chat.sendMessage(promptText);

      // The model will most likely return a function call to the declared
      // function `getCurrentWeather` with "Paris" as the value for the
      // argument `location`.
      System.out.println("\nPrint response: ");
      System.out.println(ResponseHandler.getContent(response));

      // Provide an answer to the model so that it knows what the result
      // of a "function call" is.
      Content content =
          ContentMaker.fromMultiModalData(
              PartMaker.fromFunctionResponse(
                  "getCurrentWeather",
                  Collections.singletonMap("currentWeather", "sunny")));
      System.out.println("Provide the function response: ");
      System.out.println(content);
      response = chat.sendMessage(content);

      // See what the model replies now
      System.out.println("Print response: ");
      String finalAnswer = ResponseHandler.getText(response);
      System.out.println(finalAnswer);

      return finalAnswer;
    }
  }
}

Se o modelo determinar que precisa do resultado de uma função específica, a resposta que a aplicação recebe do modelo contém o nome da função e os valores dos parâmetros com os quais a função deve ser chamada.

Segue-se um exemplo de uma resposta do modelo ao comando do utilizador "Como está o tempo em Boston?". O modelo propõe chamar a função get_current_weather com o parâmetro Boston, MA.

candidates {
  content {
    role: "model"
    parts {
      function_call {
        name: "get_current_weather"
        args {
          fields {
            key: "location"
            value {
              string_value: "Boston, MA"
            }
          }
        }
      }
    }
  }
  ...
}

Passo 2: forneça a saída da API ao modelo

Invocar a API externa e transmitir a saída da API de volta ao modelo.

O exemplo seguinte usa dados sintéticos para simular uma carga útil de resposta de uma API externa e envia o resultado de volta para o modelo.

REST

PROJECT_ID=myproject
MODEL_ID=gemini-2.0-flash
LOCATION="us-central1"

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
  "role": "user",
  "parts": {
    "text": "What is the weather in Boston?"
  }
},
{
  "role": "model",
  "parts": [
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "Boston, MA"
        }
      }
    }
  ]
},
{
  "role": "user",
  "parts": [
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 20,
          "unit": "C"
        }
      }
    }
  ]
}
],
"tools": [
{
  "function_declarations": [
    {
      "name": "get_current_weather",
      "description": "Get the current weather in a specific location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
        "required": [
          "location"
        ]
      }
    }
  ]
}
]
}'

Python

function_response_contents = []
function_response_parts = []

# Iterates through the function calls in the response in case there are parallel function call requests
for function_call in response.candidates[0].function_calls:
    print(f"Function call: {function_call.name}")

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    if (function_call.args['location'] == "Boston, MA"):
      api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
    if (function_call.args['location'] == "San Francisco, CA"):
      api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }

    function_response_parts.append(
        Part.from_function_response(
            name=function_call.name,
            response={"contents": api_response}
        )
    )
    # Add the function call response to the contents
    function_response_contents = Content(role="user", parts=function_response_parts)

# Submit the User's prompt, model's response, and API output back to the model
response = model.generate_content(
  [
    Content( # User prompt
      role="user",
      parts=[
          Part.from_text("What is the weather like in Boston?"),
      ],
    ),
    response.candidates[0].content,  # Function call response
    function_response_contents   # API output
  ],
  tools=[
    Tool(
      function_declarations=[get_current_weather_func],
    )
  ],
)
# Get the model summary response
print(response.text)

Para ver as práticas recomendadas relacionadas com a invocação da API, consulte o artigo Práticas recomendadas – Invocação da API.

Se o modelo tiver proposto várias chamadas de funções paralelas, a aplicação tem de fornecer todas as respostas ao modelo. Para saber mais, consulte o Exemplo de chamadas de funções paralelas.

O modelo pode determinar que o resultado de outra função é necessário para responder ao comando. Neste caso, a resposta que a aplicação recebe do modelo contém outro nome de função e outro conjunto de valores de parâmetros.

Se o modelo determinar que a resposta da API é suficiente para responder ao comando do utilizador, cria uma resposta em linguagem natural e devolve-a à aplicação. Neste caso, a aplicação tem de transmitir a resposta ao utilizador. Segue-se um exemplo de uma resposta em linguagem natural:

It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies.

Chamada de função com reflexões

Quando chama funções com a opção thinking ativada, tem de obter o thought_signature do objeto de resposta do modelo e devolvê-lo quando envia o resultado da execução da função de volta para o modelo. Por exemplo:

Python

# Call the model with function declarations
# ...Generation config, Configure the client, and Define user prompt (No changes)

# Send request with declarations (using a thinking model)
response = client.models.generate_content(
  model="gemini-2.5-flash", config=config, contents=contents)

# See thought signatures
for part in response.candidates[0].content.parts:
  if not part.text:
    continue
  if part.thought and part.thought_signature:
    print("Thought signature:")
    print(part.thought_signature)

Não é necessário ver as assinaturas de raciocínio, mas tem de ajustar o passo 2 para as devolver juntamente com o resultado da execução da função, de modo que possa incorporar os raciocínios na resposta final:

Python

# Create user friendly response with function result and call the model again
# ...Create a function response part (No change)

# Append thought signatures, function call and result of the function execution to contents
function_call_content = response.candidates[0].content
# Append the model's function call message, which includes thought signatures
contents.append(function_call_content)
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

final_response = client.models.generate_content(
    model="gemini-2.5-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

Quando devolver assinaturas de pensamento, siga estas diretrizes:

  • O modelo devolve assinaturas noutras partes na resposta, por exemplo, partes de chamadas de funções ou de texto, texto ou resumos de ideias. Devolver toda a resposta com todas as partes ao modelo em turnos subsequentes.
  • Não junte uma parte com uma assinatura a outra parte que também contenha uma assinatura. Não é possível concatenar assinaturas.
  • Não combine uma parte com uma assinatura com outra parte sem assinatura. Isto interrompe o posicionamento correto do pensamento representado pela assinatura.

Saiba mais sobre as limitações e a utilização de assinaturas de pensamento, e sobre os modelos de pensamento em geral, na página Thinking.

Chamadas de funções paralelas

Para comandos como "Quais são os detalhes meteorológicos em Boston e São Francisco?", o modelo pode propor várias chamadas de funções paralelas. Para ver uma lista de modelos que suportam a Chamada de funções paralela, consulte o artigo Modelos suportados.

REST

Este exemplo demonstra um cenário com uma função get_current_weather. O comando do utilizador é "Quais são os detalhes meteorológicos em Boston e São Francisco?". O modelo propõe duas chamadas de função get_current_weather paralelas: uma com o parâmetro Boston e a outra com o parâmetro San Francisco.

Para saber mais sobre os parâmetros de pedido, consulte a API Gemini.

{
"candidates": [
  {
    "content": {
      "role": "model",
      "parts": [
        {
          "functionCall": {
            "name": "get_current_weather",
            "args": {
              "location": "Boston"
            }
          }
        },
        {
          "functionCall": {
            "name": "get_current_weather",
            "args": {
              "location": "San Francisco"
            }
          }
        }
      ]
    },
    ...
  }
],
...
}

O comando seguinte demonstra como pode fornecer o resultado da função ao modelo. Substitua my-project pelo nome do seu Google Cloud projeto.

Pedido de modelo

PROJECT_ID=my-project
MODEL_ID=gemini-2.0-flash
LOCATION="us-central1"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
  "role": "user",
  "parts": {
    "text": "What is difference in temperature in Boston and San Francisco?"
  }
},
{
  "role": "model",
  "parts": [
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "Boston"
        }
      }
    },
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "San Francisco"
        }
      }
    }
  ]
},
{
  "role": "user",
  "parts": [
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 30.5,
          "unit": "C"
        }
      }
    },
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 20,
          "unit": "C"
        }
      }
    }
  ]
}
],
"tools": [
{
  "function_declarations": [
    {
      "name": "get_current_weather",
      "description": "Get the current weather in a specific location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
        "required": [
          "location"
        ]
      }
    }
  ]
}
]
}'
  

A resposta em linguagem natural criada pelo modelo é semelhante à seguinte:

Resposta do modelo

[
{
    "candidates": [
        {
            "content": {
                "parts": [
                    {
                        "text": "The temperature in Boston is 30.5C and the temperature in San Francisco is 20C. The difference is 10.5C. \n"
                    }
                ]
            },
            "finishReason": "STOP",
            ...
        }
    ]
    ...
}
]
  

Python

Este exemplo demonstra um cenário com uma função get_current_weather. O comando do utilizador é "Como está o tempo em Boston e São Francisco?".

Substitua my-project pelo nome do seu Google Cloud projeto.

import vertexai
from vertexai.generative_models import (
    Content,
    FunctionDeclaration,
    GenerationConfig,
    GenerativeModel,
    Part,
    Tool,
    ToolConfig
)

# Initialize Vertex AI
# TODO(developer): Update the project
vertexai.init(project="my-project", location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.0-flash")

# Manual function declaration
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "location": {
              "type": "string",
              "description": "The city name of the location for which to get the weather.",
              "default": {
                "string_value": "Boston, MA"
              }
          }
        },
    },
)

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston and San Francisco?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)

O comando seguinte demonstra como pode fornecer o resultado da função ao modelo.

function_response_contents = []
function_response_parts = []

# You can have parallel function call requests for the same function type.
# For example, 'location_to_lat_long("London")' and 'location_to_lat_long("Paris")'
# In that case, collect API responses in parts and send them back to the model

for function_call in response.candidates[0].function_calls:
    print(f"Function call: {function_call.name}")

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    if (function_call.args['location'] == "Boston, MA"):
      api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
    if (function_call.args['location'] == "San Francisco, CA"):
      api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }

    function_response_parts.append(
        Part.from_function_response(
            name=function_call.name,
            response={"contents": api_response}
        )
    )
    # Add the function call response to the contents
    function_response_contents = Content(role="user", parts=function_response_parts)

function_response_contents

response = model.generate_content(
    contents = [
        Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston and San Francisco?"),
          ],
        ),  # User prompt
        response.candidates[0].content,  # Function call response
        function_response_contents,  # Function response
    ],
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)
# Get the model summary response
print(response.text)

Ir

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// parallelFunctionCalling shows how to execute multiple function calls in parallel
// and return their results to the model for generating a complete response.
func parallelFunctionCalling(w io.Writer, projectID, location, modelName string) error {
	// location = "us-central1"
	// modelName = "gemini-2.0-flash-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("failed to create GenAI client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)
	// Set temperature to 0.0 for maximum determinism in function calling.
	model.SetTemperature(0.0)

	funcName := "getCurrentWeather"
	funcDecl := &genai.FunctionDeclaration{
		Name:        funcName,
		Description: "Get the current weather in a given location",
		Parameters: &genai.Schema{
			Type: genai.TypeObject,
			Properties: map[string]*genai.Schema{
				"location": {
					Type: genai.TypeString,
					Description: "The location for which to get the weather. " +
						"It can be a city name, a city name and state, or a zip code. " +
						"Examples: 'San Francisco', 'San Francisco, CA', '95616', etc.",
				},
			},
			Required: []string{"location"},
		},
	}
	// Add the weather function to our model toolbox.
	model.Tools = []*genai.Tool{
		{
			FunctionDeclarations: []*genai.FunctionDeclaration{funcDecl},
		},
	}

	prompt := genai.Text("Get weather details in New Delhi and San Francisco?")
	resp, err := model.GenerateContent(ctx, prompt)

	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}
	if len(resp.Candidates) == 0 {
		return errors.New("got empty response from model")
	} else if len(resp.Candidates[0].FunctionCalls()) == 0 {
		return errors.New("got no function call suggestions from model")
	}

	// In a production environment, consider adding validations for function names and arguments.
	for _, fnCall := range resp.Candidates[0].FunctionCalls() {
		fmt.Fprintf(w, "The model suggests to call the function %q with args: %v\n", fnCall.Name, fnCall.Args)
		// Example response:
		// The model suggests to call the function "getCurrentWeather" with args: map[location:New Delhi]
		// The model suggests to call the function "getCurrentWeather" with args: map[location:San Francisco]
	}

	// Use synthetic data to simulate responses from the external API.
	// In a real application, this would come from an actual weather API.
	mockAPIResp1, err := json.Marshal(map[string]string{
		"location":         "New Delhi",
		"temperature":      "42",
		"temperature_unit": "C",
		"description":      "Hot and humid",
		"humidity":         "65",
	})
	if err != nil {
		return fmt.Errorf("failed to marshal function response to JSON: %w", err)
	}

	mockAPIResp2, err := json.Marshal(map[string]string{
		"location":         "San Francisco",
		"temperature":      "36",
		"temperature_unit": "F",
		"description":      "Cold and cloudy",
		"humidity":         "N/A",
	})
	if err != nil {
		return fmt.Errorf("failed to marshal function response to JSON: %w", err)
	}

	// Note, that the function calls don't have to be chained. We can obtain both responses in parallel
	// and return them to Gemini at once.
	funcResp1 := &genai.FunctionResponse{
		Name: funcName,
		Response: map[string]any{
			"content": mockAPIResp1,
		},
	}
	funcResp2 := &genai.FunctionResponse{
		Name: funcName,
		Response: map[string]any{
			"content": mockAPIResp2,
		},
	}

	// Return both API responses to the model allowing it to complete its response.
	resp, err = model.GenerateContent(ctx, prompt, funcResp1, funcResp2)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}
	if len(resp.Candidates) == 0 || len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("got empty response from model")
	}

	fmt.Fprintln(w, resp.Candidates[0].Content.Parts[0])
	// Example response:
	// The weather in New Delhi is hot and humid with a humidity of 65 and a temperature of 42°C. The weather in San Francisco ...

	return nil
}

Modos de chamadas de funções

Pode controlar a forma como o modelo usa as ferramentas fornecidas (declarações de funções) definindo o modo no function_calling_config.

Modo Descrição
AUTO O comportamento predefinido do modelo. O modelo decide se deve prever chamadas de funções ou responder com linguagem natural com base no contexto. Este é o modo mais flexível e recomendado para a maioria dos cenários.
VALIDATED (Pré-visualização) O modelo está restrito a prever chamadas de funções ou linguagem natural e garante a conformidade com o esquema de funções. Se allowed_function_names não for fornecido, o modelo escolhe entre todas as declarações de funções disponíveis. Se for fornecido um allowed_function_names, o modelo escolhe a partir do conjunto de funções permitidas.
ANY O modelo está restrito a prever sempre uma ou mais chamadas de funções e garante a conformidade com o esquema de funções. Se allowed_function_names não for fornecido, o modelo escolhe entre todas as declarações de funções disponíveis. Se for fornecido um allowed_function_names, o modelo escolhe a partir do conjunto de funções permitidas. Use este modo quando precisar de uma resposta de chamada de função para cada comando (se aplicável).
NONE O modelo está proibido de fazer chamadas de funções. Isto é equivalente a enviar uma solicitação sem declarações de funções. Use este modo para desativar temporariamente as chamadas de funções sem remover as definições das ferramentas.

Chamada de função forçada

Em vez de permitir que o modelo escolha entre uma resposta em linguagem natural e uma chamada de função, pode forçá-lo a prever apenas chamadas de função. Isto é conhecido como chamada de função forçada. Também pode optar por fornecer ao modelo um conjunto completo de declarações de funções, mas restringir as respetivas respostas a um subconjunto destas funções.

O exemplo seguinte é forçado a prever apenas chamadas de função get_weather.

Python

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_weather_func, some_other_function],
      )
    ],
    tool_config=ToolConfig(
        function_calling_config=ToolConfig.FunctionCallingConfig(
            # ANY mode forces the model to predict only function calls
            mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
            # Allowed function calls to predict when the mode is ANY. If empty, any of
            # the provided function calls will be predicted.
            allowed_function_names=["get_weather"],
        )
    )
)

Exemplos de esquemas de funções

As declarações de funções são compatíveis com o esquema OpenAPI. Suportamos os seguintes atributos: type, nullable, required, format, description, properties, items, enum, anyOf, $ref e $defs. Os restantes atributos não são suportados.

Função com parâmetros de objeto e matriz

O exemplo seguinte usa um dicionário Python para declarar uma função que usa parâmetros de objeto e matriz:

extract_sale_records_func = FunctionDeclaration(
  name="extract_sale_records",
  description="Extract sale records from a document.",
  parameters={
      "type": "object",
      "properties": {
          "records": {
              "type": "array",
              "description": "A list of sale records",
              "items": {
                  "description": "Data for a sale record",
                  "type": "object",
                  "properties": {
                      "id": {"type": "integer", "description": "The unique id of the sale."},
                      "date": {"type": "string", "description": "Date of the sale, in the format of MMDDYY, e.g., 031023"},
                      "total_amount": {"type": "number", "description": "The total amount of the sale."},
                      "customer_name": {"type": "string", "description": "The name of the customer, including first name and last name."},
                      "customer_contact": {"type": "string", "description": "The phone number of the customer, e.g., 650-123-4567."},
                  },
                  "required": ["id", "date", "total_amount"],
              },
          },
      },
      "required": ["records"],
  },
)
  

Função com parâmetro enum

O exemplo seguinte usa um dicionário Python para declarar uma função que recebe um parâmetro enum inteiro:

set_status_func = FunctionDeclaration(
  name="set_status",
  description="set a ticket's status field",
  # Function parameters are specified in JSON schema format
  parameters={
      "type": "object",
      "properties": {
        "status": {
          "type": "integer",
          "enum": [ "10", "20", "30" ],   # Provide integer (or any other type) values as strings.
        }
      },
  },
)
  

Função com ref e def

A declaração de função JSON seguinte usa os atributos ref e defs:

{
  "contents": ...,
  "tools": [
    {
      "function_declarations": [
        {
          "name": "get_customer",
          "description": "Search for a customer by name",
          "parameters": {
            "type": "object",
            "properties": {
              "first_name": { "ref": "#/defs/name" },
              "last_name": { "ref": "#/defs/name" }
            },
            "defs": {
              "name": { "type": "string" }
            }
          }
        }
      ]
    }
  ]
}
  

Notas de utilização:

  • Ao contrário do esquema OpenAPI, especifique ref e defs sem o símbolo $.
  • ref tem de se referir ao elemento secundário direto de defs; não são permitidas referências externas.
  • A profundidade máxima do esquema aninhado é de 32.
  • A profundidade da recursão em defs (autorreferência) está limitada a dois.

from_func com parâmetro de matriz

O seguinte exemplo de código declara uma função que multiplica uma matriz de números e usa from_func para gerar o esquema FunctionDeclaration.

from typing import List

# Define a function. Could be a local function or you can import the requests library to call an API
def multiply_numbers(numbers: List[int] = [1, 1]) -> int:
  """
  Calculates the product of all numbers in an array.

  Args:
      numbers: An array of numbers to be multiplied.

  Returns:
      The product of all the numbers. If the array is empty, returns 1.
  """

  if not numbers:  # Handle empty array
      return 1

  product = 1
  for num in numbers:
      product *= num

  return product

multiply_number_func = FunctionDeclaration.from_func(multiply_numbers)

"""
multiply_number_func contains the following schema:

{'name': 'multiply_numbers',
  'description': 'Calculates the product of all numbers in an array.',
  'parameters': {'properties': {'numbers': {'items': {'type': 'INTEGER'},
    'description': 'list of numbers',
    'default': [1.0, 1.0],
    'title': 'Numbers',
    'type': 'ARRAY'}},
  'description': 'Calculates the product of all numbers in an array.',
  'title': 'multiply_numbers',
  'property_ordering': ['numbers'],
  'type': 'OBJECT'}}
"""
  

Práticas recomendadas para a chamada de funções

Escrever nomes de funções, descrições de parâmetros e instruções claras e detalhadas

  • Os nomes das funções devem começar por uma letra ou um sublinhado e conter apenas carateres a-z, A-Z, 0-9, sublinhados, pontos ou travessões com um comprimento máximo de 64.

  • Seja extremamente claro e específico nas descrições de funções e parâmetros. O modelo baseia-se nestes para escolher a função correta e fornecer argumentos adequados. Por exemplo, uma função book_flight_ticket pode ter a descrição book flight tickets after confirming users' specific requirements, such as time, departure, destination, party size and preferred airline

Use parâmetros fortemente tipados

Se os valores dos parâmetros forem de um conjunto finito, adicione um campo enum em vez de colocar o conjunto de valores na descrição. Se o valor do parâmetro for sempre um número inteiro, defina o tipo como integer em vez de number.

Seleção de ferramentas

Embora o modelo possa usar um número arbitrário de ferramentas, fornecer demasiadas ferramentas pode aumentar o risco de selecionar uma ferramenta incorreta ou abaixo do ideal. Para obter os melhores resultados, procure fornecer apenas as ferramentas relevantes para o contexto ou a tarefa, mantendo idealmente o conjunto ativo num máximo de 10 a 20. Se tiver um número total elevado de ferramentas, considere a seleção dinâmica de ferramentas com base no contexto da conversa.

Se fornecer ferramentas genéricas de baixo nível (como bash), o modelo pode usar a ferramenta com mais frequência, mas com menor precisão. Se fornecer uma ferramenta específica de alto nível (como get_weather), o modelo vai poder usar a ferramenta com maior precisão, mas a ferramenta pode não ser usada com tanta frequência.

Use instruções do sistema

Quando usar funções com parâmetros de data, hora ou localização, inclua a data, a hora ou as informações de localização relevantes (por exemplo, cidade e país) atuais na instrução do sistema. Isto fornece ao modelo o contexto necessário para processar o pedido com precisão, mesmo que o comando do utilizador não tenha detalhes.

Engenharia de comandos

Para ter os melhores resultados, adicione os seguintes detalhes ao comando do utilizador:

  • Contexto adicional para o modelo, por exemplo, You are a flight API assistant to help with searching flights based on user preferences.
  • Detalhes ou instruções sobre como e quando usar as funções, por exemplo, Don't make assumptions on the departure or destination airports. Always use a future date for the departure or destination time.
  • Instruções para fazer perguntas esclarecedoras se as consultas do utilizador forem ambíguas, por exemplo, Ask clarifying questions if not enough information is available.

Use a configuração de geração

Para o parâmetro de temperatura, use 0 ou outro valor baixo. Isto indica ao modelo que gere resultados mais confiantes e reduz as alucinações.

Use a saída estruturada

A chamada de funções pode ser usada em conjunto com o resultado estruturado para permitir que o modelo preveja sempre chamadas de funções ou resultados que seguem um esquema específico, para que receba respostas formatadas de forma consistente quando o modelo não gera chamadas de funções.

Valide a chamada da API

Se o modelo propuser a invocação de uma função que envie uma encomenda, atualize uma base de dados ou tenha outras consequências significativas, valide a chamada de função com o utilizador antes de a executar.

Use assinaturas de pensamentos

As assinaturas de pensamento devem ser sempre usadas com a chamada de funções para obter os melhores resultados.

Preços

O preço das chamadas de funções baseia-se no número de carateres nas entradas e saídas de texto. Para saber mais, consulte os preços da Vertex AI.

Aqui, a entrada de texto (comando) refere-se ao comando do utilizador para a volta de conversa atual, às declarações de funções para a volta de conversa atual e ao histórico da conversa. O histórico da conversa inclui as consultas, as chamadas de funções e as respostas das funções das fases anteriores da conversa. A Vertex AI trunca o histórico da conversa em 32 000 carateres.

O resultado de texto (resposta) refere-se às chamadas de funções e às respostas de texto para a interação atual da conversa.

Exemplos de utilização da Chamada de funções

Pode usar a chamada de funções para as seguintes tarefas:

Exemplo de utilização Descrição de exemplo Exemplo de link
Faça a integração com APIs externas Receba informações meteorológicas através de uma API meteorológica Tutorial do bloco de notas
Converta moradas em coordenadas de latitude/longitude Tutorial do bloco de notas
Converta moedas através de uma API de câmbio Codelab
Crie bots de chat avançados Responda a perguntas dos clientes sobre produtos e serviços Tutorial do bloco de notas
Crie um assistente para responder a perguntas financeiras e de notícias sobre empresas Tutorial do bloco de notas
Estruture e controle as chamadas de funções Extraia entidades estruturadas de dados de registo não processados Tutorial do bloco de notas
Extraia um ou vários parâmetros da entrada do utilizador Tutorial do bloco de notas
Processar listas e estruturas de dados aninhadas em chamadas de funções Tutorial do bloco de notas
Processar o comportamento de chamadas de funções Processar chamadas e respostas de funções paralelas Tutorial do bloco de notas
Faça a gestão de quando e que funções o modelo pode chamar Tutorial do bloco de notas
Consulte bases de dados com linguagem natural Converter perguntas em linguagem natural em consultas SQL para o BigQuery App de exemplo
Chamada de função multimodal Usar imagens, vídeos, áudio e PDFs como entrada para acionar chamadas de funções Tutorial do bloco de notas

Seguem-se mais exemplos de utilização:

  • Interpretar comandos de voz: crie funções que correspondam a tarefas no veículo. Por exemplo, pode criar funções que ligam a rádio ou ativam o ar condicionado. Enviar ficheiros de áudio dos comandos de voz do utilizador para o modelo e pedir ao modelo para converter o áudio em texto e identificar a função que o utilizador quer chamar.

  • Automatize fluxos de trabalho com base em acionadores ambientais: crie funções para representar processos que podem ser automatizados. Fornecer ao modelo dados de sensores ambientais e pedir-lhe que analise e processe os dados para determinar se um ou mais dos fluxos de trabalho devem ser ativados. Por exemplo, um modelo pode processar dados de temperatura num armazém e optar por ativar uma função de aspersor.

  • Automatize a atribuição de pedidos de apoio técnico: forneça ao modelo pedidos de apoio técnico, registos e regras sensíveis ao contexto. Peça ao modelo para processar todas estas informações para determinar a quem o pedido deve ser atribuído. Chamar uma função para atribuir o pedido à pessoa sugerida pelo modelo.

  • Obter informações de uma base de conhecimentos: crie funções que obtenham artigos académicos sobre um determinado assunto e os resumam. Permitir que o modelo responda a perguntas sobre assuntos académicos e forneça citações para as respetivas respostas.

O que se segue?