Configuration

Configure model selection, authentication, request behavior, tools, retries, batching, and other options supported by @orcushq/gemini.

Configure a GeminiWeb instance through its constructor. You can override supported options for individual calls when needed. Although most constructor options are optional at the TypeScript level, authenticated requests require non-empty session cookies and an XSRF token. A model must also be provided in the constructor or at call time before making a request.

Constructor Options

typescript
import 'dotenv/config'import { GeminiWeb } from '@orcushq/gemini' const cookies = process.env.GEMINI_COOKIESconst xsrfToken = process.env.GEMINI_XSRF_TOKEN if (!cookies?.trim() || !xsrfToken?.trim()) {  throw new Error(    'GEMINI_COOKIES and GEMINI_XSRF_TOKEN are required',  )} const model = new GeminiWeb({  model: 'gemini-3.6-flash',   // Authentication  cookies,  xsrfToken,  authUser: 0,   // Request settings  hl: 'en',  temporaryChats: false,  timeoutMs: 180_000,   // Retry policy  retry: {    attempts: 3,    delayMs: 2_000,    backoffFactor: 2,    maxDelayMs: 30_000,  },   // Batch execution  concurrency: 4,   // Tools  tools: [],  toolChoice: 'auto',   // Model resolution  unknownModel: 'fallback',   // Transport and upload settings  fetchImpl: fetch,  defaultHeaders: {},  includeErrorBody: false,  pageTokenTtlMs: 600_000,})

Model Selection

model selects the model ID used by default. You can override it for an individual call. Model IDs may also include an @think=<n> suffix to override the configured thinking level. If no model is supplied, the request fails with GeminiConfigurationError.

unknownModel controls how an unrecognized model ID is handled. It defaults to fallback, which resolves to the package default model configuration. Set it to throw to raise GeminiConfigurationError instead.

typescript
const model = new GeminiWeb({  model: 'gemini-3.6-flash',  cookies,  xsrfToken,  unknownModel: 'throw',}) const response = await model.invoke(  'Explain closures.',  { model: 'gemini-3.5-flash-thinking@think=2' },)

See Models for supported model IDs. Selecting a model does not guarantee that Gemini Web will serve that exact model; the result depends on upstream availability and access.

Authentication

  • cookies: The complete Cookie header from a signed-in Gemini Web session. A non-empty value is required to initialize an authenticated client.
  • xsrfToken: The XSRF token sent in the request field named at. Supply the token from the same signed-in session. It is required for client initialization and can be overridden per call when needed.
  • authUser: The Google account index used in the request context, such as 0 for /u/0.

The SDK uses the supplied session cookies and XSRF token to prepare authenticated requests. Providing credentials does not guarantee access to every model; the session must be current and authorized for the requested operation. See Authentication for instructions on obtaining the required values.

Request Context

  • bl: Overrides the frontend build label. If omitted, the SDK uses its built-in value.
  • hl: Sets the request language. The default is English (en).
  • userAgent: Overrides the User-Agent header with a custom string.
  • temporaryChats: Enables the temporary-chat request format. Defaults to false.
  • sessionId: A per-call option that reuses a conversation ID. If omitted, the SDK generates one.

bl and hl apply to generation requests. Image-upload page-token requests do not inherit these settings in the same way and use their own defaults.

Timeouts and Retries

timeoutMs sets the request timeout in milliseconds. The default is 180,000 ms (3 minutes). A value of 0 disables the timeout.

retry accepts a partial retry policy or false to disable retries. Its default policy uses 3 total attempts, including the initial request.

  • attempts: Total attempts, including the first request. Default: 3; must be an integer of at least 1.
  • delayMs: Base delay between attempts. Default: 2000.
  • backoffFactor: Exponential backoff multiplier. Default: 2.
  • maxDelayMs: Maximum delay between attempts. Default: 30000.
typescript
const model = new GeminiWeb({  model: 'gemini-3.6-flash',  cookies,  xsrfToken,  timeoutMs: 60_000,  retry: {    attempts: 2,    delayMs: 1_000,  },}) // Override settings for one call.const response = await model.invoke('Hello', {  timeoutMs: 15_000,  retry: false,})

Per-call timeout and retry settings override the client defaults. See Reliability for more details.

Batch Execution

concurrency sets the maximum number of requests running at the same time in batch() and batchSettled(). It defaults to 4, must be a positive integer, and is limited to the number of inputs.

continueOnError is available in batch(). When enabled, the batch collects results and errors instead of stopping at the first failure. batchSettled() collects individual outcomes without failing the entire operation because of one rejected request.

Batch methods schedule independent requests on the client. They do not use a native upstream batch API. Results retain input order. concurrency has no effect on invoke() or stream().

Tools

tools defines the tools available by default. Each tool includes a name, description, and parameters object containing its JSON Schema. toolChoice controls how the SDK instructs the model to use tools.

  • auto: Let the model decide whether to use a tool.
  • none: Instruct the model not to use tools.
  • required: Instruct the model to use a tool.
  • A function choice object can specify a tool by name.

Per-call tools and toolChoice override the client-level settings. Tool instructions are represented in the prompt, and tool calls are parsed from the response. This is not a native Gemini Web function-calling channel.

Transport Options

  • fetchImpl: Supplies a custom Fetch-compatible implementation. Defaults to globalThis.fetch.
  • defaultHeaders: Adds custom headers to generation transport requests. Protected headers, including cookie, authorization, origin, and referer, cannot be overridden through this option.
  • includeErrorBody: Includes a truncated upstream response body in HTTP error messages when enabled. Defaults to false.
  • pageTokenTtlMs: Sets the lifetime of cached image-upload page tokens. Defaults to 600000 ms (10 minutes). The cache belongs to the client instance.
  • signal: Supplies a default AbortSignal. A per-call signal can also be provided; the SDK combines the configured signals.

defaultHeaders applies to generation transport requests, not image-upload requests, which use their own headers. The same Fetch implementation can be used by the transport and image-upload components.

Per-call Options

invoke(), stream(), batch(), and batchSettled() accept options supported by their respective operations. Available options include model, signal, timeoutMs, retry, sessionId, tools, toolChoice, temporaryChats, and xsrfToken. Batch operations also support concurrency; batch() supports continueOnError.

typescript
const controller = new AbortController() const response = await model.invoke(  'Explain closures.',  {    model: 'gemini-3.6-flash',    timeoutMs: 30_000,    retry: { attempts: 2 },    sessionId: 'conversation-123',    temporaryChats: true,    xsrfToken,    signal: controller.signal,  },)

Not every constructor option is available per call. For example, cookies, authUser, bl, hl, userAgent, fetchImpl, defaultHeaders, includeErrorBody, pageTokenTtlMs, and unknownModel are configured at the client level.

Structured Output

withStructuredOutput(schema, options?) creates a structured-output runnable. Its options include name, instructions, jsonSchema, and parse. Use jsonSchema to provide a schema directly instead of relying on the schema derived from the supplied validator. Use parse to provide a custom extractor that returns a JSON string.

Image Configuration

Image resolution and upload APIs expose additional options for image metadata, downloading, and cancellation. Depending on the operation, these include mimeType, filename, fetchImpl, signal, maxBytes, and maxRedirects. The default maximum remote image size is 20 MB, and the default redirect limit is 3. Redirect targets are checked for unsafe URLs.

Upload-specific options can also include authentication context and page-token cache settings. These lower-level options apply to the relevant image APIs rather than every GeminiWeb call.

Derived Clients

withConfig() creates a new client with configuration overrides. bindTools() creates a new client with the specified tools and optional tool choice. These methods return new instances and do not mutate the original client.

typescript
const production = model.withConfig({  timeoutMs: 60_000,}) const withTools = model.bindTools([weatherTool], {  toolChoice: 'auto',})

Reuse configured clients

A GeminiWeb instance owns its transport, uploader, and image-upload page-token cache. Reuse an instance when multiple calls share the same configuration.

Environment Variables

The SDK does not read environment variables automatically. Read them in your application and pass their values to the constructor or supported per-call options. Both authentication variables are required for client initialization.

dotenv
GEMINI_COOKIES="your_complete_cookie_header"GEMINI_XSRF_TOKEN="your_at_value"

Security

  • Treat cookies and XSRF tokens as sensitive session credentials.
  • Keep credentials in server-side environment variables or a secret manager.
  • Never commit real credentials to Git or expose them in frontend code.
  • Do not publish screenshots containing real cookies or token values.
  • Avoid enabling upstream error-body output in production unless needed for debugging.
  • Use the image URL safeguards when processing remote images, and do not bypass validation for untrusted URLs.
  • If session credentials are exposed, revoke or replace the affected session.