Menggunakan OpenAI API
OpenAI API adalah cara paling umum mengintegrasikan AI ke web app. SDK tersedia untuk Node.js, Python, dan bahasa lain.
Setup
npm install openai
// .env
OPENAI_API_KEY=sk-...
Chat Completion
import OpenAI from "openai";
const openai = new OpenAI(); // reads OPENAI_API_KEY from env
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "Kamu adalah asisten coding." },
{ role: "user", content: "Bagaimana cara membuat REST API di Express?" },
],
temperature: 0.7,
max_tokens: 1000,
});
console.log(response.choices[0].message.content);
Multi-turn Conversation
// Kirim seluruh history percakapan
const messages = [
{ role: "system", content: "Asisten coding." },
{ role: "user", content: "Apa itu middleware?" },
{ role: "assistant", content: "Middleware adalah fungsi..." },
{ role: "user", content: "Berikan contoh di Express" }, // follow-up
];
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages,
});
Cost Management
// response.usage menunjukkan token usage
{
prompt_tokens: 150, // input
completion_tokens: 320, // output
total_tokens: 470
}
// GPT-4o: ~$2.50 per 1M input tokens, ~$10 per 1M output tokens
// Estimasi: 1000 percakapan sederhana ≈ $1-5
Error Handling
try {
const response = await openai.chat.completions.create({...});
} catch (err) {
if (err.status === 429) {
// Rate limited — implement exponential backoff
} else if (err.status === 401) {
// Invalid API key
}
}