API d'appel de fonction

L'appel de fonction améliore la capacité des LLM à fournir des réponses pertinentes et contextuelles.

Vous pouvez fournir des fonctions personnalisées à un modèle d'IA générative avec l'API d'appel de fonction. Le modèle n'appelle pas directement ces fonctions, mais génère une sortie de données structurées spécifiant le nom de la fonction et les arguments suggérés. Cette sortie permet d'appeler des API ou des systèmes d'information externes tels que des bases de données, des systèmes de gestion de la relation client et des référentiels de documents. Le LLM peut utiliser le résultat d'API obtenu pour améliorer la qualité de la réponse.

Modèles compatibles :

  • Gemini 1.0 Pro
    • gemini-1.0-pro
    • gemini-1.0-pro-001
    • gemini-1.0-pro-002
  • Gemini 1.5 Pro
    • gemini-1.5-pro-preview-0409

Limites :

  • Le nombre maximal de fonctions pouvant être fournies est de 64.
  • FunctionCallingConfig est en version preview et n'est disponible que pour "gemini-1.5-pro-preview-0409".

Syntaxe

  • PROJECT_ID = PROJECT_ID
  • REGION = REGION
  • MODEL_ID = MODEL_ID

curl

https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      ...
    }],
    "tools": [{
      "function_declarations": [
        {
          ...
        }
      ]
    }]
  }'

Python

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[
        Tool(
            function_declarations=[
                FunctionDeclaration(
                    ...
                )
            ]
        )
    ],
)

Liste des paramètres

FunctionDeclaration

Représentation structurée d'une déclaration de fonction telle que définie par la spécification OpenAPI 3.0, qui représente une fonction pour laquelle le modèle peut générer des entrées JSON.

Paramètres

name

string

Nom de la fonction à appeler.

description

Facultatif : string.

Description et objectif de la fonction.

parameters

Facultatif : Schema.

Décrit les paramètres de cette fonction au format d'objet de schéma JSON OpenAPI: Spécification OpenAPI 3.0

response

Facultatif : Schema.

Décrit le résultat de cette fonction au format de schéma JSON.

FunctionCallingConfig [Preview]

Il s'agit d'une configuration supplémentaire pour l'utilisation de la fonctionnalité d'appel de fonction qui n'est disponible que pour "gemini-1.5-pro-preview-0409".

Paramètres

mode

Facultatif : enum/string[].

  • AUTO: comportement par défaut du modèle. Le modèle décide de prédire un appel de fonction ou une réponse en langage naturel.
  • NONE: le modèle ne prédit aucun appel de fonction. Le comportement du modèle est le même que lorsqu'il ne transmet aucune déclaration de fonction.
  • ANY: le modèle est contraint de toujours prédire un seul appel de fonction.

Lorsque allowed_function_names est défini, l'appel de fonction prédit est limité à l'un des éléments allowed_function_names. Par défaut, l'appel de fonction prédite proviendra de n'importe lequel des function_declarations fournis.

allowed_function_names

Facultatif : string[].

Noms des fonctions à appeler. Défini uniquement lorsque la valeur de mode est ANY. Les noms de fonction doivent correspondre à [FunctionDeclaration.name]. Lorsque le mode est défini sur ANY, le modèle prédit un appel de fonction à partir de l'ensemble de noms de fonctions fournis.

Schéma

Le schéma permet de définir le format des données d'entrée et de sortie dans un appel de fonction. Représentation structurée d'une déclaration de fonction telle que définie par la spécification Schéma OpenAPI 3.0.

Paramètres
Type

string

Enum. Type des données. Doit être l'un des suivants:

  • STRING
  • INTEGER
  • BOOLEAN
  • NUMBER
  • ARRAY
  • OBJECT
description

Facultatif : string.

Description des données.

enum

Facultatif : string[].

Valeurs possibles de l'élément de type Type.STRING avec le format enum.

items

Facultatif : Schema[].

Schéma des éléments de Type.ARRAY

properties

Facultatif : Schema.

Schéma des propriétés de Type.OBJECT

required

Facultatif : string[].

Propriétés obligatoires de Type.OBJECT.

nullable

Facultatif : bool.

Indique si la valeur peut être null.

Examples

  • PROJECT_ID = PROJECT_ID
  • REGION = REGION
  • MODEL_ID = MODEL_ID

Cas d'utilisation de base

Voici un exemple d'envoi d'une requête et de déclarations de fonction au modèle.

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "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 or a zip code e.g. 95616"
              }
            },
            "required": [
              "location"
            ]
          }
        }
      ]
    }]
  }'

Python

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

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"}},
    },
)

# Define a tool that includes the above get_current_weather_func
weather_tool = Tool(
    function_declarations=[get_current_weather_func],
)

gemini_model = GenerativeModel(
    MODEL_ID, generation_config={"temperature": 0}, tools=[weather_tool]
)
model_response = gemini_model.generate_content("What is the weather in Boston?")

print(model_response)

Cas d'utilisation avancé

L'exemple suivant montre comment transmettre la configuration de génération et la configuration de l'outil au modèle. La configuration d'appel de fonction permet de vous assurer que la sortie du modèle est toujours un appel de fonction spécifique. Pour ce faire, définissez le mode d'appel de la fonction sur ANY et spécifiez les noms de fonction autorisés dans le paramètre allowed_function_names. Lorsque allowed_function_names est vide, toutes les fonctions fournies peuvent être renvoyées.

  • MODEL_ID = gemini-1.5-pro-preview-0409

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${REGION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "name": "get_product_sku",
          "description": "Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
          "parameters": {
            "type": "object",
            "properties": {
                "product_name": {"type": "string", "description": "Product name"}
            }
          }
        },
        {
          "name": "get_store_location",
          "description": "Get the location of the closest store",
          "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "Location"}},
          }
        }
      ]
    }],
    "tool_config": {
        "function_calling_config": {
            "mode":"ANY",
            "allowed_function_names": ["get_product_sku"]
       }
    },
    "generationConfig": {
      "temperature": 0.95,
      "topP": 1.0,
      "maxOutputTokens": 8192
    }
  }'

Python

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

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_product_info_func = FunctionDeclaration(
    name="get_product_sku",
    description="Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "product_name": {"type": "string", "description": "Product name"}
        },
    },
)

# Specify another function declaration and parameters for an API request
get_store_location_func = FunctionDeclaration(
    name="get_store_location",
    description="Get the location of the closest store",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "Location"}},
    },
)

# Define a tool that includes the above functions
retail_tool = Tool(
    function_declarations=[
        get_product_info_func,
        get_store_location_func,
    ],
)

# Define a tool config for the above functions
retail_tool_config = ToolConfig(
    function_calling_config=ToolConfig.FunctionCallingConfig(
        # ANY mode forces the model to predict a function call
        mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
        # List of functions that can be returned when the mode is ANY.
        # If the list is empty, any declared function can be returned.
        allowed_function_names=["get_product_sku"],
    )
)

generation_config = GenerationConfig(
    temperature=0.95, top_p=1.0, max_output_tokens=8192
)

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[retail_tool],
    tool_config=retail_tool_config,
)
model_response = gemini_model.generate_content(
    "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
)

print(model_response)

En savoir plus

Pour obtenir une documentation détaillée, consultez les pages suivantes: