文本生成

本页面介绍了如何使用 Google Cloud 控制台、REST API 和受支持的 SDK 向 Gemini 模型发送聊天提示。

如需了解如何向请求添加图片和其他媒体,请参阅图片理解

如需查看 Gemini 支持的语言列表,请参阅语言支持


如需探索 Vertex AI 上可用的生成式 AI 模型和 API,请转到 Google Cloud 控制台中的 Model Garden。

转到 Model Garden


如果您正在寻找一种直接在移动应用和 Web 应用中使用 Gemini 的方法,请参阅适用于 Android、Swift、Web 和 Flutter 应用的 Vertex AI in Firebase SDK

如需测试和迭代聊天提示,我们建议使用 Google Cloud 控制台。如需以编程方式将提示发送到模型,您可以使用 REST API、Python 版 Vertex AI SDK 或以下标签页中显示的其他受支持的库和 SDK。

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

流式回答和非流式回答

您可以选择模型是生成流式回答还是非流式回答。 对于流式回答,您将在生成每个响应的输出词元后立即收到响应。对于非流式回答,您将在生成所有输出词元后收到所有响应。

对于流式回答,请使用 generate_content 中的 stream 参数。

  response = model.generate_content(contents=[...], stream = True)
  

对于非流式回答,请移除该参数或将参数设置为 False

示例代码

import vertexai

from vertexai.generative_models import GenerativeModel, ChatSession

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-flash-002")

chat_session = 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_session, prompt))
# Example response:
# Hello there! How can I help you today?

prompt = "What are all the colors in a rainbow?"
print(get_chat_response(chat_session, prompt))
# Example response:
# The colors in a rainbow are often remembered using the acronym ROY G. BIV:
# * **Red**
# * **Orange** ...

prompt = "Why does it appear when it rains?"
print(get_chat_response(chat_session, prompt))
# Example response:
# It's important to note that these colors blend smoothly into each other, ...

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

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

流式回答和非流式回答

您可以选择模型是生成流式回答还是非流式回答。 对于流式回答,您将在生成每个响应的输出词元后立即收到响应。对于非流式回答,您会在生成所有输出词元之后收到所有回答。

对于流式回答,请使用 StreamGenerateContent 方法。

  public virtual PredictionServiceClient.StreamGenerateContentStream StreamGenerateContent(GenerateContentRequest request)
  

对于非流式回答,请使用 GenerateContentAsync 方法。

  public virtual Task<GenerateContentResponse> GenerateContentAsync(GenerateContentRequest request)
  

如需详细了解服务器如何流式传输回答,请参阅流式传输 RPC

示例代码


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

public class MultiTurnChatSample
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.5-flash-001"
    )
    {
        // Create a chat session to keep track of the context
        ChatSession chatSession = new ChatSession($"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}", location);

        string prompt = "Hello.";
        Console.WriteLine($"\nUser: {prompt}");

        string response = await chatSession.SendMessageAsync(prompt);
        Console.WriteLine($"Response: {response}");

        prompt = "What are all the colors in a rainbow?";
        Console.WriteLine($"\nUser: {prompt}");

        response = await chatSession.SendMessageAsync(prompt);
        Console.WriteLine($"Response: {response}");

        prompt = "Why does it appear when it rains?";
        Console.WriteLine($"\nUser: {prompt}");

        response = await chatSession.SendMessageAsync(prompt);
        Console.WriteLine($"Response: {response}");

        return response;
    }

    private class ChatSession
    {
        private readonly string _modelPath;
        private readonly PredictionServiceClient _predictionServiceClient;

        private readonly List<Content> _contents;

        public ChatSession(string modelPath, string location)
        {
            _modelPath = modelPath;

            _predictionServiceClient = new PredictionServiceClientBuilder
            {
                Endpoint = $"{location}-aiplatform.googleapis.com"
            }.Build();

            // Initialize contents to send over in every request.
            _contents = new List<Content>();
        }

        public async Task<string> SendMessageAsync(string prompt)
        {
            var content = new Content
            {
                Role = "USER",
                Parts =
                {
                    new Part { Text = prompt }
                }
            };
            _contents.Add(content);

            var generateContentRequest = new GenerateContentRequest
            {
                Model = _modelPath,
                GenerationConfig = new GenerationConfig
                {
                    Temperature = 0.9f,
                    TopP = 1,
                    TopK = 32,
                    CandidateCount = 1,
                    MaxOutputTokens = 2048
                }
            };
            generateContentRequest.Contents.AddRange(_contents);

            GenerateContentResponse response = await _predictionServiceClient.GenerateContentAsync(generateContentRequest);

            _contents.Add(response.Candidates[0].Content);

            return response.Candidates[0].Content.Parts[0].Text;
        }
    }
}

