图片理解

您可以向 Gemini 请求添加图片,以便执行涉及理解所含图片内容的任务。本页面介绍了如何使用 Google Cloud 控制台和 Vertex AI API,在 Vertex AI 中向发送给 Gemini 的请求添加图片。

支持的模型

下表列出了支持图片理解的模型:

模型 图片模态详细信息 试用模型
Gemini 2.0 Flash
gemini-2.0-flash
  • 每个提示的图片数量上限:3,000
试用 Gemini 2.0 Flash
Gemini 2.0 Flash-Lite
gemini-2.0-flash-lite
  • 每个提示的图片数量上限:3,000
试用 Gemini 2.0 Flash-Lite
Gemini 1.5 Flash
gemini-1.5-flash
  • 每个提示的图片数量上限:3,000
试用 Gemini 1.5 Flash
Gemini 1.5 Pro
gemini-1.5-pro
  • 每个提示的图片数量上限:3,000
试用 Gemini 1.5 Pro
Gemini 1.0 Pro Vision
gemini-1.0-pro-vision
  • 每个提示的图片数量上限:16
试用 Gemini 1.0 Pro Vision

如需查看 Gemini 模型支持的语言列表,请参阅 Google 模型的模型信息。如需详细了解如何设计多模态提示,请参阅设计多模态提示。如果您正在寻找一种直接在移动应用和 Web 应用中使用 Gemini 的方法,请参阅适用于 Android、Swift、Web 和 Flutter 应用的 Vertex AI in Firebase SDK

向请求添加图片

您可以在向 Gemini 发送的请求中添加单张图片或多张图片。

单张图片

以下各个标签页中的示例代码展示了标识图片中内容的不同方式。此示例适用于所有多模态 Gemini 模型。

了解如何安装或更新 Google Gen AI SDK for Python
如需了解详情,请参阅 Gen AI SDK for Python API 参考文档python-genai GitHub 代码库
设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions, Part

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.0-flash-001",
    contents=[
        "What is shown in this image?",
        Part.from_uri(
            file_uri="gs://cloud-samples-data/generative-ai/image/scones.jpg",
            mime_type="image/jpeg",
        ),
    ],
)
print(response.text)
# Example response:
# The image shows a flat lay of blueberry scones arranged on parchment paper. There are ...

如需了解如何安装或更新 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, Part

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

image_file = Part.from_uri(
    "gs://cloud-samples-data/generative-ai/image/scones.jpg", "image/jpeg"
)

# Query the model
response = model.generate_content([image_file, "what is this image?"])
print(response.text)
# Example response:
# That's a lovely overhead flatlay photograph of blueberry scones.
# The image features:
# * **Several blueberry scones:** These are the main focus,
# arranged on parchment paper with some blueberry juice stains.
# ...

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

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

流式回答和非流式回答

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

对于流式回答,请使用 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.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.util.Base64;

public class MultimodalQuery {

  public static void main(String[] args) throws Exception {
    // 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";
    String dataImageBase64 = "your-base64-encoded-image";

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


  // Ask the model to recognise the brand associated with the logo image.
  public static String multimodalQuery(String projectId, String location, String modelName,
      String dataImageBase64) throws Exception {
    // 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 output;
      byte[] imageBytes = Base64.getDecoder().decode(dataImageBase64);

      GenerativeModel model = new GenerativeModel(modelName, vertexAI);
      GenerateContentResponse response = model.generateContent(
          ContentMaker.fromMultiModalData(
              "What is this image?",
              PartMaker.fromMimeTypeAndData("image/png", imageBytes)
          ));

      output = ResponseHandler.getText(response);
      return output;
    }
  }
}

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

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

流式回答和非流式回答

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

对于流式回答,请使用 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 createNonStreamingMultipartContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-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:');

  // Generate a response
  const response = await generativeVisionModel.generateContent(request);

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

  console.log(fullTextResponse);
}

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

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

流式回答和非流式回答

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

对于流式回答,请使用 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 tryGemini(w io.Writer, projectID string, location string, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-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
}

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

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

流式回答和非流式回答

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

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

  public virtual PredictionServiceClient.StreamGenerateContentStream StreamGenerateContent(GenerateContentRequest request)
  

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

  public virtual Task<GenerateContentResponse> GenerateContentAsync(GenerateContentRequest request)
  

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

