API del modello per Gemini in Vertex AI

L'API Vertex AI per Gemini consente di creare un'applicazione con i modelli Gemini. Utilizzala per creare richieste e poi ricevere risposte per creare applicazioni per il tuo caso d'uso. Gli argomenti seguenti includono alcuni casi d'uso di esempio per i modelli Gemini:

Per iniziare, crea un account Google Cloud

Per iniziare a utilizzare l'API Vertex AI Model per Gemini, crea un account Google Cloud.

Dopo aver creato l'account, utilizza questo documento per esaminare il corpo della richiesta, i parametri del modello, il corpo della risposta e alcuni richieste e risposte di esempio.

Quando è tutto pronto, consulta la guida rapida dell'API Vertex AI per Gemini per scoprire come inviare una richiesta all'API Vertex AI Gemini utilizzando un SDK del linguaggio di programmazione o l'API REST.

Invia una richiesta HTTP

Le seguenti schede mostrano come inviare una richiesta HTTP con ogni modello Gemini:

Gemini 1.5 Pro

POST https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/publishers/google/models/gemini-1.5-pro:streamGenerateContent

Gemini 1.0 Pro

POST https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/publishers/google/models/gemini-1.0-pro:streamGenerateContent

Gemini 1.0 Pro Vision

POST https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/publishers/google/models/gemini-1.0-pro-vision:streamGenerateContent

Per inviare una richiesta di flusso al modello, consulta il metodo streamGenerateContent per ulteriori informazioni.

Per inviare una richiesta non di streaming al modello, utilizza invece il metodo generateContent.

Per un elenco delle regioni supportate, consulta Località disponibili.

Versioni modello

Per utilizzare la versione aggiornata automaticamente, specifica il nome del modello senza il numero di versione finale, ad esempio gemini-1.0-pro anziché gemini-1.0-pro-001.

Per ulteriori informazioni, consulta Versioni e ciclo di vita dei modelli Gemini.

Corpo della richiesta

Il corpo della richiesta contiene dati con la seguente struttura:

{
  "contents": [
    {
      "role": string,
      "parts": [
        {
          // Union field data can be only one of the following:
          "text": string,
          "inlineData": {
            "mimeType": string,
            "data": string
          },
          "fileData": {
            "mimeType": string,
            "fileUri": string
          },
          // End of list of possible types for union field data.

          "videoMetadata": {
            "startOffset": {
              "seconds": integer,
              "nanos": integer
            },
            "endOffset": {
              "seconds": integer,
              "nanos": integer
            }
          }
        }
      ]
    }
  ],
  "systemInstruction": {
    "role": string,
    "parts": [
      {
        "text": string
      }
    ]
  },
  "tools": [
    {
      "functionDeclarations": [
        {
          "name": string,
          "description": string,
          "parameters": {
            object (OpenAPI Object Schema)
          }
        }
      ]
    }
  ],
  "safetySettings": [
    {
      "category": enum (HarmCategory),
      "threshold": enum (HarmBlockThreshold)
    }
  ],
  "generationConfig": {
    "temperature": number,
    "topP": number,
    "topK": number,
    "candidateCount": integer,
    "maxOutputTokens": integer,
    "stopSequences": [
      string
    ],
    "responseMimeType": string
  }
}

Parametri del modello Gemini

Puoi utilizzare i seguenti parametri nel corpo della richiesta:

Parametro Descrizione
role Il ruolo in una conversazione associata ai contenuti. È necessario specificare un ruolo anche nei casi d'uso a turno singolo. I valori accettati includono:
  • USER: specifica i contenuti inviati da te.
  • MODEL: specifica la risposta del modello.
parts Parti ordinate che compongono l'input. Le parti possono avere tipi MIME diversi.

Per gemini-1.0-pro, è valido solo il campo text. Il limite di token è 32.760.

Per gemini-1.0-pro-vision, puoi specificare solo testo, testo e fino a 16 immagini oppure testo e un video clip. Il limite di token è 16.384.

Per gemini-1.5-pro, puoi specificare qualsiasi combinazione e numero di file di testo, immagine, video e audio. Il limite di token è 1.000.000.

