Skip to content

zidane/providers/google

The Google Gemini providers, on the Gemini API with an API key or on Vertex AI with Google Cloud credentials.

import { … } from 'zidane/providers/google'src/providers/google.ts

Use google() for the Gemini API (Google AI Studio). With no key passed, it reads GEMINI_API_KEY, then GOOGLE_API_KEY. Use googleVertex() for Vertex AI. It uses a Vertex API key (GOOGLE_CLOUD_API_KEY) when one is set. Otherwise it uses Google Cloud credentials (GOOGLE_APPLICATION_CREDENTIALS, or the gcloud Application Default Credentials) for GOOGLE_CLOUD_PROJECT in GOOGLE_CLOUD_LOCATION, which defaults to global. Both providers keep the Gemini thought signatures in the session and send them back to the route that issued them. Gemini 3 needs them for multi-step tool use. Without an API key, Vertex AI also takes a service-account key or the metadata server on Google Cloud. Files such as PDFs go to the model as file parts. googleCompatible() runs the same plumbing over another Gemini-wire backend, such as an extension's transport: the route sends the request zidane builds and returns the SSE response.

TypeScript
import { createAgent } from 'zidane'
import { google, googleVertex } from 'zidane/providers/google'

const agent = createAgent({ provider: google({ defaultModel: 'gemini-3.8-flash' }) })
await agent.run({ prompt: 'Summarize README.md in three bullets.' })

const vertex = createAgent({ provider: googleVertex({ project: 'my-project', location: 'us-central1' }) })
await vertex.run({ prompt: 'List the files in this directory.' })

Functions#

classifyGoogleErrorFunction#

Classify a Gemini API / Vertex AI error.

TypeScript
function classifyGoogleError(err: unknown, label?: string): ClassifiedError | null
Parameters
NameTypeDefaultDescription
errunknown

Error a Google provider threw.

label?string'Gemini'

Product a limit's message names; routes over other services (Antigravity) pass their own.

src/providers/google.ts:155

googleFunction#

Creates the Google Gemini provider on the Gemini API (Google AI Studio). Authenticates with apiKey, else GEMINI_API_KEY, else GOOGLE_API_KEY.

TypeScript
function google(params?: GoogleParams): Provider
Parameters
NameTypeDescription
params?GoogleParams

API key, default model, capabilities and extra headers.

Example
import { createAgent } from 'zidane'
import { google } from 'zidane/providers/google'

const agent = createAgent({
  provider: google({ apiKey: process.env.GEMINI_API_KEY }),
})
await agent.run({ prompt: 'Say hello.' })

src/providers/google.ts:481

googleCompatibleFunction#

Creates a provider over another Gemini-wire backend: an extension supplies the transport (send, parseChunk) and model records; message conversion, thought signatures (tagged with the route's scope, never replayed elsewhere), tool names, thinking levels, SSE parsing, usage and cost come from the same plumbing as google and googleVertex.

TypeScript
function googleCompatible(
  route: GoogleCompatibleRoute,
  params?: GoogleSharedParams,
): Provider
Parameters
NameTypeDescription
routeGoogleCompatibleRoute

The backend: name, transport and models.

params?GoogleSharedParams

Default model, capabilities and extra headers.

Example
import { googleCompatible } from 'zidane/providers'

const provider = googleCompatible({
  name: 'my-gateway',
  isOAuth: false,
  send: (turn, fetch) => fetch(`https://gateway.example/v1beta/models/${turn.model.id}:streamGenerateContent?alt=sse`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'authorization': `Bearer ${process.env.MY_GATEWAY_KEY}` },
    body: JSON.stringify(turn.body),
    signal: turn.signal,
  }),
  resolveModel: id => myModels[id],
}, { defaultModel: 'gemini-3.8-flash' })

src/providers/google.ts:452

googleVertexFunction#

Creates the Google Vertex AI provider. Authenticates with a pinned account's Google sign-in, else a Vertex API key (apiKey or GOOGLE_CLOUD_API_KEY), else the active "Sign in with Google" grant, else Google Cloud credentials for project in location. See resolveVertexAuth.

TypeScript
function googleVertex(params?: GoogleVertexParams): Provider
Parameters
NameTypeDescription
params?GoogleVertexParams

Credentials, project, location, default model, capabilities and extra headers.

Example
import { createAgent } from 'zidane'
import { googleVertex } from 'zidane/providers/google'

// After `gcloud auth application-default login`:
const agent = createAgent({
  provider: googleVertex({ project: 'my-project' }),
})
await agent.run({ prompt: 'Say hello.' })

src/providers/google.ts:646

resolveGoogleModelFunction#

