Cấp độ: intermediate40 phútminMiễn phíFreeProduct DeveloperProduct Developer

AI Agent: Tích hợp OpenAI APIAI Agent: Integrate OpenAI API

Chatbot song ngữ Việt–Anh đơn giảnA simple bilingual Viet–English chatbot

Bạn sẽ học gìWhat you will learn

  • Gọi OpenAI Chat Completions APICall OpenAI Chat Completions API
  • Viết system prompt hiệu quảWrite effective system prompts
  • Xử lý lỗi và rate limitHandle errors and rate limits

Bạn sẽ tạo gìWhat you will build

Chatbot song ngữ Việt–Anh đơn giảnA simple bilingual Viet–English chatbot

Nội dung bài họcLesson content

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.

javascript
                      
                        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).

javascript
                      
                        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.';
  }
}
                      
                    

Bài tập thực hànhHands-on exercises

1Viết hàm chat() gọi OpenAI API với system prompt "Bạn là giáo viên Python" và trả về câu trả lời.Write a chat() function calling OpenAI API with system prompt "You are a Python teacher" and returning the answer.

Gợi ýHint

Dùng client.chat.completions.create với messages: system + user.Use client.chat.completions.create with messages: system + user.

Lời giảiSolution
javascript
                      
                        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à giáo viên Python. Giải thích rõ ràng, có ví dụ code.' },
      { role: 'user', content: userMessage }
    ],
    max_tokens: 500,
  });
  return response.choices[0].message.content;
}
                      
                    

2Thêm try/catch vào hàm chat() để xử lý lỗi API key sai và rate limit.Add try/catch to chat() to handle wrong API key and rate limit errors.

Gợi ýHint

Bọc code trong try/catch. Kiểm tra error.type.Wrap code in try/catch. Check error.type.

Lời giảiSolution
javascript
                      
                        async function chat(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 === 'invalid_api_key') return 'Lỗi: API key không hợp lệ';
    if (error.type === 'rate_limit_exceeded') return 'Lỗi: quá nhiều request';
    return 'Lỗi: ' + error.message;
  }
}
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: OpenAI API cần gì để gọi?Q1: What do you need to call the OpenAI API?

Câu 2: Role "system" trong messages dùng để làm gì?Q2: What is the "system" role in messages used for?

Câu 3: Prompt engineering là gì?Q3: What is prompt engineering?

Câu 4: Rate limit exceeded nghĩa là gì?Q4: What does "rate limit exceeded" mean?

Code mẫuSample code

javascript
                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. / You are a bilingual Viet–English education assistant.'
      },
      { role: 'user', content: userMessage }
    ],
    max_tokens: 500,
  });
  return response.choices[0].message.content;
}