Chiamate di funzione

Panoramica

I modelli linguistici di grandi dimensioni (LLM) sono efficaci nel risolvere molti tipi di problemi. Tuttavia, sono vincolati dalle seguenti limitazioni:

  • Vengono bloccati dopo l'addestramento, il che porta a conoscenze obsolete.
  • Non possono eseguire query o modificare dati esterni.

Le chiamate di funzione possono risolvere questi problemi. Puoi usare le chiamate di funzione per definire funzioni personalizzate e fornirle a un modelloAIA generativa. Ad esempio, puoi definire una funzione get_weather che prende un parametro di località e restituisce informazioni sulle condizioni meteo nella località in questione.

Durante l'elaborazione di un prompt, il modello può scegliere di delegare determinate attività di elaborazione dei dati alle funzioni che identifichi. Il modello non chiama direttamente le funzioni. Il modello fornisce invece un output di dati strutturati che include la funzione da chiamare e i valori dei parametri da utilizzare. Ad esempio, per un prompt What is the weather like in Boston?, il modello può delegare l'elaborazione alla funzione get_weather e fornire il valore parametro di località Boston, MA.

Puoi utilizzare l'output strutturato dal modello per richiamare le API esterne. Ad esempio, puoi connetterti a un'API di servizio meteo, fornire la località Boston, MA e ricevere informazioni su temperatura, copertura nuvolosa e condizioni del vento.

Puoi quindi fornire l'output dell'API al modello, consentendogli di completare la risposta al prompt. Per l'esempio del meteo, il modello può fornire la risposta seguente: It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies.

Interazione chiamata di funzione 

I seguenti modelli forniscono il supporto per le chiamate di funzione:

Modello Versione Fase di avvio chiamata di funzione Supporto per le chiamate di funzioni parallele Supporto per le chiamate di funzione forzate.
Gemini 1.0 Pro gemini-1.0-pro-001 Disponibilità generale No No
Gemini 1.0 Pro gemini-1.0-pro-002 Disponibilità generale No No
Gemini 1.5 Flash gemini-1.5-flash-001 Disponibilità generale No
Gemini 1.5 Pro gemini-1.5-pro-001 Disponibilità generale

Casi d'uso delle chiamate di funzione

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

