API Inference

Utilizza l'API Inference per generare prompt Gemini.

La famiglia di modelli Gemini include modelli che funzionano con richieste di prompt multimodali. Il termine multimodale indica che puoi usare più di una modalità, o tipo di input, in un prompt. I modelli che non sono multimodali accettano richieste solo con testo. Le modalità possono includere testo, audio, video e altro ancora.

Per ulteriori informazioni di panoramica, vedi:

Modelli supportati:

Modello Versione
Gemini 1.5 Flash gemini-1.5-flash-001
Gemini 1.5 Pro gemini-1.5-pro-001
Gemini 1.0 Pro Vision gemini-1.0-pro-001
gemini-1.0-pro-vision-001
Gemini 1.0 Pro gemini-1.0-pro
gemini-1.0-pro-001
gemini-1.0-pro-002

Limitazioni:

Se fornisci molte immagini, la latenza potrebbe essere elevata.

Sintassi di esempio

Sintassi per generare una risposta del modello.

Non in streaming

arricciatura

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \

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

Python

gemini_model = GenerativeModel(MODEL_ID)
generation_config = GenerationConfig(...)

model_response = gemini_model.generate_content([...], generation_config, safety_settings={...})

Buffer dei

arricciatura

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:streamGenerateContent \
  -d '{
    "contents": [{
      ...
    }],
    "generation_config": {
      ...
    },
    "safety_settings": {
      ...
    }
    ...
  }'

Python

gemini_model = GenerativeModel(MODEL_ID)
model_response = gemini_model.generate_content([...], generation_config, safety_settings={...}, stream=True)

Elenco parametri

Consulta gli esempi per i dettagli di implementazione.

Corpo della richiesta

Il corpo della richiesta contiene dati con i seguenti parametri:

Parametri

contents

Obbligatorio: Content

I contenuti della conversazione corrente con il modello.

Per le query a turno singolo, si tratta di una singola istanza. Per le query in più passaggi, si tratta di un campo ripetuto contenente la cronologia della conversazione e l'ultima richiesta.

system_instruction

Facoltativo: Content

L'utente ha fornito le istruzioni di sistema per il modello.

Nota: in parts deve essere utilizzato solo text e i contenuti di ogni part devono essere in un paragrafo separato.

tools

Facoltativo. Vedi API Function Calling.

tool_config

Facoltativo. Vedi API Function Calling.

safety_settings

Facoltativo: SafetySetting

Impostazioni In base alla richiesta per il blocco di contenuti non sicuri.

Data applicazione: GenerateContentResponse.candidates.

generation_config

Facoltativo: GenerationConfig

Impostazioni di configurazione di generazione.

Contenuti

Il tipo di dati strutturati di base con contenuti in più parti di un messaggio.

Questa classe è costituita da due proprietà principali: role e parts. La proprietà role indica la persona che produce i contenuti, mentre la proprietà parts contiene più elementi, ognuno dei quali rappresenta un segmento di dati all'interno di un messaggio.

Parametri

role

Facoltativo: string

L'identità dell'entità che crea il messaggio. Sono supportati i seguenti valori:

  • user: indica che il messaggio è stato inviato da una persona reale, in genere un messaggio generato da un utente.
  • model: indica che il messaggio è generato dal modello.

Il valore model viene utilizzato per inserire i messaggi del modello nella conversazione durante le conversazioni a turni multipli.

Per le conversazioni a più turni, questo campo può essere lasciato vuoto o non impostato.

parts

Part

Un elenco di parti ordinate che compongono un singolo messaggio. Parti diverse possono avere tipi MIME IANA diversi.

Parte

Un tipo di dati contenente contenuti multimediali all'interno di un messaggio Content in più parti.

Parametri

text

Facoltativo: string

Un prompt di testo o uno snippet di codice.

inline_data

Facoltativo: Blob

Dati in linea in byte non elaborati.

file_data

Facoltativo: FileData

Dati archiviati in un file.

function_call

Facoltativo: FunctionCall.

Contiene una stringa che rappresenta il campo FunctionDeclaration.name e un oggetto JSON strutturato contenente i parametri per la chiamata di funzione prevista dal modello.

Vedi API Function Calling.

function_response

Facoltativo: FunctionResponse.

L'output risultato di un FunctionCall che contiene una stringa che rappresenta il campo FunctionDeclaration.name e un oggetto JSON strutturato contenente qualsiasi output della chiamata di funzione. Viene utilizzato come contesto del modello.

Vedi API Function Calling.

video_metadata

Facoltativo: VideoMetadata