在尝试此示例之前,请按照《生成式 AI 快速入门:使用 Node.js SDK》中的 Node.js 设置说明执行操作。如需了解详情,请参阅适用于 Gemini 的 Node.js SDK 参考文档

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

流式回答和非流式回答

您可以选择模型是生成流式回答还是非流式回答。 对于流式回答,您将在生成每个响应的输出词元后立即收到响应。对于非流式回答,您会在生成所有输出词元之后收到所有回答。

对于流式回答,请使用 generateContentStream 方法。

  const streamingResp = await generativeModel.generateContentStream(request);
  

对于非流式回答,请使用 generateContent 方法。

  const streamingResp = await generativeModel.generateContent(request);
  

示例代码

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);
  }
}

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

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

流式回答和非流式回答

您可以选择模型是生成流式回答还是非流式回答。 对于流式回答,您将在生成每个响应的输出词元后立即收到响应。对于非流式回答,您会在生成所有输出词元之后收到所有回答。

对于流式回答,请使用 generateContentStream 方法。

  public ResponseStream<GenerateContentResponse> generateContentStream(Content content)
  

对于非流式回答,请使用 generateContent 方法。

  public GenerateContentResponse generateContent(Content content)
  

示例代码

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.5-flash-001";

    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.");
    }
  }
}

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

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

流式回答和非流式回答

您可以选择模型是生成流式回答还是非流式回答。 对于流式回答,您将在生成每个响应的输出词元后立即收到响应。对于非流式回答,您会在生成所有输出词元之后收到所有回答。

对于流式回答,请使用 GenerateContentStream 方法。

  iter := model.GenerateContentStream(ctx, genai.Text("Tell me a story about a lumberjack and his giant ox. Keep it very short."))
  

对于非流式回答,请使用 GenerateContent 方法。

  resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
  

示例代码

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

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

func makeChatRequests(ctx context.Context, w io.Writer, projectID, region, modelName string) error {
	client, err := genai.NewClient(ctx, projectID, region)

	if err != nil {
		return fmt.Errorf("error creating client: %w", err)
	}
	defer client.Close()

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

	send := func(message string) error {
		r, err := chat.SendMessage(ctx, genai.Text(message))
		if err != nil {
			return err
		}
		rb, err := json.MarshalIndent(r, "", "  ")
		if err != nil {
			return err
		}
		fmt.Fprintln(w, string(rb))
		return nil
	}

	if err := send("Hello"); err != nil {
		return err
	}
	if err := send("What are all the colors in a rainbow?"); err != nil {
		return err
	}
	return send("Why does it appear when it rains?")
}

设置您的环境后,您可以使用 REST 测试文本提示。以下示例会向发布方模型端点发送请求。

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

  • GENERATE_RESPONSE_METHOD:您希望模型生成的回答类型。选择一种方法来生成您希望返回模型回答的方式:
    • streamGenerateContent:在生成回答时进行流式传输,以降低真人受众群体对于延迟的感知度。
    • generateContent:回答在完全生成后返回。
  • LOCATION:处理请求的区域。可用的选项包括:
    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的项目 ID
  • MODEL_ID:您要使用的多模态模型 ID。一些选项包括:
    • gemini-1.0-pro-002
    • gemini-1.0-pro-vision-001
    • gemini-1.5-pro-002
    • gemini-1.5-flash
  • TEXT1
    要包含在多轮对话的第一个提示中的文本说明。例如,What are all the colors in a rainbow?
  • TEXT2
    要包含在第二个提示中的文本说明。例如,Why does it appear when it rains?
  • TEMPERATURE:温度 (temperature) 在生成回答期间用于采样,在应用 topPtopK 时会生成回答。温度可以控制词元选择的随机性。 较低的温度有利于需要更少开放性或创造性回复的提示,而较高的温度可以带来更具多样性或创造性的结果。温度为 0 表示始终选择概率最高的词元。在这种情况下,给定提示的回复大多是确定的,但可能仍然有少量变化。

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

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

将请求正文保存在名为 request.json 的文件中。在终端中运行以下命令,在当前目录中创建或覆盖此文件:

