Chiamata di funzione

Panoramica

Puoi usare le chiamate di funzione per definire funzioni personalizzate e fornirle a un modelloAIA generativa. Durante l'elaborazione di una query, il modello può scegliere di delegare determinate attività di elaborazione dati a queste funzioni. Non chiama le funzioni. Fornisce invece un output di dati strutturati che includono il nome di una funzione selezionata e gli argomenti con cui il modello propone la funzione di chiamata. Puoi utilizzare questo output per richiamare le API esterne. Puoi quindi fornire nuovamente l'output dell'API al modello, in modo che possa completare la sua risposta alla query. Quando vengono utilizzate in questo modo, le chiamate di funzione consentono agli LLM di accedere a informazioni in tempo reale e interagire con vari servizi, come database SQL, sistemi di gestione dei rapporti con i clienti e repository di documenti.

Il seguente diagramma illustra il funzionamento delle chiamate di funzione: Interazione chiamata funzione 

Per informazioni sui casi d'uso delle chiamate di funzione, consulta Casi d'uso delle chiamate di funzione. Per scoprire come creare un'applicazione di chiamata di funzione, vedi Creare un'applicazione di chiamata di funzione. Per le best practice, consulta le best practice.

Modello Fase di avvio chiamata funzione Supporto per le chiamate di funzione parallele Supporto per le chiamate di funzione forzate
gemini-1.0-pro-001 Disponibilità generale No No
gemini-1.0-pro-002 Anteprima No No
gemini-1.5-flash-preview-0514 Anteprima No
gemini-1.5-pro-preview-0409 Anteprima No
gemini-1.5-pro-preview-0514 Anteprima

Casi d'uso delle chiamate di funzione

Puoi utilizzare le chiamate di funzione per le attività seguenti:

Creazione di un'applicazione che chiama funzione

Per consentire a un utente di interfacciarsi con il modello e utilizzare le chiamate di funzione, devi creare un codice che esegua le attività seguenti:

Puoi creare un'applicazione che gestisca tutte queste attività. Può essere un chatbot di testo, un agente vocale, un flusso di lavoro automatizzato o qualsiasi altro programma.

Definire e descrivere un insieme di funzioni disponibili

L'applicazione deve dichiarare un insieme di funzioni che il modello può utilizzare per elaborare la query. Ogni dichiarazione di funzione deve includere un nome funzione e un parametro di funzione. Consigliamo vivamente di includere anche una descrizione della funzione in ogni dichiarazione della funzione.

Nome funzione

L'applicazione e il modello utilizzano il nome della funzione per identificarla.

Per le best practice relative al nome della funzione, consulta Best practice - Nome funzione.

Parametri della funzione

I parametri delle funzioni devono essere forniti in un formato compatibile con lo schema OpenAPI.

Vertex AI offre un supporto limitato dello schema OpenAPI. Sono supportati i seguenti attributi: type, nullable, required, format, description, properties, items, enum. I seguenti attributi non sono supportati: default, optional, maximum, oneOf.

Quando utilizzi curl, specifica lo schema utilizzando JSON. Quando utilizzi l'SDK Vertex AI per Python, specifica lo schema utilizzando un dizionario Python.

Per le best practice relative ai parametri delle funzioni, consulta Best practice - Parametri delle funzioni.

Descrizione della funzione

Il modello utilizza le descrizioni delle funzioni per comprenderne lo scopo e per determinare se queste sono utili per l'elaborazione delle query degli utenti.

Per le best practice relative alla descrizione della funzione, consulta Best practice - Descrizione della funzione.

Esempio di dichiarazione di una funzione

Di seguito è riportato un esempio di semplice dichiarazione di una funzione in Python:

get_current_weather_func = FunctionDeclaration(
    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."}},
    },
)

Di seguito è riportato un esempio di dichiarazione di una funzione con un array di elementi:

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"],
   },
)

Invia la query e le dichiarazioni delle funzioni al modello

Quando l'utente fornisce un prompt, l'applicazione deve fornire il modello con la richiesta dell'utente e le dichiarazioni delle funzioni. Per configurare il modo in cui il modello genera risultati, l'applicazione può fornire al modello una configurazione di generazione. Per configurare il modo in cui il modello utilizza le dichiarazioni delle funzioni, l'applicazione può fornire al modello una configurazione dello strumento.

