A Chamada de função permite-lhe definir funções personalizadas e fornecer aos MDIs/CEs a capacidade de as chamar para obter informações em tempo real ou interagir com sistemas externos, como bases de dados SQL ou ferramentas de serviço ao cliente.
Para mais informações conceptuais sobre a Chamada de funções, consulte o artigo Introdução à Chamada de funções.
Use chamadas de funções
Os exemplos seguintes mostram como usar a chamada de funções.
Python
Antes de experimentar este exemplo, siga as Pythoninstruçõ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 Python 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.
Antes de executar este exemplo, certifique-se de que define a variável de ambiente OPENAI_BASE_URL
.
Para mais informações, consulte o artigo 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 quer usar, por exemplo,
qwen/qwen3-next-80b-a3b-instruct-maas
. - CONTENT: o comando do utilizador a enviar para o modelo.
- FUNCTION_NAME: o nome da função a chamar.
- 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 seu ambiente, pode usar a API REST para testar um comando de texto. O exemplo seguinte envia um pedido para o ponto final do modelo do publicador.
Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:
- PROJECT_ID: o ID do seu projeto do Google Cloud.
- LOCATION: Uma região que suporta modelos abertos.
- MODEL: o nome do modelo que quer usar, por exemplo,
qwen/qwen3-next-80b-a3b-instruct-maas
. - CONTENT: o comando do utilizador a enviar para o modelo.
- FUNCTION_NAME: o nome da função a chamar.
- 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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions
Corpo JSON do pedido:
{ "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 o seu pedido, escolha uma destas opções:
curl
Guarde o corpo do pedido num ficheiro com o nome request.json
,
e execute o seguinte comando:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"
PowerShell
Guarde o corpo do pedido num ficheiro com o nome request.json
,
e execute o seguinte comando:
$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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content
Deve receber um código de estado de êxito (2xx) e uma resposta vazia.
Exemplo
Segue-se o resultado completo que pode esperar após usar a função get_current_weather
para obter informações meteorológicas.
Python
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="qwen/qwen3-next-80b-a3b-instruct-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://us-central1-aiplatform.googleapis.com/v1/projects/sample-project/locations/us-central1/endpoints/openapi/chat/completions -d \ '{ "model": "qwen/qwen3-next-80b-a3b-instruct-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": "qwen/qwen3-next-80b-a3b-instruct-maas", "object": "chat.completion", "system_fingerprint": "", "usage": { "completion_tokens": 66, "prompt_tokens": 217, "total_tokens": 283 } }
Orientação específica do modelo
As secções seguintes fornecem orientações específicas do modelo para a chamada de funções.
DeepSeek
Os modelos DeepSeek não têm um desempenho tão bom nas chamadas de funções se usar um comando do sistema. Para um desempenho ideal, omita o comando do sistema quando usar a chamada de funções com os modelos DeepSeek.
Llama
O meta/llama3-405b-instruct-maas
não suporta a resolução tool_choice = 'required'
.
OpenAI
Quando usar openai/gpt-oss-120b-instruct-maas
e openai/gpt-oss-20b-instruct-maas
, coloque as definições das ferramentas no comando do sistema para um desempenho ideal. Por 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?"}, ... ]}
Estes modelos não são compatíveis com tool_choice = 'required'
nem com a chamada de ferramentas com nome.
Qwen
Os modelos Qwen têm o melhor desempenho quando tool_choice
está explicitamente definido como auto
ou none
. Se tool_choice
não estiver definido, o modelo pode não ter um desempenho tão bom.
O que se segue?
- Saiba mais sobre a saída estruturada.
- Saiba mais sobre o Thinking.
- Saiba mais sobre as previsões em lote.