Caso d'usoDescrizione di esempioLink di esempio
Estrae entità dalle storie in linguaggio naturale Estrai elenchi di personaggi, relazioni, cose e luoghi da una storia. Estrazione di dati strutturati mediante chiamate di funzione [SDK Vertex AI per il blocco note Python]
esegui query e comprendi i database SQL utilizzando il linguaggio naturale Chiedi al modello di convertire domande come What percentage of orders are returned? in query SQL e di creare funzioni che inviano queste query a BigQuery. Creazione di un'app di esplorazione dei dati BigQuery basata sull'AI utilizzando la chiamata di funzione in Gemini [post del blog]
Aiuta i clienti a interagire con le attività Creare funzioni che si connettono all'API di un'azienda, consentendo al modello di fornire risposte accurate a query quali Do you have the Pixel 8 Pro in stock? o Is there a store in Mountain View, CA that I can visit to try it out? Chiamate di funzione con l'API Gemini di Vertex AI e l'SDK per Python [SDK Vertex AI per il blocco note Python]
Esempio di REST
Esempio di chat per l'SDK Vertex AI per Python
Crea applicazioni di AI generativa connettendoti alle API pubbliche Convertire le valute tra le varie valute. Crea una funzione che si connetta a un'app di scambio di valute, consentendo al modello di fornire risposte accurate a query quali What's the exchange rate for euros to dollars today? Come interagire con le API utilizzando le chiamate di funzione in Gemini [Codelab]
Ricevi il meteo di una determinata località. Crea una funzione che si connette a un'API di un servizio meteorologico, consentendo al modello di fornire risposte accurate a query come What's the weather like in Paris? Chiamate di funzione con l'API Gemini di Vertex AI e l'SDK per Python [SDK Vertex AI per il blocco note Python]
Chiamate di funzione: un framework nativo per connettere Gemini a sistemi, dati e API esterni [post del blog]
Esempi di testo dell'SDK Vertex AI per Python e Node.js
Esempi di chat di Node.js, Java e Go
Convertire un indirizzo in coordinate di latitudine e longitudine. Crea una funzione che converta i dati strutturati sulla posizione in coordinate di latitudine e longitudine. Chiedi al modello di identificare via, città, stato e codice postale nelle query come I want to get the lat/lon coordinates for the following address: 1600 Amphitheatre Pkwy, Mountain View, CA 94043, US. Chiamate di funzione con l'API Gemini di Vertex AI e l'SDK per Python [SDK Vertex AI per il blocco note Python]
Interpretare i comandi vocali Creare funzioni che corrispondano alle attività nel veicolo. Ad esempio, puoi creare funzioni che accendono la radio o attivino l'aria condizionata. Invia i file audio dei comandi vocali dell'utente al modello e chiedi al modello di convertire l'audio in testo e di identificare la funzione che l'utente vuole chiamare.  
Automatizzare i flussi di lavoro in base a trigger ambientali Creare funzioni per rappresentare i processi che possono essere automatizzati. Fornisci al modello i dati dei sensori ambientali e chiedigli di analizzare ed elaborare i dati per determinare se uno o più flussi di lavoro debbano essere attivati. Ad esempio, un modello potrebbe elaborare i dati sulla temperatura in un magazzino e scegliere di attivare una funzione di irrigatori.  
Automatizza l'assegnazione dei ticket di assistenza Fornisci al modello ticket di assistenza, log e regole sensibili al contesto. Chiedi al modello di elaborare tutte queste informazioni per determinare a chi assegnare il ticket. Richiama una funzione per assegnare il ticket alla persona suggerita dal modello.  
Recuperare informazioni da una knowledge base Creare funzioni che recuperano articoli accademici su un determinato argomento e li riepilogano. Consenti al modello di rispondere a domande su argomenti accademici e di fornire citazioni per le sue risposte.  

crea un'applicazione di chiamata di funzione

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

  1. Inizializza il modello.
  2. Definisci il prompt dell'utente.
  3. Definire e descrivere un insieme di funzioni disponibili utilizzando le dichiarazioni di funzione.
  4. Invia al modello il prompt di un utente e le dichiarazioni di funzione.
  5. Richiama una funzione utilizzando l'output dei dati strutturati dal modello.
  6. Fornisci l'output della funzione al modello.

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

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

Se utilizzi le chiamate di funzione per generare una singola risposta, devi fornire al modello il contesto completo dell'interazione. Se invece utilizzi le chiamate di funzione nel contesto di una sessione di chat, la sessione archivia il contesto al posto tuo e lo include in tutte le richieste del modello. In entrambi i casi, Vertex AI archivia la cronologia dell'interazione sul lato client.

Questa guida illustra come utilizzare le chiamate di funzione per generare una singola risposta di testo. Per un esempio end-to-end, consulta Esempi di testo. Per informazioni su come utilizzare le chiamate di funzione per supportare una sessione di chat, consulta Esempi di chat.

Inizializzare il modello

Di seguito è riportato un esempio di come inizializzare il modello:

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")

Definisci il prompt dell'utente

Di seguito è riportato un esempio di prompt dell'utente: "Com'è il tempo a Boston?"

Di seguito è riportato un esempio di come puoi definire il prompt dell'utente:

Python

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

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

Definire e descrivere un insieme di funzioni disponibili

L'applicazione deve dichiarare un insieme di funzioni che il modello può utilizzare per elaborare il prompt. Ogni dichiarazione di funzione deve includere un nome di funzione e parametri di funzione. Ti consigliamo vivamente di includere anche una descrizione della funzione in ogni dichiarazione di funzione.

Il numero massimo di dichiarazioni di funzione che è possibile fornire con la richiesta è 128.

Nome funzione

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

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

Parametri della funzione