Comando dell'utente

Ecco un esempio di prompt dell'utente: "Che tempo fa a Boston?".

Per le best practice relative alla richiesta dell'utente, consulta Best practice - Prompt dell'utente.

Configurazione di generazione

Il modello può generare risultati diversi a seconda dei valori parametro. Il parametro di temperatura controlla il grado di casualità in questa generazione. Le temperature più basse sono ideali per funzioni che richiedono valori di parametri deterministici, mentre le temperature più alte sono ideali per funzioni con parametri che accettano valori parametro più diversificati o creativi. Una temperatura di 0 è deterministica. In questo caso, le risposte per un dato prompt sono per lo più deterministiche, ma è comunque possibile una piccola variazione. Per saperne di più, consulta la pagina dedicata all'API Gemini.

Per impostare questo parametro, invia una configurazione di generazione (generation_config) insieme al prompt e alle dichiarazioni della funzione. Puoi aggiornare il parametro temperature durante una conversazione in chat utilizzando l'API Vertex AI e un generation_config aggiornato. Per un esempio di impostazione del parametro temperature, consulta Come inviare il prompt e le dichiarazioni delle funzioni.

Per le best practice relative alla configurazione di generazione, consulta Best practice - Configurazione di generazione.

Configurazione dello strumento

Puoi imporre alcuni vincoli su come il modello dovrebbe utilizzare le dichiarazioni della funzione che gli fornisci. Ad esempio, anziché consentire al modello di scegliere tra una risposta in linguaggio naturale e una chiamata di funzione, puoi forzarlo a prevedere solo le chiamate di funzione ("chiamate di funzione forzata"). Puoi anche scegliere di fornire al modello un set completo di dichiarazioni di funzioni, ma limitare le sue risposte a un sottoinsieme di queste funzioni.

Per inserire questi vincoli, invia una configurazione dello strumento (tool_config) insieme al prompt e alle dichiarazioni della funzione. Nella configurazione, puoi specificare una delle seguenti modalità:

Modalità Descrizione
AUTOMATICA Il comportamento predefinito del modello. Il modello decide se prevedere una chiamata di funzione o una risposta in linguaggio naturale.
QUALSIASI Il modello deve prevedere solo chiamate di funzione. Per limitare il modello a un sottoinsieme di funzioni, definisci i nomi delle funzioni consentiti in allowed_function_names.
NESSUNO Il modello non deve prevedere le chiamate di funzione. Questo comportamento equivale a una richiesta di modello senza alcuna dichiarazione di funzione associata.

La modalità ANY della configurazione dello strumento ("chiamate di funzione forzata") è una funzionalità di Anteprima. È supportato solo per i modelli Gemini 1.5 Pro.

Per scoprire di più, consulta API Function Calling.

Come inviare le dichiarazioni del prompt e delle funzioni

Di seguito è riportato un esempio di come puoi inviare al modello la query e le dichiarazioni della funzione e vincolare il modello a prevedere solo le chiamate di funzione get_current_weather.

# Initialize Vertex AI
from vertexai.preview.generative_models import ToolConfig

vertexai.init(project=project_id, location=location)

# Initialize Gemini model
model = GenerativeModel("Gemini 1.5 Pro")

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

# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
    role="user",
    parts=[
        Part.from_text(prompt),
    ],
)

# Send the prompt and instruct the model to generate content using the Tool object that you just created
response = model.generate_content(
    user_prompt_content,
    generation_config={"temperature": 0},
    tools=[weather_tool],
    tool_config=ToolConfig(
        function_calling_config=ToolConfig.FunctionCallingConfig(
            # ANY mode forces the model to predict a function call
            mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
            # Allowed functions to call when the mode is ANY. If empty, any one of
            # the provided functions are called.
            allowed_function_names=["get_current_weather"],
    ))
)
response_function_call_content = response.candidates[0].content

Se il modello stabilisce che ha bisogno dell'output di una determinata funzione, la risposta che l'applicazione riceve dal modello contiene il nome della funzione e i valori parametro con cui la funzione deve essere chiamata.

Di seguito è riportato un esempio di risposta del modello al prompt dell'utente "Che tempo fa a Boston?". Il modello propone di chiamare la funzione get_current_weather con il parametro Boston, MA.

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

