Building AI-Powered Applications with OpenAI APIs
Introduction
Artificial Intelligence has transformed how we build applications. With OpenAI's APIs, developers can add advanced AI capabilities to their applications without needing ML expertise.
Setting Up OpenAI API
bash1npm install openai
typescript1import OpenAI from 'openai'; 2 3const openai = new OpenAI({ 4 apiKey: process.env.OPENAI_API_KEY, 5});
GPT-4 Integration
Basic Chat Completion
typescript1async function generateResponse(prompt: string) { 2 const completion = await openai.chat.completions.create({ 3 model: "gpt-4", 4 messages: [ 5 { 6 role: "system", 7 content: "You are a helpful assistant specialized in programming." 8 }, 9 { 10 role: "user", 11 content: prompt 12 } 13 ], 14 temperature: 0.7, 15 max_tokens: 500, 16 }); 17 18 return completion.choices[0].message.content; 19}
Function Calling
typescript1const functions = [ 2 { 3 name: "get_current_weather", 4 description: "Get the current weather in a given location", 5 parameters: { 6 type: "object", 7 properties: { 8 location: { 9 type: "string", 10 description: "The city and state, e.g. San Francisco, CA", 11 }, 12 unit: { 13 type: "string", 14 enum: ["celsius", "fahrenheit"], 15 }, 16 }, 17 required: ["location"], 18 }, 19 }, 20]; 21 22const response = await openai.chat.completions.create({ 23 model: "gpt-4", 24 messages: [{ role: "user", content: "What's the weather in London?" }], 25 functions: functions, 26 function_call: "auto", 27});
DALL-E Image Generation
typescript1async function generateImage(prompt: string) { 2 const response = await openai.images.generate({ 3 model: "dall-e-3", 4 prompt: prompt, 5 n: 1, 6 size: "1024x1024", 7 quality: "hd", 8 style: "vivid", 9 }); 10 11 return response.data[0].url; 12} 13 14// Generate blog post header image 15const imageUrl = await generateImage( 16 "A futuristic tech blog header with neural networks and code" 17);
Whisper Speech-to-Text
typescript1import fs from 'fs'; 2 3async function transcribeAudio(audioPath: string) { 4 const transcription = await openai.audio.transcriptions.create({ 5 file: fs.createReadStream(audioPath), 6 model: "whisper-1", 7 response_format: "text", 8 language: "en", 9 temperature: 0.0, 10 }); 11 12 return transcription.text; 13}
Building a Content Generation Platform
typescript1class ContentGenerator { 2 constructor(private openai: OpenAI) {} 3 4 async generateBlogPost(topic: string) { 5 // Step 1: Generate outline 6 const outline = await this.generateOutline(topic); 7 8 // Step 2: Generate sections 9 const sections = await Promise.all( 10 outline.sections.map(section => 11 this.generateSection(section.title, section.keywords) 12 ) 13 ); 14 15 // Step 3: Generate SEO metadata 16 const metadata = await this.generateSEOMetadata(topic); 17 18 // Step 4: Generate featured image 19 const imageUrl = await this.generateImage(topic); 20 21 return { 22 title: outline.title, 23 content: sections.join('\n\n'), 24 metadata, 25 imageUrl 26 }; 27 } 28 29 private async generateOutline(topic: string) { 30 const response = await this.openai.chat.completions.create({ 31 model: "gpt-4", 32 messages: [ 33 { 34 role: "system", 35 content: "You are a professional blog post outline generator. Return JSON format." 36 }, 37 { 38 role: "user", 39 content: `Generate a detailed outline for a blog post about ${topic}` 40 } 41 ], 42 response_format: { type: "json_object" }, 43 }); 44 45 return JSON.parse(response.choices[0].message.content); 46 } 47}
Rate Limiting and Cost Optimization
typescript1class OptimizedOpenAIClient { 2 private requestQueue: Array<() => Promise<any>> = []; 3 private processing = false; 4 private maxConcurrent = 5; 5 private concurrentCount = 0; 6 7 async executeWithRetry<T>( 8 operation: () => Promise<T>, 9 maxRetries = 3 10 ): Promise<T> { 11 for (let i = 0; i < maxRetries; i++) { 12 try { 13 return await operation(); 14 } catch (error) { 15 if (error.status === 429) { // Rate limit 16 const delay = Math.pow(2, i) * 1000; // Exponential backoff 17 await new Promise(resolve => setTimeout(resolve, delay)); 18 continue; 19 } 20 throw error; 21 } 22 } 23 throw new Error('Max retries exceeded'); 24 } 25 26 // Token usage tracking 27 trackTokenUsage(response: any) { 28 const tokens = response.usage?.total_tokens || 0; 29 // Store for analytics and cost tracking 30 this.storeTokenUsage(tokens); 31 } 32}