I parametri della funzione devono essere forniti in un formato compatibile con lo schema OpenAPI.

Vertex AI offre un supporto limitato per lo 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 della funzione, consulta Best practice - Parametri funzione.

Descrizione della funzione

Il modello utilizza le descrizioni delle funzioni per comprendere lo scopo delle funzioni e determinare se queste sono utili per elaborare le query degli utenti.

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

Esempi di dichiarazioni di funzione

Python: dichiarazione semplice

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

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

Python: array di elementi

Di seguito è riportato un esempio di dichiarazione di 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 le dichiarazioni del prompt e della funzione al modello

Quando l'utente fornisce un prompt, l'applicazione deve fornire il modello con il prompt dell'utente e le dichiarazioni di funzione. 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 di funzione, l'applicazione può fornire al modello una configurazione dello strumento. La chiamata di funzione non supporta l'input multimodale.

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 parametro deterministici, mentre le temperature più alte sono ideali per funzioni con parametri che accettano valori parametro più diversificati o creativi. La temperatura di 0 è deterministica. In questo caso, le risposte per un determinato prompt sono per lo più deterministiche, ma è comunque possibile una piccola variazione. Per scoprire di più, consulta la pagina relativa all'API Gemini.

Per impostare questo parametro, invia una configurazione di generazione (generation_config) insieme alle dichiarazioni del prompt e 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 le dichiarazioni del prompt e delle funzioni.

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

Configurazione dello strumento

Puoi applicare alcuni vincoli al modo in cui il modello dovrebbe utilizzare le dichiarazioni di funzione fornite. Ad esempio, invece di 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 forzate"). Puoi anche scegliere di fornire al modello un set completo di dichiarazioni di funzione, ma limitarne le risposte a un sottoinsieme di queste funzioni.

Per inserire questi vincoli, invia una configurazione dello strumento (tool_config) insieme alle dichiarazioni del prompt e di 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 le chiamate di funzione. Per limitare il modello a un sottoinsieme di funzioni, definisci i nomi consentiti delle funzioni in allowed_function_names.
NESSUNO Il modello non deve prevedere le chiamate di funzione. Questo comportamento equivale a una richiesta di modello senza dichiarazioni di funzione associate.

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

Per saperne di più, consulta la sezione API Functions Contact.

Come inviare le dichiarazioni del prompt e della funzione

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

Python

# Define a tool that includes the function declaration 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 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 determina che ha bisogno dell'output di una particolare funzione, la risposta che l'applicazione riceve dal modello contiene il nome della funzione e i valori dei parametri con cui deve essere chiamata la funzione.

Di seguito è riportato un esempio di risposta del modello al prompt dell'utente "Com'è il tempo 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"
            }
          }
        }
      }
    }
  }
  ...
}

Per prompt come "Ricevi dettagli sul meteo a Nuova Delhi e San Francisco?", il modello può proporre diverse chiamate di funzione parallele. Le chiamate di funzione parallele sono una funzionalità di Anteprima. È supportato dai modelli Gemini 1.5 Pro e Gemini 1.5 Flash. Per scoprire di più, consulta l'esempio di chiamata di funzione parallela.

Richiama un'API esterna

Se l'applicazione riceve un nome di funzione e valori parametro dal modello, l'applicazione 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:

Python

# 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 al richiamo delle API, consulta Best practice - Chiamata API.

Fornisci l'output della funzione al modello

Quando 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 con Python:

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 propone diverse chiamate di funzione parallele, l'applicazione deve fornire tutte le risposte al modello. Le chiamate di funzione parallele sono una funzionalità di anteprima. È supportato dai modelli Gemini 1.5 Pro e Gemini 1.5 Flash. Per scoprire di più, consulta l'esempio di chiamata di funzione parallela.

I modelli gemini-1.0-pro-001 e gemini-1.0-pro-002 possono determinare che l'output di un'altra funzione è necessario per rispondere al prompt. In questo caso, la risposta che l'applicazione riceve dal modello contiene un altro nome di funzione e un altro set di valori parametro.