Di seguito è riportato un esempio di risposta del modello al prompt dell'utente "Ricevi le informazioni sul meteo a Nuova Delhi e San Francisco?". Il modello propone due chiamate di funzione get_current_weather parallele: una con il parametro New Delhi e l'altra con il parametro San Francisco. Le chiamate di funzione parallele sono una funzionalità di anteprima. È supportata dai modelli Gemini 1.5 Pro e Gemini 1.5 Flash.

candidates {
  content {
    role: "model"
    parts: [
      {
        function_call {
          name: "get_current_weather"
          args {
            fields {
              key: "location"
              value {
                string_value: "New Delhi"
              }
            }
          }
        }
      },
      {
        function_call {
          name: "get_current_weather"
          args {
            fields {
              key: "location"
              value {
                string_value: "San Francisco"
              }
            }
          }
        }
      }
    ]
  }
  ...
}

Richiama un'API esterna

Se l'applicazione riceve il nome di una funzione e i valori dei parametri dal modello, deve connettersi a un'API esterna e chiamare la funzione.

L'esempio seguente utilizza dati sintetici per simulare un payload di risposta da un'API esterna:

# Check the function name that the model responded with, and make an API call to an external system
if (
    response.candidates[0].content.parts[0].function_call.name
    == "get_current_weather"
):
    # Extract the arguments to use in your API call
    location = (
        response.candidates[0].content.parts[0].function_call.args["location"]
    )

    # Here you can use your preferred method to make an API request to fetch the current weather, for example:
    # api_response = requests.post(weather_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
                    "icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""

Per le best practice relative alla chiamata delle API, consulta Best practice - Chiamata API.

Fornisci l'output della funzione al modello

Dopo che un'applicazione riceve una risposta da un'API esterna, deve fornire questa risposta al modello. Di seguito è riportato un esempio di come puoi eseguire questa operazione utilizzando Python:

response = model.generate_content(
    [
        user_prompt_content,  # User prompt
        response_function_call_content,  # Function call response
        Content(
            parts=[
                Part.from_function_response(
                    name="get_current_weather",
                    response={
                        "content": api_response,  # Return the API response to Gemini
                    },
                )
            ],
        ),
    ],
    tools=[weather_tool],
)
# Get the model summary response
summary = response.candidates[0].content.parts[0].text

Se il modello stabilisce che la risposta dell'API è sufficiente per rispondere alla query dell'utente, crea una risposta in linguaggio naturale e la restituisce all'applicazione. In questo caso, l'applicazione deve ritrasmettere la risposta all'utente. Di seguito è riportato un esempio di risposta a una query: It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies. The humidity is 65% and the wind is blowing at 10 mph from the northwest.

Se il modello stabilisce che l'output di un'altra funzione è necessario per rispondere alla query, la risposta che l'applicazione riceve dal modello contiene un altro nome di funzione e un altro insieme di valori parametro.

best practice

Nome funzione

Non utilizzare punti (.), trattini (-) o spazi nel nome della funzione. Utilizza invece il trattino basso (_) o qualsiasi altro carattere.

Parametri della funzione

Scrivi descrizioni dei parametri chiare e dettagliate, inclusi dettagli come il formato o i valori che preferisci. Ad esempio, per una funzione book_flight_ticket:

  • Di seguito è riportato un buon esempio di descrizione del parametro departure: Use the 3 char airport code to represent the airport. For example, SJC or SFO. Don't use the city name.
  • Di seguito è riportato un esempio non corretto di descrizione del parametro departure: the departure airport

Se possibile, utilizza parametri con una forte digitazione per ridurre le allucinazioni nei modelli. Ad esempio, se i valori dei parametri provengono da un insieme finito, aggiungi un campo enum anziché inserire l'insieme di valori nella descrizione. Se il valore del parametro è sempre un numero intero, imposta il tipo su integer anziché su number.

Descrizione della funzione

Scrivi descrizioni delle funzioni in modo chiaro e dettagliato. Ad esempio, per una funzione book_flight_ticket:

  • Di seguito è riportato un esempio di descrizione della funzione corretta: book flight tickets after confirming users' specific requirements, such as time, departure, destination, party size and preferred airline
  • Di seguito è riportato un esempio di descrizione di una funzione non valida: book flight ticket

Comando dell'utente