示例代码


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.5-flash-001"
    )
    {
        // 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();
    }
}

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

您可以添加存储在 Cloud Storage 中的图片,也可以使用 base64 编码的图片数据。

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

  • LOCATION:处理请求的区域。输入支持的区域。如需查看支持的区域的完整列表,请参阅可用位置
    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的项目 ID
  • FILE_URI:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。 对于 gemini-1.5-progemini-1.5-flash,大小限制为 2 GB。对于 gemini-1.0-pro-vision,大小限制为 20 MB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有图片文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/generative-ai/image/scones.jpg,MIME 类型为 image/jpeg。如需查看此图片,请打开示例图片文件。

  • MIME_TYPE:在 datafileUri 字段中指定的文件的媒体类型。可接受的值包括:
    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv
  • TEXT:要包含在提示中的文本说明。 例如 What is shown in this image?

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

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

cat > request.json << 'EOF'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
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/gemini-1.5-flash:generateContent"

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

@'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
'@  | 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/gemini-1.5-flash:generateContent" | Select-Object -Expand Content

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

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": " The image shows a table with a cup of coffee, a bowl of blueberries, and a plate of scones with blueberries on it. There are also pink flowers on the table."
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.027742893,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.07276838
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.026155617,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.07172113
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.04304285,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.037608635
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.08803312,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.09203286
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 265,
    "candidatesTokenCount": 35,
    "totalTokenCount": 300
  }
}

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

  • LOCATION:处理请求的区域。输入支持的区域。如需查看支持的区域的完整列表,请参阅可用位置
    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的项目 ID
  • B64_BASE_IMAGE
    要在提示中包含内嵌的图片、PDF 或视频的 base64 编码。添加媒体内嵌时,您还必须指定数据的媒体类型 (mimeType)。
  • MIME_TYPE:在 datafileUri 字段中指定的文件的媒体类型。可接受的值包括:
    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv
  • TEXT:要包含在提示中的文本说明。 例如,What is shown in this image?

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

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

cat > request.json << 'EOF'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "inlineData": {
          "data": "B64_BASE_IMAGE",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
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/gemini-1.5-flash:generateContent"

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

@'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "inlineData": {
          "data": "B64_BASE_IMAGE",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
'@  | 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/gemini-1.5-flash:generateContent" | Select-Object -Expand Content

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

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": " The image shows a table with a cup of coffee, a bowl of blueberries, and a plate of scones with blueberries on it. There are also pink flowers on the table."
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.027742893,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.07276838
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.026155617,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.07172113
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.04304285,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.037608635
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.08803312,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.09203286
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 265,
    "candidatesTokenCount": 35,
    "totalTokenCount": 300
  }
}
请注意此示例网址中的以下内容:
  • 使用 generateContent 方法请求在回答完全生成后返回回答。 为了降低真人观众对于延迟的感知度,请使用 streamGenerateContent 方法在生成回答时流式传输回答。
  • 多模态模型 ID 位于网址末尾且位于方法之前(例如 gemini-1.5-flashgemini-1.0-pro-vision)。此示例可能还支持其他模型。