Metadati del video. I metadati devono essere specificati solo quando i dati del video sono presentati in inline_data o file_data.

Blob

BLOB di contenuti. Se possibile, invia come testo anziché byte non elaborati.

Parametri

mime_type

string

Tipo MIME IANA dei dati.

data

bytes

Byte non elaborati.

FileData

Dati basati su URI.

Parametri

mime_type

string

Tipo MIME IANA dei dati.

file_uri

string

L'URI Cloud Storage del file in cui sono archiviati i dati

FunctionCall

Un valore FunctionCall previsto restituito dal modello contenente una stringa che rappresenta l'elemento FunctionDeclaration.name e un oggetto JSON strutturato contenente i parametri e i relativi valori.

Parametri

name

string

Il nome della funzione da chiamare.

args

Struct

I parametri e i valori delle funzioni nel formato oggetto JSON.

Per i dettagli dei parametri, consulta API Function Calling.

FunctionResponse

L'output risultante da un elemento FunctionCall che contiene una stringa che rappresenta FunctionDeclaration.name. Contiene anche un oggetto JSON strutturato con l'output della funzione (e lo utilizza come contesto per il modello). Questo dovrebbe contenere il risultato di un FunctionCall creato in base alla previsione del modello.

Parametri

name

string

Il nome della funzione da chiamare.

response

Struct

La risposta della funzione in formato di oggetto JSON.

VideoMetadata

Metadati che descrivono i contenuti video di input.

Parametri

start_offset

Facoltativo: google.protobuf.Duration

L'offset iniziale del video.

end_offset

Facoltativo: google.protobuf.Duration

L'offset finale del video.

SafetySetting

Impostazioni di sicurezza.

Parametri

category

Facoltativo: HarmCategory

La categoria del danno.

threshold

Facoltativo: HarmBlockThreshold

La soglia del blocco dei danni.

max_influential_terms

Facoltativo: int

Il numero massimo di termini influenti che contribuiscono maggiormente ai punteggi di sicurezza e che potrebbero causare un blocco.

method

Facoltativo: HarmBlockMethod

Specifica se la soglia viene utilizzata per il punteggio di probabilità o gravità. Se non specificata, la soglia viene utilizzata per il punteggio di probabilità.

HarmCategory

Categorie HRM che bloccano contenuti.

Parametri

HARM_CATEGORY_UNSPECIFIED

La categoria dei danni non è specificata.

HARM_CATEGORY_HATE_SPEECH

La categoria dei danni è l'incitamento all'odio.

HARM_CATEGORY_DANGEROUS_CONTENT

La categoria dei contenuti dannosi è quella dei contenuti pericolosi.

HARM_CATEGORY_HARASSMENT

La categoria dei danni è molestie.

HARM_CATEGORY_SEXUALLY_EXPLICIT

La categoria dei contenuti dannosi è costituita da contenuti sessualmente espliciti.

HarmBlockThreshold

Livelli di soglie di probabilità utilizzati per bloccare una risposta.

Parametri

HARM_BLOCK_THRESHOLD_UNSPECIFIED

Soglia di blocco dei danni non specificata.

BLOCK_LOW_AND_ABOVE

Blocca soglia bassa e superiore (ad es. blocca altri).

BLOCK_MEDIUM_AND_ABOVE

Blocca soglia media e superiore.

BLOCK_ONLY_HIGH

Blocca solo la soglia alta (ossia blocca meno).

BLOCK_NONE

Nessun blocco.

HarmBlockMethod

Una soglia di probabilità che blocca una risposta in base a una combinazione di probabilità e gravità.

Parametri

HARM_BLOCK_METHOD_UNSPECIFIED

Il metodo di blocco dei danni non è specificato.

SEVERITY

Il metodo di blocco dei danni utilizza sia punteggi di probabilità che punteggi di gravità.

PROBABILITY

Il metodo di blocco dei danni utilizza il punteggio di probabilità.

GenerationConfig

Impostazioni di configurazione utilizzate durante la generazione della richiesta.

Parametri

temperature

Facoltativo: float

Controlla la casualità delle previsioni.

top_p

Facoltativo: float

Se specificato, viene utilizzato il campionamento del nucleo.

top_k

Facoltativo: se specificato, viene utilizzato il campionamento top-k.

candidate_count

Facoltativo: int

Numero di candidati da generare.

max_output_tokens

Facoltativo: int

Il numero massimo di token di output da generare per messaggio.

stop_sequences

Facoltativo: List[string]

Interrompi le sequenze.

presence_penalty

Facoltativo: float

Sanzioni positive.

frequency_penalty

Facoltativo: float

Sanzioni relative alla frequenza.