Per ottenere risultati ottimali, anteponi i seguenti dettagli alla query dell'utente:

  • Contesto aggiuntivo per il modello, ad esempio You are a flight API assistant to help with searching flights based on user preferences.
  • Dettagli o istruzioni su come e quando utilizzare le funzioni, ad esempio Don't make assumptions on the departure or destination airports. Always use a future date for the departure or destination time.
  • Istruzioni per porre domande di chiarimento in caso di query degli utenti ambigue, ad esempio Ask clarifying questions if not enough information is available.

Configurazione di generazione

Per il parametro della temperatura, utilizza 0 o un altro valore basso. Questo indica al modello di generare risultati più affidabili e riduce le allucinazioni.

Chiamata API

Se il modello propone di chiamare una funzione che invierebbe un ordine, aggiornerà un database o avrebbe comunque conseguenze significative, convalida la chiamata della funzione con l'utente prima di eseguirla.

Prezzi

I prezzi per le chiamate di funzione si basano sul numero di caratteri negli input e negli output di testo. Per scoprire di più, consulta i prezzi di Vertex AI.

In questo caso, l'input di testo (messaggio) fa riferimento alla query dell'utente relativa al turno della conversazione in corso, alle dichiarazioni delle funzioni per il turno della conversazione in corso e alla cronologia della conversazione. La cronologia della conversazione include le query, le chiamate di funzione e le risposte di funzione della conversazione precedente. Vertex AI tronca la cronologia della conversazione a 32.000 caratteri.

L'output testo (risposta) si riferisce alle chiamate di funzione e alle risposte testuali per il turno della conversazione in corso.

La funzione chiama i campioni

Puoi utilizzare le chiamate di funzione per generare una singola risposta di testo o supportare una sessione di chat. Le risposte di testo ad hoc sono utili per attività aziendali specifiche, inclusa la generazione di codice. Le sessioni di chat sono utili in scenari conversazionali in formato libero, in cui è probabile che un utente faccia domande aggiuntive.

Se utilizzi le chiamate di funzione per generare una singola risposta, devi fornire al modello il contesto completo dell'interazione. D'altra parte, se utilizzi le chiamate di funzione nel contesto di una sessione di chat, la sessione memorizza il contesto per te e lo include in ogni richiesta del modello. In entrambi i casi, Vertex AI archivia la cronologia dell'interazione sul lato client.

Per scoprire come utilizzare le chiamate di funzione per generare una singola risposta di testo, vedi esempi di testo. Per scoprire come utilizzare le chiamate di funzione per supportare una sessione di chat, vedi esempi di chat.

Esempi di testo

Python

Questo esempio mostra uno scenario di testo con una funzione e un prompt. Utilizza la classe GenerativeModel e i relativi metodi. Per ulteriori informazioni sull'utilizzo dell'SDK Vertex AI per Python con i modelli multimodali Gemini, consulta Introduzione alle classi multimodali nell'SDK Vertex AI per Python.

Python

Per scoprire come installare o aggiornare l'SDK Vertex AI per Python, consulta Installare l'SDK Vertex AI per Python. Per saperne di più, consulta la documentazione di riferimento dell'API Python.

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

# Initialize Vertex AI
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-1.0-pro-001")

# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
    role="user",
    parts=[
        Part.from_text("What is the weather like in Boston?"),
    ],
)

# Specify a function declaration and parameters for an API request
function_name = "get_current_weather"
get_current_weather_func = FunctionDeclaration(
    name=function_name,
    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": "Location"}},
    },
)

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

# Send the prompt and instruct the model to generate content using the Tool that you just created
response = model.generate_content(
    user_prompt_content,
    generation_config=GenerationConfig(temperature=0),
    tools=[weather_tool],
)
function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == function_name:
    # Extract the arguments to use in your API call
    location = function_call.args["location"]  # noqa: F841

    # Here you can use your preferred method to make an API request to fetch the current weather, for example:
    # api_response = requests.post(weather_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
                    "icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""

# Return the API response to Gemini so it can generate a model response or request another function call
response = model.generate_content(
    [
        user_prompt_content,  # User prompt
        response.candidates[0].content,  # Function call response
        Content(
            parts=[
                Part.from_function_response(
                    name=function_name,
                    response={
                        "content": api_response,  # Return the API response to Gemini
                    },
                ),
            ],
        ),
    ],
    tools=[weather_tool],
)