如需使用 Google Cloud 控制台发送多模态提示,请执行以下操作:

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

    前往 Vertex AI Studio

  2. 点击打开自由格式模式

  3. 可选:配置模型和参数:

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

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

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

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

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

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

    • 添加停止序列:可选。输入停止序列,即包含空格的一系列字符。如果模型遇到停止序列,则回答生成会停止。停止序列不包含在回答中,您最多可以添加五个停止序列。

  4. 可选:如需配置高级参数,请点击高级,然后按如下方式进行配置:

    • Top-K:使用滑块或文本框输入 top-K 值。 (Gemini 1.5 不支持)。

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

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

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

    • Top-P:使用滑块或文本框输入 top-P 值。 系统会按照概率从最高到最低的顺序选择词元,直到所选词元的概率总和等于 top-P 的值。如需获得数量最小的变量结果,请将 top-P 设置为 0
    • 回答数量上限:使用滑块或文本框输入要生成的回答数量的值。
    • 流式回答:启用此选项可在生成回答时输出回答。
    • 安全过滤器阈值:选择您看到可能有害的回答的可能性的阈值。
    • 启用接地:多模态提示不支持接地。

  5. 点击插入媒体,然后为文件选择一个来源。

    选择您要上传的文件,然后点击打开

    输入要使用的文件的网址,然后点击插入

    选择存储桶,接着从存储桶选择您要导入的文件,然后点击选择

    1. 选择一个账号,并在您首次选择此选项时同意 Vertex AI Studio 访问您的账号。您可以上传多个文件,但总大小不得超过 10 MB。单个文件的大小不能超过 7 MB。
    2. 点击要添加的文件。
    3. 点击选择

      文件缩略图会显示在提示窗格中。 系统还会显示 token 总数。如果提示数据超过 token 限制,则 token 会被截断,并且不会用于处理数据。

  6. 提示窗格中输入文本提示。

  7. 可选:如需查看 Token ID 到文本Token ID,请点击提示窗格中的 token 数量

  8. 点击提交

  9. 可选:如需将提示保存到我的提示,请点击 保存

  10. 可选:如需获取提示的 Python 代码或 curl 命令,请点击 获取代码

多张图片

以下各个标签页展示了在提示请求中添加多张图片的不同方式。每个示例接受以下两组输入:

  • 热门城市地标的图片
  • 图片的媒体类型
  • 图片中指示城市和地标的文本

该示例还接受第三张图片和媒体类型,但不接受文本。该示例会返回一个文本回答,指明第三张图片中的城市和地标。

这些图片示例适用于所有多模态 Gemini 模型。

了解如何安装或更新 Google Gen AI SDK for Python
如需了解详情,请参阅 Gen AI SDK for Python API 参考文档python-genai GitHub 代码库
设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions, Part

client = genai.Client(http_options=HttpOptions(api_version="v1"))

# Read content from GCS
gcs_file_img_path = "gs://cloud-samples-data/generative-ai/image/scones.jpg"

# Read content from a local file
with open("test_data/latte.jpg", "rb") as f:
    local_file_img_bytes = f.read()

response = client.models.generate_content(
    model="gemini-2.0-flash-001",
    contents=[
        "Generate a list of all the objects contained in both images.",
        Part.from_uri(file_uri=gcs_file_img_path, mime_type="image/jpeg"),
        Part.from_bytes(data=local_file_img_bytes, mime_type="image/jpeg"),
    ],
)
print(response.text)
# Example response:
# Okay, here's the list of objects present in both images:
# ...

如需了解如何安装或更新 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, Part

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-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("gemini-1.5-flash-002")
response = model.generate_content(
    [
        image_file1,
        "city: Rome, Landmark: the Colosseum",
        image_file2,
        "city: Beijing, Landmark: Forbidden City",
        image_file3,
    ]
)
print(response.text)
# Example response:
# city: Rio de Janeiro, Landmark: Christ the Redeemer

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

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

流式回答和非流式回答

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

对于流式回答,请使用 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.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.5-flash-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);
    }
  }
}

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

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

流式回答和非流式回答

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

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

  const streamingResp = await generativeModel.generateContentStream(request);
  

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

  const streamingResp = await generativeModel.generateContent(request);
  

示例代码

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

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

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

流式回答和非流式回答

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

对于流式回答,请使用 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"
	"fmt"
	"io"
	"mime"
	"path/filepath"

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

// generateMultimodalContent shows how to generate a text from a multimodal prompt using the Gemini model,
// writing the response to the provided io.Writer.
func generateMultimodalContent(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-001"
	ctx := context.Background()

	// create prompt image parts
	colosseum := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext("landmark1.png")),
		FileURI:  "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png",
	}
	forbiddenCity := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext("landmark2.png")),
		FileURI:  "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark2.png",
	}
	newImage := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext("landmark3.png")),
		FileURI:  "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark3.png",
	}
	// 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
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

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

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

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

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

流式回答和非流式回答

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

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

  public virtual PredictionServiceClient.StreamGenerateContentStream StreamGenerateContent(GenerateContentRequest request)
  

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

  public virtual Task<GenerateContentResponse> GenerateContentAsync(GenerateContentRequest request)
  

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

