Building with AI APIs: A Developer's Guide
Ready to add AI to your applications? This guide covers the major AI APIs and how to use them effectively.
Overview of Major AI APIs
Text/Chat APIs
| Provider | Models | Best For |
|---|
| OpenAI | GPT-4, GPT-3.5 | General purpose |
| Anthropic | Claude 3 | Long context, safety |
| Google | Gemini | Multimodal |
| Cohere | Command | Enterprise |
Image APIs
| Provider | Models | Best For |
|---|
| OpenAI | DALL-E 3 | Quality, accuracy |
| Stability AI | SDXL | Customization |
| Midjourney | MJ API | Aesthetics |
Voice APIs
| Provider | Features | Best For |
|---|
| ElevenLabs | TTS, cloning | Quality voices |
| OpenAI | Whisper, TTS | Transcription |
| AssemblyAI | Transcription | Accuracy |
Getting Started with OpenAI
Setup
npm install openai
Basic Chat Completion
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function chat(message) {
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: message }
],
});
return completion.choices[0].message.content;
}
Streaming Responses
async function streamChat(message) {
const stream = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: message }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
}
Anthropic Claude API
Setup
npm install @anthropic-ai/sdk
Basic Usage
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function askClaude(message) {
const response = await anthropic.messages.create({
model: "claude-3-sonnet-20250229",
max_tokens: 1024,
messages: [
{ role: "user", content: message }
],
});
return response.content[0].text;
}
Image Generation
DALL-E 3
async function generateImage(prompt) {
const response = await openai.images.generate({
model: "dall-e-3",
prompt: prompt,
n: 1,
size: "1024x1024",
quality: "hd",
});
return response.data[0].url;
}
Stability AI
async function generateWithStability(prompt) {
const response = await fetch(
"https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STABILITY_API_KEY}`,
},
body: JSON.stringify({
text_prompts: [{ text: prompt }],
cfg_scale: 7,
steps: 30,
}),
}
);
const data = await response.json();
return data.artifacts[0].base64;
}
Best Practices
Error Handling
async function safeAPICall(fn) {
try {
return await fn();
} catch (error) {
if (error.status === 429) {
// Rate limited - implement backoff
await sleep(1000);
return safeAPICall(fn);
}
if (error.status === 500) {
// Server error - retry
return safeAPICall(fn);
}
throw error;
}
}
Cost Management
// Track token usage
function trackUsage(response) {
const usage = response.usage;
console.log(`Tokens: ${usage.total_tokens}`);
console.log(`Cost: $${(usage.total_tokens / 1000) * 0.03}`);
}
Caching
const cache = new Map();
async function cachedChat(message) {
const key = hashMessage(message);
if (cache.has(key)) {
return cache.get(key);
}
const response = await chat(message);
cache.set(key, response);
return response;
}
Building a Simple AI App
Example: AI Writing Assistant
import express from 'express';
import OpenAI from 'openai';
const app = express();
const openai = new OpenAI();
app.post('/api/improve-writing', async (req, res) => {
const { text, style } = req.body;
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: [
{
role: "system",
content: `You are a writing assistant. Improve the given text to be more ${style}. Return only the improved text.`
},
{ role: "user", content: text }
],
});
res.json({ improved: completion.choices[0].message.content });
});
app.listen(3000);
Pricing Comparison
| Provider | Model | Input | Output |
|---|
| OpenAI | GPT-4 | $30/1M | $60/1M |
| OpenAI | GPT-3.5 | $0.50/1M | $1.50/1M |
| Anthropic | Claude 3 Sonnet | $3/1M | $15/1M |
| Google | Gemini Pro | $0.50/1M | $1.50/1M |
Security Considerations
- Never expose API keys in client-side code
- Implement rate limiting to prevent abuse
- Validate inputs before sending to AI
- Filter outputs for sensitive content
- Log usage for monitoring and debugging