cat > request.json << 'EOF'
{
  "contents": [
    {
      "role": "user",
      "parts": { "text": "TEXT1" }
    },
    {
      "role": "model",
      "parts": { "text": "What a great question!" }
    },
    {
      "role": "user",
      "parts": { "text": "TEXT2" }
    }
  ],
  "generation_config": {
    "temperature": TEMPERATURE
  }
}
EOF

然后,执行以下命令以发送 REST 请求:

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:GENERATE_RESPONSE_METHOD"

将请求正文保存在名为 request.json 的文件中。在终端中运行以下命令,在当前目录中创建或覆盖此文件:

@'
{
  "contents": [
    {
      "role": "user",
      "parts": { "text": "TEXT1" }
    },
    {
      "role": "model",
      "parts": { "text": "What a great question!" }
    },
    {
      "role": "user",
      "parts": { "text": "TEXT2" }
    }
  ],
  "generation_config": {
    "temperature": TEMPERATURE
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

然后,执行以下命令以发送 REST 请求:

$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:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

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

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "You're right to ask that! Rainbows are a beautiful and fascinating phenomenon. Here's the breakdown:\n\n**1. Sunlight and Water Droplets:**\n\n* Rainbows are created when sunlight interacts with water droplets suspended in the air, typically after rain.\n\n**2. Refraction and Reflection:**\n\n* **Refraction:** When sunlight enters a water droplet, it bends or refracts. This bending is different for each color of light (red bends the least, violet the most).\n* **Reflection:** Inside the droplet, the light bounces off the back surface and then refracts again as it exits the droplet.\n\n**3. Dispersion:**\n\n* The refraction and reflection process separates the white sunlight into its component colors, just like a prism. This separation of colors is called dispersion.\n\n**4. Our Perspective:**\n\n* You only see a rainbow when you're standing with the sun behind you and the rain in front of you. The colors appear in an arc because the angle at which the light refracts and reflects is specific for each color.\n\n**In short:**\n\nRainbows are created when sunlight hits water droplets in the air, causing the light to be refracted, reflected, and dispersed into its individual colors.  \n"
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.06255973,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.039937314
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.096705794,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.08404062
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.10818896,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.036631368
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.116764,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.05023736
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 22,
    "candidatesTokenCount": 256,
    "totalTokenCount": 278
  }
}
请注意此示例网址中的以下内容:
  • 使用 generateContent 方法请求在回答完全生成后返回回答。 为了降低真人观众对于延迟的感知度,请使用 streamGenerateContent 方法在生成回答时流式传输回答。
  • 多模态模型 ID 位于网址末尾且位于方法之前(例如 gemini-1.5-flashgemini-1.0-pro-vision)。此示例可能还支持其他模型。

如需使用 Vertex AI Studio 在 Google Cloud 控制台中发送聊天提示,请执行以下操作:

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

    进入 Vertex AI Studio

  2. 发起对话中,点击文本聊天
  3. 可选:配置模型和参数:

    • 模型:选择 Gemini Pro
    • 区域:选择您要使用的区域。
    • 温度:使用滑块或文本框输入温度值。

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

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

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

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

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

    • 添加停止序列:可选。输入停止序列,即包含空格的一系列字符。如果模型遇到停止序列,则回答生成会停止。停止序列不包含在响应中,您最多可以添加五个停止序列。
  4. 可选:如需配置高级参数,请点击高级,然后按如下方式进行配置:
    • 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
    • 启用接地:添加接地源路径以自定义此功能。
  5. 提示窗格中输入文本提示。随后,模型会使用之前的消息作为新回答的语境。
  6. 可选:如需显示文本词元数量,请点击查看词元。您可以查看文本提示的词元或词元 ID。
    • 如需在文本提示中查看词元(使用不同颜色标记每个词元 ID 的边界进行突出显示),请点击词元 ID 转换为文本。不支持媒体词元。
    • 如需查看词元 ID,请点击词元 ID

      要关闭词元化器工具窗格,请点击 X,或点击窗格外部。

  7. 点击提交
  8. 可选:如需将提示保存到我的提示,请点击 保存
  9. 可选:如需获取提示的 Python 代码或 curl 命令,请点击 获取代码
  10. 可选:如需清除之前的所有消息,请点击 清除对话

您可以使用系统说明根据特定需求或使用情形来控制模型的行为。例如,您可以为响应客户服务请求的聊天机器人定义角色。如需了解详情,请参阅系统指令代码示例

后续步骤