llm-api-101

API không nhớ gì. Mọi thứ model biết nằm trong request bạn gửi. The API remembers nothing. Everything the model knows is in the request you send.

Bài "hello world" trước mcp-function-calling (201). Mỗi dòng của request dưới đây là một bài học. Bấm vào dòng để nhảy tới phần giải thích. The "hello world" lesson before mcp-function-calling (201). Each line of the request below is one lesson. Select a line to jump to it.

  1. POST /v1/messages
  2. {
  3. "model": "claude-sonnet-5-5",
  4. "max_tokens": 1024,06 Token và chi phíTokens and cost
  5. "system": "You are the support assistant…",02 System prompt
  6. "messages": [{ "role": "user", "content": "…" }],01 Messages vàand roles
  7. "stream": true,03 Streaming
  8. "output_config": { "format": { "type": "json_schema", … } },04 Structured output
  9. "tools": [{ "name": "get_order_status", … }]05 Tool calling
  10. }
  11. Anthropic(timeout=60, max_retries=3)07 Rate limit, retry, timeout

Dòng cuối không nằm trong request: timeout và retry là việc của client. The last line isn't part of the request: timeouts and retries live in the client.

Chọn cái nàoWhich one do I need

Bảy khái niệm không loại trừ nhau. Câu hỏi là bật thêm cái gì, và trước hết là có cần LLM không. The seven concepts aren't alternatives. The question is what to add, and first, whether you need an LLM at all.

Không cần gọi LLM khiSkip the LLM when

  • Kết quả tính được bằng quy tắc: regex, bảng tra, vài dòng if.
  • Sai một lần là không chấp nhận được: tính tiền, thuế, lương.
  • Cần phản hồi dưới khoảng 100 ms.
  • Dữ liệu không được rời khỏi hạ tầng của bạn.
  • Việc làm một lần, khối lượng nhỏ.
  • Rules can compute the result: a regex, a lookup table, a few ifs.
  • A single mistake is unacceptable: billing, tax, payroll.
  • You need a response in under about 100 ms.
  • The data must not leave your infrastructure.
  • It's a one-off, low-volume job.

Phương án rẻ nhất: thử prompt trong giao diện chat. Chỉ viết code khi kết quả đã ổn và cần lặp lại hàng trăm lần. Cheapest option: try the prompt in a chat interface. Write code only once results are good and you need them hundreds of times.

Cần gì thì bật nấyNeed this, add that

  • Câu trả lời văn bản cho người đọcA text answer for a human 0102
  • Có người ngồi chờ và câu trả lời dàiSomeone is waiting and the answer is long + 03
  • Code đọc kết quả (ghi DB, gọi API khác)Code consumes the result (DB write, another API) 04
  • Cần dữ liệu thời gian thực hoặc phải thực hiện hành độngNeeds live data or has to take an action 05
  • Chỉ cần JSON đúng dạng, không gọi gì cảJust need well-formed JSON, nothing to call 04, không phải 0504, not 05
  • Có người dùng thật và hoá đơn thậtReal users and a real bill 0607

Bảy bài, theo thứ tự họcSeven lessons, in learning order

Mỗi bài dùng lại bài trước: tool calling cần hiểu messages, retry cần biết request nào có tác dụng phụ. Each lesson builds on the last: tool calling needs messages, retries need to know which requests have side effects.

01

Messages và rolesMessages and roles

Đầu vàoInput

Danh sách lượt hội thoại user/assistant. Server không lưu gì, mỗi lần gọi bạn gửi lại toàn bộ lịch sử. The list of user/assistant turns. The server stores nothing; every call resends the full history.

Đánh đổi: chọn stateless là đổi chi phí gửi lại toàn bộ lịch sử mỗi lượt lấy quyền kiểm soát và tái hiện chính xác từng request. Trade-off: going stateless trades the cost of resending the full history every turn for control over, and exact replay of, every request.

Dùng choUse for

  • Chatbot nhiều lượt
  • Few-shot bằng cặp user/assistant mẫu
  • Tác vụ một lượt: tóm tắt, phân loại
  • Multi-turn chatbots
  • Few-shot via example user/assistant pairs
  • Single-turn jobs: summarise, classify

ĐượcGain

  • Kiểm soát toàn bộ ngữ cảnh
  • Log request là tái hiện được lỗi
  • Đổi model giữa chừng được
  • Full control of context
  • Logged requests replay bugs exactly
  • Switch models mid-conversation

MấtLose

  • Token input tăng gần theo bình phương số lượt
  • Chạm trần context nếu không cắt
  • Lịch sử từ client giả mạo được
  • Input tokens grow roughly with turns squared
  • Context overflow unless trimmed
  • Client-sent history can be forged

Dấu hiệu nhận biết: người dùng nói "như trên", "cái đó", tức câu mới phụ thuộc câu cũ. Signal: users say "like above" or "that one", so the new message depends on earlier ones.

02

System prompt

Đầu vàoInput

Vai trò, phạm vi, quy tắc và định dạng đặt ngoài hội thoại, áp dụng cho mọi lượt. Với Anthropic là tham số system; với OpenAI là message role system/developer. Role, scope, rules and format set outside the conversation, applied to every turn. Anthropic: the system parameter; OpenAI: a system/developer message.

Đánh đổi: đặt quy tắc vào system prompt là đổi một khoản token cố định ở mọi request lấy hành vi nhất quán mà không phải nhắc lại. Trade-off: putting rules in the system prompt trades a fixed token cost on every request for consistent behaviour without repeating yourself.

Dùng choUse for

  • Giới hạn phạm vi bot
  • Cố định giọng và ngôn ngữ
  • Nhúng chính sách, bảng giá
  • Limiting a bot's scope
  • Fixing tone and language
  • Embedding policies, price lists

ĐượcGain

  • Tách quy tắc khỏi input người dùng
  • Hợp với prompt caching
  • Version hoá và A/B test như code
  • Rules separated from user input
  • A natural fit for prompt caching
  • Versioned and A/B tested like code

MấtLose

  • Không phải lớp bảo mật
  • Coi như công khai, người dùng moi ra được
  • Dài thì tốn token mọi request
  • Not a security layer
  • Treat as public; users can extract it
  • Long ones cost tokens on every call

Dấu hiệu nhận biết: bạn đang chép cùng một chỉ dẫn vào mọi tin nhắn. Signal: you're pasting the same instruction into every message.

03

Streaming

Đầu raOutput

Nhận câu trả lời từng mảnh qua Server-Sent Events ngay khi model sinh ra, thay vì chờ trọn vẹn. Receive the answer piece by piece over Server-Sent Events as the model generates it, instead of waiting for all of it.

Đánh đổi: chọn streaming là đổi sự đơn giản của một response trọn vẹn lấy việc người dùng thấy chữ gần như ngay lập tức. Trade-off: streaming trades the simplicity of one complete response for users seeing text almost immediately.

Dùng choUse for

  • Giao diện chat
  • Đầu ra dài dễ vượt timeout
  • Dừng sớm khi đầu ra đi lệch
  • Chat interfaces
  • Long outputs that risk timeouts
  • Cancelling early when output drifts

ĐượcGain

  • Chữ đầu tiên thường dưới 1 giây
  • Huỷ giữa chừng, phần chưa sinh không tính tiền
  • Proxy không cắt vì im lặng
  • First text usually under a second
  • Cancel midway; ungenerated tokens aren't billed
  • Proxies don't drop it as idle

MấtLose

  • Tổng thời gian không giảm
  • Lỗi có thể đến sau 200 OK
  • Proxy buffer làm mất tác dụng
  • Total time doesn't drop
  • Errors can arrive after 200 OK
  • Proxy buffering defeats it

Dấu hiệu nhận biết: có người đang nhìn màn hình chờ chữ hiện ra. Signal: someone is staring at the screen waiting for text.

04

Structured output

Đầu raOutput

JSON khớp schema, được bảo đảm bằng constrained decoding. Claude API: output_config.format với type: "json_schema". JSON that matches your schema, guaranteed by constrained decoding. Claude API: output_config.format with type: "json_schema".

Đánh đổi: chọn structured output là đổi sự tự do diễn đạt của model lấy bảo đảm code phía sau luôn parse được kết quả. Trade-off: structured output trades the model's freedom of expression for a guarantee that downstream code can always parse the result.

Dùng choUse for

  • Trích xuất dữ liệu vào DB
  • Phân loại vào enum cố định
  • Sinh payload cho API khác
  • Extracting data into a DB
  • Classifying into a fixed enum
  • Payloads for another API

ĐượcGain

  • Hết lỗi JSON.parse
  • enum chặn nhãn lạ
  • Schema là hợp đồng review được
  • No more JSON.parse errors
  • enum blocks unknown labels
  • The schema is a reviewable contract

MấtLose

  • Đúng schema không có nghĩa là đúng sự thật
  • Không chừa lối thoát thì model bịa
  • Schema mới chậm hơn ở lần đầu
  • Valid schema doesn't mean true facts
  • No escape hatch, so the model invents
  • New schemas are slower on first use

Dấu hiệu nhận biết: kết quả được ghi vào database chứ không ai đọc. Signal: the result goes into a database, not in front of a person.

05

Tool calling

Hành độngAction

Còn gọi là function calling. Model đề xuất gọi hàm kèm tham số; code của bạn chạy hàm và gửi tool_result lại. Model không bao giờ tự thực thi. Đây là vòng lặp, không phải một lần gọi. Also called function calling. The model proposes a function call with arguments; your code runs it and sends back a tool_result. The model never executes anything. It's a loop, not a single call.

Đánh đổi: chọn tool calling là đổi một request đơn giản lấy vòng lặp nhiều request, để trả lời bằng dữ liệu thật và làm được việc thật. Trade-off: tool calling trades one simple request for a multi-request loop, in exchange for real data and real actions.

Dùng choUse for

  • Tra dữ liệu thời gian thực
  • Tạo ticket, đặt lịch, gửi email
  • Truy vấn DB, CRM nội bộ
  • Live data lookups
  • Create tickets, book slots, send email
  • Query internal DBs and CRMs

ĐượcGain

  • Giảm bịa với dữ liệu hay thay đổi
  • Bạn giữ quyền thực thi
  • Tham số có cấu trúc, kiểm tra được
  • Fewer made-up answers on changing data
  • You keep execution control
  • Structured, checkable arguments

MấtLose

  • Độ trễ và token cộng dồn theo vòng
  • Có thể lặp vô hạn nếu không đặt trần
  • Retry cộng tác dụng phụ là làm hai lần
  • Latency and tokens add up per loop
  • Can loop forever without a cap
  • Retries plus side effects means doing it twice

Dấu hiệu nhận biết: câu trả lời đúng phụ thuộc dữ liệu model không thể biết lúc huấn luyện. Signal: the right answer depends on data the model couldn't have known at training time.

06

Đếm token và chi phíToken counting and cost

Vận hànhOperations

Input và output tính giá riêng, output thường đắt gấp vài lần. Mọi thứ bạn gửi đều là input: system, lịch sử, định nghĩa tool, kết quả tool. Đếm trước bằng endpoint đếm token, tính tiền thật bằng usage. Giá trong sơ đồ chỉ là số liệu minh hoạ; luôn kiểm tra trang pricing. Input and output are priced separately; output usually costs several times more. Everything you send is input: system, history, tool definitions, tool results. Count ahead with the token counting endpoint; bill from usage. Prices in the diagram are illustrative; always check the pricing page.

Đánh đổi: đo token cho từng request là đổi một chút công ghi log và lưu trữ lấy khả năng biết chính xác tiền đang đi đâu. Trade-off: measuring every request trades a little logging and storage effort for knowing exactly where the money goes.

Dùng choUse for

  • Dự toán trước khi ra mắt
  • Chặn request vượt context
  • Giới hạn chi tiêu theo người dùng
  • Budgeting before launch
  • Blocking oversized requests
  • Per-user spend caps

ĐượcGain

  • Không bất ngờ cuối tháng
  • Phát hiện prompt phình to
  • So sánh theo chi phí mỗi tác vụ
  • No month-end surprises
  • Spot prompts bloating over time
  • Compare by cost per task

MấtLose

  • Đếm theo ký tự sai nhiều với tiếng Việt
  • Tokenizer khác nhau theo model (Claude 4.7+ ra nhiều hơn khoảng 30% token)
  • Giá hardcode âm thầm sai
  • Character-based estimates are far off for some languages
  • Tokenizers differ by model (Claude 4.7+ produces roughly 30% more tokens)
  • Hardcoded prices go silently stale

Dấu hiệu nhận biết: ai đó hỏi "tháng này tốn bao nhiêu?" và bạn chưa trả lời được. Signal: someone asks "what will this cost per month?" and you can't answer.

07

Rate limit, retry, timeout

Vận hànhOperations

Chỉ retry lỗi tạm thời (408, 409, 429, 5xx, 529, lỗi mạng) bằng exponential backoff có jitter và tôn trọng retry-after. Lỗi 429 do chạm trần chi tiêu không có retry-after và retry cũng không thành công. Không retry 400/401/403/404/413. Luôn đặt timeout. Retry only temporary failures (408, 409, 429, 5xx, 529, network) with exponential backoff and jitter, honouring retry-after. A spend-cap 429 has no retry-after and won't succeed on retry. Never retry 400/401/403/404/413. Always set a timeout.

Đánh đổi: chọn retry tự động là đổi độ trễ ở nhóm request chậm nhất và một phần chi phí lấy tỷ lệ thành công cao khi API chập chờn. Trade-off: automatic retries trade higher tail latency and some extra cost for a high success rate when the API is flaky.

Dùng choUse for

  • Batch job hàng nghìn tài liệu
  • Giờ cao điểm nhiều người dùng
  • Pipeline chạy đêm không ai giám sát
  • Batch jobs over thousands of docs
  • Peak-hour traffic
  • Unattended overnight pipelines

ĐượcGain

  • Lỗi tạm tự hồi phục
  • Không request nào treo vô hạn
  • Không dội thêm request khi bị giới hạn
  • Temporary failures self-heal
  • No request hangs forever
  • No hammering a throttled API

MấtLose

  • Retry nhân tải và chi phí
  • Tool có tác dụng phụ bị chạy hai lần
  • Timeout ngắn cắt câu trả lời hợp lệ
  • Retries multiply load and cost
  • Side-effecting tools run twice
  • Short timeouts cut valid answers

Dấu hiệu nhận biết: chạy song song nhiều worker và bắt đầu thấy 429. Signal: you run workers in parallel and 429s start appearing.

Bật thêm thì trả gìWhat each one costs you

Trục so sánh là bốn thứ bạn thật sự phải trả: tiền, thời gian chờ, công viết code, và kiểu hỏng. The axes are the four things you actually pay: money, waiting time, code effort, and the way it breaks.

Khái niệmConcept Chi phíCost Độ trễLatency Độ phức tạpComplexity Điểm hỏng điển hìnhTypical failure
01 Messages Tăng theo độ dài hội thoạiGrows with conversation length Tăng nhẹ theo đầu vàoSlightly up with input ThấpLow Không cắt lịch sử, vượt contextHistory never trimmed, context overflow
02 System Cố định mỗi requestFixed per request Không đáng kểNegligible ThấpLow Coi nó là lớp bảo mậtTreating it as security
03 Streaming Không đổi, giảm nếu huỷ sớmSame, lower if cancelled early Cảm nhận giảm mạnh, tổng không đổiPerceived far lower, total same Trung bìnhMedium Proxy buffer, lỗi giữa streamProxy buffering, mid-stream errors
04 Structured Không đổiSame Chậm hơn ở lần đầu dùng schema mớiSlower on a new schema's first use ThấpLow Đúng schema, sai sự thậtValid shape, false facts
05 Tools Tăng theo số vòngGrows per iteration Tăng theo số vòngGrows per iteration Trung bình đến caoMedium to high Lặp vô hạn, tác dụng phụ trùngInfinite loops, duplicated side effects
06 Tokens Không đổi, giúp giảmSame, helps reduce it Thêm một lượt nếu đếm trướcOne extra call if counting first ThấpLow Giá hardcode, đếm theo ký tựHardcoded prices, counting characters
07 Retry Tăng khi retryUp when retrying Tăng tail latencyHigher tail latency Thấp nếu dùng SDKLow with the SDK Retry lỗi 4xx, retry tác dụng phụRetrying 4xx, retrying side effects

Anti-patterns

Những lỗi gặp nhiều nhất ở lần đầu gọi LLM, và cách sửa. The most common first-time mistakes, and the fix.

Sai lầmMistake Vì sao saiWhy it's wrong Sửa thế nàoFix
Bỏ qua stop_reasonIgnoring stop_reason Câu trả lời bị cắt do chạm max_tokens trông như đã xongAn answer cut off at max_tokens looks finished Kiểm tra mọi lần, xử lý riêng max_tokensCheck every time; handle max_tokens explicitly
Nhận lịch sử hội thoại từ clientAccepting history from the client Người dùng sửa được lượt assistant để lái modelUsers can edit assistant turns to steer the model Lưu lịch sử ở server, client chỉ gửi tin mớiKeep history server-side; client sends only the new message
API key ở frontend hoặc trong repoAPI key in the frontend or repo Ai mở DevTools cũng lấy được và tiêu tiền của bạnAnyone with DevTools can take it and spend your money Gọi từ backend, key trong biến môi trườngCall from the backend; key in env vars
"Xin" JSON trong prompt rồi parseAsking for JSON in the prompt, then parsing Thỉnh thoảng hỏng, và luôn hỏng lúc tải caoBreaks occasionally, always at peak load Dùng structured output với JSON SchemaUse structured output with a JSON Schema
Vòng lặp tool không có trầnTool loop without a cap Model gọi đi gọi lại, đốt token tới khi bạn phát hiệnThe model keeps calling, burning tokens until noticed Giới hạn 5–10 vòng, log khi chạm trầnCap at 5–10 iterations, log when hit
Retry mọi lỗiRetrying every error Retry 400/401 chỉ lặp lại lỗiRetrying 400/401 just repeats the error Chỉ retry 408, 409, 429, 5xx, 529, lỗi mạngRetry only 408, 409, 429, 5xx, 529, network
Gửi hàng trăm request song song không giới hạnUnlimited parallel requests 429 hàng loạt, retry dồn dập làm tệ hơnMass 429s, and retry storms make it worse Semaphore hoặc hàng đợi giới hạn đồng thờiA semaphore or queue capping concurrency

3 câu cần nhớ3 things to remember

API không nhớ gì.Mọi thứ model biết nằm trong request bạn gửi, và bạn trả tiền cho từng token trong đó. The API remembers nothing.Everything the model knows is in the request you send, and you pay for every token in it.

Model chỉ đề xuất, code của bạn quyết định.Schema quyết định định dạng, code của bạn thực thi hành động, chính sách retry kiểm soát việc thử lại. The model proposes, your code decides.The schema sets the format, your code runs the actions, your retry policy controls retries.

Đo ngay từ request đầu tiên.Ghi usage, stop_reason và độ trễ cho mọi lời gọi. Không có số liệu thì mọi tối ưu chỉ là đoán. Measure from the very first request.Log usage, stop_reason and latency on every call. Without numbers, every optimisation is a guess.