AI integration is no longer optional for modern applications. Here's how we approach adding AI capabilities to client projects.
Choosing the Right AI Service
Different AI providers excel at different tasks:
API Integration Patterns
Keep your API keys secure with environment variables:
// api/chat/route.ts
import { OpenAI } from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(req: Request) {
const { message } = await req.json();
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
});
return Response.json({
reply: response.choices[0].message.content
});
}Streaming Responses
For better UX, stream responses to show text as it's generated:
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
stream: true,
});
for await (const chunk of stream) {
// Send chunk to client
}Cost Management
AI APIs can get expensive. Implement:
Conclusion
AI integration adds significant value to applications when done thoughtfully. Start small, measure impact, and iterate.