Per calcolare il numero di token nella richiesta, consulta Ottenere il conteggio dei token.
text Le istruzioni di testo o la finestra di dialogo della chat da includere nel prompt.
inlineData Byte di dati serializzati relativi a immagini, clip audio o video clip.

Per gemini-1.0-pro-vision, puoi specificare al massimo 1 immagine con inlineData. Per specificare fino a 16 immagini, utilizza fileData.
mimeType Il tipo multimediale dell'immagine, del PDF o del video specificato nei campi data o fileUri. I valori accettati includono:

Fai clic per espandere i tipi MIME

  • application/pdf
  • audio/mpeg
  • audio/mp3
  • audio/wav
  • image/png
  • image/jpeg
  • text/plain
  • video/mov
  • video/mpeg
  • video/mp4
  • video/mpg
  • video/avi
  • video/wmv
  • video/mpegps
  • video/flv


Per gemini-1.0-pro-vision, la durata massima del video è di 2 minuti.

Per Gemini 1.5 Pro, la durata massima di un file audio è 8,4 ore e la durata massima di un file video (senza audio) è di un'ora. Per maggiori informazioni, consulta i requisiti per i contenuti multimediali di Gemini 1.5 Pro.

I file di testo devono utilizzare la codifica UTF-8. I contenuti del file di testo vengono conteggiati ai fini del limite di token.

Non esiste alcun limite alla risoluzione delle immagini.
data La codifica Base64 dell'immagine, del PDF o del video da includere in linea nel prompt. Quando includi contenuti multimediali incorporati, devi anche specificare MIMETYPE.

dimensione massima: 20 MB

fileUri L'URI Cloud Storage dell'immagine o del video da includere nel prompt. Il bucket in cui viene archiviato il file deve trovarsi nello stesso progetto Google Cloud che invia la richiesta. Devi anche specificare MIMETYPE.

Per gemini-1.5-pro, il limite di dimensioni è di 2 GB.

Per gemini-1.0-pro-vision, il limite per le dimensioni è di 20 MB.
videoMetadata Facoltativo. Per l'input video, l'offset di inizio e di fine del video in formato Durata. Ad esempio, per specificare un clip di 10 secondi a partire dal minuto 1:00, imposta "start_offset": { "seconds": 60 } e "end_offset": { "seconds": 70 }.
systemInstruction (anteprima) Facoltativo. Disponibile per gemini-1.5-pro e gemini-1.0-pro-002.

Istruzioni sul modello per orientarlo verso un rendimento migliore. Ad esempio, "Rispondi nel modo più conciso possibile" o "Non utilizzare termini tecnici nella risposta".

Le stringhe text contano per il limite di token.

Il campo role di systemInstruction viene ignorato e non influisce sulle prestazioni del modello.
tools Una porzione di codice che consente al sistema di interagire con sistemi esterni per eseguire un'azione o un insieme di azioni, al di fuori della conoscenza e dell'ambito del modello.
functionDeclarations Una o più dichiarazioni di funzione. Ogni dichiarazione di una funzione contiene informazioni su una funzione che include quanto segue:
  • name Il nome della funzione da chiamare. Deve iniziare con una lettera o un trattino basso. Deve essere a-z, A-Z, 0-9 o contenere trattini bassi e trattini con una lunghezza massima di 64.
  • description (facoltativo). La descrizione e lo scopo della funzione. Il modello utilizza questa funzione per decidere come e se chiamare la funzione. Per ottenere risultati ottimali, ti consigliamo di includere una descrizione.
  • parameters I parametri di questa funzione in un formato compatibile con il formato schema OpenAPI.

Per saperne di più, consulta Chiamate di funzione.
category La categoria di sicurezza per cui configurare una soglia. I valori accettati includono:

Fai clic per espandere le categorie di sicurezza

  • HARM_CATEGORY_SEXUALLY_EXPLICIT
  • HARM_CATEGORY_HATE_SPEECH
  • HARM_CATEGORY_HARASSMENT
  • HARM_CATEGORY_DANGEROUS_CONTENT
threshold La soglia per il blocco delle risposte che potrebbero appartenere alla categoria di sicurezza specificata in base alla probabilità.
  • BLOCK_NONE
  • BLOCK_LOW_AND_ABOVE
  • BLOCK_MED_AND_ABOVE
  • BLOCK_ONLY_HIGH
