发送文本提示请求

借助 Vertex 生成式 AI,您可以使用 Google Cloud 控制台中的 Vertex AI Studio、Vertex AI API 和 Python 版 Vertex AI SDK 测试提示。本页面介绍了如何使用上述任何界面测试文本提示。

如需详细了解文本提示设计,请参阅设计文本提示

测试文本提示

如需测试文本提示,请选择以下方法之一。

REST

如需使用 Vertex AI API 测试文本提示,请向发布方模型端点发送 POST 请求。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • PROMPT:提示是提交到语言模型用以接收回答的自然语言请求。提示可以包含问题、说明、语境信息、示例和文本,供模型完成或继续。 (请勿为此处的提示添加引号。)
  • TEMPERATURE:温度 (temperature) 在生成回答期间用于采样,在应用 topPtopK 时会生成回答。温度可以控制词元选择的随机性。 较低的温度有利于需要更少开放性或创造性回复的提示,而较高的温度可以带来更具多样性或创造性的结果。温度为 0 表示始终选择概率最高的词元。在这种情况下,给定提示的回复大多是确定的,但可能仍然有少量变化。

    如果模型返回的回答过于笼统、过于简短,或者模型给出后备回答,请尝试提高温度。

  • MAX_OUTPUT_TOKENS:回答中可生成的词元数量上限。词元约为 4 个字符。100 个词元对应大约 60-80 个单词。

    指定较低的值可获得较短的回答,指定较高的值可获得可能较长的回答。

  • TOP_P:Top-P 可更改模型选择输出词元的方式。系统会按照概率从最高(见 top-K)到最低的顺序选择词元,直到所选词元的概率总和等于 top-P 的值。例如,如果词元 A、B 和 C 的概率分别为 0.3、0.2 和 0.1,并且 top-P 值为 0.5,则模型将选择 A 或 B 作为下一个词元(通过温度确定),并会排除 C,将其作为候选词元。

    指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

  • TOP_K:Top-K 可更改模型选择输出词元的方式。如果 top-K 设为 1,表示所选词元是模型词汇表的所有词元中概率最高的词元(也称为贪心解码)。如果 top-K 设为 3,则表示系统将从 3 个概率最高的词元(通过温度确定)中选择下一个词元。

    在每个词元选择步骤中,系统都会对概率最高的 top-K 词元进行采样。然后,系统会根据 top-P 进一步过滤词元,并使用温度采样选择最终的词元。

    指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

HTTP 方法和网址:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict

请求 JSON 正文:

{
  "instances": [
    { "prompt": "PROMPT"}
  ],
  "parameters": {
    "temperature": TEMPERATURE,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "topP": TOP_P,
    "topK": TOP_K
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

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/text-bison:predict"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$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/text-bison:predict" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应。

text-bison curl 命令示例

MODEL_ID="text-bison"
PROJECT_ID=PROJECT_ID

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}:predict -d \
$'{
  "instances": [
    { "prompt": "Give me ten interview questions for the role of program manager." }
  ],
  "parameters": {
    "temperature": 0.2,
    "maxOutputTokens": 256,
    "topK": 40,
    "topP": 0.95
  }
}'

Python

如需了解如何安装或更新 Python 版 Vertex AI SDK,请参阅安装 Python 版 Vertex AI SDK。 如需了解详情,请参阅 Python API 参考文档

import vertexai

from vertexai.language_models import TextGenerationModel

# TODO(developer): Update values for project_id, location & temperature
vertexai.init(project=project_id, location=location)
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.
}

model = TextGenerationModel.from_pretrained("text-bison@002")
response = model.predict(
    "Give me ten interview questions for the role of program manager.",
    **parameters,
)
print(f"Response from Model: {response.text}")

return response.text

Go

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Go 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Go API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import (
	"context"
	"fmt"
	"io"

	aiplatform "cloud.google.com/go/aiplatform/apiv1beta1"
	"cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb"
	"google.golang.org/api/option"
	"google.golang.org/protobuf/types/known/structpb"
)

