Crux
API ReferenceAdapters

@crux/google

Google GenAI SDK adapter — factory pattern with provider caching plus dense embedding helpers.

Peer dependency: @google/genai

import { createGoogle, embedding, googleProviderRuntime, googleTranscript, toMessages, fromMessages } from '@crux/google'
import { createGenerateObjectFn, createGenerateTextFn } from '@crux/google'

For usage examples and provider comparison, see the Execution guide.

createGoogle(client, opts?)

Create an adapter bound to a Google GenAI client with optional cache configuration.

createGoogle() binds googleProviderRuntime.create(client, { cacheManager }) after resolving cache options. The package-owned googleTranscript owns Content[] conversion plus assistant text/function-call extraction. The Google package still owns the SDK request shape, function-call normalization, response metadata normalization, and CachedContent manager; the provider runtime supplies the adapter shell and default tool-round formatting.

FieldTypeDescription
clientGoogleGenAIThe Google GenAI client instance
opts.cacheGoogleCacheConfig | falseCache configuration (optional). Omit for defaults, false to disable.

GoogleCacheConfig:

FieldTypeDefaultDescription
enabledbooleantrueEnable/disable cache management
defaultTtlSecondsnumber300TTL for server-side cache objects
maxEntriesnumber50Max concurrent cache entries in memory

Returns:

MethodDescription
.generate(prompt, options)Execute a prompt via Google GenAI with Zod validation (structured) or text generation
.stream(prompt, options)Stream a prompt execution
import { createGoogle } from '@crux/google'
import { GoogleGenAI } from '@google/genai'

const adapter = createGoogle(new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY }))

const result = await adapter.generate(sentiment, {
  model: 'gemini-2.5-flash',
  input: { text: 'Great product!' },
})
result.text
result._meta.usage

When the leading resolved system blocks have providerCache: true, the adapter automatically creates and reuses a Google CachedContent object for that prefix, then sends any uncached remainder as systemInstruction. The cache manager is passed to the native chat profile as provider-owned dependencies, so the same planner is used for generate() and stream() without moving cache lifecycle into core.

// Custom cache configuration
const adapter = createGoogle(client, {
  cache: { defaultTtlSeconds: 600, maxEntries: 100 },
})

// Disable caching entirely
const adapter = createGoogle(client, { cache: false })

// Skip or tune cache lifecycle for one request
await adapter.generate(prompt, {
  model: 'gemini-2.5-flash',
  extra: { cache: { ttlSeconds: 600 } },
})

adapter.generate(prompt, options)

FieldTypeDescription
promptPromptThe prompt to execute
options.modelstring | FallbackModel<string>Model name or fallback() wrapper
options.inputobjectInput values
options.toolsRecord<string, unknown>?Additional Crux tools to merge at call time
options.toolMiddlewareToolMiddleware | readonly ToolMiddleware[]?Tool execution hooks, including Crux resumable approvals through result.messages.
options.extra.toolsGoogleFunctionDeclaration[]?Google-native function declarations that bypass Crux tool conversion
options.temperaturenumber?Temperature
options.maxOutputTokensnumber?Max output tokens
options.topPnumber?Top-p sampling
options.topKnumber?Top-k sampling
options.extra.cache.skipboolean?Skip caching for this call
options.extra.cache.ttlSecondsnumber?TTL in seconds for a newly-created cache on this call

Returns: normalized Crux generate result with:

  • result.text — extracted assistant text
  • result.raw — raw Google SDK response
  • result._meta — normalized usage, finish reason, tool calls, and model metadata
  • result._meta.usage.cacheReadTokens — tokens served from cache when available

Structured output is validated with Zod after generation. Invalid JSON from the model produces a Zod error, not a Google SDK error.

adapter.stream(prompt, options)

Stream a prompt execution.

FieldTypeDescription
promptPromptThe prompt to execute
options.modelstring | FallbackModel<string>Model name or fallback() wrapper
options.inputobjectInput values
options.toolsRecord<string, unknown>?Additional Crux tools to merge at call time
options.toolMiddlewareToolMiddleware | readonly ToolMiddleware[]?Tool execution hooks, including Crux resumable approvals through result.messages.
options.extra.toolsGoogleFunctionDeclaration[]?Google-native function declarations that bypass Crux tool conversion
options.temperaturenumber?Temperature
options.maxOutputTokensnumber?Max output tokens
options.topPnumber?Top-p sampling
options.topKnumber?Top-k sampling
options.extra.cache.skipboolean?Skip caching for this call
options.extra.cache.ttlSecondsnumber?TTL in seconds for a newly-created cache on this call

Returns: Google GenAI stream.

toMessages(sdkMessages)

Convert Google Content[] to canonical Message[].

FieldTypeDescription
sdkMessagesContent[]Google GenAI content messages

Returns: Message[]

fromMessages(messages)

Convert canonical Message[] to Google Content[].

FieldTypeDescription
messagesMessage[]Canonical messages

Returns: Content[]

Assistant tool calls become functionCall parts and tool results become functionResponse parts. When Google does not provide a tool-call id, the adapter synthesizes stable per-turn ids such as tc_0 for the Crux tool round.

googleTranscript is the lower-level NativeTranscriptCodec used by createGoogle(). The public toMessages() and fromMessages() wrappers delegate to it.

createGenerateObjectFn(client, model)

Create a GenerateObjectFn bound to a client and model.

FieldTypeDescription
clientGoogleGenAIGoogle GenAI client instance
modelstringModel name

Returns: GenerateObjectFn

This is a provider-native helper. It uses Google GenAI structured JSON output and returns the parsed { object }, preserving provider errors. It does not run Crux prompt resolution, validation retry, safety, cassettes, tools, memory capture, or instrumentation. Use createGenerateObjectFnFromGenerate(generate) from @crux/core/compaction when a GenerateObjectFn needs full adapter runtime behavior.

createGenerateTextFn(client, model)

Create a GenerateTextFn bound to a client and model.

FieldTypeDescription
clientGoogleGenAIGoogle GenAI client instance
modelstringModel name

Returns: GenerateTextFn

embedding(client, config)

Create a dense Crux embedding backed by client.models.embedContent().

import { GoogleGenAI } from '@google/genai'
import { embedding } from '@crux/google'

const client = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY })

const docsEmbedding = embedding(client, {
  name: 'docs-embedding',
  model: 'text-embedding-004',
  dimensions: 768,
  maxInputTokens: 2048,
  taskType: 'RETRIEVAL_DOCUMENT',
})

This helper is dense-only. Google's SDK returns token counts per embedded input when available, and the Crux helper aggregates them into embedding usage metadata automatically.

FieldTypeDescription
clientGoogleGenAIGoogle GenAI client instance
config.namestringStable embedding identifier
config.modelstringGoogle embedding model
config.dimensionsnumberOutput vector dimensionality
config.maxInputTokensnumberPer-input token ceiling
config.batch.maxSizenumber?Top-level Crux batch size. Defaults to 100.
config.batch.concurrencynumber?Top-level Crux batch concurrency. Defaults to 1.
config.taskTypestring?Retrieval/task hint for Google embedding models
config.titlestring?Document title. Only applies to retrieval-document tasks.
config.mimeTypestring?Optional input MIME type
config.autoTruncateboolean?Vertex-only truncation behavior

Types

import type {
  CreateGoogleOptions,
  GoogleCacheConfig,
  GoogleEmbeddingConfig,
  GoogleExtra,
  GoogleFunctionDeclaration,
  GoogleRequest,
} from '@crux/google'

On this page