@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.
| Field | Type | Description |
|---|---|---|
client | GoogleGenAI | The Google GenAI client instance |
opts.cache | GoogleCacheConfig | false | Cache configuration (optional). Omit for defaults, false to disable. |
GoogleCacheConfig:
| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable/disable cache management |
defaultTtlSeconds | number | 300 | TTL for server-side cache objects |
maxEntries | number | 50 | Max concurrent cache entries in memory |
Returns:
| Method | Description |
|---|---|
.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.usageWhen 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)
| Field | Type | Description |
|---|---|---|
prompt | Prompt | The prompt to execute |
options.model | string | FallbackModel<string> | Model name or fallback() wrapper |
options.input | object | Input values |
options.tools | Record<string, unknown>? | Additional Crux tools to merge at call time |
options.toolMiddleware | ToolMiddleware | readonly ToolMiddleware[]? | Tool execution hooks, including Crux resumable approvals through result.messages. |
options.extra.tools | GoogleFunctionDeclaration[]? | Google-native function declarations that bypass Crux tool conversion |
options.temperature | number? | Temperature |
options.maxOutputTokens | number? | Max output tokens |
options.topP | number? | Top-p sampling |
options.topK | number? | Top-k sampling |
options.extra.cache.skip | boolean? | Skip caching for this call |
options.extra.cache.ttlSeconds | number? | TTL in seconds for a newly-created cache on this call |
Returns: normalized Crux generate result with:
result.text— extracted assistant textresult.raw— raw Google SDK responseresult._meta— normalized usage, finish reason, tool calls, and model metadataresult._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.
| Field | Type | Description |
|---|---|---|
prompt | Prompt | The prompt to execute |
options.model | string | FallbackModel<string> | Model name or fallback() wrapper |
options.input | object | Input values |
options.tools | Record<string, unknown>? | Additional Crux tools to merge at call time |
options.toolMiddleware | ToolMiddleware | readonly ToolMiddleware[]? | Tool execution hooks, including Crux resumable approvals through result.messages. |
options.extra.tools | GoogleFunctionDeclaration[]? | Google-native function declarations that bypass Crux tool conversion |
options.temperature | number? | Temperature |
options.maxOutputTokens | number? | Max output tokens |
options.topP | number? | Top-p sampling |
options.topK | number? | Top-k sampling |
options.extra.cache.skip | boolean? | Skip caching for this call |
options.extra.cache.ttlSeconds | number? | TTL in seconds for a newly-created cache on this call |
Returns: Google GenAI stream.
toMessages(sdkMessages)
Convert Google Content[] to canonical Message[].
| Field | Type | Description |
|---|---|---|
sdkMessages | Content[] | Google GenAI content messages |
Returns: Message[]
fromMessages(messages)
Convert canonical Message[] to Google Content[].
| Field | Type | Description |
|---|---|---|
messages | Message[] | 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.
| Field | Type | Description |
|---|---|---|
client | GoogleGenAI | Google GenAI client instance |
model | string | Model 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.
| Field | Type | Description |
|---|---|---|
client | GoogleGenAI | Google GenAI client instance |
model | string | Model 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.
| Field | Type | Description |
|---|---|---|
client | GoogleGenAI | Google GenAI client instance |
config.name | string | Stable embedding identifier |
config.model | string | Google embedding model |
config.dimensions | number | Output vector dimensionality |
config.maxInputTokens | number | Per-input token ceiling |
config.batch.maxSize | number? | Top-level Crux batch size. Defaults to 100. |
config.batch.concurrency | number? | Top-level Crux batch concurrency. Defaults to 1. |
config.taskType | string? | Retrieval/task hint for Google embedding models |
config.title | string? | Document title. Only applies to retrieval-document tasks. |
config.mimeType | string? | Optional input MIME type |
config.autoTruncate | boolean? | Vertex-only truncation behavior |
Types
import type {
CreateGoogleOptions,
GoogleCacheConfig,
GoogleEmbeddingConfig,
GoogleExtra,
GoogleFunctionDeclaration,
GoogleRequest,
} from '@crux/google'Related
- Guide: Execution
- Guide: Embeddings
- Reference: Prompts
- Reference: @crux/ai (Vercel AI SDK)