// textPredict generates text from prompt and configurations provided.
func textPredict(w io.Writer, prompt, projectID, location, publisher, model string, parameters map[string]interface{}) error {
	ctx := context.Background()

	apiEndpoint := fmt.Sprintf("%s-aiplatform.googleapis.com:443", location)

	client, err := aiplatform.NewPredictionClient(ctx, option.WithEndpoint(apiEndpoint))
	if err != nil {
		fmt.Fprintf(w, "unable to create prediction client: %v", err)
		return err
	}
	defer client.Close()

	// PredictRequest requires an endpoint, instances, and parameters
	// Endpoint
	base := fmt.Sprintf("projects/%s/locations/%s/publishers/%s/models", projectID, location, publisher)
	url := fmt.Sprintf("%s/%s", base, model)

	// Instances: the prompt to use with the text model
	promptValue, err := structpb.NewValue(map[string]interface{}{
		"prompt": prompt,
	})
	if err != nil {
		fmt.Fprintf(w, "unable to convert prompt to Value: %v", err)
		return err
	}

	// Parameters: the model configuration parameters
	parametersValue, err := structpb.NewValue(parameters)
	if err != nil {
		fmt.Fprintf(w, "unable to convert parameters to Value: %v", err)
		return err
	}

	// PredictRequest: create the model prediction request
	req := &aiplatformpb.PredictRequest{
		Endpoint:   url,
		Instances:  []*structpb.Value{promptValue},
		Parameters: parametersValue,
	}

	// PredictResponse: receive the response from the model
	resp, err := client.Predict(ctx, req)
	if err != nil {
		fmt.Fprintf(w, "error in prediction: %v", err)
		return err
	}

	fmt.Fprintf(w, "text-prediction response: %v", resp.Predictions[0])
	return nil
}

Java

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Java API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextPromptSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Details of designing text prompts for supported large language models:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/text/text-overview
    String instance =
        "{ \"prompt\": " + "\"Give me ten interview questions for the role of program manager.\"}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0.2,\n"
            + "  \"maxOutputTokens\": 256,\n"
            + "  \"topP\": 0.95,\n"
            + "  \"topK\": 40\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String location = "us-central1";
    String publisher = "google";
    String model = "text-bison@001";

    predictTextPrompt(instance, parameters, project, location, publisher, model);
  }

  // Get a text prompt from a supported text model
  public static void predictTextPrompt(
      String instance,
      String parameters,
      String project,
      String location,
      String publisher,
      String model)
      throws IOException {
    String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // 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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

      // Use Value.Builder to convert instance to a dynamically typed value that can be
      // processed by the service.
      Value.Builder parameterValueBuilder = Value.newBuilder();
      JsonFormat.parser().merge(parameters, parameterValueBuilder);
      Value parameterValue = parameterValueBuilder.build();

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameterValue);
      System.out.println("Predict Response");
      System.out.println(predictResponse);
    }
  }
}

Node.js

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Node.js 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Node.js API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