Model record for modelId on route: the registry's entry, else a GOOGLE_EXTRA_MODELS overlay, else the default model's shape under the requested id. A catalog entry overlays whichever applies.

TypeScript
function resolveGoogleModel(
  route: GoogleRouteName,
  modelId: string,
  catalog?: ModelCatalog,
): GoogleWireModel
Parameters
NameTypeDescription
routeGoogleRouteName

Backend the request goes to.

modelIdstring

Requested model id.

catalog?ModelCatalog

Per-run catalog override.

src/providers/google.ts:106

resolveVertexAuthFunction#

Where a Vertex AI request goes and its credentials, read per turn so a credential configured after the provider was built still applies. In order: a pinned account's sign-in, a Vertex API key, the active "Sign in with Google" grant, then Google Cloud credentials for the project (a credentials file, gcloud's Application Default Credentials, the metadata server), a fresh token minted per request.

TypeScript
function resolveVertexAuth(
  params?: GoogleVertexParams,
  callbacks?: StreamCallbacks,
  signal?: AbortSignal,
): Promise<VertexRequestAuth>
Parameters
NameTypeDescription
params?GoogleVertexParams

Explicit settings; environment variables fill the rest.

callbacks?StreamCallbacks

Stream callbacks, for the OAuth refresh hook.

signal?AbortSignal

Aborts a token request.

src/providers/google.ts:601

toGeminiContentsFunction#

Converts session messages to Gemini contents.

An assistant turn stays whole: Gemini signs only the FIRST function call of a parallel step, so splitting the calls into separate model turns would leave the others unsigned. Its results follow in call order, in one user turn, with the synthetic placeholder for any the history lost.

TypeScript
function toGeminiContents(
  messages: SessionMessage[],
  model: GoogleWireModel,
  scope: GeminiSignatureScope,
  provider?: string,
): GeminiContent[]
Parameters
NameTypeDefaultDescription
messagesSessionMessage[]

Session messages, tool names already on the wire.

modelGoogleWireModel

Target model.

scopeGeminiSignatureScope

Signature scope of the target.

provider?stringscope

Provider named in unsupported-media errors. Defaults to scope.

src/providers/gemini/request.ts:202

Constants#

GOOGLE_DEFAULT_MODELConstant#

Model used when a request names none. Served on free-tier Gemini API keys.

TypeScript
const GOOGLE_DEFAULT_MODEL = 'gemini-3.8-flash'

src/providers/google.ts:58

GOOGLE_EXTRA_MODELSConstant#

Models pi-ai's registry hasn't bundled yet, served on both routes. A pi-ai release that bundles one supersedes its entry (bundled metadata always wins), so delete the entry then.

TypeScript
const GOOGLE_EXTRA_MODELS: readonly GoogleExtraModel[]

src/providers/google.ts:81

Interfaces#

GeminiContentInterface#

One turn of the conversation.

TypeScript
interface GeminiContent
GeminiContent properties
NameTypeDescription
partsGeminiPart[]

What was said.

role'user' | 'model'

Who spoke.

src/providers/gemini/types.ts:54

GeminiFunctionDeclarationInterface#

A tool the model may call.

TypeScript
interface GeminiFunctionDeclaration
GeminiFunctionDeclaration properties
NameTypeDescription
descriptionstring

What it does.

namestring

Function name.

parameters?unknown

OpenAPI-subset schema of the arguments (the legacy field some backends translate).

parametersJsonSchema?unknown

Full JSON Schema of the arguments.

src/providers/gemini/types.ts:62

GeminiGenerationConfigInterface#

Generation settings.

TypeScript
interface GeminiGenerationConfig
GeminiGenerationConfig properties
NameTypeDescription
maxOutputTokens?number

Output ceiling in tokens.

temperature?number

Sampling temperature.

thinkingConfig?GeminiThinkingConfig

Thinking settings.

src/providers/gemini/types.ts:84

GeminiPartInterface#

One part of a turn.

TypeScript
interface GeminiPart
GeminiPart properties
NameTypeDescription
functionCall?GeminiFunctionCall

A function call.

functionResponse?GeminiFunctionResponse

A function result.

inlineData?GeminiBlob

Inline media or file.

text?string

Text, or a thought summary when thought is set.

thought?boolean

Marks text as thought content.

thoughtSignature?string

Opaque signature of the model's reasoning, replayed as received.

src/providers/gemini/types.ts:38

GeminiRequestInterface#

A GenerateContentRequest body.

TypeScript
interface GeminiRequest
GeminiRequest properties
NameTypeDescription
contentsGeminiContent[]

The conversation.

generationConfig?GeminiGenerationConfig

Generation settings.

systemInstruction?{ parts: { text: string }[]; role: 'user' }