Se il modello determina che la risposta dell'API è sufficiente per rispondere al prompt 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:

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.

Esempi di testo

Puoi utilizzare le chiamate di funzione per generare una singola risposta di testo. Le risposte testuali ad hoc sono utili per attività aziendali specifiche, inclusa la generazione di codice.

Se utilizzi le chiamate di funzione per generare una singola risposta, devi fornire al modello il contesto completo dell'interazione. Vertex AI archivia la cronologia dell'interazione sul lato client.

Python

Questo esempio illustra uno scenario di testo con una funzione e un prompt. Utilizza la classe GenerativeModel e i suoi 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, vedi 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 (
    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.5-flash-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 illustra uno scenario di testo con una funzione e un prompt.

Node.js

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

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

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {role: 'user', parts: [{text: 'What is the weather in Boston?'}]},
      {
        role: 'model',
        parts: [
          {
            functionCall: {
              name: 'get_current_weather',
              args: {location: 'Boston'},
            },
          },
        ],
      },
      {role: 'user', parts: functionResponseParts},
    ],
    tools: functionDeclarations,
  };
  const streamingResp = await generativeModel.generateContentStream(request);
  for await (const item of streamingResp.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

REST

Questo esempio illustra 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 il prompt e le dichiarazioni di funzione.
  • Nella seconda chiamata, fornisci al modello la risposta dell'API.

Prima richiesta di modello

La richiesta deve definire un prompt nel parametro text. In questo esempio viene definito il seguente prompt: "In quali cinema a Mountain View viene mostrato il film di Barbie?".

La richiesta deve anche definire uno strumento (tools) con un set 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 i cinema in base alla posizione.
  • get_showtimes trova l'ora di inizio dei film in programmazione in un cinema specifico.

Per scoprire di più sui parametri della richiesta del modello, consulta l'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 "In quali cinema a Mountain View viene mostrato 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 modello

Questo esempio utilizza dati sintetici anziché chiamare l'API esterna. Vengono visualizzati 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 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 richiesta del secondo 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

Puoi utilizzare le chiamate di funzione per supportare una sessione di chat. Le sessioni di chat sono utili negli scenari conversazionali in formato libero, in cui è probabile che un utente faccia domande di follow-up.

Se utilizzi le chiamate di funzione nel contesto di una sessione di chat, la sessione archivia il contesto automaticamente e lo include in tutte le richieste del modello. Vertex AI archivia la cronologia dell'interazione sul lato client.

Python

Questo esempio mostra uno scenario di chat con due funzioni e due prompt sequenziali. Utilizza la classe GenerativeModel e i suoi metodi. Per ulteriori 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 ulteriori 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.5-flash-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 per la configurazione di Java nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java Vertex AI.

Per eseguire l'autenticazione su Vertex AI, configura 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.5-flash-001";

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

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

  // A request involving the interaction with an external tool
  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    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 per la configurazione di Go nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Go Vertex AI.

Per eseguire l'autenticazione su Vertex AI, configura 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.5-flash-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", 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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))
	return nil
}

Node.js

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

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

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamChat(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  // Create a chat session and pass your function declarations
  const chat = generativeModel.startChat({
    tools: functionDeclarations,
  });

  const chatInput1 = 'What is the weather in Boston?';

  // This should include a functionCall response from the model
  const result1 = await chat.sendMessageStream(chatInput1);
  for await (const item of result1.stream) {
    console.log(item.candidates[0]);
  }
  await result1.response;

  // Send a follow up message with a FunctionResponse
  const result2 = await chat.sendMessageStream(functionResponseParts);
  for await (const item of result2.stream) {
    console.log(item.candidates[0]);
  }

  // This should include a text response from the model using the response content
  // provided above
  const response2 = await result2.response;
  console.log(response2.candidates[0].content.parts[0].text);
}

Esempio di chiamata di funzione parallela

Per prompt come "Ricevi dettagli sul meteo a Nuova Delhi e San Francisco?", il modello può proporre diverse chiamate di funzione parallele. Le chiamate di funzione parallele sono una funzionalità di Anteprima. È supportato dai modelli Gemini 1.5 Pro e Gemini 1.5 Flash.

