マルチモーダル AI モデルでコンテンツ ストリーミングを生成する

このコードサンプルでは、生成 AI モデルを使用して、動画、画像、テキストの入力を組み合わせて、ストリーミング形式でテキストを生成する方法を示します。

もっと見る

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

Go

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Go の設定手順を完了してください。 詳細については、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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、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 サンプル ブラウザをご覧ください。