import{ GoogleGenerativeAI }from"@google/generative-ai";const genAI =newGoogleGenerativeAI(process.env.GOOGLE_API_KEY!);const model = genAI.getGenerativeModel({ model:"gemini-2.5-flash", systemInstruction:"You are a helpful assistant.",});const result =await model.generateContent("Hello!");console.log(result.response.text());
Google Gemini — Streaming
const result =await model.generateContentStream("Hello!");forawait(const chunk of result.stream){ process.stdout.write(chunk.text());}
// OpenAIconst text = response.choices[0].message.content;const tokens = response.usage?.total_tokens;// Anthropicconst text = message.content[0].type ==="text"? message.content[0].text :"";const tokens = message.usage.input_tokens + message.usage.output_tokens;// Geminiconst text = result.response.text();const tokens = result.response.usageMetadata?.totalTokenCount;
Error Handling Template
asyncfunctioncallAI(provider:"openai"|"anthropic"|"gemini"){try{// Your API call here}catch(error:any){if(error?.status ===429|| error?.message?.includes("429")){console.error("Rate limited — implement retry with backoff");}elseif(error?.status ===401|| error?.message?.includes("API_KEY")){console.error("Authentication failed — check your API key");}elseif(error?.status ===400){console.error("Bad request — check your parameters");}elseif(error?.status >=500){console.error("Server error — retry later");}else{throw error;}}}
Retry with Exponential Backoff
asyncfunctionwithRetry<T>(fn:()=>Promise<T>, maxRetries =3, baseDelay =1000):Promise<T>{for(let i =0; i <= maxRetries; i++){try{returnawaitfn();}catch(error:any){if(error?.status ===429&& i < maxRetries){const delay = baseDelay * Math.pow(2, i);awaitnewPromise((r)=>setTimeout(r, delay));}else{throw error;}}}thrownewError("Unreachable");}
AI Prompts for API Integration
Getting Started
"Set up a Node.js project with TypeScript that can call the [OpenAI/Anthropic/Google] API. Include environment variables and error handling."
"I want to compare responses from OpenAI, Anthropic, and Google for the same prompt. Build a script that calls all three and shows the results."
"Create a reusable AI client class that supports multiple providers. I should be able to switch between OpenAI, Anthropic, and Google easily."
Building Features
"Build a chat API endpoint that supports streaming responses using [provider]. The frontend is built with React."
"Create a text summarization feature using [provider]. It should accept long text and return a 3-sentence summary."
"Build a code review tool that analyzes code and returns structured feedback as JSON using OpenAI's structured output."
"Create a function-calling setup with OpenAI where the AI can search a database and return results."
Production Readiness
"Add rate limiting, retry logic, and error handling to my AI API calls. I'm using [provider]."
"Set up cost tracking for my AI API usage. Log tokens used per request and estimate daily costs."
"Build a prompt caching layer that stores AI responses in [Redis/Firestore] to avoid redundant API calls."
"Create a fallback system that tries OpenAI first, then falls back to Anthropic if it fails."
Optimization
"My AI API costs are too high. Here's my current setup: [describe]. How can I reduce costs?"
"Optimize my prompts for token efficiency. Here are my current prompts: [paste]. Make them shorter without losing quality."
"I'm hitting rate limits. Help me implement request queuing with concurrency control."
Debugging
"I'm getting a 429 error from [provider]. What does this mean and how do I fix it?"
"My streaming implementation isn't working. Here's my code: [paste]. What's wrong?"
"The AI response doesn't match my expected JSON format. Here's my prompt and the response: [paste]. How do I fix this?"
"My API key works in curl but not in my Node.js app. Here's my code: [paste]."
Quick Start Checklist
1. SIGN UP for an API account (OpenAI, Anthropic, or Google)
2. GET your API key from the provider's dashboard
3. INSTALL the SDK: npm install [package]
4. CREATE a .env file with your API key
5. ADD .env to .gitignore
6. SET a spending limit on your account
7. WRITE your first API call
8. TEST with a cheap model first (mini/haiku/flash)
9. ADD error handling and retries
10. UPGRADE to a better model if needed
You now have everything you need to integrate AI into your applications. Start with one provider, build something small, and expand from there. The best way to learn AI APIs is to build with them.