REST

Questo esempio mostra uno scenario con una funzione get_current_weather. Il prompt dell'utente è "Vuoi ricevere dettagli 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. È supportato dai modelli Gemini 1.5 Pro e Gemini 1.5 Flash.

Per scoprire di più sui parametri della richiesta del modello, consulta l'API Gemini.

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"
            }
          }
        }
      }
    }
  ]
}
...
}

Il seguente comando mostra come fornire l'output della funzione al modello. Sostituisci my-project con il nome del tuo progetto Google Cloud.

Richiesta di modello

PROJECT_ID=my-project
MODEL_ID=gemini-1.5-pro-001
VERSION="v1"
LOCATION="us-central1"
ENDPOINT=${LOCATION}-aiplatform.googleapis.com
API="generateContent"
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://${ENDPOINT}/${VERSION}/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": [
    {
        "role": "user",
        "parts": {
            "text": "What is difference in temperature in New Delhi and San Francisco?"
        }
    },
    {
        "role": "model",
        "parts": [
            {
                "functionCall": {
                    "name": "get_current_weather",
                    "args": {
                        "location": "New Delhi"
                    }
                }
            },
            {
                "functionCall": {
                    "name": "get_current_weather",
                    "args": {
                        "location": "San Francisco"
                    }
                }
            }
        ]
    },
    {
        "role": "user",
        "parts": [
            {
                "functionResponse": {
                    "name": "get_current_weather",
                    "response": {
                        "temperature": 30.5,
                        "unit": "C"
                    }
                }
            },
            {
                "functionResponse": {
                    "name": "get_current_weather",
                    "response": {
                        "temperature": 20,
                        "unit": "C"
                    }
                }
            }
        ]
    }
],
"tools": [
    {
        "function_declarations": [
            {
                "name": "get_current_weather",
                "description": "Get the current weather in a specific 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"
                    ]
                }
            }
        ]
    }
]
}'
  

La risposta in linguaggio naturale creata dal modello è simile alla seguente:

Risposta del modello

[
{
    "candidates": [
        {
            "content": {
                "parts": [
                    {
                        "text": "The temperature in New Delhi is 30.5C and the temperature in San Francisco is 20C. The difference is 10.5C. \n"
                    }
                ]
            },
            "finishReason": "STOP",
            ...
        }
    ]
    ...
}
]
  

Best practice

Nome funzione

Non utilizzare punto (.), trattino (-) o spazio 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 preferiti. Ad esempio, per una funzione book_flight_ticket:

  • Di seguito è riportato un buon esempio di descrizione di un 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 di un parametro departure: the departure airport

Se possibile, utilizza parametri di digitazione elevata per ridurre le allucinazioni del modello. 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 le descrizioni delle funzioni in modo chiaro e dettagliato. Ad esempio, per una funzione book_flight_ticket:

  • Di seguito è riportato un esempio di descrizione efficace di una funzione: 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 al prompt dell'utente i seguenti dettagli:

  • 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 se le query degli utenti sono 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 istruisce il modello di generare risultati più sicuri e di ridurre le allucinazioni.

Chiamata all'API

Se il modello propone il richiamo di una funzione che invia un ordine, aggiorna un database o comunque comporta conseguenze significative, convalida la chiamata di funzione con l'utente prima di eseguirla.

Prezzi

I prezzi per le chiamate di funzione si basano sul numero di caratteri all'interno degli input e degli output di testo. Per saperne di più, consulta i prezzi di Vertex AI.

Qui, l'input di testo (prompt) si riferisce al prompt dell'utente per il turno della conversazione corrente, le dichiarazioni di funzione per il turno della conversazione corrente e la cronologia della conversazione. La cronologia della conversazione include le query, le chiamate di funzione e le risposte di funzione dei turni di conversazione precedenti. Vertex AI tronca la cronologia della conversazione a 32.000 caratteri.

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