temperature La temperatura viene utilizzata per il campionamento durante la generazione delle risposte, che si verifica quando vengono applicati topP e topK. La temperatura controlla il grado di casualità nella selezione dei token. Le temperature più basse sono ideali per prompt che richiedono una risposta meno creativa o meno aperta, mentre le temperature più alte possono portare a risultati più diversificati o creativi. Una temperatura pari a 0 significa che vengono sempre selezionati i token con la probabilità più alta. In questo caso, le risposte per un determinato messaggio sono per lo più deterministiche, ma è comunque possibile una piccola variazione.

Se il modello restituisce una risposta troppo generica, troppo breve o fornisce una risposta di riserva, prova ad aumentare la temperatura.

  • Intervallo per gemini-1.5-pro: 0.0 - 2.0 (valore predefinito: 1.0)
  • Intervallo per gemini-1.0-pro-vision: 0.0 - 1.0 (valore predefinito: 0.4)
  • Intervallo per gemini-1.0-pro-002: 0.0 - 2.0 (predefinito: 1.0)
  • Intervallo per gemini-1.0-pro-001: 0.0 - 1.0 (predefinito: 0.9)
maxOutputTokens Numero massimo di token che possono essere generati nella risposta. Un token equivale a circa quattro caratteri. 100 token corrispondono a circa 60-80 parole.

Specifica un valore più basso per risposte più brevi e un valore più alto per risposte potenzialmente più lunghe.


Intervallo per gemini-1.5-pro: 1-8192 (valore predefinito: 8192)

Intervallo per gemini-1.0-pro: 1-8192 (valore predefinito: 8192)

Intervallo per gemini-1.0-pro-vision: 1-2048 (valore predefinito: 2048)
topK Top-K cambia il modo in cui il modello seleziona i token per l'output. Un top-K pari a 1 indica che il token successivo selezionato è il più probabile tra tutti i token nel vocabolario del modello (detta anche decodifica greedy), mentre un top-K pari a 3 indica che il token successivo viene selezionato tra i tre token più probabili utilizzando la temperatura.

Per ogni fase di selezione dei token, vengono campionati i token top-K con le probabilità più alte. Quindi, i token vengono ulteriormente filtrati in base a top-P e il token finale viene selezionato utilizzando il campionamento con temperatura.

Specifica un valore più basso per risposte meno casuali e un valore più alto per risposte più casuali.


Intervallo: 1-40

gemini-1.0-pro e gemini-1.5-pro non supportano topK

Valore predefinito per gemini-1.0-pro-vision: 32
topP Top-P cambia il modo in cui il modello seleziona i token per l'output. I token vengono selezionati dal più probabile (vedi top-K) al meno probabile finché la somma delle loro probabilità non corrisponde al valore top-P. Ad esempio, se i token A, B e C hanno una probabilità di 0,3, 0,2 e 0,1 e il valore di top-P è 0.5, il modello selezionerà A o B come token successivo utilizzando la temperatura ed esclude C come candidato.

Specifica un valore più basso per risposte meno casuali e un valore più alto per risposte più casuali.


Intervallo: 0.0 - 1.0

gemini-1.5-pro: 0.94

Valore predefinito per gemini-1.0-pro: 1

Valore predefinito per gemini-1.0-pro-vision: 1
candidateCount Il numero di varianti della risposta da restituire.

Questo valore deve essere 1.
stopSequences Specifica un elenco di stringhe che indica al modello di interrompere la generazione di testo se una delle stringhe viene rilevata nella risposta. Se una stringa compare più volte nella risposta, la risposta viene troncata nel punto in cui è stata rilevata per la prima volta. Le stringhe sono sensibili alle maiuscole.

Ad esempio, se quanto segue è la risposta restituita quando stopSequences non è specificato:

public static string reverse(string myString)

La risposta restituita con stopSequences impostato su ["Str", "reverse"] è:

public static string

Massimo 5 elementi nell'elenco.
responseMimeType (anteprima) Facoltativo. Disponibilità per il periodo gemini-1.5-pro.

Il formato di output del testo candidato generato.

Tipi MIME supportati:
  • text/plain: (predefinito) output di testo.
  • application/json: risposta JSON nei candidati.

