vertexai

package
v0.61.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package vertexai exposes Google Gen AI capabilities through Vertex AI's GCP backend and Application Default Credentials.

Chat, transcription, speech, and text embedding share the official Google Gen AI DTOs and native protocol boundary with package google while supplying genai.BackendVertexAI, project, and location. Image generation has its own adapter because the current Vertex contract is GenerateContent with Gemini image models, whereas the public Gemini Developer API now recommends the Interactions API. Treating those two transports as interchangeable would leak backend details and preserve deprecated Imagen behavior. Image person controls use ImagePersonGeneration and genai.ProminentPeople; unknown values fail before dispatch. Empty controls omit the parameter so the service retains its default. Aspect ratio and size remain model-defined strings. Native chat request extensions use SDK camelCase fields. Core exclusively owns sampling, output format, reasoning effort, system messages, function tools, and tool choice; duplicate native fields are rejected. Provider-only safety, grounding, modalities, and thinking-budget fields remain available. Thinking budget and Core reasoning effort are mutually exclusive after resolving defaults. The full SDK request converter owns backend-specific admission and wire projection, including image controls, model selection, and cached-content names. One locally prepared request reaches the host HTTP client; strict native response decoding preserves JSON numbers and rejects conflicting Part data payloads. HTTP extensions admit headers and integer-nanosecond timeouts only. Omission and zero add no per-request timeout; host HTTP policy still applies. Code execution is rejected before I/O because Core cannot represent its output and replay losslessly. Execution parts in responses fail validation. Each stream binds the first reported response ID and model version; later omissions preserve them, while conflicting values fail validation. Core ToolCall.ID is replayed unchanged on the call and its matching result, including IDs synthesized when the provider omitted one. ToolResult.IsError alone selects the native error or output envelope. The complete result stays inside it so business fields cannot change its status. Core Citation owns validation of native citations with a URI. Invalid citations fail Call and Stream rather than disappearing from a successful response. Citation-only chunks reach Core's accumulator, which owns text attachment. Thought signatures, including empty-text Parts, survive Core history serialization and replay in their original Part positions. Core Part.Kind owns the thought classification of visible text. Native part_state retains the independent flag on signature-only, tool, and media Parts. Stored visible-text state containing a competing thought flag is rejected. Embedding extensions admit only taskType, title, mimeType, autoTruncate, documentOcr, and audioTrackExtraction. HTTP envelopes are excluded because SDK extra-body merging could overwrite Core's texts, model, or dimensions. An explicit autoTruncate boolean survives SDK encoding; omission leaves the service default intact. The selected model determines whether it applies. Positive dimensions must fit the SDK's int32 representation; the service determines the selected model's supported dimensions. Embedding responses retain the exact native JSON. Optional token, truncation, and billing metadata is projected only when reported, including zero and false.

API keys are not used. Authenticate locally with Application Default Credentials or provide an authenticated HTTP client; production workloads normally use a service account or Workload Identity.

Model availability and regions change independently on Vertex AI. Select an explicit model id and location from the current Vertex model documentation.

Constructors take a context because construction reaches the network. On the Vertex AI backend with application default credentials, building the client resolves them and then asks the resolved credential for its quota project, which is a metadata-server call the context governs — so a caller can bound or cancel its own wiring instead of a background context deciding for it.

See https://cloud.google.com/vertex-ai/generative-ai/docs.

NewSpeechModel performs unary-only Gemini 2.5 speech synthesis. Unary speech and transcription require a STOP finish reason and return the modality's ErrInvalidResponse for truncated, blocked, or unterminated output. Gemini 3.1 uses NewStreamingSpeechModel: Call aggregates Stream, and both require successful stream completion. Call discards partial audio on error. SpeechModelConfig.MaxResponseBytes bounds decoded audio returned by either Call capability; Stream retains the native per-event budget and incremental delivery. Token-count and embedding JSON responses use Core's httpclient.DefaultMaxJSONResponseBytes before native validation or SDK decoding. Native speech_response metadata describes the latest stream event, not a fabricated unary response. Request model overrides must stay in that capability.