# Get the model response
print(response.text)

Node.js

Questo esempio mostra uno scenario di testo con una funzione e un prompt.

REST

Questo esempio mostra uno scenario di testo con tre funzioni e un prompt.

In questo esempio, il modello di AI generativa viene chiamato due volte.

  • Nella prima chiamata, fornisci al modello le dichiarazioni del prompt e della funzione.
  • Nella seconda chiamata, fornisci il modello con la risposta dell'API.

Prima richiesta di modello

La richiesta deve definire una query nel parametro text. Questo esempio definisce la query seguente: "Quali cinema a Mountain View mostrano il film di Barbie?".

La richiesta deve anche definire uno strumento (tools) con un insieme di dichiarazioni di funzione (functionDeclarations). Queste dichiarazioni di funzione devono essere specificate in un formato compatibile con lo schema OpenAPI. Questo esempio definisce le seguenti funzioni:

  • find_movies trova i titoli di film in programmazione nei cinema.
  • find_theatres trova cinema in base alla località.
  • get_showtimes trova l'ora di inizio dei film in programmazione in un cinema specifico.

Per saperne di più sui parametri della richiesta del modello, consulta API Gemini.

Sostituisci my-project con il nome del tuo progetto Google Cloud.

Prima richiesta di modello

PROJECT_ID=my-project
MODEL_ID=gemini-1.0-pro
API=streamGenerateContent
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": {
  "role": "user",
  "parts": {
    "text": "Which theaters in Mountain View show the Barbie movie?"
  }
},
"tools": [
  {
    "function_declarations": [
      {
        "name": "find_movies",
        "description": "find movie titles currently playing in theaters based on any description, genre, title words, etc.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "description": {
              "type": "string",
              "description": "Any kind of description including category or genre, title words, attributes, etc."
            }
          },
          "required": [
            "description"
          ]
        }
      },
      {
        "name": "find_theaters",
        "description": "find theaters based on location and optionally movie title which are is currently playing in theaters",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "movie": {
              "type": "string",
              "description": "Any movie title"
            }
          },
          "required": [
            "location"
          ]
        }
      },
      {
        "name": "get_showtimes",
        "description": "Find the start times for movies playing in a specific theater",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "movie": {
              "type": "string",
              "description": "Any movie title"
            },
            "theater": {
              "type": "string",
              "description": "Name of the theater"
            },
            "date": {
              "type": "string",
              "description": "Date for requested showtime"
            }
          },
          "required": [
            "location",
            "movie",
            "theater",
            "date"
          ]
        }
      }
    ]
  }
]
}'
  

Per il prompt "Quali cinema a Mountain View mostrano il film di Barbie?", il modello potrebbe restituire la funzione find_theatres con i parametri Barbie e Mountain View, CA.

Risposta alla prima richiesta del modello

[{
"candidates": [
  {
    "content": {
      "parts": [
        {
          "functionCall": {
            "name": "find_theaters",
            "args": {
              "movie": "Barbie",
              "location": "Mountain View, CA"
            }
          }
        }
      ]
    },
    "finishReason": "STOP",
    "safetyRatings": [
      {
        "category": "HARM_CATEGORY_HARASSMENT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "probability": "NEGLIGIBLE"
      }
    ]
  }
],
"usageMetadata": {
  "promptTokenCount": 9,
  "totalTokenCount": 9
}
}]
  

Seconda richiesta del modello

Questo esempio utilizza dati sintetici anziché chiamare l'API esterna. Ci sono due risultati, ciascuno con due parametri (name e address):

  1. name: AMC Mountain View 16, address: 2000 W El Camino Real, Mountain View, CA 94040
  2. name: Regal Edwards 14, address: 245 Castro St, Mountain View, CA 94040

Sostituisci my-project con il nome del tuo progetto Google Cloud.

Seconda richiesta del modello

