Kiểm chứng với package anthropic 0.109 (Python). Tool use xem Claude API tool use , cache xem prompt caching , JSON có cấu trúc xem structured output .
Model id#
Model
Dùng khi
claude-opus-5-5
Việc khó: phân tích sự cố nhiều bước, review thay đổi lớn, làm judge cho eval
claude-sonnet-5-5
Mặc định cho agent: cân bằng chất lượng, tốc độ, chi phí
claude-haiku-5-5
Phân loại, trích xuất, tóm tắt log số lượng lớn, cần nhanh và rẻ
Client và tham số messages.create#
Mục đích
Cú pháp
Tạo client (đọc ANTHROPIC_API_KEY)
client = anthropic.Anthropic()
Client async
client = anthropic.AsyncAnthropic()
Retry / timeout (mặc định 2 lần retry, timeout 10 phút)
anthropic.Anthropic(max_retries=5, timeout=60.0)
Ghi đè cho một lần gọi
client.with_options(timeout=20.0).messages.create(...)
Tham số bắt buộc
model, max_tokens, messages
System prompt
system="..." hoặc list block [{"type": "text", "text": "..."}]
Giới hạn độ dài output
max_tokens=1024 (chạm ngưỡng thì stop_reason == "max_tokens")
Độ ngẫu nhiên
temperature=0.0 (0-1)
Dừng tại chuỗi
stop_sequences=["END"]
Tool
tools=[...], tool_choice={"type": "auto"}
Extended thinking
thinking={"type": "adaptive"} (SDK hiện cảnh báo type: "enabled" đã deprecated)
Mức effort
output_config={"effort": "low"} (low / medium / high / xhigh / max)
Gắn metadata user
metadata={"user_id": "noc-42"}
Lấy text từ response
"".join(b.text for b in resp.content if b.type == "text")
Request id để báo lỗi
resp._request_id
Streaming#
Mục đích
Cú pháp
Stream text (helper)
with client.messages.stream(model=..., max_tokens=..., messages=...) as s:
In từng đoạn text
for text in s.text_stream: print(text, end="", flush=True)
Lấy message hoàn chỉnh sau khi stream
msg = s.get_final_message()
Stream event thô
client.messages.create(..., stream=True) rồi lặp các event message_start, content_block_delta, message_delta, message_stop
Request có max_tokens lớn (output dài) nên dùng streaming để tránh timeout HTTP. SDK có thể báo lỗi nếu ước tính request không stream sẽ chạy quá lâu.
Đếm token và Batch API#
Mục đích
Cú pháp
Đếm token trước khi gửi
client.messages.count_tokens(model=..., messages=..., system=..., tools=...).input_tokens
Tạo batch (rẻ hơn ~50%, xử lý bất đồng bộ, tối đa 24 giờ)
client.messages.batches.create(requests=[{"custom_id": "pe1", "params": {...}}])
Xem trạng thái
client.messages.batches.retrieve(batch_id).processing_status (in_progress / canceling / ended)
Đếm kết quả
.request_counts (succeeded, errored, expired, canceled, processing)
Đọc kết quả
for r in client.messages.batches.results(batch_id): r.custom_id, r.result.type
Huỷ batch
client.messages.batches.cancel(batch_id)
params của mỗi request trong batch giống hệt tham số messages.create. Kết quả không theo thứ tự , nên luôn ghép theo custom_id.
Mã lỗi#
HTTP
error.type
Exception SDK
Xử lý
400
invalid_request_error
BadRequestError
Sửa request (thiếu tool_result, sai schema, sai thứ tự message)
401
authentication_error
AuthenticationError
Kiểm tra ANTHROPIC_API_KEY
403
permission_error
PermissionDeniedError
Key không có quyền với model/tính năng
404
not_found_error
NotFoundError
Sai model id hoặc endpoint
413
request_too_large
RequestTooLargeError
Request quá lớn: cắt bớt tài liệu, chia nhỏ
429
rate_limit_error
RateLimitError
Vượt RPM/ITPM/OTPM: đợi theo retry-after, giảm song song
500
api_error
InternalServerError
Lỗi phía server: retry có backoff
529
overloaded_error
OverloadedError
API quá tải tạm thời: retry có backoff, có thể chuyển model
SDK tự retry (mặc định 2 lần, backoff) cho lỗi kết nối, 408, 409, 429 và lỗi 5xx. Mọi lỗi HTTP đều kế thừa anthropic.APIStatusError (có .status_code, .response). Lỗi mạng là anthropic.APIConnectionError.
Header
Ý nghĩa
retry-after
Số giây nên đợi trước khi thử lại (trả kèm 429)
anthropic-ratelimit-requests-limit / -remaining / -reset
Giới hạn request mỗi phút
anthropic-ratelimit-input-tokens-limit / -remaining / -reset
Giới hạn input token mỗi phút
anthropic-ratelimit-output-tokens-limit / -remaining / -reset
Giới hạn output token mỗi phút
request-id
Mã request, gửi kèm khi báo lỗi cho support
raw = client.messages.with_raw_response.create(
model = "claude-haiku-5-5" , max_tokens = 64 ,
messages = [{ "role" : "user" , "content" : "ping" }],
)
print (raw.headers.get( "anthropic-ratelimit-requests-remaining" ))
msg = raw.parse() # Message như bình thường
curl#
curl -s https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY " \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-haiku-5-5", "max_tokens": 256,
"messages": [{"role": "user", "content": "Giải thích BGP hold timer trong 2 câu"}]}' | jq -r '.content[0].text'