Corpo della risposta

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": string
          }
        ]
      },
      "finishReason": enum (FinishReason),
      "safetyRatings": [
        {
          "category": enum (HarmCategory),
          "probability": enum (HarmProbability),
          "blocked": boolean
        }
      ],
      "citationMetadata": {
        "citations": [
          {
            "startIndex": integer,
            "endIndex": integer,
            "uri": string,
            "title": string,
            "license": string,
            "publicationDate": {
              "year": integer,
              "month": integer,
              "day": integer
            }
          }
        ]
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": integer,
    "candidatesTokenCount": integer,
    "totalTokenCount": integer
  }
}
Elemento risposta Descrizione
text Il testo generato.
finishReason Il motivo per cui il modello ha smesso di generare token. Se è vuoto, il modello non ha smesso di generare i token. Poiché la risposta utilizza la richiesta di contesto, non è possibile modificare il comportamento del modo in cui il modello interrompe la generazione di token.
  • FINISH_REASON_UNSPECIFIED Il motivo dell'arrivo non è specificato.
  • FINISH_REASON_STOP Punto di arresto naturale del modello o sequenza di interruzioni fornita.
  • FINISH_REASON_MAX_TOKENS È stato raggiunto il numero massimo di token specificato nella richiesta.
  • FINISH_REASON_SAFETY La generazione del token è stata interrotta perché la risposta è stata segnalata per motivi di sicurezza. Tieni presente che Candidate.content è vuoto se i filtri dei contenuti bloccano l'output.
  • FINISH_REASON_RECITATION La generazione del token è stata interrotta in quanto la risposta è stata segnalata per citazioni non autorizzate.
  • FINISH_REASON_OTHER Tutti gli altri motivi che hanno interrotto il token
category La categoria di sicurezza per cui configurare una soglia. I valori accettati includono:

Fai clic per espandere le categorie di sicurezza

  • HARM_CATEGORY_SEXUALLY_EXPLICIT
  • HARM_CATEGORY_HATE_SPEECH
  • HARM_CATEGORY_HARASSMENT
  • HARM_CATEGORY_DANGEROUS_CONTENT
probability I livelli di probabilità di danno nei contenuti.
  • HARM_PROBABILITY_UNSPECIFIED
  • NEGLIGIBLE
  • LOW
  • MEDIUM
  • HIGH
blocked Un flag booleano associato a un attributo di sicurezza che indica se l'input o l'output del modello è stato bloccato.
startIndex Un numero intero che specifica il punto in cui inizia una citazione nel contenuto.
endIndex Un numero intero che specifica dove termina una citazione con content.
url L'URL della fonte di una citazione. Un URL può essere, ad esempio, un sito web di notizie o un repository GitHub.
title Il titolo della fonte della citazione. Esempi di titoli di origine potrebbero essere quelli di un articolo o di un libro.
license La licenza associata a una citazione.
publicationDate La data di pubblicazione di una citazione. I formati validi sono YYYY, YYYY-MM e YYYY-MM-DD.
promptTokenCount Numero di token nella richiesta.
candidatesTokenCount Numero di token nelle risposte.
totalTokenCount Numero di token nella richiesta e nella risposta.

Richieste di esempio

Testo

REST

Per testare un prompt di testo utilizzando l'API Vertex AI con gli eventi inviati dal server (SSE) abilitati, invia una richiesta POST all'endpoint del modello del publisher aggiungendo ?alt=sse alla fine dell'URL.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

Per gli altri campi, consulta la tabella Corpo della richiesta.

Metodo HTTP e URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse

Corpo JSON della richiesta:

{
  "contents": {
    "role": "user",
    "parts": {
        "text": "Give me a recipe for banana bread."
    }
  },
  "safety_settings": {
    "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    "threshold": "BLOCK_LOW_AND_ABOVE"
  },
  "generation_config": {
    "temperature": 0.2,
    "topP": 0.8,
    "topK": 40
  }
}

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse"

PowerShell

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse" | Select-Object -Expand Content

Dovresti ricevere una risposta in formato JSON simile alla risposta di esempio.

Chat

Vedi anche Inviare richieste di prompt di chat (Gemini).

REST