const publisher = 'google';
const model = 'text-bison@001';

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function callPredict() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/publishers/${publisher}/models/${model}`;

  const prompt = {
    prompt:
      'Give me ten interview questions for the role of program manager.',
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

  const parameter = {
    temperature: 0.2,
    maxOutputTokens: 256,
    topP: 0.95,
    topK: 40,
  };
  const parameters = helpers.toValue(parameter);

  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const response = await predictionServiceClient.predict(request);
  console.log('Get text prompt response');
  console.log(response);
}

callPredict();

C#

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 C# 设置说明执行操作。 如需了解详情,请参阅 Vertex AI C# API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.AIPlatform.V1;
using System;
using System.Collections.Generic;
using System.Linq;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class PredictTextPromptSample
{
    public string PredictTextPrompt(
        string projectId = "your-project-id",
        string locationId = "us-central1",
        string publisher = "google",
        string model = "text-bison@001"
    )
    {
        // Initialize client that will be used to send requests.
        // This client only needs to be created
        // once, and can be reused for multiple requests.
        var client = new PredictionServiceClientBuilder
        {
            Endpoint = $"{locationId}-aiplatform.googleapis.com"
        }.Build();

        // Configure the parent resource
        var endpoint = EndpointName.FromProjectLocationPublisherModel(projectId, locationId, publisher, model);

        // Initialize request argument(s)
        var prompt = "Give me ten interview questions for the role of program manager.";

        var instanceValue = Value.ForStruct(new()
        {
            Fields =
            {
                ["prompt"] = Value.ForString(prompt)
            }
        });

        var instances = new List<Value>
        {
            instanceValue
        };

        var parameters = Value.ForStruct(new()
        {
            Fields =
            {
                { "temperature", new Value { NumberValue = 0.2 } },
                { "maxOutputTokens", new Value { NumberValue = 256 } },
                { "topP", new Value { NumberValue = 0.95 } },
                { "topK", new Value { NumberValue = 40 } }
            }
        });

        // Make the request
        var response = client.Predict(endpoint, instances, parameters);

        // Parse and return the content.
        var content = response.Predictions.First().StructValue.Fields["content"].StringValue;
        Console.WriteLine($"Content: {content}");
        return content;
    }
}

Ruby

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Ruby 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Ruby API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/ai_platform/v1"

##
# Vertex AI Predict Text Prompt
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Processor Location (e.g. "us-central1")
# @param publisher [String] The Model Publisher (e.g. "google")
# @param model [String] The Model Identifier (e.g. "text-bison@001")
#
def predict_text_prompt project_id:, location_id:, publisher:, model:
  # Create the Vertex AI client.
  client = ::Google::Cloud::AIPlatform::V1::PredictionService::Client.new do |config|
    config.endpoint = "#{location_id}-aiplatform.googleapis.com"
  end

  # Build the resource name from the project.
  endpoint = client.endpoint_path(
    project: project_id,
    location: location_id,
    publisher: publisher,
    model: model
  )

  prompt = "Give me ten interview questions for the role of program manager."

  # Initialize the request arguments
  instance = Google::Protobuf::Value.new(
    struct_value: Google::Protobuf::Struct.new(
      fields: {
        "prompt" => Google::Protobuf::Value.new(
          string_value: prompt
        )
      }
    )
  )

  instances = [instance]

  parameters = Google::Protobuf::Value.new(
    struct_value: Google::Protobuf::Struct.new(
      fields: {
        "temperature" => Google::Protobuf::Value.new(number_value: 0.2),
        "maxOutputTokens" => Google::Protobuf::Value.new(number_value: 256),
        "topP" => Google::Protobuf::Value.new(number_value: 0.95),
        "topK" => Google::Protobuf::Value.new(number_value: 40)
      }
    )
  )

  # Make the prediction request
  response = client.predict endpoint: endpoint, instances: instances, parameters: parameters

  # Handle the prediction response
  puts "Predict Response"
  puts response
end

控制台

如需在 Google Cloud 控制台中使用 Vertex AI Studio 测试文本提示,请执行以下步骤:

  1. 在 Google Cloud 控制台的“Vertex AI”部分,进入 Vertex AI Studio 页面。

    进入 Vertex AI Studio

  2. 点击开始使用标签页。
  3. 点击 文本提示
  4. 选择输入提示的方法:

    • 对于零样本提示或复制粘贴式的少样本提示,建议使用自由格式
    • 如果要在 Vertex AI Studio 中设计少样本提示,建议使用结构化

    自由格式

    提示文本字段中输入提示。

    结构化

    用于输入提示的结构化方法将提示的组成部分分为不同的字段:

    • 语境:输入您希望模型执行的任务的说明,并添加供模型参考的语境信息。
    • 示例:对于少样本提示,请添加输入-输出样本,用于展示模型要模拟的行为模式。您可以选择性地为输入和输出添加前缀。如果您选择添加前缀,它们应在所有样本中保持一致。
    • 测试:在输入字段中,输入要用于获取回复的提示的输入。可以选择性地为测试输入和输出添加前缀。如果您的样本有前缀,则测试应具有相同的前缀。
  5. 配置模型和参数:

    • 模型:选择 text-bisongemini-1.0-pro 模型。
    • 温度:使用滑块或文本框输入温度值。

      温度 (temperature) 在生成回复期间用于采样,在应用 topPtopK 时会生成回复。温度可以控制词元选择的随机性。 较低的温度有利于需要更少开放性或创造性回复的提示,而较高的温度可以带来更具多样性或创造性的结果。温度为 0 表示始终选择概率最高的词元。在这种情况下,给定提示的回复大多是确定的,但可能仍然有少量变化。

      如果模型返回的回答过于笼统、过于简短,或者模型给出后备回答,请尝试提高温度。

    • 词元上限:使用滑块或文本框输入输出上限值。

      回答中可生成的词元数量上限。词元约为 4 个字符。100 个词元对应大约 60-80 个单词。

      指定较低的值可获得较短的回答,指定较高的值可获得可能较长的回答。

    • Top-K:使用滑块或文本框输入 top-K 值。

      top-K 可更改模型选择输出词元的方式。如果 top-K 设为 1,表示所选词元是模型词汇表的所有词元中概率最高的词元(也称为贪心解码)。如果 top-K 设为 3,则表示系统将从 3 个概率最高的词元(通过温度确定)中选择下一个词元。

      在每个词元选择步骤中,系统都会对概率最高的 top-K 词元进行采样。然后,系统会根据 top-P 进一步过滤词元,并使用温度采样选择最终的词元。

      指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

    • Top-P:使用滑块或文本框输入 top-P 值。 系统会按照概率从最高到最低的顺序选择词元,直到所选词元的概率总和等于 top-P 的值。如需获得数量最小的变量结果,请将 top-P 设置为 0
  6. 点击提交
  7. 可选:如需将提示保存到我的提示,请点击 保存
  8. 可选:如需获取提示的 Python 代码或 curl 命令,请点击 查看代码

流式传输文本模型的回复

如需使用 REST API 查看示例代码请求和响应,请参阅使用 REST API 的示例

如需使用 Python 版 Vertex AI SDK 查看示例代码请求和响应,请参阅使用 Python 版 Vertex AI SDK 的示例

后续步骤