Risposte dinamiche dai modelli di IA generativa

I flussi di dati richiedono la ricezione di risposte ai prompt man mano che vengono generati.In altre parole, non appena il modello genera i token di output, questi vengono inviati.

Puoi effettuare richieste di flussi di dati al modello linguistico di grandi dimensioni (LLM) di Vertex AI utilizzando quanto segue:

Le API di elaborazione in modalità flusso e non in modalità flusso utilizzano gli stessi parametri e non sono previste differenze a livello di prezzi e quote.

Vertex AI Studio

Puoi usare Vertex AI Studio per progettare ed eseguire prompt e ricevere risposte dinamiche. Nella pagina di progettazione dei prompt, fai clic sul pulsante Streaming Response per abilitare il flusso di dati.

Pulsante risposta streaming

Esempi

Puoi chiamare l'API Streaming utilizzando uno dei seguenti metodi:

API REST con eventi inviati dal server (SSE)

I parametri sono diversi tra i tipi di modello utilizzati nei seguenti esempi:

Testo

Gli attuali modelli supportati sono text-bison e text-unicorn. Vedi le versioni disponibili.

Richiedi

  PROJECT_ID=YOUR_PROJECT_ID
  PROMPT="PROMPT"
  MODEL_ID=text-bison

  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}:serverStreamingPredict?alt=sse -d \
  '{
    "inputs": [
      {
        "struct_val": {
          "prompt": {
            "string_val": [ "'"${PROMPT}"'" ]
          }
        }
      }
    ],
    "parameters": {
      "struct_val": {
        "temperature": { "float_val": 0.8 },
        "maxOutputTokens": { "int_val": 1024 },
        "topK": { "int_val": 40 },
        "topP": { "float_val": 0.95 }
      }
    }
  }'

Risposta

Le risposte sono messaggi di evento inviati dal server.

  data: {"outputs": [{"structVal": {"content": {"stringVal": [RESPONSE]},"safetyAttributes": {"structVal": {"blocked": {"boolVal": [BOOLEAN]},"categories": {"listVal": [{"stringVal": [Safety category name]}]},"scores": {"listVal": [{"doubleVal": [Safety category score]}]}}},"citationMetadata": {"structVal": {"citations": {}}}}}]}

Chat