PROJECT_ID=my-project
MODEL_ID=gemini-1.0-pro
API=streamGenerateContent
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": [{
  "role": "user",
  "parts": [{
    "text": "Which theaters in Mountain View show the Barbie movie?"
  }]
}, {
  "role": "model",
  "parts": [{
    "functionCall": {
      "name": "find_theaters",
      "args": {
        "location": "Mountain View, CA",
        "movie": "Barbie"
      }
    }
  }]
}, {
  "parts": [{
    "functionResponse": {
      "name": "find_theaters",
      "response": {
        "name": "find_theaters",
        "content": {
          "movie": "Barbie",
          "theaters": [{
            "name": "AMC Mountain View 16",
            "address": "2000 W El Camino Real, Mountain View, CA 94040"
          }, {
            "name": "Regal Edwards 14",
            "address": "245 Castro St, Mountain View, CA 94040"
          }]
        }
      }
    }
  }]
}],
"tools": [{
  "functionDeclarations": [{
    "name": "find_movies",
    "description": "find movie titles currently playing in theaters based on any description, genre, title words, etc.",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "description": {
          "type": "STRING",
          "description": "Any kind of description including category or genre, title words, attributes, etc."
        }
      },
      "required": ["description"]
    }
  }, {
    "name": "find_theaters",
    "description": "find theaters based on location and optionally movie title which are is currently playing in theaters",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "movie": {
          "type": "STRING",
          "description": "Any movie title"
        }
      },
      "required": ["location"]
    }
  }, {
    "name": "get_showtimes",
    "description": "Find the start times for movies playing in a specific theater",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "movie": {
          "type": "STRING",
          "description": "Any movie title"
        },
        "theater": {
          "type": "STRING",
          "description": "Name of the theater"
        },
        "date": {
          "type": "STRING",
          "description": "Date for requested showtime"
        }
      },
      "required": ["location", "movie", "theater", "date"]
    }
  }]
}]
}'
  

La risposta del modello potrebbe essere simile alla seguente:

Risposta alla seconda richiesta del modello

{
"candidates": [
  {
    "content": {
      "parts": [
        {
          "text": " OK. Barbie is showing in two theaters in Mountain View, CA: AMC Mountain View 16 and Regal Edwards 14."
        }
      ]
    }
  }
],
"usageMetadata": {
  "promptTokenCount": 9,
  "candidatesTokenCount": 27,
  "totalTokenCount": 36
}
}
  

Esempi di chat

Python

Questo esempio mostra uno scenario di chat con due funzioni e due prompt sequenziali. Utilizza la classe GenerativeModel e i relativi metodi. Per maggiori informazioni sull'utilizzo dell'SDK Vertex AI per Python con i modelli multimodali, consulta Introduzione alle classi multimodali nell'SDK Vertex AI per Python.

Per scoprire come installare o aggiornare Python, consulta Installare l'SDK Vertex AI per Python. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python.

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

# Initialize Vertex AI
# project_id = "PROJECT_ID"
# TODO(developer): Update and un-comment below lines
vertexai.init(project=project_id, location="us-central1")

# Specify a function declaration and parameters for an API request
get_product_sku = "get_product_sku"
get_product_sku_func = FunctionDeclaration(
    name=get_product_sku,
    description="Get the SKU for a product",
    # 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_sku_func,
        get_store_location_func,
    ],
)

# Initialize Gemini model
model = GenerativeModel(
    model_name="gemini-1.0-pro-001",
    generation_config=GenerationConfig(temperature=0),
    tools=[retail_tool],
)

# Start a chat session
chat = model.start_chat()

# Send a prompt for the first conversation turn that should invoke the get_product_sku function
response = chat.send_message("Do you have the Pixel 8 Pro in stock?")

function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == get_product_sku:
    # Extract the arguments to use in your API call
    product_name = function_call.args["product_name"]  # noqa: F841

    # Here you can use your preferred method to make an API request to retrieve the product SKU, as in:
    # api_response = requests.post(product_api_url, data={"product_name": product_name})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = {"sku": "GA04834-US", "in_stock": "yes"}

# Return the API response to Gemini, so it can generate a model response or request another function call
response = chat.send_message(
    Part.from_function_response(
        name=get_product_sku,
        response={
            "content": api_response,
        },
    ),
)
# Extract the text from the model response
print(response.text)

# Send a prompt for the second conversation turn that should invoke the get_store_location function
response = chat.send_message(
    "Is there a store in Mountain View, CA that I can visit to try it out?"
)

function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == "get_store_location":
    # Extract the arguments to use in your API call
    location = function_call.args["location"]  # noqa: F841

    # Here you can use your preferred method to make an API request to retrieve store location closest to the user, as in:
    # api_response = requests.post(store_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = {"store": "2000 N Shoreline Blvd, Mountain View, CA 94043, US"}