Per testare un prompt di chat utilizzando l'API Vertex AI con gli eventi inviati dal server (SSE) abilitati, invia una richiesta POST all'endpoint del modello del publisher inserendo ?alt=sse alla fine dell'URL.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

Per gli altri campi, consulta la tabella Corpo della richiesta.

Metodo HTTP e URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse

Corpo JSON della richiesta:

{
  "contents": [
    {
      "role": "USER",
      "parts": { "text": "Hello!" }
    },
    {
      "role": "MODEL",
      "parts": { "text": "Argh! What brings ye to my ship?" }
    },
    {
      "role": "USER",
      "parts": { "text": "Wow! You are a real-life priate!" }
    }
  ],
  "safety_settings": {
    "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    "threshold": "BLOCK_LOW_AND_ABOVE"
  },
  "generation_config": {
    "temperature": 0.2,
    "topP": 0.8,
    "topK": 40,
    "maxOutputTokens": 200,
  }
}

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse"

PowerShell

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent?alt=sse" | Select-Object -Expand Content

Dovresti ricevere una risposta in formato JSON simile alla risposta di esempio.

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 GenerativeModel, ChatSession

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

model = GenerativeModel(model_name="gemini-1.0-pro-002")

chat = model.start_chat()

def get_chat_response(chat: ChatSession, prompt: str) -> str:
    text_response = []
    responses = chat.send_message(prompt, stream=True)
    for chunk in responses:
        text_response.append(chunk.text)
    return "".join(text_response)

prompt = "Hello."
print(get_chat_response(chat, prompt))

prompt = "What are all the colors in a rainbow?"
print(get_chat_response(chat, prompt))

prompt = "Why does it appear when it rains?"
print(get_chat_response(chat, prompt))

Node.js

Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js riportate nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js 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.

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function createStreamChat(
  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 chat = generativeModel.startChat({});
  const chatInput1 = 'How can I learn more about that?';

  console.log(`User: ${chatInput1}`);

  const result1 = await chat.sendMessageStream(chatInput1);
  for await (const item of result1.stream) {
    console.log(item.candidates[0].content.parts[0].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.GenerateContentResponse;
import com.google.cloud.vertexai.generativeai.ChatSession;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;

public class ChatDiscussion {

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

    chatDiscussion(projectId, location, modelName);
  }

  // Ask interrelated questions in a row using a ChatSession object.
  public static void chatDiscussion(String projectId, String location, String modelName)
      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)) {
      GenerateContentResponse response;

      GenerativeModel model = new GenerativeModel(modelName, vertexAI);
      // Create a chat session to be used for interactive conversation.
      ChatSession chatSession = new ChatSession(model);

      response = chatSession.sendMessage("Hello.");
      System.out.println(ResponseHandler.getText(response));

      response = chatSession.sendMessage("What are all the colors in a rainbow?");
      System.out.println(ResponseHandler.getText(response));

      response = chatSession.sendMessage("Why does it appear when it rains?");
      System.out.println(ResponseHandler.getText(response));
      System.out.println("Chat Ended.");
    }
  }
}

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"
	"fmt"
	"io"

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

