Crea una sesión de chat con un modelo generativo

En esta muestra, se indica cómo usar modelos generativos para crear una sesión de chat.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración para Go incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Go.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Python.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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:
# ...

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos Google Cloud , consulta el Google Cloud navegador de muestras.