示例代码


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

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

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

  • LOCATION:处理请求的区域。输入支持的区域。如需查看支持的区域的完整列表,请参阅可用位置
    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的项目 ID
  • FILE_URI1:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。 对于 gemini-1.5-progemini-1.5-flash,大小限制为 2 GB。对于 gemini-1.0-pro-vision,大小限制为 20 MB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有图片文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png,MIME 类型为 image/png。如需查看此图片,请打开示例图片文件。

  • MIME_TYPE:在 datafileUri 字段中指定的文件的媒体类型。可接受的值包括:
    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv
    为简单起见,此示例对所有三张输入图片都使用相同的媒体类型。
  • TEXT1:要包含在提示中的文本说明。 例如 city: Rome, Landmark: the Colosseum
  • FILE_URI2:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。 对于 gemini-1.5-progemini-1.5-flash,大小限制为 2 GB。对于 gemini-1.0-pro-vision,大小限制为 20 MB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有图片文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/vertex-ai/llm/prompts/landmark2.png,MIME 类型为 image/png。如需查看此图片,请打开示例图片文件。

  • TEXT2:要包含在提示中的文本说明。 例如 city: Beijing, Landmark: Forbidden City
  • FILE_URI3:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。 对于 gemini-1.5-progemini-1.5-flash,大小限制为 2 GB。对于 gemini-1.0-pro-vision,大小限制为 20 MB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有图片文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/vertex-ai/llm/prompts/landmark3.png,MIME 类型为 image/png。如需查看此图片,请打开示例图片文件。

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

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

cat > request.json << 'EOF'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI1",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT1"
      },
      {
        "fileData": {
          "fileUri": "FILE_URI2",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT2"
      },
      {
        "fileData": {
          "fileUri": "FILE_URI3",
          "mimeType": "MIME_TYPE"
        }
      }
    ]
  }
}
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/gemini-1.5-flash:generateContent"

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

@'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI1",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT1"
      },
      {
        "fileData": {
          "fileUri": "FILE_URI2",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT2"
      },
      {
        "fileData": {
          "fileUri": "FILE_URI3",
          "mimeType": "MIME_TYPE"
        }
      }
    ]
  }
}
'@  | 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/gemini-1.5-flash:generateContent" | Select-Object -Expand Content

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

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "city: Rio de Janeiro, Landmark: Christ the Redeemer statue \n"
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.05340333,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.08740791
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.13050689,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.10338596
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.05399884,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.09947021
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.10576342,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.066934206
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 791,
    "candidatesTokenCount": 14,
    "totalTokenCount": 805
  }
}
请注意此示例网址中的以下内容:
  • 使用 generateContent 方法请求在回答完全生成后返回回答。 为了降低真人观众对于延迟的感知度,请使用 streamGenerateContent 方法在生成回答时流式传输回答。
  • 多模态模型 ID 位于网址末尾且位于方法之前(例如 gemini-1.5-flashgemini-1.0-pro-vision)。此示例可能还支持其他模型。
如需使用 Google Cloud 控制台发送多模态提示,请执行以下操作:

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

    前往 Vertex AI Studio

  2. 点击打开自由格式模式

  3. 可选:配置模型和参数:

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

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

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

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

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

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

    • 添加停止序列:可选。输入停止序列,即包含空格的一系列字符。如果模型遇到停止序列,则回答生成会停止。停止序列不包含在回答中,您最多可以添加五个停止序列。

  4. 可选:如需配置高级参数,请点击高级,然后按如下方式进行配置:

    • Top-K:使用滑块或文本框输入 top-K 值。 (Gemini 1.5 不支持)。

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

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

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

    • Top-P:使用滑块或文本框输入 top-P 值。 系统会按照概率从最高到最低的顺序选择词元,直到所选词元的概率总和等于 top-P 的值。如需获得数量最小的变量结果,请将 top-P 设置为 0
    • 回答数量上限:使用滑块或文本框输入要生成的回答数量的值。
    • 流式回答:启用此选项可在生成回答时输出回答。
    • 安全过滤器阈值:选择您看到可能有害的回答的可能性的阈值。
    • 启用接地:多模态提示不支持接地。

  5. 点击插入媒体,然后为文件选择一个来源。

    选择您要上传的文件,然后点击打开

    输入要使用的文件的网址,然后点击插入

    选择存储桶,接着从存储桶选择您要导入的文件,然后点击选择

    1. 选择一个账号,并在您首次选择此选项时同意 Vertex AI Studio 访问您的账号。您可以上传多个文件,但总大小不得超过 10 MB。单个文件的大小不能超过 7 MB。
    2. 点击要添加的文件。
    3. 点击选择

      文件缩略图会显示在提示窗格中。 系统还会显示 token 总数。如果提示数据超过 token 限制,则 token 会被截断,并且不会用于处理数据。

  6. 提示窗格中输入文本提示。

  7. 可选:如需查看 Token ID 到文本Token ID,请点击提示窗格中的 token 数量

  8. 点击提交

  9. 可选:如需将提示保存到我的提示,请点击 保存

  10. 可选:如需获取提示的 Python 代码或 curl 命令,请点击 获取代码

设置可选模型参数

每个模型都有一组可设置的可选参数。如需了解详情,请参阅内容生成参数

图片要求

多模态 Gemini 模型支持以下图片 MIME 类型:

图片 MIME 类型 Gemini 2.0 Flash Gemini 2.0 Flash-Lite Gemini 1.5 Flash Gemini 1.5 Pro Gemini 1.0 Pro Vision
PNG - image/png
JPEG - image/jpeg
WebP - image/webp

对图片中的像素数量没有具体限制。不过,较大的图片会被缩小和填充,以适应最大分辨率 (3072 x 3072),同时保留其原始宽高比。

提示请求中允许的图片文件数量上限如下:

  • Gemini 2.0 Flash、Gemini 2.0 Flash-Lite、Gemini 1.5 Flash 和 Gemini 1.5 Pro:3,000 张图片
  • Gemini 1.0 Pro Vision:16 张图片

以下是图片的 token 计算方式:

  • Gemini 2.0 Flash、Gemini 2.0 Flash-Lite、Gemini 1.5 Flash 和 Gemini 1.5 Pro
    • 如果图片的两个维度均小于或等于 384 像素,则使用 258 个 token。
    • 如果图片的某个尺寸大于 384 像素,则图片会被剪裁成图块。每个图块大小默认为最小维度(宽度或高度)除以 1.5。如有必要,系统会调整每个图块,使其不小于 256 像素且不大于 768 像素。随后系统会将每个图块的大小调整为 768x768,并使用 258 个 token。
  • Gemini 1.0 Pro Vision:每张图片占 258 个 token。

最佳做法

使用图片时,请遵循以下最佳实践和信息以获得最佳结果。

  • 如果您想要检测图片中的文本,则使用包含单张图片的提示可生成比包含多张图片的提示更好的结果。
  • 如果提示包含单张图片,请将该图片放在请求中的文本提示前面。
  • 如果您的提示包含多张图片,并且您希望稍后在提示中引用这些图片,或者希望模型在模型回答中引用这些图片,则在图片之前为每张图片提供索引会有所帮助。对于索引,请使用 a b cimage 1 image 2 image 3。以下是在提示中使用已编入索引的图片的示例:
    image 1 
    image 2 
    image 3 
    
    Write a blogpost about my day using image 1 and image 2. Then, give me ideas
    for tomorrow based on image 3.
  • 使用分辨率更高的图片;这样可生成更好的结果。
  • 在提示中添加一些示例。
  • 请先将图片旋转到适当方向,然后再将其添加到提示中。
  • 避免使用模糊的图片。

限制

虽然多模态 Gemini 模型在许多多模态应用场景中表现出强大功能,但了解模型的限制非常重要:

  • 内容审核:模型拒绝对违反我们安全政策的图片提供回答。
  • 空间推理:模型在定位图片中的文本或对象时并不精确。它们可能只返回对象数的近似值。
  • 医疗用途:模型不适合解读医学图片(例如 X 光片和 CT 扫描),也不适合提供医学建议。
  • 人物识别:模型不应用于识别图片中并非名人的人。
  • 准确率:模型在解读低画质、旋转或分辨率极低的图片时可能会产生幻觉或出错。在解读图片文档中的手写文本时,模型也可能会产生幻觉。

后续步骤