func makeChatRequests(w io.Writer, projectID string, location string, 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("error creating client: %w", err)
	}
	defer client.Close()

	gemini := client.GenerativeModel(modelName)
	chat := gemini.StartChat()

	r, err := chat.SendMessage(
		ctx,
		genai.Text("Hello"))
	if err != nil {
		return err
	}
	rb, err := json.MarshalIndent(r, "", "  ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintln(w, string(rb))

	r, err = chat.SendMessage(
		ctx,
		genai.Text("What are all the colors in a rainbow?"))
	if err != nil {
		return err
	}
	rb, err = json.MarshalIndent(r, "", "  ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintln(w, string(rb))

	r, err = chat.SendMessage(
		ctx,
		genai.Text("Why does it appear when it rains?"))
	if err != nil {
		return fmt.Errorf("chat.SendMessage: %w", err)
	}
	rb, err = json.MarshalIndent(r, "", "  ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintln(w, string(rb))

	return nil
}

Multimodale

Vedi anche Inviare richieste di prompt multimodali.

REST

Per testare un prompt multimodale utilizzando l'API Vertex AI, invia una richiesta POST all'endpoint del modello del publisher.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

Per gli altri campi, consulta la tabella Corpo della richiesta.

Metodo HTTP e URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro-vision:streamGenerateContent

Corpo JSON della richiesta:

{
  "contents": {
    "role": "user",
    "parts": [
      {
        "fileData": {
          "mimeType": "image/jpeg",
          "fileUri": "gs://cloud-samples-data/ai-platform/flowers/daisy/10559679065_50d2b16f6d.jpg"
        }
      },
      {
        "text": "Describe this picture."
      }
    ]
  },
  "safety_settings": {
    "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    "threshold": "BLOCK_LOW_AND_ABOVE"
  },
  "generation_config": {
    "temperature": 0.4,
    "topP": 1.0,
    "topK": 32,
    "maxOutputTokens": 2048
  }
}

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro-vision:streamGenerateContent"

PowerShell

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro-vision:streamGenerateContent" | Select-Object -Expand Content

Dovresti ricevere una risposta in formato JSON simile alla risposta di esempio.

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 GenerativeModel, Part

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

# Load images from Cloud Storage URI
image_file1 = Part.from_uri(
    "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png",
    mime_type="image/png",
)
image_file2 = Part.from_uri(
    "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark2.png",
    mime_type="image/png",
)
image_file3 = Part.from_uri(
    "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark3.png",
    mime_type="image/png",
)

model = GenerativeModel(model_name="gemini-1.5-flash-001")
response = model.generate_content(
    [
        image_file1,
        "city: Rome, Landmark: the Colosseum",
        image_file2,
        "city: Beijing, Landmark: Forbidden City",
        image_file3,
    ]
)
print(response.text)

Node.js

Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js riportate nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js 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.

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

async function getBase64(url) {
  const image = await axios.get(url, {responseType: 'arraybuffer'});
  return Buffer.from(image.data).toString('base64');
}

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function sendMultiModalPromptWithImage(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.0-pro-vision-001'
) {
  // For images, the SDK supports base64 strings
  const landmarkImage1 = await getBase64(
    'https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png'
  );
  const landmarkImage2 = await getBase64(
    'https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark2.png'
  );
  const landmarkImage3 = await getBase64(
    'https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark3.png'
  );

  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  const generativeVisionModel = vertexAI.getGenerativeModel({
    model: model,
  });

  // Pass multimodal prompt
  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            inlineData: {
              data: landmarkImage1,
              mimeType: 'image/png',
            },
          },
          {
            text: 'city: Rome, Landmark: the Colosseum',
          },

          {
            inlineData: {
              data: landmarkImage2,
              mimeType: 'image/png',
            },
          },
          {
            text: 'city: Beijing, Landmark: Forbidden City',
          },
          {
            inlineData: {
              data: landmarkImage3,
              mimeType: 'image/png',
            },
          },
        ],
      },
    ],
  };

  // Create the response
  const response = await generativeVisionModel.generateContent(request);
  // Wait for the response to complete
  const aggregatedResponse = await response.response;
  // Select the text from the response
  const fullTextResponse =
    aggregatedResponse.candidates[0].content.parts[0].text;

  console.log(fullTextResponse);
}

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.GenerateContentResponse;
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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultimodalMultiImage {

  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-vision-001";

    multimodalMultiImage(projectId, location, modelName);
  }

  // Generates content from multiple input images.
  public static void multimodalMultiImage(String projectId, String location, String modelName)
      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)) {
      GenerativeModel model = new GenerativeModel(modelName, vertexAI);

      Content content = ContentMaker.fromMultiModalData(
          PartMaker.fromMimeTypeAndData("image/png", readImageFile(
              "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png")),
          "city: Rome, Landmark: the Colosseum",
          PartMaker.fromMimeTypeAndData("image/png", readImageFile(
              "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark2.png")),
          "city: Beijing, Landmark: Forbidden City",
          PartMaker.fromMimeTypeAndData("image/png", readImageFile(
              "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark3.png"))
      );

      GenerateContentResponse response = model.generateContent(content);

      String output = ResponseHandler.getText(response);
      System.out.println(output);
    }
  }

  // Reads the image data from the given URL.
  public static byte[] readImageFile(String url) throws IOException {
    URL urlObj = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
    connection.setRequestMethod("GET");

    int responseCode = connection.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
      InputStream inputStream = connection.getInputStream();
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
      }

      return outputStream.toByteArray();
    } else {
      throw new RuntimeException("Error fetching file: " + responseCode);
    }
  }
}

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"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"

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

