生成モデルを使用してチャット セッションを作成する

このサンプルでは、生成モデルを使用してチャット セッションを作成する方法を示します。

もっと見る

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

コードサンプル

Go

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Go の設定手順を完了してください。 詳細については、Vertex AI Go API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/genai"
)

// generateChatWithText shows how to generate chat using a text prompt.
func generateChatWithText(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"
	history := []*genai.Content{
		{
			Role: "user",
			Parts: []*genai.Part{
				{Text: "Hello there"},
			},
		},
		{
			Role: "model",
			Parts: []*genai.Part{
				{Text: "Great to meet you. What would you like to know?"},
			},
		},
	}
	chatSession, err := client.Chats.Create(ctx, modelName, nil, history)
	if err != nil {
		return fmt.Errorf("failed to create genai chat session: %w", err)
	}
	contents := genai.Part{Text: "Tell me a story."}
	resp, err := chatSession.SendMessage(ctx, contents)
	if err != nil {
		return fmt.Errorf("failed to send message: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)
	// Example response:
	// Okay, settle in. Let me tell you a story about a quiet cartographer, but not of lands and seas.
	// ...
	// In the sleepy town of Oakhaven, nestled between the Whispering Hills and the Murmuring River, lived a woman named Elara.
	// ...

	return nil
}

Python

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Vertex AI Python API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

client = genai.Client(http_options=HttpOptions(api_version="v1"))
chat_session = client.chats.create(
    model="gemini-2.5-flash",
    history=[
        UserContent(parts=[Part(text="Hello")]),
        ModelContent(
            parts=[Part(text="Great to meet you. What would you like to know?")],
        ),
    ],
)
response = chat_session.send_message("Tell me a story.")
print(response.text)
# Example response:
# Okay, here's a story for you:
# ...

次のステップ

他の Google Cloud プロダクトのコードサンプルを検索およびフィルタするには、Google Cloud サンプル ブラウザをご覧ください。