Index

Constants

View Source
const (
	Provider = "vertexai"

	RequestExtensionKey               = Provider + protocol.RequestExtensionSuffix
	ResponseExtensionKey              = Provider + protocol.ResponseExtensionSuffix
	SpeechRequestExtensionKey         = Provider + protocol.SpeechRequestExtensionSuffix
	SpeechResponseExtensionKey        = Provider + protocol.SpeechResponseExtensionSuffix
	TranscriptionRequestExtensionKey  = Provider + protocol.TranscriptionRequestExtensionSuffix
	TranscriptionResponseExtensionKey = Provider + protocol.TranscriptionResponseExtensionSuffix
	EmbeddingRequestExtensionKey      = Provider + protocol.EmbeddingRequestExtensionSuffix
	EmbeddingResponseExtensionKey     = Provider + protocol.EmbeddingResponseExtensionSuffix
	ImageRequestExtensionKey          = Provider + protocol.ImageRequestExtensionSuffix
	ImageResponseExtensionKey         = Provider + protocol.ImageResponseExtensionSuffix

	ModelGemini25FlashImage = "gemini-2.5-flash-image"
	ModelGemini3ProImage    = "gemini-3-pro-image"
)
View Source
const (
	// LocationUSCentral1 is the global default for most generative
	// models (Gemini, Imagen, embedding).
	LocationUSCentral1 = "us-central1"

	// LocationGlobal is the multi-region endpoint — useful for
	// latency-sensitive workloads that can tolerate Google's
	// internal routing.
	LocationGlobal = "global"

	// LocationEuropeWest4 hosts Gemini and Imagen in the EU.
	LocationEuropeWest4 = "europe-west4"

	// LocationAsiaSoutheast1 (Singapore) hosts Gemini in APAC.
	LocationAsiaSoutheast1 = "asia-southeast1"

	// LocationAsiaNortheast1 (Tokyo) hosts Gemini in Japan.
	LocationAsiaNortheast1 = "asia-northeast1"
)

Common Vertex AI regions. See https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations for the full list — coverage varies by model.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chat

type Chat protocol.Chat

Chat wraps this provider's protocol implementation so the wire type stays unexported. Callers depend on the Core modality contract, which lets the protocol change without breaking this module's public surface.

func NewChat

func NewChat(ctx context.Context, config ChatConfig) (*Chat, error)

func (*Chat) Call

func (c *Chat) Call(ctx context.Context, req *corechat.Request) (*corechat.Response, error)

func (*Chat) Stream

type ChatConfig

type ChatConfig struct {
	Client         ClientConfig
	DefaultOptions corechat.Options
}

func (ChatConfig) Validate

func (c ChatConfig) Validate() error

type ClientConfig

type ClientConfig struct {
	Project    string
	Location   string
	BaseURL    string
	HTTPClient *http.Client
}

HTTPClient remains caller-owned and is never closed by a model; BaseURL is reserved for compatible gateways and test servers.

func (ClientConfig) Validate

func (c ClientConfig) Validate() error

type EmbeddingModel

type EmbeddingModel = callModel[embedding.Request, embedding.Response]

EmbeddingModel exposes the VertexAI embedding capability. Its zero value rejects calls.

func NewEmbeddingModel

func NewEmbeddingModel(ctx context.Context, config EmbeddingModelConfig) (*EmbeddingModel, error)

type EmbeddingModelConfig

type EmbeddingModelConfig struct {
	Client         ClientConfig
	DefaultOptions embedding.Options
}

func (EmbeddingModelConfig) Validate

func (e EmbeddingModelConfig) Validate() error

type ImageGenerationOptions

type ImageGenerationOptions struct {
	InputImages              []*media.Media        `json:"input_images,omitempty"`
	AspectRatio              string                `json:"aspect_ratio,omitempty"`
	ImageSize                string                `json:"image_size,omitempty"`
	PersonGeneration         ImagePersonGeneration `json:"person_generation,omitempty"`
	ProminentPeople          genai.ProminentPeople `json:"prominent_people,omitempty"`
	OutputCompressionQuality *int32                `json:"output_compression_quality,omitzero"`
}

