A chamada de função permite definir funções personalizadas e fornecer aos LLMs a capacidade de chamá-las para recuperar informações em tempo real ou interagir com sistemas externos, como bancos de dados SQL ou ferramentas de atendimento ao cliente.
Para mais informações conceituais sobre chamadas de função, consulte Introdução às chamadas de função.
Antes de começar
Para usar modelos abertos com a Gemini Enterprise Agent Platform, siga as
etapas abaixo. A API Agent Platform
(aiplatform.googleapis.com) e a API Cloud Commerce Consumer
Procurement (cloudcommerceconsumerprocurement.googleapis.com)
precisam estar ativadas para usar modelos abertos na Gemini Enterprise Agent Platform. Se você já tiver um projeto com essas APIs ativadas, use-o em vez de criar um novo.
- Faça login na sua conta do Google Cloud . Se você começou a usar o Google Cloudagora, crie uma conta para avaliar o desempenho dos nossos produtos em situações reais. Clientes novos também recebem US $300 em créditos para executar, testar e implantar cargas de trabalho sem custos financeiros.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform and Cloud Commerce Consumer Procurement APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform and Cloud Commerce Consumer Procurement APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.- Acesse o card do modelo que você quer usar no Model Garden e clique em Ativar para ativar o modelo no seu projeto.
Funções exigidas
Para receber as permissões necessárias para ativar e usar modelos abertos, peça ao administrador para conceder a você os seguintes papéis do IAM no projeto:
- Usuário da Agent Platform (
roles/aiplatform.user) - Gerente de direito de compra do consumidor (
roles/consumerprocurement.entitlementManager)
Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.
Também é possível conseguir as permissões necessárias usando papéis personalizados ou outros papéis predefinidos.
Para mais informações sobre como conceder permissões e configurar políticas da organização para modelos abertos, consulte Conceder acesso de usuário a modelos abertos.
Usar chamadas de função
Os exemplos a seguir mostram como usar a chamada de função.
Python
Antes de testar este exemplo, siga as instruções de configuração do Python no guia de início rápido da plataforma de agentes: como usar bibliotecas de cliente.
Para autenticar na plataforma de agentes, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Antes de executar este exemplo, defina a variável de ambiente OPENAI_BASE_URL.
Para mais informações, consulte Autenticação e credenciais.
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="MODEL", messages=[ {"role": "user", "content": "CONTENT"} ], tools=[ { "type": "function", "function": { "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT, } } ], tool_choice="auto", )
- MODEL: o nome do modelo que você quer usar,
por exemplo,
zai-org/glm-5.2-maas. - CONTENT: o comando do usuário a ser enviado ao modelo.
- FUNCTION_NAME: o nome da função a ser chamada.
- FUNCTION_DESCRIPTION: uma descrição da função.
- PARAMETERS_OBJECT: um dicionário que define os parâmetros da função, por exemplo:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
REST
Depois de configurar o ambiente, use REST para testar um comando de texto. O exemplo a seguir envia uma solicitação ao endpoint do modelo de editor.
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
- PROJECT_ID pelo ID do projeto no Google Cloud.
- MODEL: o nome do modelo que você quer usar,
por exemplo,
zai-org/glm-5.2-maas. - CONTENT: o comando do usuário a ser enviado ao modelo.
- FUNCTION_NAME: o nome da função a ser chamada.
- FUNCTION_DESCRIPTION: uma descrição da função.
- PARAMETERS_OBJECT: um objeto de esquema JSON que define os parâmetros da função, por exemplo:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
Método HTTP e URL:
POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions
Corpo JSON da solicitação:
{
"model": "MODEL",
"messages": [
{
"role": "user",
"content": "CONTENT"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "FUNCTION_NAME",
"description": "FUNCTION_DESCRIPTION",
"parameters": PARAMETERS_OBJECT
}
}
],
"tool_choice": "auto"
}
Para enviar a solicitação, escolha uma destas opções:
curl
Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando abaixo:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions"
PowerShell
Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions" | Select-Object -Expand Content
Você receberá um código de status bem-sucedido (2xx) e uma resposta vazia.
Exemplo
Confira a seguir a saída completa que você pode esperar depois de usar a
função get_current_weather para buscar informações meteorológicas.
Python
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="zai-org/glm-5.2-maas", messages=[ { "role": "user", "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?" }, { "role": "assistant", "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.", "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}] }, { "role": "tool", "content": "The temperature in Boston is 75 degrees Fahrenheit.", "tool_call_id": "get_current_weather" }, { "role": "tool", "content": "The temperature in New Delhi is 50 degrees Fahrenheit.", "tool_call_id": "get_current_weather" } ], tools=[ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], tool_choice="auto" )
curl
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/sample-project/locations/global/endpoints/openapi/chat/completions -d \ '{ "model": "zai-org/glm-5.2-maas", "messages": [ { "role": "user", "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?" }, { "role": "assistant", "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.", "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}] }, { "role": "tool", "content": "The temperature in Boston is 75 degrees Fahrenheit.", "tool_call_id": "get_current_weather" }, { "role": "tool", "content": "The temperature in New Delhi is 50 degrees Fahrenheit.", "tool_call_id": "get_current_weather" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "tool_choice": "auto" }'
{ "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "Based on the current weather data:\n\n- **Boston, MA**: 75°F \n- **New Delhi, India**: 50°F \n\n**Comparison**: \nBoston is **25°F warmer** than New Delhi. \n\n**Answer**: \nBoston has a higher temperature than New Delhi by 25 degrees Fahrenheit.", "role": "assistant" } } ], "created": 1750450289, "id": "2025-06-20|13:11:29.240295-07|6.230.75.101|-987540014", "model": "zai-org/glm-5.2-maas", "object": "chat.completion", "system_fingerprint": "", "usage": { "completion_tokens": 66, "prompt_tokens": 217, "total_tokens": 283 } }
Orientações específicas para o modelo
As seções a seguir fornecem orientações específicas para chamadas de função em cada modelo.
DeepSeek
Os modelos DeepSeek não têm um desempenho tão bom na chamada de função se você usar um comando do sistema. Para um desempenho ideal, omita o comando do sistema ao usar a chamada de função com modelos DeepSeek.
Llama
O meta/llama3-405b-instruct-maas não é compatível com tool_choice = 'required'.
OpenAI
Ao usar openai/gpt-oss-120b-maas, coloque as definições de ferramentas no
comando do sistema para otimizar o desempenho. Exemplo:
{"messages": [ {"role": "system", "content": "You are a helpful assistant with access to the following functions. Use them if required:\n..."}, {"role": "user", "content": "What's the weather like in Boston?"}, ... ]}
Este modelo não é compatível com tool_choice = 'required' ou chamada de ferramenta nomeada.
A seguir
- Saiba mais sobre a saída estruturada.
- Aprenda mais sobre o Raciocínio.
- Saiba mais sobre predições em lote.