The system prompt.

toolConfig?GeminiToolConfig

Function-calling mode.

tools?{ functionDeclarations: GeminiFunctionDeclaration[] }[]

Function declarations.

src/providers/gemini/types.ts:100

GeminiResponseChunkInterface#

One streamed GenerateContentResponse.

TypeScript
interface GeminiResponseChunk
GeminiResponseChunk properties
NameTypeDescription
candidates?{ content?: { parts?: GeminiPart[]; role?: string }; finishReason?: string }[]

Candidates; zidane reads the first.

responseId?string

Response id.

usageMetadata?GeminiUsageMetadata

Token counts so far.

src/providers/gemini/types.ts:128

GeminiThinkingConfigInterface#

Thinking settings.

TypeScript
interface GeminiThinkingConfig
GeminiThinkingConfig properties
NameTypeDescription
includeThoughts?boolean

Stream thought summaries.

thinkingBudget?number

Token budget (Gemini 2.5); 0 turns thinking off, -1 lets the model pick.

thinkingLevel?'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH'

Discrete level (Gemini 3+).

src/providers/gemini/types.ts:74

GeminiToolInterface#

A tool as formatTools hands it to the request: name, description, JSON Schema.

TypeScript
interface GeminiTool
GeminiTool properties
NameTypeDescription
descriptionstring

What it does.

namestring

Function name on the wire.

parametersRecord<string, unknown>

JSON Schema of its arguments.

src/providers/gemini/request.ts:20

GeminiToolConfigInterface#

Function-calling mode.

TypeScript
interface GeminiToolConfig
GeminiToolConfig properties
NameTypeDescription
functionCallingConfig{ allowedFunctionNames?: string[]; mode: 'AUTO' | 'ANY' | 'NONE' | 'VALIDATED' }

AUTO, ANY (must call one) or NONE, optionally limited to some functions.

src/providers/gemini/types.ts:94

GoogleCompatibleRouteInterface#

A Gemini-wire backend for googleCompatible: where requests go and how they authenticate (send), how its stream events read (parseChunk) and which models it serves (resolveModel). Message conversion, thought-signature bookkeeping, tool names, thinking levels, SSE parsing, usage and cost stay in the shared plumbing.

TypeScript
interface GoogleCompatibleRoute
GoogleCompatibleRoute properties
NameTypeDescription
classifyError?(err: unknown) => ClassifiedError | null

Error classification. Defaults to classifyGoogleError.

isOAuthboolean

Whether the provider runs on an OAuth credential.

namestring

Provider name (Provider.name, error copy) and the default signature scope. Must not be a built-in provider name (google, google-vertex, anthropic, openai).

parseChunk?(payload: unknown) => GeminiResponseChunk

One SSE event's JSON to a GenerateContentResponse, for a backend that wraps it (Cloud Code Assist's { response }). Throw for an in-stream error. Defaults to the event as is, an { error } event thrown as a Google error.

resolveModel(modelId: string, catalog?: ModelCatalog) => GoogleWireModel

Model record for a requested model id. Its cost rates price each turn: zero rates report no cost (quota-backed access).

send(request: GoogleTurnRequest, fetch: typeof fetch) => Promise<Response>

