使用 Vertex AI Express 模式生成內容

這個範例會使用 Vertex AI Express 模式生成文字內容。

深入探索

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

程式碼範例

Go

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

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

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/genai"
)

var newClient = genai.NewClient

// generateContent shows how to use Vertex AI Express mode with an API key.
func generateContentWithApiKey(w io.Writer) error {
	ctx := context.Background()

	// TODO(developer): Replace with your actual API key
	apiKey := "YOUR_API_KEY"

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

	modelName := "gemini-2.5-flash"
	resp, err := client.Models.GenerateContent(ctx, modelName,
		[]*genai.Content{
			{Parts: []*genai.Part{
				{Text: "Explain bubble sort to me."},
			}, Role: "user"},
		},
		nil,
	)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	fmt.Fprintln(w, resp.Text())

	// Example response:
	// Bubble Sort is a simple sorting algorithm that repeatedly steps through the list

	return nil
}

Python

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

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

from google import genai

# TODO(developer): Update below line
API_KEY = "YOUR_API_KEY"

client = genai.Client(vertexai=True, api_key=API_KEY)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain bubble sort to me.",
)

print(response.text)
# Example response:
# Bubble Sort is a simple sorting algorithm that repeatedly steps through the list

後續步驟

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