AI & LLM
Updated for 2026

Google Gen AI SDK Cheatsheet 2026

Complete developer's guide to the official @google/genai TypeScript SDK: model selection, streaming, multimodal inputs, system instructions, and tool calling.

Initialization

import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
Initialize the standard modern Google Gen AI SDK client server-side.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

Text Generation

const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Hello' });
Generate non-streaming text using the ultra-fast gemini-2.5-flash model.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Hello' });

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}
const response = await ai.models.generateContent({ model: 'gemini-2.5-pro', contents: 'Hello' });
Generate text using the high-reasoning gemini-2.5-pro model.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

const response = await ai.models.generateContent({ model: 'gemini-2.5-pro', contents: 'Hello' });

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

Streaming

const responseStream = await ai.models.generateContentStream({ model: 'gemini-2.5-flash', contents: 'Write a poem' });
Establish a real-time server response stream for low-latency delivery.

When to Use

When building conversational UIs where the model's response needs to be displayed token-by-token in real-time.

Common Mistakes

Awaiting the entire generateContentStream response instead of iterating through chunk.text.

Shortcut / Pro-Tip

Use 'for await (const chunk of responseStream)' to handle low-latency rendering of content.

Example

const responseStream = await ai.models.generateContentStream({ model: 'gemini-2.5-flash', contents: 'Write a poem' });

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}
for await (const chunk of responseStream) { console.log(chunk.text); }
Iterate over incoming stream content chunks in real-time.

When to Use

When building conversational UIs where the model's response needs to be displayed token-by-token in real-time.

Common Mistakes

Awaiting the entire generateContentStream response instead of iterating through chunk.text.

Shortcut / Pro-Tip

Use 'for await (const chunk of responseStream)' to handle low-latency rendering of content.

Example

for await (const chunk of responseStream) { console.log(chunk.text); }

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

Multimodal

const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: [ai.files.upload({file}), 'describe this image'] });
Submit a multi-part payload containing both media/image components and text instructions.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: [ai.files.upload({file}), 'describe this image'] });

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

System & Configuration

config: { systemInstruction: 'Respond only in code blocks.' }
Define system-level instructions using the config parameter.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

config: { systemInstruction: 'Respond only in code blocks.' }

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}
config: { responseMimeType: 'application/json', responseSchema: {type: 'OBJECT', properties: {...}} }
Enforce a structured, schema-validated JSON payload return from the model.

When to Use

When you require strict, structured JSON outputs that map perfectly to typed databases or backend models.

Common Mistakes

Failing to define the structural schema mapping in config, which can cause the model to output stray markdown tags.

Shortcut / Pro-Tip

Explicitly specify 'responseMimeType: "application/json"' in the configurations.

Example

config: { responseMimeType: 'application/json', responseSchema: {type: 'OBJECT', properties: {...}} }

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

Tool Calling

config: { tools: [{ functionDeclarations: [{ name: 'getWeather', parameters: {...} }] }] }
Provide client function declarations to enable smart tool-calling and arguments extraction.

When to Use

When leveraging Google's Gemini models for text generation, streaming, multimodal vision, structured outputs, or tool calling.

Common Mistakes

Exposing the Gemini API key in the client-side code; always use the key on the server-side via process.env.GEMINI_API_KEY.

Shortcut / Pro-Tip

Configure systemInstruction inside the config object to define persistent model behavior rules.

Example

config: { tools: [{ functionDeclarations: [{ name: 'getWeather', parameters: {...} }] }] }

Output Example

Console / Terminal
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hello! I am Gemini, a helpful AI assistant."
          }
        ],
        "role": "model"
      }
    }
  ]
}

Gemini API Best Practices

1Use the Modern @google/genai SDK

Prefer Google's modern @google/genai SDK which simplifies API calls, structures payloads, and organizes models under clear aliases.

2Secure your GEMINI_API_KEY

Always handle your Gemini API Key in server-side environment variables. Never load it directly in your React client.

3Configure responseSchema for Structured JSON

Utilize responseMimeType: 'application/json' and provide a schema layout to guarantee fully-typed, parsed object returns.

4Leverage Multi-turn Chat Objects

Use ai.chats.create() to automatically handle conversation history arrays and state updates under the hood.

5Apply System Instructions for Rules Enforcements

Define critical persona boundaries and coding guidelines inside the systemInstruction config block.

Common Gemini API Errors & Solutions

Error

API key not found / Unauthorized

Solution

Set process.env.GEMINI_API_KEY in your server-side environment or configure it in the AI Studio Settings.

Error

Model not found exception

Solution

Ensure you are targeting valid model aliases, such as 'gemini-2.5-flash' or 'gemini-2.5-pro' in your API parameters.

Error

Blocked by Safety Settings

Solution

The API blocked the request or response because it violated default safety boundaries. Adjust safetySettings thresholds.

Error

IllegalStateException: Chat history out of sync

Solution

The roles in your message history do not strictly alternate between 'user' and 'model'.

Error

Async iterator streaming error

Solution

Awaiting the return object instead of looping over the asynchronous generator blocks. Use for await (const chunk of responseStream).

Common Gemini API Interview Questions

Q1What are the recommended model aliases for the Gemini 2.5 family?

The primary aliases are 'gemini-2.5-flash' (designed for speed, multimodal tasks, and cost efficiency) and 'gemini-2.5-pro' (ideal for complex coding, logical reasoning, and agentic workflows).

Q2How do you enforce structured JSON responses in the @google/genai SDK?

You set config.responseMimeType to 'application/json' and define the shape using config.responseSchema with Type definitions (e.g. Type.OBJECT) in the SDK.

Q3What is Google Search Grounding in Gemini?

Search Grounding is a feature that allows Gemini to perform Google searches in real-time to augment its response with up-to-date information, complete with search source citations.

Q4Does Gemini support multimodal inputs?

Yes. Gemini is natively multimodal from the ground up, allowing you to pass images, video files, audio clips, and PDFs directly in the contents array alongside text.

Q5What is the purpose of systemInstruction in Gemini?

It sets the overall tone, behavior rules, and operational guardrails for the model before it begins reading any user-provided prompt messages.