L'attuale modello supportato è chat-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
AUTHOR="USER"
MODEL_ID=chat-bison

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}:serverStreamingPredict?alt=sse -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "messages": {
          "list_val": [
            {
              "struct_val": {
                "content": {
                  "string_val": [ "'"${PROMPT}"'" ]
                },
                "author": {
                  "string_val": [ "'"${AUTHOR}"'"]
                }
              }
            }
          ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.5 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

Le risposte sono messaggi di evento inviati dal server.

data: {"outputs": [{"structVal": {"candidates": {"listVal": [{"structVal": {"author": {"stringVal": [AUTHOR]},"content": {"stringVal": [RESPONSE]}}}]},"citationMetadata": {"listVal": [{"structVal": {"citations": {}}}]},"safetyAttributes": {"structVal": {"blocked": {"boolVal": [BOOLEAN]},"categories": {"listVal": [{"stringVal": [Safety category name]}]},"scores": {"listVal": [{"doubleVal": [Safety category score]}]}}}}}]}

Codice

L'attuale modello supportato è code-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
MODEL_ID=code-bison

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}:serverStreamingPredict?alt=sse -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "prefix": {
          "string_val": [ "'"${PROMPT}"'" ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.8 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

Le risposte sono messaggi di evento inviati dal server.

data: {"outputs": [{"structVal": {"citationMetadata": {"structVal": {"citations": {}}},"safetyAttributes": {"structVal": {"blocked": {"boolVal": [BOOLEAN]},"categories": {"listVal": [{"stringVal": [Safety category name]}]},"scores": {"listVal": [{"doubleVal": [Safety category score]}]}}},"content": {"stringVal": [RESPONSE]}}}]}

Chat di codice

L'attuale modello supportato è codechat-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
AUTHOR="USER"
MODEL_ID=codechat-bison

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}:serverStreamingPredict?alt=sse -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "messages": {
          "list_val": [
            {
              "struct_val": {
                "content": {
                  "string_val": [ "'"${PROMPT}"'" ]
                },
                "author": {
                  "string_val": [ "'"${AUTHOR}"'"]
                }
              }
            }
          ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.5 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

Le risposte sono messaggi di evento inviati dal server.

data: {"outputs": [{"structVal": {"safetyAttributes": {"structVal": {"blocked": {"boolVal": [BOOLEAN]},"categories": {"listVal": [{"stringVal": [Safety category name]}]},"scores": {"listVal": [{"doubleVal": [Safety category score]}]}}},"citationMetadata": {"listVal": [{"structVal": {"citations": {}}}]},"candidates": {"listVal": [{"structVal": {"content": {"stringVal": [RESPONSE]},"author": {"stringVal": [AUTHOR]}}}]}}}]}

API REST

I parametri sono diversi tra i tipi di modello utilizzati nei seguenti esempi:

Testo

Gli attuali modelli supportati sono text-bison e text-unicorn. Vedi le versioni disponibili.

Richiedi

  PROJECT_ID=YOUR_PROJECT_ID
  PROMPT="PROMPT"
  MODEL_ID=text-bison

  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}:serverStreamingPredict -d \
  '{
    "inputs": [
      {
        "struct_val": {
          "prompt": {
            "string_val": [ "'"${PROMPT}"'" ]
          }
        }
      }
    ],
    "parameters": {
      "struct_val": {
        "temperature": { "float_val": 0.8 },
        "maxOutputTokens": { "int_val": 1024 },
        "topK": { "int_val": 40 },
        "topP": { "float_val": 0.95 }
      }
    }
  }'

Risposta

{
  "outputs": [
    {
      "structVal": {
        "citationMetadata": {
          "structVal": {
            "citations": {}
          }
        },
        "safetyAttributes": {
          "structVal": {
            "categories": {},
            "scores": {},
            "blocked": {
              "boolVal": [
                false
              ]
            }
          }
        },
        "content": {
          "stringVal": [
            RESPONSE
          ]
        }
      }
    }
  ]
}

Chat

L'attuale modello supportato è chat-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
AUTHOR="USER"
MODEL_ID=chat-bison

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}:serverStreamingPredict -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "messages": {
          "list_val": [
            {
              "struct_val": {
                "content": {
                  "string_val": [ "'"${PROMPT}"'" ]
                },
                "author": {
                  "string_val": [ "'"${AUTHOR}"'"]
                }
              }
            }
          ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.5 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

{
  "outputs": [
    {
      "structVal": {
        "candidates": {
          "listVal": [
            {
              "structVal": {
                "content": {
                  "stringVal": [
                    RESPONSE
                  ]
                },
                "author": {
                  "stringVal": [
                    AUTHOR
                  ]
                }
              }
            }
          ]
        },
        "citationMetadata": {
          "listVal": [
            {
              "structVal": {
                "citations": {}
              }
            }
          ]
        },
        "safetyAttributes": {
          "listVal": [
            {
              "structVal": {
                "categories": {},
                "blocked": {
                  "boolVal": [
                    false
                  ]
                },
                "scores": {}
              }
            }
          ]
        }
      }
    }
  ]
}

Codice

L'attuale modello supportato è code-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
MODEL_ID=code-bison

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}:serverStreamingPredict -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "prefix": {
          "string_val": [ "'"${PROMPT}"'" ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.8 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

{
  "outputs": [
    {
      "structVal": {
        "safetyAttributes": {
          "structVal": {
            "categories": {},
            "scores": {},
            "blocked": {
              "boolVal": [
                false
              ]
            }
          }
        },
        "citationMetadata": {
          "structVal": {
            "citations": {}
          }
        },
        "content": {
          "stringVal": [
            RESPONSE
          ]
        }
      }
    }
  ]
}

Chat di codice

L'attuale modello supportato è codechat-bison. Vedi le versioni disponibili.

Richiedi

PROJECT_ID=YOUR_PROJECT_ID
PROMPT="PROMPT"
AUTHOR="USER"
MODEL_ID=codechat-bison

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}:serverStreamingPredict -d \
$'{
  "inputs": [
    {
      "struct_val": {
        "messages": {
          "list_val": [
            {
              "struct_val": {
                "content": {
                  "string_val": [ "'"${PROMPT}"'" ]
                },
                "author": {
                  "string_val": [ "'"${AUTHOR}"'"]
                }
              }
            }
          ]
        }
      }
    }
  ],
  "parameters": {
    "struct_val": {
      "temperature": { "float_val": 0.5 },
      "maxOutputTokens": { "int_val": 1024 },
      "topK": { "int_val": 40 },
      "topP": { "float_val": 0.95 }
    }
  }
}'

Risposta

{
  "outputs": [
    {
      "structVal": {
        "candidates": {
          "listVal": [
            {
              "structVal": {
                "content": {
                  "stringVal": [
                    RESPONSE
                  ]
                },
                "author": {
                  "stringVal": [
                    AUTHOR
                  ]
                }
              }
            }
          ]
        },
        "citationMetadata": {
          "listVal": [
            {
              "structVal": {
                "citations": {}
              }
            }
          ]
        },
        "safetyAttributes": {
          "listVal": [
            {
              "structVal": {
                "categories": {},
                "blocked": {
                  "boolVal": [
                    false
                  ]
                },
                "scores": {}
              }
            }
          ]
        }
      }
    }
  ]
}

SDK Vertex AI per Python

Per informazioni sull'installazione dell'SDK Vertex AI per Python, consulta Installare l'SDK Vertex AI per Python.

Testo

  import vertexai
  from vertexai.language_models import TextGenerationModel

  def streaming_prediction(
      project_id: str,
      location: str,
  ) -> str:
      """Streaming Text Example with a Large Language Model"""

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

  text_generation_model = TextGenerationModel.from_pretrained("text-bison")
  parameters = {
      "temperature": temperature,  # Temperature controls the degree of randomness in token selection.
      "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
      "top_p": 0.8,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
      "top_k": 40,  # A top_k of 1 means the selected token is the most probable among all tokens.
  }

  responses = text_generation_model.predict_streaming(prompt="Give me ten interview questions for the role of program manager.", **parameters)
  for response in responses:
      `print(response)`

Chat

import vertexai
from vertexai.language_models import ChatModel, InputOutputTextPair

def streaming_prediction(
    project_id: str,
    location: str,
) -> str:
    """Streaming Chat Example with a Large Language Model"""

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

    chat_model = ChatModel.from_pretrained("chat-bison")

    parameters = {
        "temperature": 0.8,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
        "top_p": 0.95,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
        "top_k": 40,  # A top_k of 1 means the selected token is the most probable among all tokens.
    }

    chat = chat_model.start_chat(
        context="My name is Miles. You are an astronomer, knowledgeable about the solar system.",
        examples=[
            InputOutputTextPair(
                input_text="How many moons does Mars have?",
                output_text="The planet Mars has two moons, Phobos and Deimos.",
            ),
        ],
    )

    responses = chat.send_message_streaming(
        message="How many planets are there in the solar system?", **parameters)
    for response in responses:
        `print(response)`

Codice

import vertexai
from vertexai.language_models import CodeGenerationModel

def streaming_prediction(
    project_id: str,
    location: str,
) -> str:
    """Streaming Chat Example with a Large Language Model"""

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

    code_model = CodeGenerationModel.from_pretrained("code-bison")
    parameters = {
        "temperature": 0.8,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
    }

    responses = code_model.predict_streaming(
        prefix="Write a function that checks if a year is a leap year.", **parameters)
    for response in responses:
        `print(response)`

Chat di codice

import vertexai
from vertexai.language_models import CodeChatModel

def streaming_prediction(
    project_id: str,
    location: str,
) -> str:
    """Streaming Chat Example with a Large Language Model"""

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

    codechat_model = CodeChatModel.from_pretrained("codechat-bison")
    parameters = {
        "temperature": 0.8,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 1024,  # Token limit determines the maximum amount of text output.
    }
    codechat = codechat_model.start_chat()

    responses = codechat.send_message_streaming(
        message="Please help write a function to calculate the min of two numbers", **parameters)
    for response in responses:
        `print(response)`

Librerie client disponibili

Puoi utilizzare una delle seguenti librerie client per trasmettere le risposte in streaming:

  • Python
  • Node.js
  • Java

Per visualizzare richieste di codice e risposte di esempio utilizzando l'API REST, consulta Esempi di utilizzo dell'API REST.

Per visualizzare richieste di codice e risposte di esempio utilizzando l'SDK Vertex AI per Python, consulta Esempi di utilizzo dell'SDK Vertex AI per Python.

AI responsabile

I filtri per l'intelligenza artificiale responsabile (RAI) scansionano l'output del flusso mentre il modello lo genera. Se viene rilevata una violazione, i filtri bloccano i token di output in violazione e restituiscono un output con un flag bloccato in safetyAttributes, che termina il flusso.

Passaggi successivi