response_mime_type

Facoltativo: string (enum)

Tipo MIME della risposta di output del testo del candidato generato.

Tipo MIME supportato:

  • text/plain: (predefinito) output di testo.
  • application/json: risposta JSON nei candidati.
  • Al modello deve essere richiesto di restituire il tipo di risposta appropriato, altrimenti il comportamento non è definito.

Questa è una funzionalità in anteprima.

Esempi

Risposta di testo non in streaming

Genera una risposta del modello non in modalità flusso da un input di testo.

REST

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

  • PROJECT_ID: il tuo ID progetto.
  • LOCATION: la regione in cui elaborare la richiesta.
  • TEXT: le istruzioni testuali da includere nel prompt.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

Corpo JSON della richiesta:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

Python

import vertexai
from vertexai.generative_models import GenerativeModel

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

response = model.generate_content(
    "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
)

print(response.text)

NodeJS

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generate_from_text_input(projectId = 'PROJECT_ID') {
  const vertexAI = new VertexAI({project: projectId, location: 'us-central1'});

  const generativeModel = vertexAI.getGenerativeModel({
    model: 'gemini-1.5-flash-001',
  });

  const prompt =
    "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?";

  const resp = await generativeModel.generateContent(prompt);
  const contentResponse = await resp.response;
  console.log(JSON.stringify(contentResponse));
}

Java

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;

public class TextInput {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.0-pro-002";
    String textPrompt =
        "What's a good name for a flower shop that specializes in selling bouquets of"
            + " dried flowers?";

    String output = textInput(projectId, location, modelName, textPrompt);
    System.out.println(output);
  }

  // Passes the provided text input to the Gemini model and returns the text-only response.
  // For the specified textPrompt, the model returns a list of possible store names.
  public static String textInput(
      String projectId, String location, String modelName, String textPrompt) 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);

      GenerateContentResponse response = model.generateContent(textPrompt);
      String output = ResponseHandler.getText(response);
      return output;
    }
  }
}

Go

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

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

func generateContentFromText(w io.Writer, projectID string) error {
	location := "us-central1"
	modelName := "gemini-1.0-pro-vision-001"

	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("error creating client: %w", err)
	}
	gemini := client.GenerativeModel(modelName)
	prompt := genai.Text(
		"What's a good name for a flower shop that specializes in selling bouquets of dried flowers?")

	resp, err := gemini.GenerateContent(ctx, prompt)
	if err != nil {
		return fmt.Errorf("error generating content: %w", err)
	}
	// See the JSON response in
	// https://pkg.go.dev/cloud.google.com/go/vertexai/genai#GenerateContentResponse.
	rb, err := json.MarshalIndent(resp, "", "  ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintln(w, string(rb))
	return nil
}

C#


using Google.Cloud.AIPlatform.V1;
using System;
using System.Threading.Tasks;

public class TextInputSample
{
    public async Task<string> TextInput(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.5-flash-001")
    {

        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();
        string prompt = @"What's a good name for a flower shop that specializes in selling bouquets of dried flowers?";

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = prompt }
                    }
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);

        return responseText;
    }
}

Risposta multimodale non in streaming

Genera una risposta del modello non in modalità flusso da un input multimodale, come testo e immagine.

REST

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

  • PROJECT_ID: il tuo ID progetto.
  • LOCATION: la regione in cui elaborare la richiesta.
  • TEXT: le istruzioni testuali da includere nel prompt.
  • FILE_URI: l'URI Cloud Storage del file in cui sono archiviati i dati.
  • MIME_TYPE: il tipo MIME TIANA dei dati.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

Corpo JSON della richiesta:

{
"contents": [{
  "role": "user",
  "parts": [
    {
      "text": "TEXT"
    },
    {
      "file_data": {"file_uri": "FILE_URI", "MIME_TYPE"}
    },
    {
      "file_data": {"file_uri": "FILE_URI", "MIME_TYPE"}
    }
  ]
}]
}

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

Python

# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


def generate_text(project_id: str) -> str:
    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")

    model = GenerativeModel(model_name="gemini-1.0-pro-vision-001")

    response = model.generate_content(
        [
            Part.from_uri(
                "gs://cloud-samples-data/generative-ai/image/scones.jpg",
                mime_type="image/jpeg",
            ),
            "What is shown in this image?",
        ]
    )

    print(response.text)

    return response.text

