DDevArchive
Đăng nhập

AI integration: gọi API, prompt engineering & RAG cơ bản

2025-2026 — không biết AI = mất lợi thế cạnh tranh lớn. Nhưng bạn không cần train model. Chỉ cần biết GỌI API đúng cách. Bài này dạy: OpenAI/Claude API, prompt engineering, streaming response, và RAG (tìm kiếm trên data riêng).

Gọi OpenAI API cơ bản

// File: openai.ts
import OpenAI from 'openai'

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
})

async function askAI(userMessage: string) {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini", // rẻ + nhanh, đủ cho hầu hết use case
    messages: [
      { role: "system", content: "Bạn là trợ lý chuyên về lập trình. Trả lời ngắn gọn, có code ví dụ." },
      { role: "user", content: userMessage },
    ],
    temperature: 0.7,    // 0 = deterministic, 1 = creative
    max_tokens: 1000,    // giới hạn chi phí
  })

  return response.choices[0].message.content
}

Streaming response: hiển thị từng từ như ChatGPT

// File: stream.ts
// Server: stream response
app.post("/api/chat", async (req, res) => {
  const stream = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: req.body.messages,
    stream: true, // ← bật streaming
  })

  res.setHeader("Content-Type", "text/event-stream")

  for await (const chunk of stream) {
    const text = chunk.choices[0]?.delta?.content || ""
    res.write(`data: ${JSON.stringify({ text })}

`)
  }

  res.write("data: [DONE]

")
  res.end()
})

RAG: AI trả lời dựa trên data CỦA BẠN

RAG (Retrieval-Augmented Generation): thay vì AI trả lời từ kiến thức chung, bạn cho AI đọc tài liệu của bạn trước rồi trả lời. Ví dụ: chatbot hỗ trợ khách hàng dựa trên docs sản phẩm.

// File: rag.md
## Flow RAG đơn giản

1. Chuẩn bị data: chia tài liệu thành chunk nhỏ (~500 tokens)
2. Embedding: chuyển mỗi chunk thành vector (openai.embeddings)
3. Lưu vectors vào vector database (Pinecone, Supabase pgvector)

4. Khi user hỏi:
   a. Embed câu hỏi → vector
   b. Tìm 3-5 chunk liên quan nhất (cosine similarity)
   c. Đưa chunks vào system prompt:
      "Dựa trên tài liệu sau đây, trả lời câu hỏi: {chunks}"
   d. AI trả lời dựa trên data thật → chính xác hơn
Chi phí AI: cẩn thận bill shock

GPT-4o: ~$5/1M input tokens. Nếu mỗi request dùng 2000 tokens, 10K users/ngày = $100/ngày. Dùng gpt-4o-mini (rẻ 15x) cho hầu hết use case. Cache response nếu có thể. Set max_tokens để limit chi phí.

❓ RAG giải quyết vấn đề gì của AI?

  • Gọi OpenAI/Claude API từ backend
  • Implement streaming response (SSE)
  • Hiểu flow RAG cơ bản
  • Set max_tokens và cache để kiểm soát chi phí