OpenAI API là gì?What is the OpenAI API?
OpenAI API cho phép ứng dụng của bạn dùng GPT (mô hình AI) qua HTTP. Bạn gửi prompt (câu lệnh), API trả về text AI tạo. Cần API key từ platform.openai.com. Cài: npm install openai. Mỗi request tốn token (chi phí).The OpenAI API lets your application use GPT (an AI model) over HTTP. You send a prompt, the API returns AI-generated text. You need an API key from platform.openai.com. Install: npm install openai. Each request costs tokens (money).
Gọi Chat Completions APICalling the Chat Completions API
Chat Completions là endpoint phổ biến nhất. Truyền mảng messages: system (định nghĩa vai trò AI), user (câu hỏi). Mỗi message có role và content. Model phổ biến: gpt-4o-mini (rẻ), gpt-4o (chất lượng cao). max_tokens giới hạn độ dài trả lời.Chat Completions is the most popular endpoint. Pass an array of messages: system (defines AI role), user (the question). Each message has a role and content. Popular models: gpt-4o-mini (cheap), gpt-4o (high quality). max_tokens limits response length.
import OpenAI from 'openai';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function chat(userMessage) {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: 'Bạn là trợ lý giáo dục song ngữ Việt–Anh. Trả lời ngắn gọn, dễ hiểu.'
},
{ role: 'user', content: userMessage }
],
max_tokens: 500,
});
return response.choices[0].message.content;
}
const reply = await chat('Giải thích biến trong Python');
console.log(reply);
Prompt engineeringPrompt engineering
Prompt engineering là nghệ thuật viết prompt để AI trả lời đúng ý. Quy tắc: (1) Rõ ràng, cụ thể — tránh mơ hồ. (2) Đặt vai trò cho AI: "Bạn là giáo viên...". (3) Cho ví dụ. (4) Chỉ định định dạng: "Trả lời trong 3 câu". (5) Chia nhỏ câu hỏi phức tạp.Prompt engineering is the art of writing prompts so AI responds as intended. Rules: (1) Clear, specific — avoid vagueness. (2) Assign AI a role: "You are a teacher...". (3) Give examples. (4) Specify format: "Answer in 3 sentences". (5) Break complex questions into parts.
Xử lý lỗi và rate limitError handling and rate limits
OpenAI API có thể lỗi: sai API key, hết quota, rate limit (gọi quá nhanh). Luôn dùng try/catch. Kiểm tra error.type: "invalid_api_key", "rate_limit_exceeded", "insufficient_quota". Thêm retry với backoff (đợi rồi thử lại).The OpenAI API can error: wrong API key, out of quota, rate limit (calling too fast). Always use try/catch. Check error.type: "invalid_api_key", "rate_limit_exceeded", "insufficient_quota". Add retry with backoff (wait then try again).
async function chatSafe(userMessage) {
try {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: userMessage }],
max_tokens: 500,
});
return response.choices[0].message.content;
} catch (error) {
if (error.type === 'rate_limit_exceeded') {
console.log('Quá nhiều request, đợi 5 giây...');
await new Promise(r => setTimeout(r, 5000));
return chatSafe(userMessage); // Thử lại
}
console.error('Lỗi OpenAI:', error.message);
return 'Xin lỗi, đã có lỗi xảy ra.';
}
}