any-llm-ts
Providers

Gemini

Use Google's native Gemini API for completions, streaming, tools, thinking, multimodal input, embeddings, Responses, Files, image and video generation, and model discovery.

The gemini adapter uses Google's official @google/genai SDK. It translates the common any-llm-ts request and response shapes rather than routing through Gemini's OpenAI-compatible endpoint.

Configure credentials

Create a Gemini API key in Google AI Studio, then set either supported environment variable:

export GEMINI_API_KEY="..."
# GOOGLE_API_KEY is also supported as a fallback.

You can override the key and native API base programmatically:

import { AnyLLM } from "any-llm-ts";

const gemini = AnyLLM.create("gemini", {
  apiKey: process.env.GEMINI_API_KEY,
  apiBase: "https://generativelanguage.googleapis.com",
  clientOptions: {
    apiVersion: "v1beta",
  },
});

GOOGLE_GEMINI_BASE_URL is the environment-variable equivalent of apiBase. SDK constructor fields belong in clientOptions; per-request GenerateContentConfig fields belong in providerOptions and use the Google SDK's camel-cased names.

Complete and stream

import { completion } from "any-llm-ts";

const response = await completion({
  provider: "gemini",
  model: "gemini-2.5-flash",
  messages: [
    { role: "system", content: "Be concise." },
    { role: "user", content: "Explain discriminated unions." },
  ],
});

console.log(response.choices[0]?.message.content);

Set stream: true to receive normalized ChatCompletionChunk values. Text is exposed on delta.content, thinking on delta.reasoning, and tool calls on delta.toolCalls.

System and developer messages are combined into Gemini's systemInstruction. A request made only of system or developer messages is sent as the user turn, because Gemini rejects empty contents. User, assistant, and tool messages are translated into native Content and Part values. Tool results use a user turn carrying functionResponse parts; consecutive parallel tool results share one turn.

Thinking

Use the common reasoning-effort vocabulary:

const response = await gemini.completion({
  model: "gemini-2.5-pro",
  messages: [{ role: "user", content: "Solve this carefully." }],
  reasoningEffort: "high",
});

console.log(response.choices[0]?.message.reasoning);

The adapter maps minimal, low, medium, high, xhigh, and max to Gemini thinking budgets. Use none to disable returned thoughts or auto to leave thinking configuration to the model. Reasoning is optional because availability depends on the selected model and account.

Function and built-in tools

Function tools use the common OpenAI-shaped declaration:

const response = await gemini.completion({
  model: "gemini-2.5-flash",
  messages: [{ role: "user", content: "What's the weather in Paris?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the weather for a city",
        parameters: {
          type: "object",
          properties: { city: { type: "string" } },
          required: ["city"],
        },
      },
    },
  ],
  toolChoice: "auto",
});

toolChoice supports auto, required, none, validated, and a named function choice. Native built-ins can be requested with { type: "google_search" }, { type: "code_execution" }, or { type: "url_context" }. Combining a built-in with function tools sets includeServerSideToolInvocations so Gemini does not reject the mix.

Code execution parts land on message.extraContent.google.code_execution (and on streamed delta.extraContent) as executable_code, code_execution_result, and produced-file code_execution_output items. Pass that assistant message back unchanged to replay the parts; ids the adapter synthesized are not sent to Gemini. Through messages() those items become server_tool_use / code_execution_tool_result blocks.

When Google Search grounds an answer, usage.serverToolUse.webSearchRequests is the number of search queries across candidates. Gemini 3 bills each query; earlier models bill one grounded prompt. The adapter reports the raw count so the caller can apply pricing.

Gemini thought signatures are preserved at toolCall.extraContent.google.thoughtSignature. Pass the returned tool call back unchanged in the next assistant message so the adapter can return the signature to Gemini. The adapter adds Google's documented validator-bypass sentinel only when an older or manually constructed first function call has no signature. Omit parallelToolCalls; Gemini does not implement that normalized request flag.

Anthropic-style cacheControl breakpoints become Gemini context caches. See Prompt caching.

Images, files, and audio

The adapter translates common message content blocks:

await gemini.completion({
  model: "gemini-2.5-flash",
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "Describe this image and PDF." },
        {
          type: "image_url",
          image_url: { url: "https://example.com/photo.webp" },
        },
        {
          type: "file",
          file: {
            file_id: "https://example.com/report.pdf",
            filename: "report.pdf",
          },
        },
      ],
    },
  ],
});

