googleapis/js-genai
Tentang
SDK TypeScript/JavaScript untuk Gemini dan Vertex AI.
AI dan pembelajaran mesinPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- +12
- dalam 15 hari
- +16
- dalam 1 bulan
- +30
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliGoogle Gen AI SDK for TypeScript and JavaScript
Documentation: https://googleapis.github.io/js-genai/
The Google Gen AI JavaScript SDK is designed for TypeScript and JavaScript developers to build applications powered by Gemini. The SDK supports both the Gemini Developer API and Gemini platform (formerly Vertex AI).
[!TIP]
Use the Interactions API for new code.
ai.interactions.create()is the standard interface for Gemini models and agents. It covers text, streaming, multi-turn state, tools, structured output, thinking, and multimodal input and output.ai.models.generateContent()is the legacy API and remains fully supported for existing code. Start with the Quickstart below.
[!WARNING] Updates to Automatic Function Calling (AFC) in upcoming SDK version: We are changing AFC behavior in the next major version. Specifically, users will not be able to invoke AFC from direct calls to
Models.generateContentor its stream variants. Instead, users should invoke AFC fromChatsmodules.Upcoming Change to Node.js Support: Starting from SDK version 3.0.0, Node.js version 22 or later is required.
Methods/fields to be removed migration guide LiveConnectConfig.generation_configSet fields on LiveConnectConfigdirectlyprompt/text/imagearguments inModels.generate_videos(and async variants)Use sourceargument insteadGenerationConfigThinkingConfigUse ThinkingConfiginsteadTo avoid unexpected updates, pin the SDK version to
< 3.0.0.
The Google Gen AI SDK is designed to work with Gemini 2.0+ features.
[!CAUTION] API Key Security: Avoid exposing API keys in client-side code. Use server-side implementations in production environments.
Code Generation
Generative models are often unaware of recent API and SDK updates and may suggest outdated or legacy code.
We recommend using our Code Generation instructions 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.
Prerequisites
- Node.js version 22 or later
The following are required for Gemini platform users (excluding Vertex AI Studio)
Configure authentication for your project.
- Install the gcloud CLI.
- Initialize the gcloud CLI.
- Create local authentication credentials for your user account:
gcloud auth application-default login
A list of accepted authentication options are listed in GoogleAuthOptions interface of google-auth-library-node.js GitHub repo.
Installation
To install the SDK, run the following command:
npm install @google/genai
Quickstart
The Interactions API (ai.interactions.create()) is the standard interface
for Gemini models and agents. All examples below use it.
The simplest way to get started is to use an API key from
Google AI Studio and set it as the
GEMINI_API_KEY environment variable:
export GEMINI_API_KEY='your-api-key'
The examples in this section use the Gemini Developer API. In Node.js,
new GoogleGenAI({}) reads your API key from GEMINI_API_KEY.
For Gemini Enterprise Agent Platform, set the environment variables described in Initialization instead.
Generate text
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Why is the sky blue?',
});
console.log(interaction.output_text);
System instructions and generation config
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
system_instruction: 'You are a pirate. Answer in one sentence.',
input: 'What is the capital of France?',
generation_config: {
temperature: 0.7,
max_output_tokens: 1024,
thinking_level: 'low',
},
});
console.log(interaction.output_text);
Stream the response
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const stream = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Write a four-line poem about the ocean.',
stream: true,
});
for await (const event of stream) {
if (event.event_type === 'step.delta' && event.delta.type === 'text') {
process.stdout.write(event.delta.text);
}
}
console.log();
Multi-turn conversation
You can keep the conversation history yourself (client-side) or let the server keep it (server-side).
Client-side history. Keep the list of steps, append the model's returned
steps after each turn, add the next user_input step, and send the whole
list as input. With store: false, nothing is stored on the server. If the
model thinks or calls tools, resend all returned steps unchanged.
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const firstTurn = {
type: 'user_input' as const,
content: [{type: 'text' as const, text: 'Hi, my name is Amir.'}],
};
const first = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: [firstTurn],
store: false,
});
console.log(first.output_text);
const second = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: [
firstTurn,
...(first.steps ?? []),
{type: 'user_input', content: [{type: 'text', text: 'What is my name?'}]},
],
store: false,
});
console.log(second.output_text);
Server-side history. Pass previous_interaction_id to continue from an
earlier turn without resending the history. Re-send tools,
system_instruction, and generation_config on each turn if you need them.
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const first = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Hi, my name is Amir.',
});
const second = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'What is my name?',
previous_interaction_id: first.id,
});
console.log(second.output_text);
Structured output
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Give me a simple cookie recipe.',
response_format: {
type: 'text',
mime_type: 'application/json',
schema: {
type: 'object',
properties: {
recipe_name: {type: 'string'},
ingredients: {type: 'array', items: {type: 'string'}},
},
required: ['recipe_name', 'ingredients'],
},
},
});
const recipe = JSON.parse(interaction.output_text!);
console.log(recipe.recipe_name, recipe.ingredients);
Function calling
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
function getWeather(city: string): string {
return `It is sunny and 22°C in ${city}.`;
}
const weatherTool = {
type: 'function' as const,
name: 'get_weather',
description: 'Gets the current weather for a city.',
parameters: {
type: 'object',
properties: {city: {type: 'string'}},
required: ['city'],
},
};
let interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'What is the weather in Paris and in London?',
tools: [weatherTool],
});
// The model can request several calls at once. Answer all of them in one turn.
const toolResults = [];
for (const step of interaction.steps ?? []) {
if (step.type === 'function_call') {
toolResults.push({
type: 'function_result' as const,
name: step.name,
call_id: step.id,
result: getWeather(step.arguments.city as string),
});
}
}
if (toolResults.length > 0) {
interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
previous_interaction_id: interaction.id,
tools: [weatherTool],
input: toolResults,
});
}
console.log(interaction.output_text);
Thinking
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'What is the sum of the first 10 prime numbers?',
generation_config: {
thinking_level: 'high',
thinking_summaries: 'auto',
},
});
for (const step of interaction.steps ?? []) {
if (step.type === 'thought') {
for (const block of step.summary ?? []) {
if (block.type === 'text') {
console.log('Thought summary:', block.text);
}
}
}
}
console.log('Answer:', interaction.output_text);
Image input
import {GoogleGenAI} from '@google/genai';
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const imageData = fs.readFileSync('image.png').toString('base64');
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: [
{type: 'text', text: 'Describe this image.'},
{type: 'image', data: imageData, mime_type: 'image/png'},
],
});
console.log(interaction.output_text);
PDF, audio, and video input
Pass the file inline as base64 data. Use 'document' for PDFs, 'audio' for
audio, and 'video' for video. For large files on the Gemini Developer API,
upload them with ai.files.upload() and pass uri instead of data.
import {GoogleGenAI} from '@google/genai';
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const pdfData = fs.readFileSync('document.pdf').toString('base64');
const audioData = fs.readFileSync('audio.mp3').toString('base64');
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: [
{type: 'text', text: 'Summarize the PDF, then list action items from the audio.'},
{type: 'document', data: pdfData, mime_type: 'application/pdf'},
{type: 'audio', data: audioData, mime_type: 'audio/mp3'},
],
});
console.log(interaction.output_text);
Safety settings
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Tell me a story about a dragon.',
safety_settings: [
{type: 'hate_speech', threshold: 'block_low_and_above'},
{type: 'dangerous_content', threshold: 'block_medium_and_above'},
],
});
console.log(interaction.output_text);
Context caching
Requests that repeat the same long prefix (system instruction, tools, and the
start of input) reuse it through implicit caching. Keep the shared part first
and identical across calls, then check usage.total_cached_tokens. Implicit
caching is best effort, so the first call (and sometimes later ones) reports 0.
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
const manual = Array.from(
{length: 800},
(_, i) =>
`Policy ${i + 1}: Standard response time is 4 hours for tier ${((i + 1) % 3) + 1}.`,
).join('\n');
const systemInstruction = 'Answer questions using only the policy manual.';
for (const question of ['What is policy 7?', 'What is policy 42?']) {
const interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
system_instruction: systemInstruction,
input: `${manual}\n\nQuestion: ${question}`,
});
console.log(interaction.output_text);
console.log('Cached tokens:', interaction.usage?.total_cached_tokens ?? 0);
}
Background mode
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({});
let interaction = await ai.interactions.create({
model: 'gemini-4-hydrogen',
input: 'Write a short guide to space exploration.',
background: true,
});
while (interaction.status === 'queued' || interaction.status === 'in_progress') {
await new Promise((resolve) => setTimeout(resolve, 5000));
interaction = await ai.interactions.get(interaction.id);
}
console.log(interaction.status);
console.log(interaction.output_text);
Initialization
The Google Gen AI SDK provides support for both the Gemini Developer API and Gemini platform implementations of the Gemini API.
Gemini Developer API or Gemini platform?
Both services serve Gemini models through the same GoogleGenAI interface.
Gemini platform was formerly called Vertex AI. The older
vertexai: true option and GOOGLE_GENAI_USE_VERTEXAI variable still select
it.
| Gemini Developer API | Gemini platform | |
|---|---|---|
| Select it with | The default | enterprise: true, or GOOGLE_GENAI_USE_ENTERPRISE=true in Node.js |
| Authentication | An API key from Google AI Studio | Google Cloud credentials with a project and location, or an API key (Express mode) |
| Setup | An API key only | A Google Cloud project with billing and the Vertex AI API enabled. See Prerequisites. |
| Endpoint | generativelanguage.googleapis.com |
aiplatform.googleapis.com for the global location, or a regional endpoint for the location you set |
| Browser | Supported, with an API key | Express mode only: select it with vertexai: true and an API key. Browsers do not support enterprise: true, project or location. |
| Available only on this service | ai.files, ai.fileSearchStores, ai.authTokens.create, ai.batches.createEmbeddings, ai.live.music |
ai.models.generateImages, generateVideos, editImage, upscaleImage, recontextImage, segmentImage and computeTokens |
Models, quotas and pricing differ between the services. See the Gemini Developer API docs and the Gemini platform docs.
Start with the Gemini Developer API if you want an API key and no Google Cloud setup. Use Gemini platform if your app runs in a Google Cloud project and needs Google Cloud authentication or regional endpoints.
Gemini Developer API
For server-side applications, initialize using an API key, which can be acquired from Google AI Studio:
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});
Browser
[!CAUTION] API Key Security: Avoid exposing API keys in client-side code. Use server-side implementations in production environments.
In the browser the initialization code is identical:
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});
Gemini platform
Sample code for Gemini platform initialization:
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({
enterprise: true,
project: 'your_project',
location: 'your_location',
});
(Optional) (NodeJS only) Using environment variables:
For NodeJS environments, you can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini Developer API or Gemini platform.
Gemini Developer API: Set GOOGLE_API_KEY as shown below:
export GOOGLE_API_KEY='your-api-key'
Gemini platform: Set GOOGLE_GENAI_USE_ENTERPRISE,
GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION, as shown below:
export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI();
API Selection
By default, the SDK uses:
- the stable
v1API endpoints for the Gemini Developer API. - and the beta
v1beta1API endpoints for Gemini platform.
A different API version (for example v1beta or v1alpha) can be selected
with apiVersion (or httpOptions.apiVersion). In Node.js, it can also be
selected with the GOOGLE_GENAI_API_VERSION environment variable. An
explicitly configured version takes precedence over the environment variable.
Setting GOOGLE_GENAI_API_VERSION=beta selects the beta version of whichever
backend is in use: v1beta for the Gemini Developer API and v1beta1 for
Gemini platform.
To set the API version use apiVersion. For example, to set the API version to
v1 for Gemini platform:
const ai = new GoogleGenAI({
enterprise: true,
project: 'your_project',
location: 'your_location',
apiVersion: 'v1'
});
To set the API version to v1alpha for the Gemini Developer API:
const ai = new GoogleGenAI({
apiKey: 'GEMINI_API_KEY',
apiVersion: 'v1alpha'
});
GoogleGenAI overview
All API features are accessed through an instance of the GoogleGenAI classes.
The submodules bundle together related API methods:
ai.interactions: Useinteractionsto call Gemini models and agents (recommended for new code). See Quickstart and Interactions.ai.models: Usemodelsto query models (generateContent,generateImages, ...), or examine their metadata.ai.caches: Create and managecachesto reduce costs when repeatedly using the same large prompt prefix.ai.chats: Create local statefulchatobjects to simplify multi turn interactions.ai.files: Uploadfilesto the API and reference them in your prompts. This reduces bandwidth if you use a file many times, and handles files too large to fit inline with your prompt.ai.live: Start alivesession for real time interaction, allows text + audio + video input, and text or audio output.
Samples
[!NOTE] The samples in this section use the legacy
generateContentAPI, which remains fully supported. For new code, useai.interactions.create(). See Quickstart.
More samples can be found in the github samples directory.
Streaming
For quicker, more responsive API interactions use the generateContentStream
method which yields chunks as they're generated:
import {GoogleGenAI} from '@google/genai';
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});
async function main() {
const response = await ai.models.generateContentStream({
model: 'gemini-3.8-flash',
contents: 'Write a 100-word poem.',
});
for await (const chunk of response) {
console.log(chunk.text);
}
}
main();
Function Calling
To let Gemini interact with external systems, you can provide
functionDeclaration objects as tools. Using these tools requires a
four-step process:
- Declare the function name, description, and
parametersJsonSchema - Call
generateContentwith function calling enabled - Use the returned
FunctionCallparameters to call your actual function - Send the result back to the model (with history, easier in
ai.chat) as aFunctionResponse
import {GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type} from '@google/genai';
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
async function main() {
const controlLightDeclaration: FunctionDeclaration = {
name: 'controlLight',
parametersJsonSchema: {
type: 'object',
properties:{
brightness: {
type:'number',
},
colorTemperature: {
type:'string',
},
},
required: ['brightness', 'colorTemperature'],
},
};
const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: 'Dim the lights so the room feels cozy and warm.',
config: {
toolConfig: {
functionCallingConfig: {
// Override default AUTO mode to force function calling
mode: FunctionCallingConfigMode.ANY,
// Restrict the function call to the specified list
allowedFunctionNames: ['controlLight'],
}
},
tools: [{functionDeclarations: [controlLightDeclaration]}]
}
});
console.log(response.functionCalls);
}
main();
Model Context Protocol (MCP) support (experimental)
Built-in MCP support is an experimental feature. You can pass a local MCP server as a tool directly.
import { GoogleGenAI, mcpToTool} from '@google/genai';
import { Client as McpClient } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
command: "npx", // Executable
args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});
// Configure the MCP client
const mcpClient = new McpClient(
{
name: "example-client",
version: "1.0.0"
}
);
// Initialize the connection between client and server
await mcpClient.connect(serverParams);
// Instantiate the GoogleGenAI SDK
const ai = new GoogleGenAI({});
// Send request to the model with MCP tools
const response = await ai.models.generateContent({
model: "gemini-3.8-flash",
contents: `What is the weather in London on ${new Date().toLocaleDateString()}?`,
config: {
tools: [mcpToTool(mcpClient)], // uses the session, will automatically call the tool using automatic function calling
},
});
console.log(response.text);
// Close the connection
await mcpClient.close();
Generate Content
import {GoogleGenAI} from '@google/genai';
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});
async function main() {
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: 'Why is the sky blue?',
});
console.log(response.text);
}
main();
How to structure contents argument for generateContent
The SDK allows you to specify the following types in the contents parameter:
Content
Content: The SDK will wrap the singularContentinstance in an array which contains only the given content instanceContent[]: No transformation happens
Part
Parts will be aggregated on a singular Content, with role 'user'.
Part | string: The SDK will wrap thestringorPartin aContentinstance with role 'user'.Part[] | string[]: The SDK will wrap the full provided list into a singleContentwith role 'user'.
NOTE: This doesn't apply to FunctionCall and FunctionResponse parts,
if you are specifying those, you need to explicitly provide the full
Content[] structure making it explicit which Parts are 'spoken' by the model,
or the user. The SDK will throw an exception if you try this.
Automatic Continuation
Automatic continuation is enabled by default. When a response stops with
finishReason set to CONTINUATION and returns a continuationToken, the SDK
automatically sends follow-up requests with the token until generation completes
and returns the merged response. To disable automatic continuation, set
automaticContinuation: false in config.
Streaming (generateContentStream) and chats (chat.sendMessage and
chat.sendMessageStream) work very similarly.
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({
enterprise: true,
project: 'your_project',
location: 'your_location',
});
async function main() {
// Automatic continuation is enabled by default.
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: 'Write a comprehensive multi-chapter guide on compiler design.',
});
console.log(response.text);
// Set automaticContinuation to false to disable automatic continuation.
const singleHopResponse = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: 'Write a comprehensive multi-chapter guide on compiler design.',
config: {
automaticContinuation: false,
},
});
console.log(singleHopResponse.text);
}
main();
Error Handling
To handle errors raised by the API, the SDK provides this ApiError class.
import {GoogleGenAI} from '@google/genai';
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY});
async function main() {
await ai.models.generateContent({
model: 'non-existent-model',
contents: 'Write a 100-word poem.',
}).catch((e) => {
console.error('error name: ', e.name);
console.error('error message: ', e.message);
console.error('error status: ', e.status);
});
}
main();
Interactions
The Interactions API is a unified interface for interacting with Gemini models and agents. It simplifies state management, tool orchestration, and long-running tasks.
See the documentation site for more details.
Basic Interaction
const interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'Hello, how are you?',
});
console.log(interaction.output_text);
Stateful Conversation
The Interactions API supports server-side state management. You can continue a
conversation by referencing the previous_interaction_id.
// 1. First turn
const interaction1 = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'Hi, my name is Amir.',
});
console.log(interaction1.output_text);
// 2. Second turn (passing previous_interaction_id)
const interaction2 = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'What is my name?',
previous_interaction_id: interaction1.id,
});
console.log(interaction2.output_text);
Agents (Deep Research)
You can use specialized agents like deep-research-preview-04-2026 for
complex tasks.
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 1. Start the Deep Research Agent
const initialInteraction = await ai.interactions.create({
input:
'Research the history of the Google TPUs with a focus on 2025 and 2026.',
agent: 'deep-research-preview-04-2026',
background: true,
});
console.log(`Research started. Interaction ID: ${initialInteraction.id}`);
// 2. Poll for results
while (true) {
const interaction = await ai.interactions.get(initialInteraction.id);
console.log(`Status: ${interaction.status}`);
if (interaction.status === 'completed') {
console.log('\nFinal Report:\n', interaction.output_text);
break;
} else if (['failed', 'cancelled'].includes(interaction.status)) {
console.log(`Failed with status: ${interaction.status}`);
break;
}
await sleep(10000); // Sleep for 10 seconds
}
Multimodal Input
You can provide multimodal data (text, images, audio, etc.) in the input list.
import * as fs from 'node:fs';
const base64Image = fs.readFileSync('image.png').toString('base64');
const interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: [
{ type: 'text', text: 'Describe the image.' },
{ type: 'image', data: base64Image, mime_type: 'image/png' },
],
});
console.log(interaction.output_text);
Function Calling
You can define custom functions for the model to use. The Interactions API handles the tool selection, and you provide the execution result back to the model.
// 1. Define the tool
const getWeather = (location: string) => {
/* Gets the weather for a given location. */
return `The weather in ${location} is sunny.`;
};
// 2. Send the request with tools
let interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'What is the weather in Mountain View, CA?',
tools: [
{
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city and state, e.g. San Francisco, CA',
},
},
required: ['location'],
},
},
],
});
// 3. Handle the tool calls (the model may request several at once)
const toolResults = [];
for (const step of interaction.steps ?? []) {
if (step.type === 'function_call') {
console.log(`Tool Call: ${step.name}(${JSON.stringify(step.arguments)})`);
// Execute your actual function here
toolResults.push({
type: 'function_result' as const,
name: step.name,
call_id: step.id,
result: getWeather(step.arguments.location as string),
});
}
}
// 4. Send all results back to the model in one request
if (toolResults.length > 0) {
interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
previous_interaction_id: interaction.id,
input: toolResults,
});
console.log(`Response: ${interaction.output_text}`);
}
Built-in Tools
You can also use Google's built-in tools, such as Google Search or Code Execution.
Grounding with Google Search
const interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'Who won the last Super Bowl',
tools: [{ type: 'google_search' }],
});
console.log(interaction.output_text);
Code Execution
const interaction = await ai.interactions.create({
model: 'gemini-3.8-flash',
input: 'Calculate the 50th Fibonacci number.',
tools: [{ type: 'code_execution' }],
});
console.log(interaction.output_text);
Multimodal Output
The Interactions API can generate multimodal outputs, such as images or audio.
You must specify the response_modalities.
Image Output
import * as fs from 'node:fs';
const interaction = await ai.interactions.create({
model: 'gemini-nano-banana-2.1',
input: 'Generate an image of a futuristic city.',
response_modalities: ['image'],
});
const image = interaction.output_image;
if (image?.data) {
console.log(`Generated image with mime_type: ${image.mime_type}`);
const ext = image.mime_type?.split('/')[1] ?? 'png';
fs.writeFileSync(`generated_city.${ext}`, image.data, 'base64');
}
Audio Output
import * as fs from 'node:fs';
const interaction = await ai.interactions.create({
model: 'gemini-3.8-flash-tts',
input: 'Say hello and give a one sentence motivational quote.',
response_modalities: ['audio'],
});
const audio = interaction.output_audio;
if (audio?.data) {
console.log(`Generated audio with mime_type: ${audio.mime_type}`);
fs.writeFileSync('greeting.wav', audio.data, 'base64');
}
How is this different from the other Google AI SDKs
This SDK (@google/genai) is Google Deepmind’s "vanilla" SDK for its generative
AI offerings, and is where Google Deepmind adds new AI features.
Models hosted either on the Gemini platform or the Gemini Developer platform are accessible through this SDK.
Other SDKs may be offering additional AI frameworks on top of this SDK, or may be targeting specific project environments (like Firebase).
The @google/generative_language and @google-cloud/vertexai SDKs are previous
iterations of this SDK and are no longer receiving new Gemini 2.0+ features.
Jelajahi proyek terkait
Memuat…