# Return the API response to Gemini, so it can generate a model response or request another function call
response = chat.send_message(
    Part.from_function_response(
        name="get_store_location",
        response={
            "content": api_response,
        },
    ),
)

# Extract the text from the model response
print(response.text)

Java

Prima di provare questo esempio, segui le istruzioni di configurazione di Java riportate nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java Vertex AI.

Per eseguire l'autenticazione in Vertex AI, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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-1.0-pro-002";

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

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

  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {

    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;
    }
  }
}

Go

Prima di provare questo esempio, segui le istruzioni di configurazione di Go riportate nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go Vertex AI.

Per eseguire l'autenticazione in Vertex AI, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

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

// functionCallsChat opens a chat session and sends 4 messages to the model:
// - convert a first text question into a structured function call request
// - convert the first structured function call response into natural language
// - convert a second text question into a structured function call request
// - convert the second structured function call response into natural language
func functionCallsChat(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.0-pro-002"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %v", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	// Build an OpenAPI schema, in memory
	paramsProduct := &genai.Schema{
		Type: genai.TypeObject,
		Properties: map[string]*genai.Schema{
			"productName": {
				Type:        genai.TypeString,
				Description: "Product name",
			},
		},
	}
	fundeclProductInfo := &genai.FunctionDeclaration{
		Name:        "getProductSku",
		Description: "Get the SKU for a product",
		Parameters:  paramsProduct,
	}
	paramsStore := &genai.Schema{
		Type: genai.TypeObject,
		Properties: map[string]*genai.Schema{
			"location": {
				Type:        genai.TypeString,
				Description: "Location",
			},
		},
	}
	fundeclStoreLocation := &genai.FunctionDeclaration{
		Name:        "getStoreLocation",
		Description: "Get the location of the closest store",
		Parameters:  paramsStore,
	}
	model.Tools = []*genai.Tool{
		{FunctionDeclarations: []*genai.FunctionDeclaration{
			fundeclProductInfo,
			fundeclStoreLocation,
		}},
	}
	model.SetTemperature(0.0)

	chat := model.StartChat()

	// Send a prompt for the first conversation turn that should invoke the getProductSku function
	prompt := "Do you have the Pixel 8 Pro in stock?"
	fmt.Fprintf(w, "Question: %s\n", prompt)
	resp, err := chat.SendMessage(ctx, genai.Text(prompt))
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has returned a function call to the declared function `getProductSku`
	// with a value for the argument `productName`.
	jsondata, err := json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call generated by the model:\n\t%s\n", string(jsondata))

	// Create a function call response, to simulate the result of a call to a
	// real service
	funresp := &genai.FunctionResponse{
		Name: "getProductSku",
		Response: map[string]any{
			"sku":      "GA04834-US",
			"in_stock": "yes",
		},
	}
	jsondata, err = json.MarshalIndent(funresp, "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call response sent to the model:\n\t%s\n\n", string(jsondata))

	// And provide the function call response to the model
	resp, err = chat.SendMessage(ctx, funresp)
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has taken the function call response as input, and has
	// reformulated the response to the user.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))

	// Send a prompt for the second conversation turn that should invoke the getStoreLocation function
	prompt2 := "Is there a store in Mountain View, CA that I can visit to try it out?"
	fmt.Fprintf(w, "Question: %s\n", prompt)

	resp, err = chat.SendMessage(ctx, genai.Text(prompt2))
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has returned a function call to the declared function `getStoreLocation`
	// with a value for the argument `store`.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call generated by the model:\n\t%s\n", string(jsondata))

	// Create a function call response, to simulate the result of a call to a
	// real service
	funresp = &genai.FunctionResponse{
		Name: "getStoreLocation",
		Response: map[string]any{
			"store": "2000 N Shoreline Blvd, Mountain View, CA 94043, US",
		},
	}
	jsondata, err = json.MarshalIndent(funresp, "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call response sent to the model:\n\t%s\n\n", string(jsondata))

	// And provide the function call response to the model
	resp, err = chat.SendMessage(ctx, funresp)
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has taken the function call response as input, and has
	// reformulated the response to the user.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))
	return nil
}