Images and files can use a URI or a base64 data URL. input_audio maps OpenAI { data, format } parts to Gemini audio/<format> MIME types such as wav, mp3, flac, and ogg. Inline payloads are validated before the request and must not exceed Gemini's 20 MB inline-data limit. For larger content, upload it with Google's Files API and pass its URI as file.file_id.

Structured JSON

Gemini supports text, json_object, and json_schema response formats:

const response = await gemini.completion({
  model: "gemini-2.5-flash",
  messages: [{ role: "user", content: "Extract the city: I live in Kolkata." }],
  responseFormat: {
    type: "json_schema",
    json_schema: {
      name: "location",
      schema: {
        type: "object",
        properties: { city: { type: "string" } },
        required: ["city"],
      },
    },
  },
});

The returned content remains a string for consistency across providers. Parse and validate it in your application.

Embeddings and models

const embeddings = await gemini.embedding({
  model: "gemini-embedding-001",
  input: ["First document", "Second document"],
  dimensions: 768,
  providerOptions: { taskType: "RETRIEVAL_DOCUMENT" },
});

const models = await gemini.listModels({ pageSize: 20 });

Gemini embeddings accept a string or an array of strings and return float vectors. Request encodingFormat: "base64" to encode those floats locally as little-endian float32 bytes. Model listing consumes all pages returned by the SDK.

Responses

Text-only responses() calls use Google's Interactions API and return an OpenAI-shaped Response. completion() continues to use generateContent. The supported subset is a string input plus optional instructions, maxOutputTokens, timeout, and streaming. Tools, media, chaining, structured output, store, metadata, and background raise UnsupportedParameterError before any request is sent.

const response = await gemini.responses({
  model: "gemini-3.5-flash",
  input: "Explain event loops in one paragraph.",
  instructions: "Be concise.",
  maxOutputTokens: 256,
});

console.log(response.output_text);

Set stream: true to receive the OpenAI Responses event lifecycle. Vertex AI keeps Responses disabled; it never imports the Interactions path.

Image generation and edit

Gemini image models (Nano Banana and ids that carry image as a dash-separated word) answer imageGeneration and imageEdit through generateContent. n images become n concurrent requests. size maps to Gemini aspect ratios such as 1:1 or 16:9. Gemini returns image bytes, so responseFormat: "url" is rejected. OpenAI-only fields background, quality, style, and user are also rejected; pass Gemini imageConfig fields in providerOptions.

const image = await gemini.imageGeneration({
  model: "gemini-nano-banana-2.1",
  prompt: "A red apple on a wooden table",
  size: "1536x1024",
  providerOptions: { imageSize: "1K" },
});

console.log(image.data[0]?.b64Json);
console.log(image.usage?.totalTokens);

const edited = await gemini.imageEdit({
  model: "gemini-nano-banana-2.1",
  image: "./apple.png",
  prompt: "Make the apple green",
  size: "1024x1024",
});

Vertex AI does not advertise or implement image generation or edit.

Video generation

Gemini Omni Flash renders video through the same Interactions API, as a background job. Pass size, or resolution and aspectRatio; the video must be 16:9 or 9:16 with a short side of 360, 720, 1080, or 2160 pixels. seconds, negativePrompt, referenceAudios, referenceVideos, and generateAudio are rejected. See Video generation.

Capability boundary

The adapter advertises completions, streaming, thinking, image and PDF input, embeddings, model listing, batch jobs, Files (upload, list, retrieve, delete), text-only Responses, image generation and edit, video generation, and text-to-speech. Batch creation accepts /v1/chat/completions JSONL input, translates each record into an inline Google batch request, and normalizes inline results through the same completion converter.

See the Files page for Gemini upload, list, retrieve, and delete.

messages() is available through the common Messages compatibility layer. Moderation and transcription remain outside this adapter's current public surface. Vertex AI does not inherit Files, Responses, image generation, video generation, or speech. Vertex completions for Model Garden partner IDs (qwen, openai/gpt-oss-, deepseek-ai, llama, meta/llama, minimaxai/, moonshotai/, zai-org/) go to Vertex's OpenAI-compatible endpoint. IDs starting with mistral or codestral go to the mistralai publisher's rawPredict endpoints. Gemini models stay on generateContent.

On this page