NodeJS

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function createNonStreamingMultipartContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.0-pro-vision-001',
  image = 'gs://generativeai-downloads/images/scones.jpg',
  mimeType = 'image/jpeg'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

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

  // For images, the SDK supports both Google Cloud Storage URI and base64 strings
  const filePart = {
    fileData: {
      fileUri: image,
      mimeType: mimeType,
    },
  };

  const textPart = {
    text: 'what is shown in this image?',
  };

  const request = {
    contents: [{role: 'user', parts: [filePart, textPart]}],
  };

  console.log('Prompt Text:');
  console.log(request.contents[0].parts[1].text);

  console.log('Non-Streaming Response Text:');
  // Create the response stream
  const responseStream =
    await generativeVisionModel.generateContentStream(request);

  // Wait for the response stream to complete
  const aggregatedResponse = await responseStream.response;

  // Select the text from the response
  const fullTextResponse =
    aggregatedResponse.candidates[0].content.parts[0].text;

  console.log(fullTextResponse);
}

Java

import com.google.cloud.vertexai.VertexAI;
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 java.io.IOException;

public class Quickstart {

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

    String output = quickstart(projectId, location, modelName);
    System.out.println(output);
  }

  // Analyzes the provided Multimodal input.
  public static String quickstart(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)) {
      String imageUri = "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";

      GenerativeModel model = new GenerativeModel(modelName, vertexAI);
      GenerateContentResponse response = model.generateContent(ContentMaker.fromMultiModalData(
          PartMaker.fromMimeTypeAndData("image/png", imageUri),
          "What's in this photo"
      ));

      return response.toString();
    }
  }
}

Go

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

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

func tryGemini(w io.Writer, projectID string, location string, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.0-pro-vision-001"

	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("error creating client: %w", err)
	}
	gemini := client.GenerativeModel(modelName)

	img := genai.FileData{
		MIMEType: "image/jpeg",
		FileURI:  "gs://generativeai-downloads/images/scones.jpg",
	}
	prompt := genai.Text("What is in this image?")

	resp, err := gemini.GenerateContent(ctx, img, prompt)
	if err != nil {
		return fmt.Errorf("error generating content: %w", err)
	}
	rb, err := json.MarshalIndent(resp, "", "  ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintln(w, string(rb))
	return nil
}

C#


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

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

        // Initialize content request
        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0.4f,
                TopP = 1,
                TopK = 32,
                MaxOutputTokens = 2048
            },
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = "What's in this photo?" },
                        new Part { FileData = new() { MimeType = "image/png", FileUri = "gs://generativeai-downloads/images/scones.jpg" } }
                    }
                }
            }
        };

        // Make the request, returning a streaming response
        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        // Read streaming responses from server until complete
        AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
        await foreach (GenerateContentResponse responseItem in responseStream)
        {
            fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
        }

        return fullText.ToString();
    }
}

Risposta di testo in streaming

Genera una risposta del modello di flusso da un input di testo.

REST

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

  • PROJECT_ID: il tuo ID progetto.
  • LOCATION: la regione in cui elaborare la richiesta.
  • TEXT: le istruzioni testuali da includere nel prompt.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

Corpo JSON della richiesta:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID: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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel

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

model = GenerativeModel(MODEL_ID)
responses = model.generate_content(
    "Write a story about a magic backpack.", stream=True
)

for response in responses:
    print(response)

NodeJS

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContent(
  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: 'Write a story about a magic backpack.',
          },
        ],
      },
    ],
  };

  console.log(JSON.stringify(request));

  const result = await generativeModel.generateContentStream(request);
  for await (const item of result.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

Risposta multimodale in streaming

Generare una risposta del modello in modalità flusso da un input multimodale, come testo e immagine.

REST

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

  • PROJECT_ID: il tuo ID progetto.
  • LOCATION: la regione in cui elaborare la richiesta.
  • TEXT: le istruzioni testuali da includere nel prompt.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

Corpo JSON della richiesta:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID: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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel, Part

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

model = GenerativeModel(MODEL_ID)
responses = model.generate_content(
    [
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/video/animals.mp4", "video/mp4"
        ),
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/character.jpg",
            "image/jpeg",
        ),
        "Are these video and image correlated?",
    ],
    stream=True,
)

for response in responses:
    print(response)

NodeJS

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

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

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            file_data: {
              file_uri: 'gs://cloud-samples-data/video/animals.mp4',
              mime_type: 'video/mp4',
            },
          },
          {
            file_data: {
              file_uri:
                'gs://cloud-samples-data/generative-ai/image/character.jpg',
              mime_type: 'image/jpeg',
            },
          },
          {text: 'Are this video and image correlated?'},
        ],
      },
    ],
  };

  const result = await generativeModel.generateContentStream(request);

  for await (const item of result.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

Passaggi successivi