ImageGenerationOptions carries Vertex-specific GenerateContent controls and optional source images for editing. Store it under ImageRequestExtensionKey.

func (*ImageGenerationOptions) UnmarshalJSON added in v0.58.0

func (i *ImageGenerationOptions) UnmarshalJSON(data []byte) error

type ImageModel

type ImageModel struct {
	// contains filtered or unexported fields
}

ImageModel implements Gemini native image generation on Vertex AI through GenerateContent. It intentionally does not expose Imagen's Predict endpoint: Google deprecated the Imagen GA endpoints in favor of Gemini image models.

func NewImageModel

func NewImageModel(ctx context.Context, config ImageModelConfig) (*ImageModel, error)

func (*ImageModel) Call

func (i *ImageModel) Call(ctx context.Context, req *image.Request) (*image.Response, error)

type ImageModelConfig

type ImageModelConfig struct {
	Client         ClientConfig
	DefaultOptions image.Options
}

func (ImageModelConfig) Validate

func (i ImageModelConfig) Validate() error

type ImagePersonGeneration added in v0.61.0

type ImagePersonGeneration string

ImagePersonGeneration uses GenerateContent's vocabulary. Imagen's similarly named SDK enum uses a different spelling for blocking people.

const (
	ImagePersonGenerationUnspecified ImagePersonGeneration = "PERSON_GENERATION_UNSPECIFIED"
	ImagePersonGenerationAllowAll    ImagePersonGeneration = "ALLOW_ALL"
	ImagePersonGenerationAllowAdult  ImagePersonGeneration = "ALLOW_ADULT"
	ImagePersonGenerationAllowNone   ImagePersonGeneration = "ALLOW_NONE"
)

type SpeechModel added in v0.41.0

type SpeechModel protocol.SpeechModel

SpeechModel wraps this provider's protocol implementation so the wire type stays unexported. Callers depend on the Core modality contract, which lets the protocol change without breaking this module's public surface.

func NewSpeechModel added in v0.41.0

func NewSpeechModel(ctx context.Context, config SpeechModelConfig) (*SpeechModel, error)

func (*SpeechModel) Call added in v0.41.0

func (s *SpeechModel) Call(ctx context.Context, req *speech.Request) (*speech.Response, error)

type SpeechModelConfig added in v0.41.0

type SpeechModelConfig struct {
	Client         ClientConfig
	DefaultOptions speech.Options
	// Call must fit in memory; Stream retains incremental delivery. Zero uses
	// speech.DefaultMaxAudioBytes, and a negative limit is invalid.
	MaxResponseBytes int64
}

func (SpeechModelConfig) Validate added in v0.41.0

func (s SpeechModelConfig) Validate() error

type StreamingSpeechModel added in v0.41.0

type StreamingSpeechModel protocol.StreamingSpeechModel

func NewStreamingSpeechModel added in v0.41.0

func NewStreamingSpeechModel(ctx context.Context, config SpeechModelConfig) (*StreamingSpeechModel, error)

func (*StreamingSpeechModel) Call added in v0.41.0

func (*StreamingSpeechModel) Stream added in v0.41.0

type TranscriptionModel added in v0.41.0

type TranscriptionModel = callModel[transcription.Request, transcription.Response]

TranscriptionModel exposes the VertexAI transcription capability. Its zero value rejects calls.

func NewTranscriptionModel added in v0.41.0

func NewTranscriptionModel(ctx context.Context, config TranscriptionModelConfig) (*TranscriptionModel, error)

type TranscriptionModelConfig added in v0.41.0

type TranscriptionModelConfig struct {
	Client         ClientConfig
	DefaultOptions transcription.Options
}

func (TranscriptionModelConfig) Validate added in v0.41.0

func (t TranscriptionModelConfig) Validate() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL