使用多模態 AI 模型產生內容串流

這個程式碼範例會示範如何使用生成式 AI 模型,根據影片、圖片和文字輸入內容的組合,以串流格式生成文字

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:

程式碼範例

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Go API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/genai"
)

// generateChatStreamWithText shows how to generate chat stream using a text prompt.
func generateChatStreamWithText(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.5-flash"

	chatSession, err := client.Chats.Create(ctx, modelName, nil, nil)
	if err != nil {
		return fmt.Errorf("failed to create genai chat session: %w", err)
	}

	var streamErr error
	contents := genai.Part{Text: "Why is the sky blue?"}

	stream := chatSession.SendMessageStream(ctx, contents)
	stream(func(resp *genai.GenerateContentResponse, err error) bool {
		if err != nil {
			streamErr = err
			return false
		}
		for _, cand := range resp.Candidates {
			for _, part := range cand.Content.Parts {
				fmt.Fprintln(w, part.Text)
			}
		}
		return true
	})

	// Example response:
	// The
	// sky appears blue due to a phenomenon called **Rayleigh scattering**.
	// Here's a breakdown:
	// ...

	return streamErr
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Node.js API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateText(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const chatSession = client.chats.create({
    model: 'gemini-2.5-flash',
  });

  for await (const chunk of await chatSession.sendMessageStream({
    message: 'Why is the sky blue?',
  })) {
    console.log(chunk.text);
  }
  // Example response:
  // The
  // sky appears blue due to a phenomenon called **Rayleigh scattering**. Here's
  // a breakdown of why:
  // ...
  return true;
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Python API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
chat_session = client.chats.create(model="gemini-2.5-flash")

for chunk in chat_session.send_message_stream("Why is the sky blue?"):
    print(chunk.text, end="")
# Example response:
# The
#  sky appears blue due to a phenomenon called **Rayleigh scattering**. Here's
#  a breakdown of why:
# ...

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器