func main() {
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	location := "us-central1"
	modelName := "gemini-1.0-pro-vision"
	temperature := 0.4

	if projectID == "" {
		log.Fatal("require environment variable GOOGLE_CLOUD_PROJECT")
	}

	// construct this multimodal prompt:
	// [image of colosseum] city: Rome, Landmark: the Colosseum
	// [image of forbidden city]  city: Beijing, Landmark: the Forbidden City
	// [new image]

	// create prompt image parts
	// colosseum
	colosseum, err := partFromImageURL("https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png")
	if err != nil {
		log.Fatalf("unable to read image: %v", err)
	}
	// forbidden city
	forbiddenCity, err := partFromImageURL("https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark2.png")
	if err != nil {
		log.Fatalf("unable to read image: %v", err)
	}
	// new image
	newImage, err := partFromImageURL("https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark3.png")
	if err != nil {
		log.Fatalf("unable to read image: %v", err)
	}

	// create a multimodal (multipart) prompt
	prompt := []genai.Part{
		colosseum,
		genai.Text("city: Rome, Landmark: the Colosseum "),
		forbiddenCity,
		genai.Text("city: Beijing, Landmark: the Forbidden City "),
		newImage,
	}

	// generate the response
	err = generateMultimodalContent(os.Stdout, prompt, projectID, location, modelName, float32(temperature))
	if err != nil {
		log.Fatalf("unable to generate: %v", err)
	}
}

// generateMultimodalContent provide a generated response using multimodal input
func generateMultimodalContent(w io.Writer, parts []genai.Part, projectID, location, modelName string, temperature float32) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)
	model.SetTemperature(temperature)

	res, err := model.GenerateContent(ctx, parts...)
	if err != nil {
		return fmt.Errorf("unable to generate contents: %v", err)
	}

	fmt.Fprintf(w, "generated response: %s\n", res.Candidates[0].Content.Parts[0])

	return nil
}

// partFromImageURL create a multimodal prompt part from an image URL
func partFromImageURL(image string) (genai.Part, error) {
	var img genai.Blob

	imageURL, err := url.Parse(image)
	if err != nil {
		return img, err
	}
	res, err := http.Get(image)
	if err != nil || res.StatusCode != 200 {
		return img, err
	}
	defer res.Body.Close()
	data, err := io.ReadAll(res.Body)
	if err != nil {
		return img, fmt.Errorf("unable to read from http: %v", err)
	}

	position := strings.LastIndex(imageURL.Path, ".")
	if position == -1 {
		return img, fmt.Errorf("couldn't find a period to indicate a file extension")
	}
	ext := imageURL.Path[position+1:]

	img = genai.ImageData(ext, data)
	return img, nil
}

C#

Prima di provare questo esempio, segui le istruzioni di configurazione di C# riportate nella guida rapida di Vertex AI sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# 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.


using Google.Api.Gax.Grpc;
using Google.Cloud.AIPlatform.V1;
using Google.Protobuf;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class MultimodalMultiImage
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.0-pro-vision"
    )
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        ByteString colosseum = await ReadImageFileAsync(
            "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png");

        ByteString forbiddenCity = await ReadImageFileAsync(
            "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark2.png");

        ByteString christRedeemer = await ReadImageFileAsync(
            "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark3.png");

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { InlineData = new() { MimeType = "image/png", Data = colosseum }},
                        new Part { Text = "city: Rome, Landmark: the Colosseum" },
                        new Part { InlineData = new() { MimeType = "image/png", Data = forbiddenCity }},
                        new Part { Text = "city: Beijing, Landmark: Forbidden City"},
                        new Part { InlineData = new() { MimeType = "image/png", Data = christRedeemer }}
                    }
                }
            }
        };

        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
        await foreach (GenerateContentResponse responseItem in responseStream)
        {
            fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
        }
        return fullText.ToString();
    }

    private static async Task<ByteString> ReadImageFileAsync(string url)
    {
        using HttpClient client = new();
        using var response = await client.GetAsync(url);
        byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();
        return ByteString.CopyFrom(imageBytes);
    }
}