Sends one turn and returns the streaming response (streamGenerateContent?alt=sse or the backend's equivalent). Send it with fetch: it is the provider's, carrying the http.request / http.response interceptors. A non-2xx response is read as a Google error; throw instead to report the backend's own (with a numeric status so it classifies by HTTP status).

signatureScope?(modelId: string) => string

Signature scope of a model: the tag its thought signatures carry, and the only scope they replay to. Defaults to name, right when every model behind the backend accepts the others' signatures (Gemini does). A backend fronting several model families returns one scope per family, so switching families mid-session sends earlier reasoning unsigned.

src/providers/google.ts:217

GoogleExtraModelInterface#

A Google model pi-ai's registry hasn't bundled yet: a bundled template with the same thinking shape, under its own id.

TypeScript
interface GoogleExtraModel
GoogleExtraModel properties
NameTypeDescription
contextWindownumber

Context window in tokens.

idstring

Model id sent to the API.

maxTokensnumber

Largest output in tokens.

namestring

Display name.

rates() => Required<ModelCostRates>

A function, so a dated price change applies to long-running hosts.

templatestring

A bundled model with the same thinking levels and budgets.

src/providers/google.ts:61

GoogleParamsInterface#

Options for google.

TypeScript
interface GoogleParams extends GoogleSharedParams
GoogleParams properties
NameTypeDefaultDescription
apiKey?string

Gemini API key. Defaults to GEMINI_API_KEY, then GOOGLE_API_KEY.

capabilities?from GoogleSharedParamsProviderCapabilities

Provider capability flags. Gemini takes images and files (PDFs and others) in prompts and in tool results; audio and video are refused.

defaultModel?from GoogleSharedParamsstring'gemini-3.8-flash'

Model used when a request does not set one.

extraHeaders?from GoogleSharedParamsRecord<string, string>

Extra HTTP headers sent on every request.

src/providers/google.ts:459

GoogleSharedParamsInterface#

Settings shared by the Google providers.

TypeScript
interface GoogleSharedParams
GoogleSharedParams properties
NameTypeDefaultDescription
capabilities?ProviderCapabilities

Provider capability flags. Gemini takes images and files (PDFs and others) in prompts and in tool results; audio and video are refused.

defaultModel?string'gemini-3.8-flash'

Model used when a request does not set one.

extraHeaders?Record<string, string>

Extra HTTP headers sent on every request.

src/providers/google.ts:276

GoogleTurnRequestInterface#

One turn's request, handed to a GoogleCompatibleRoute's send.

TypeScript
interface GoogleTurnRequest
GoogleTurnRequest properties
NameTypeDescription
bodyGeminiRequest

The standard GenerateContentRequest: contents with this route's signatures, tools, forced tool choice, and generationConfig with the output ceiling and the thinking config Gemini models take. A route may edit it, or wrap it in its backend's envelope.

callbacksStreamCallbacks

Stream callbacks, for OAuth refresh hooks.

headersRecord<string, string>

The provider's extra headers (extraHeaders), to send on top of the route's.

maxTokens?number

Output ceiling as requested (the body's is already resolved).

modelGoogleWireModel

The model record the route resolved.

signal?AbortSignal

Aborts the request.

thinking?'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'

Thinking level as requested, for a backend that maps it its own way.

src/providers/google.ts:188

GoogleVertexParamsInterface#

Options for googleVertex.

TypeScript
interface GoogleVertexParams extends GoogleSharedParams
GoogleVertexParams properties
NameTypeDefaultDescription
account?string

Run on one stored "Sign in with Google" account (its stable id) rather than the active one. See OAuthParams.account.

apiKey?string

Vertex AI API key (express mode). Defaults to GOOGLE_CLOUD_API_KEY. Without one, requests authenticate with Google Cloud credentials.

capabilities?from GoogleSharedParamsProviderCapabilities

Provider capability flags. Gemini takes images and files (PDFs and others) in prompts and in tool results; audio and video are refused.

credentialsFile?string

Service-account or authorized-user credentials file. Defaults to GOOGLE_APPLICATION_CREDENTIALS, then gcloud's Application Default Credentials (gcloud auth application-default login), then the metadata server on Google Cloud.

defaultModel?from GoogleSharedParamsstring'gemini-3.8-flash'

Model used when a request does not set one.

extraHeaders?from GoogleSharedParamsRecord<string, string>

Extra HTTP headers sent on every request.

location?string

Vertex AI location. Defaults to GOOGLE_CLOUD_LOCATION, then global.

project?string

Google Cloud project. Defaults to GOOGLE_CLOUD_PROJECT, then GCLOUD_PROJECT.

src/providers/google.ts:500

GoogleWireModelInterface#

A model on a Gemini wire: what the request builder and the cost need. The Google routes read it from pi-ai's model registry; a googleCompatible backend builds its own.

TypeScript
interface GoogleWireModel
GoogleWireModel properties
NameTypeDescription
baseUrl?string

API base URL (the Gemini API's, or Vertex's {location} template).

contextWindownumber

Context window in tokens.

costGeminiModelCost

Prices per million tokens; zero rates report no cost.

idstring

Model id sent on the wire.

inputreadonly string[]

Input kinds; a model without image gets a text marker for each image.

maxTokensnumber

Output ceiling in tokens.

namestring

Display name.

providerstring

Provider that serves it.

reasoningboolean

Whether it thinks.

thinkingLevelMap?Partial<Record<string, string | null>>

zidane level → Gemini level, null where the model lacks one. Levels absent from the map pass through (xhigh and max only when mapped).

src/providers/gemini/types.ts:160

VertexRequestAuthInterface#

Where a Vertex AI request goes and how it authenticates.

TypeScript
interface VertexRequestAuth
VertexRequestAuth properties
NameTypeDescription
headersRecord<string, string>

Auth headers: x-goog-api-key, or a bearer token and the billed project.

url(modelId: string) => string

The streamGenerateContent URL of a model.

src/providers/google.ts:525

Types#

GoogleRouteNameType#

Zidane provider (and signature route) names of the two Google backends.

TypeScript
type GoogleRouteName = 'google' | 'google-vertex'

src/providers/google.ts:55