Llamada a función para modelos abiertos

La llamada a funciones te permite definir funciones personalizadas y proporcionar a los LLM la capacidad de llamarlas para recuperar información en tiempo real o interactuar con sistemas externos, como bases de datos de SQL o herramientas de atención al cliente.

Para obtener más información conceptual sobre la llamada a funciones, consulta Introducción a la llamada a funciones.

Antes de comenzar

Para usar modelos abiertos con Gemini Enterprise Agent Platform, debes realizar los siguientes pasos. La API de Agent Platform (aiplatform.googleapis.com) y la API de Cloud Commerce Consumer Procurement (cloudcommerceconsumerprocurement.googleapis.com) deben estar habilitadas para usar modelos abiertos en Gemini Enterprise Agent Platform. Si ya tienes un proyecto existente con estas APIs habilitadas, puedes usar ese proyecto en lugar de crear uno nuevo.

  1. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  3. Verify that billing is enabled for your Google Cloud project.

  4. 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.enable permission. 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.

    Enable the APIs

  5. Ve a la tarjeta de modelo de Model Garden del modelo que quieres usar y, luego, haz clic en Habilitar para habilitar el modelo y usarlo en tu proyecto.

    Ir a Model Garden

Roles obligatorios

Para obtener los permisos que necesitas para habilitar y usar modelos abiertos, pídele a tu administrador que te otorgue los siguientes roles de IAM en tu proyecto:

Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.

También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.

Para obtener más información sobre cómo otorgar permisos y configurar políticas de la organización para modelos abiertos, consulta Otorga acceso de usuario a modelos abiertos.

Usa la llamada a funciones

En los siguientes ejemplos, se muestra cómo usar la llamada a funciones.

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python incluidas en la guía de inicio rápido de Agent Platform sobre cómo usar bibliotecas cliente.

Para autenticarte en Agent Platform, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

Antes de ejecutar esta muestra, asegúrate de configurar la variable de entorno OPENAI_BASE_URL. Para obtener más información, consulta Autenticación y credenciales.

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: Es el nombre del modelo que deseas usar, por ejemplo, zai-org/glm-5.2-maas.
  • CONTENT: Es la instrucción del usuario que se enviará al modelo.
  • FUNCTION_NAME: el nombre de la función a la que se llamará.
  • FUNCTION_DESCRIPTION: Es una descripción de la función.
  • PARAMETERS_OBJECT: Es un diccionario que define los parámetros de la función, por ejemplo:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

Después de configurar tu entorno, puedes usar REST para probar una instrucción de texto. En el siguiente ejemplo, se envía una solicitud al extremo del modelo de publicador.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID es el ID del proyecto de Google Cloud.
  • MODEL: Es el nombre del modelo que deseas usar, por ejemplo, zai-org/glm-5.2-maas.
  • CONTENT: Es la instrucción del usuario que se enviará al modelo.
  • FUNCTION_NAME: el nombre de la función a la que se llamará.
  • FUNCTION_DESCRIPTION: Es una descripción de la función.
  • PARAMETERS_OBJECT: Es un objeto de esquema JSON que define los parámetros de la función, por ejemplo:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

Método HTTP y URL:

POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions

Cuerpo JSON de la solicitud:

{
  "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 tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente 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://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions" | Select-Object -Expand Content

Deberías recibir un código de estado exitoso (2xx) y una respuesta vacía.

Ejemplo

A continuación, se muestra el resultado completo que podrías esperar después de usar la función get_current_weather para recuperar información meteorológica.

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"
}'
Después de recibir la información recuperada a través de la llamada a la función externa `get_current_weather`, el modelo puede sintetizar la información de las dos respuestas de `tool` y responder la pregunta del usuario. A continuación, se muestra un ejemplo de cómo podría verse el resultado del modelo:
{
 "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
 }
}

Orientación específica para el modelo

En las siguientes secciones, se proporciona orientación específica para cada modelo sobre las llamadas a funciones.

DeepSeek

Los modelos de DeepSeek no tienen un buen rendimiento en la llamada a funciones si usas una instrucción del sistema. Para obtener un rendimiento óptimo, omite la instrucción del sistema cuando uses la llamada a funciones con los modelos de DeepSeek.

Llama

meta/llama3-405b-instruct-maas no admite tool_choice = 'required'.

OpenAI

Cuando uses openai/gpt-oss-120b-maas, coloca las definiciones de tus herramientas en la instrucción del sistema para obtener un rendimiento óptimo. Por ejemplo:

{"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 no admite tool_choice = 'required' ni llamadas a herramientas con nombre.

¿Qué sigue?