Funzione

Vedi anche Chiamate di funzione.

REST

Per testare un prompt di funzione utilizzando l'API Vertex AI, invia una richiesta POST all'endpoint del modello del publisher.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

Per gli altri campi, consulta la tabella Corpo della richiesta.

Metodo HTTP e URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent

Corpo JSON della richiesta:

{
  "contents": {
    "role": "user",
    "parts": {
      "text": "Which theaters in Mountain View show 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 inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent"

PowerShell

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/gemini-1.0-pro:streamGenerateContent" | Select-Object -Expand Content

Dovresti ricevere una risposta in formato JSON simile alla risposta di esempio.

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)

Risposte di esempio

Testo

data: {"candidates": [{"content": {"role": "model","parts": [{"text": "Ingredients:\n\n- 3 ripe bananas, mashed\n- 1 cup sugar"}]},"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"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": "\n- 1/2 cup (1 stick) unsalted butter, softened\n"}]},"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"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": "- 2 large eggs\n- 2 cups all-purpose flour\n- 1 teaspoon baking soda\n- 1/2 teaspoon salt\n- "}]},"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"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": "1/2 cup chopped walnuts (optional)\n\nInstructions:\n\n1. Preheat oven to 350 degrees F (175 degrees C). Grease"}]},"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"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": " and flour a 9x5 inch loaf pan.\n2. In a large bowl, cream together the butter and sugar until light and fluffy. Beat in the eggs one at a time, then stir in the mashed bananas.\n3"}]},"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"}],"citationMetadata": {"citations": [{"startIndex": 322,"endIndex": 451,"uri": "https://discover.texasrealfood.com/texas-home-cooking/whats-in-season-plums-exploring-health-benefits-varieties-and-recipes"}]}}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": ". In a separate bowl, whisk together the flour, baking soda, and salt. Gradually add the dry ingredients to the wet ingredients, mixing until just combined. Fold in the walnuts, if desired.\n4. Pour the batter into the"}]},"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"}],"citationMetadata": {"citations": [{"startIndex": 472,"endIndex": 614,"uri": "https://commandame.com/urban-cookhouse-half-baked-cookie-recipe/"}]}}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": " prepared loaf pan and bake for 50-60 minutes, or until a toothpick inserted into the center comes out clean.\n5. Let the bread cool in the pan for 10 minutes before turning it out onto a wire rack to cool completely."}]},"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"}],"citationMetadata": {"citations": [{"startIndex": 666,"endIndex": 796,"uri": "https://dessertdonelight.com/healthy-hawaiian-banana-bread/"},{"startIndex": 728,"endIndex": 851,"uri": "https://earlsgrocery.com/gluten-free-bread/gluten-free-yeast-free-bread-healthy-and-nutition"}]}}],"usageMetadata": {"promptTokenCount": 8,"candidatesTokenCount": 245,"totalTokenCount": 253}}

Chat

data: {"candidates": [{"content": {"role": "model","parts": [{"text": "Avast there, landlubber! Ye be mistaken. I be but a"}]},"safetyRatings": [{"category": "HARM_CATEGORY_HARASSMENT","probability": "LOW"},{"category": "HARM_CATEGORY_HATE_SPEECH","probability": "NEGLIGIBLE"},{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","probability": "NEGLIGIBLE"},{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","probability": "NEGLIGIBLE"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": " humble pirate of the seven seas, brought to life by the magic of artificial intelligence"}]},"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"}]}]}

data: {"candidates": [{"content": {"role": "model","parts": [{"text": ". I be no real-life pirate, but I be mighty good at pretendin'!"}]},"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": 23,"candidatesTokenCount": 50,"totalTokenCount": 73}}

Multimodale

[{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": " A daisy is growing up through a pile of brown and yellow fall leaves"
          }
        ]
      },
      "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": 262,
    "candidatesTokenCount": 14,
    "totalTokenCount": 276
  }
}]

Funzione

[{
  "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
  }
}]

Passaggi successivi

Scopri come utilizzare l'API Vertex AI per Gemini: