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
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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}Text Generation
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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}Streaming
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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}Multimodal
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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}System & Configuration
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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "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
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Hello! I am Gemini, a helpful AI assistant."
}
],
"role": "model"
}
}
]
}Tool Calling
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
{
"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
API key not found / Unauthorized
Set process.env.GEMINI_API_KEY in your server-side environment or configure it in the AI Studio Settings.
Model not found exception
Ensure you are targeting valid model aliases, such as 'gemini-2.5-flash' or 'gemini-2.5-pro' in your API parameters.
Blocked by Safety Settings
The API blocked the request or response because it violated default safety boundaries. Adjust safetySettings thresholds.
IllegalStateException: Chat history out of sync
The roles in your message history do not strictly alternate between 'user' and 'model'.
Async iterator streaming error
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.
Generated from LearnHubly Developer Cheatsheets
Access interactive sandbox tests, tools, and developer code bases at https://www.learnhubly.com