{"id":28991257,"url":"https://github.com/googleapis/js-genai","last_synced_at":"2026-04-08T21:01:42.866Z","repository":{"id":281754802,"uuid":"899744532","full_name":"googleapis/js-genai","owner":"googleapis","description":"TypeScript/JavaScript SDK for Gemini and Vertex AI.","archived":false,"fork":false,"pushed_at":"2026-04-03T01:46:24.000Z","size":64631,"stargazers_count":1537,"open_issues_count":243,"forks_count":234,"subscribers_count":30,"default_branch":"main","last_synced_at":"2026-04-03T06:30:49.832Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://googleapis.github.io/js-genai/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/googleapis.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-12-06T23:16:55.000Z","updated_at":"2026-04-03T00:59:13.000Z","dependencies_parsed_at":"2025-03-11T01:29:10.123Z","dependency_job_id":"06983dce-8720-4868-9aa9-c04af85c142c","html_url":"https://github.com/googleapis/js-genai","commit_stats":null,"previous_names":["googleapis/js-genai"],"tags_count":69,"template":false,"template_full_name":null,"purl":"pkg:github/googleapis/js-genai","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjs-genai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjs-genai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjs-genai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjs-genai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/googleapis","download_url":"https://codeload.github.com/googleapis/js-genai/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjs-genai/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31573788,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-08T14:31:17.711Z","status":"ssl_error","status_checked_at":"2026-04-08T14:31:17.202Z","response_time":54,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-25T01:02:47.613Z","updated_at":"2026-04-08T21:01:42.832Z","avatar_url":"https://github.com/googleapis.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","Model SDKs","2. Libraries \u0026 Frameworks"],"sub_categories":["JavaScript / TypeScript"],"readme":"# Google Gen AI SDK for TypeScript and JavaScript\n\n[![NPM Downloads](https://img.shields.io/npm/dw/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai)\n[![Node Current](https://img.shields.io/node/v/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai)\n\n----------------------\n**Documentation:** https://googleapis.github.io/js-genai/\n\n----------------------\n\nThe Google Gen AI JavaScript SDK is designed for\nTypeScript and JavaScript developers to build applications powered by Gemini. The SDK\nsupports both the [Gemini Developer API](https://ai.google.dev/gemini-api/docs)\nand [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview).\n\nThe Google Gen AI SDK is designed to work with Gemini 2.0+ features.\n\n\u003e [!CAUTION]\n\u003e **API Key Security:** Avoid exposing API keys in client-side code.\n\u003e Use server-side implementations in production environments.\n\n## Code Generation\n\nGenerative models are often unaware of recent API and SDK updates and may suggest outdated or legacy code.\n\nWe recommend using our Code Generation instructions [`codegen_instructions.md`](https://raw.githubusercontent.com/googleapis/js-genai/refs/heads/main/codegen_instructions.md) when generating Google Gen AI SDK code to guide your model towards using the more recent SDK features. Copy and paste the instructions into your development environment to provide the model with the necessary context.\n\n## Prerequisites\n\n1. Node.js version 20 or later\n\n### The following are required for Vertex AI users (excluding Vertex AI Studio)\n1.  [Select](https://console.cloud.google.com/project) or [create](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) a Google Cloud project.\n1.  [Enable billing for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n1.  [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n1.  [Configure authentication](https://cloud.google.com/docs/authentication) for your project.\n    *   [Install the gcloud CLI](https://cloud.google.com/sdk/docs/install).\n    *   [Initialize the gcloud CLI](https://cloud.google.com/sdk/docs/initializing).\n    *   Create local authentication credentials for your user account:\n\n    ```sh\n    gcloud auth application-default login\n    ```\nA list of accepted authentication options are listed in [GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/3ae120d0a45c95e36c59c9ac8286483938781f30/src/auth/googleauth.ts#L87) interface of google-auth-library-node.js GitHub repo.\n\n## Installation\n\nTo install the SDK, run the following command:\n\n```shell\nnpm install @google/genai\n```\n\n## Quickstart\n\nThe simplest way to get started is to use an API key from\n[Google AI Studio](https://aistudio.google.com/apikey):\n\n```typescript\nimport {GoogleGenAI} from '@google/genai';\nconst GEMINI_API_KEY = process.env.GEMINI_API_KEY;\n\nconst ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});\n\nasync function main() {\n  const response = await ai.models.generateContent({\n    model: 'gemini-2.5-flash',\n    contents: 'Why is the sky blue?',\n  });\n  console.log(response.text);\n}\n\nmain();\n```\n\n## Initialization\n\nThe Google Gen AI SDK provides support for both the\n[Google AI Studio](https://ai.google.dev/gemini-api/docs) and\n[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview)\n implementations of the Gemini API.\n\n### Gemini Developer API\n\nFor server-side applications, initialize using an API key, which can\nbe acquired from [Google AI Studio](https://aistudio.google.com/apikey):\n\n```typescript\nimport { GoogleGenAI } from '@google/genai';\nconst ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n```\n\n#### Browser\n\n\u003e [!CAUTION]\n\u003e **API Key Security:** Avoid exposing API keys in client-side code.\n\u003e   Use server-side implementations in production environments.\n\nIn the browser the initialization code is identical:\n\n\n```typescript\nimport { GoogleGenAI } from '@google/genai';\nconst ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n```\n\n### Vertex AI\n\nSample code for VertexAI initialization:\n\n```typescript\nimport { GoogleGenAI } from '@google/genai';\n\nconst ai = new GoogleGenAI({\n    vertexai: true,\n    project: 'your_project',\n    location: 'your_location',\n});\n```\n\n### (Optional) (NodeJS only) Using environment variables:\n\nFor NodeJS environments, you can create a client by configuring the necessary\nenvironment variables. Configuration setup instructions depends on whether\nyou're using the Gemini Developer API or the Gemini API in Vertex AI.\n\n**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below:\n\n```bash\nexport GOOGLE_API_KEY='your-api-key'\n```\n\n**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`,\n`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below:\n\n```bash\nexport GOOGLE_GENAI_USE_VERTEXAI=true\nexport GOOGLE_CLOUD_PROJECT='your-project-id'\nexport GOOGLE_CLOUD_LOCATION='us-central1'\n```\n\n```typescript\nimport {GoogleGenAI} from '@google/genai';\n\nconst ai = new GoogleGenAI();\n```\n\n## API Selection\n\nBy default, the SDK uses the beta API endpoints provided by Google to support\npreview features in the APIs. The stable API endpoints can be selected by\nsetting the API version to `v1`.\n\nTo set the API version use `apiVersion`. For example, to set the API version to\n`v1` for Vertex AI:\n\n```typescript\nconst ai = new GoogleGenAI({\n    vertexai: true,\n    project: 'your_project',\n    location: 'your_location',\n    apiVersion: 'v1'\n});\n```\n\nTo set the API version to `v1alpha` for the Gemini Developer API:\n\n```typescript\nconst ai = new GoogleGenAI({\n    apiKey: 'GEMINI_API_KEY',\n    apiVersion: 'v1alpha'\n});\n```\n\n## GoogleGenAI overview\n\nAll API features are accessed through an instance of the `GoogleGenAI` classes.\nThe submodules bundle together related API methods:\n\n- [`ai.models`](https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html):\n  Use `models` to query models (`generateContent`, `generateImages`, ...), or\n  examine their metadata.\n- [`ai.caches`](https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html):\n  Create and manage `caches` to reduce costs when repeatedly using the same\n  large prompt prefix.\n- [`ai.chats`](https://googleapis.github.io/js-genai/release_docs/classes/chats.Chats.html):\n  Create local stateful `chat` objects to simplify multi turn interactions.\n- [`ai.files`](https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html):\n  Upload `files` to the API and reference them in your prompts.\n  This reduces bandwidth if you use a file many times, and handles files too\n  large to fit inline with your prompt.\n- [`ai.live`](https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html):\n  Start a `live` session for real time interaction, allows text + audio + video\n  input, and text or audio output.\n\n## Samples\n\nMore samples can be found in the\n[github samples directory](https://github.com/googleapis/js-genai/tree/main/sdk-samples).\n\n### Streaming\n\nFor quicker, more responsive API interactions use the `generateContentStream`\nmethod which yields chunks as they're generated:\n\n```typescript\nimport {GoogleGenAI} from '@google/genai';\nconst GEMINI_API_KEY = process.env.GEMINI_API_KEY;\n\nconst ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});\n\nasync function main() {\n  const response = await ai.models.generateContentStream({\n    model: 'gemini-2.5-flash',\n    contents: 'Write a 100-word poem.',\n  });\n  for await (const chunk of response) {\n    console.log(chunk.text);\n  }\n}\n\nmain();\n```\n\n### Function Calling\n\nTo let Gemini to interact with external systems, you can provide\n`functionDeclaration` objects as `tools`. To use these tools it's a 4 step\n\n1. **Declare the function name, description, and parametersJsonSchema**\n2. **Call `generateContent` with function calling enabled**\n3. **Use the returned `FunctionCall` parameters to call your actual function**\n3. **Send the result back to the model (with history, easier in `ai.chat`)\n   as a `FunctionResponse`**\n\n```typescript\nimport {GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type} from '@google/genai';\nconst GEMINI_API_KEY = process.env.GEMINI_API_KEY;\n\nasync function main() {\n  const controlLightDeclaration: FunctionDeclaration = {\n    name: 'controlLight',\n    parametersJsonSchema: {\n      type: 'object',\n      properties:{\n        brightness: {\n          type:'number',\n        },\n        colorTemperature: {\n          type:'string',\n        },\n      },\n      required: ['brightness', 'colorTemperature'],\n    },\n  };\n\n  const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});\n  const response = await ai.models.generateContent({\n    model: 'gemini-2.5-flash',\n    contents: 'Dim the lights so the room feels cozy and warm.',\n    config: {\n      toolConfig: {\n        functionCallingConfig: {\n          // Force it to call any function\n          mode: FunctionCallingConfigMode.ANY,\n          allowedFunctionNames: ['controlLight'],\n        }\n      },\n      tools: [{functionDeclarations: [controlLightDeclaration]}]\n    }\n  });\n\n  console.log(response.functionCalls);\n}\n\nmain();\n```\n\n#### Model Context Protocol (MCP) support (experimental)\n\nBuilt-in [MCP](https://modelcontextprotocol.io/introduction) support is an\nexperimental feature. You can pass a local MCP server as a tool directly.\n\n```javascript\nimport { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\n\n// Create server parameters for stdio connection\nconst serverParams = new StdioClientTransport({\n  command: \"npx\", // Executable\n  args: [\"-y\", \"@philschmid/weather-mcp\"] // MCP Server\n});\n\nconst client = new Client(\n  {\n    name: \"example-client\",\n    version: \"1.0.0\"\n  }\n);\n\n// Configure the client\nconst ai = new GoogleGenAI({});\n\n// Initialize the connection between client and server\nawait client.connect(serverParams);\n\n// Send request to the model with MCP tools\nconst response = await ai.models.generateContent({\n  model: \"gemini-2.5-flash\",\n  contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,\n  config: {\n    tools: [mcpToTool(client)],  // uses the session, will automatically call the tool using automatic function calling\n  },\n});\nconsole.log(response.text);\n\n// Close the connection\nawait client.close();\n```\n\n### Generate Content\n\n#### How to structure `contents` argument for `generateContent`\n\nThe SDK allows you to specify the following types in the `contents` parameter:\n\n#### Content\n\n- `Content`: The SDK will wrap the singular `Content` instance in an array which\ncontains only the given content instance\n- `Content[]`: No transformation happens\n\n#### Part\n\nParts will be aggregated on a singular Content, with role 'user'.\n\n- `Part | string`: The SDK will wrap the `string` or `Part` in a `Content`\ninstance with role 'user'.\n- `Part[] | string[]`: The SDK will wrap the full provided list into a single\n`Content` with role 'user'.\n\n**_NOTE:_** This doesn't apply to `FunctionCall` and `FunctionResponse` parts,\nif you are specifying those, you need to explicitly provide the full\n`Content[]` structure making it explicit which Parts are 'spoken' by the model,\nor the user. The SDK will throw an exception if you try this.\n\n## Error Handling\n\nTo handle errors raised by the API, the SDK provides this [ApiError](https://github.com/googleapis/js-genai/blob/main/src/errors.ts) class.\n\n```typescript\nimport {GoogleGenAI} from '@google/genai';\nconst GEMINI_API_KEY = process.env.GEMINI_API_KEY;\n\nconst ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});\n\nasync function main() {\n  await ai.models.generateContent({\n    model: 'non-existent-model',\n    contents: 'Write a 100-word poem.',\n  }).catch((e) =\u003e {\n    console.error('error name: ', e.name);\n    console.error('error message: ', e.message);\n    console.error('error status: ', e.status);\n  });\n}\n\nmain();\n```\n\n## Interactions (Preview)\n\n\u003e **Warning:** The Interactions API is in **Beta**. This is a preview of an\nexperimental feature. Features and schemas are subject to **breaking changes**.\n\nThe Interactions API is a unified interface for interacting with Gemini models\nand agents. It simplifies state management, tool orchestration, and long-running\ntasks.\n\nSee the [documentation site](https://ai.google.dev/gemini-api/docs/interactions)\nfor more details.\n\n### Basic Interaction\n\n```typescript\nconst interaction = await ai.interactions.create({\n    model: 'gemini-2.5-flash',\n    input: 'Hello, how are you?',\n});\nconsole.debug(interaction);\n\n```\n\n### Stateful Conversation\n\nThe Interactions API supports server-side state management. You can continue a\nconversation by referencing the `previous_interaction_id`.\n\n```typescript\n// 1. First turn\nconst interaction1 = await ai.interactions.create({\n    model: 'gemini-2.5-flash',\n    input: 'Hi, my name is Amir.',\n});\nconsole.debug(interaction1);\n\n// 2. Second turn (passing previous_interaction_id)\nconst interaction2 = await ai.interactions.create({\n  model: 'gemini-2.5-flash',\n  input: 'What is my name?',\n  previous_interaction_id: interaction1.id,\n});\nconsole.debug(interaction2);\n\n```\n\n### Agents (Deep Research)\n\nYou can use specialized agents like `deep-research-pro-preview-12-2025` for\ncomplex tasks.\n\n```typescript\nfunction sleep(ms: number): Promise\u003cvoid\u003e {\n  return new Promise(resolve =\u003e setTimeout(resolve, ms));\n}\n\n// 1. Start the Deep Research Agent\nconst initialInteraction = await ai.interactions.create({\n  input:\n      'Research the history of the Google TPUs with a focus on 2025 and 2026.',\n  agent: 'deep-research-pro-preview-12-2025',\n  background: true,\n});\n\nconsole.log(`Research started. Interaction ID: ${initialInteraction.id}`);\n\n// 2. Poll for results\nwhile (true) {\n  const interaction = await ai.interactions.get(initialInteraction.id);\n  console.log(`Status: ${interaction.status}`);\n\n  if (interaction.status === 'completed') {\n    console.debug('\\nFinal Report:\\n', interaction.outputs);\n    break;\n  } else if (['failed', 'cancelled'].includes(interaction.status)) {\n    console.log(`Failed with status: ${interaction.status}`);\n    break;\n  }\n\n  await sleep(10000);  // Sleep for 10 seconds\n}\n\n```\n\n### Multimodal Input\n\nYou can provide multimodal data (text, images, audio, etc.) in the input list.\n\n```typescript\nimport base64\n\n// Assuming you have a base64 string\n// const base64Image = ...;\n\nconst interaction = await ai.interactions.create({\n  model: 'gemini-2.5-flash',\n  input: [\n    { type: 'text', text: 'Describe the image.' },\n    { type: 'image', data: base64Image, mime_type: 'image/png' },\n  ],\n});\n\nconsole.debug(interaction);\n\n```\n\n### Function Calling\n\nYou can define custom functions for the model to use. The Interactions API\nhandles the tool selection, and you provide the execution result back to the\nmodel.\n\n```typescript\n// 1. Define the tool\nconst getWeather = (location: string) =\u003e {\n  /* Gets the weather for a given location. */\n  return `The weather in ${location} is sunny.`;\n};\n\n// 2. Send the request with tools\nlet interaction = await ai.interactions.create({\n  model: 'gemini-2.5-flash',\n  input: 'What is the weather in Mountain View, CA?',\n  tools: [\n    {\n      type: 'function',\n      name: 'get_weather',\n      description: 'Gets the weather for a given location.',\n      parameters: {\n        type: 'object',\n        properties: {\n          location: {\n            type: 'string',\n            description: 'The city and state, e.g. San Francisco, CA',\n          },\n        },\n        required: ['location'],\n      },\n    },\n  ],\n});\n\n// 3. Handle the tool call\nfor (const output of interaction.outputs!) {\n  if (output.type === 'function_call') {\n    console.log(\n        `Tool Call: ${output.name}(${JSON.stringify(output.arguments)})`);\n\n    // Execute your actual function here\n    // Note: ensure arguments match your function signature\n    const result = getWeather(JSON.stringify(output.arguments.location));\n\n    // Send result back to the model\n    interaction = await ai.interactions.create({\n      model: 'gemini-2.5-flash',\n      previous_interaction_id: interaction.id,\n      input: [\n        {\n          type: 'function_result',\n          name: output.name,\n          call_id: output.id,\n          result: result,\n        },\n      ],\n    });\n\n    console.debug(`Response: ${JSON.stringify(interaction)}`);\n  }\n}\n\n```\n\n### Built-in Tools\nYou can also use Google's built-in tools, such as **Google Search** or **Code\nExecution**.\n\n#### Grounding with Google Search\n\n```typescript\nconst interaction = await ai.interactions.create({\n  model: 'gemini-2.5-flash',\n  input: 'Who won the last Super Bowl',\n  tools: [{ type: 'google_search' }],\n});\n\nconsole.debug(interaction);\n\n```\n\n#### Code Execution\n\n```typescript\nconst interaction = await ai.interactions.create({\n  model: 'gemini-2.5-flash',\n  input: 'Calculate the 50th Fibonacci number.',\n  tools: [{ type: 'code_execution' }],\n});\n\nconsole.debug(interaction);\n\n```\n\n### Multimodal Output\n\nThe Interactions API can generate multimodal outputs, such as images. You must\nspecify the `response_modalities`.\n\n```typescript\nimport * as fs from 'fs';\n\nconst interaction = await ai.interactions.create({\n  model: 'gemini-3-pro-image-preview',\n  input: 'Generate an image of a futuristic city.',\n  response_modalities: ['image'],\n});\n\nfor (const output of interaction.outputs!) {\n  if (output.type === 'image') {\n    console.log(`Generated image with mime_type: ${output.mime_type}`);\n    // Save the image\n    fs.writeFileSync(\n        'generated_city.png', Buffer.from(output.data!, 'base64'));\n  }\n}\n\n```\n\n## How is this different from the other Google AI SDKs\nThis SDK (`@google/genai`) is Google Deepmind’s \"vanilla\" SDK for its generative\nAI offerings, and is where Google Deepmind adds new AI features.\n\nModels hosted either on the [Vertex AI platform](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) or the [Gemini Developer platform](https://ai.google.dev/gemini-api/docs) are accessible through this SDK.\n\nOther SDKs may be offering additional AI frameworks on top of this SDK, or may\nbe targeting specific project environments (like Firebase).\n\nThe `@google/generative_language` and `@google-cloud/vertexai` SDKs are previous\niterations of this SDK and are no longer receiving new Gemini 2.0+ features.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fjs-genai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogleapis%2Fjs-genai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fjs-genai/lists"}