DEV Community

Cover image for Hướng Dẫn Sử Dụng API Claude Opus 4.8
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

Hướng Dẫn Sử Dụng API Claude Opus 4.8

API Claude Opus 4.8 ra mắt cùng mô hình vào ngày 28/5/2026. ID mô hình là claude-opus-4-8 và vẫn dùng API Messages quen thuộc. Bài viết này hướng dẫn cách lấy API key, gọi request đầu tiên, cấu hình effort, bật adaptive thinking, streaming, tool use, xử lý lỗi và kiểm thử request bằng Apidog.

Dùng thử Apidog ngay hôm nay

Nếu bạn đã từng gọi Claude API, phần lớn thay đổi chỉ là đổi tên model. Điểm mới đáng chú ý là effort, cơ chế thay thế cách đặt “thinking budget” thủ công trước đây. Nếu bạn mới bắt đầu với Claude API, bạn có thể chạy request Opus 4.8 đầu tiên trong khoảng vài phút. Để hiểu thêm về mô hình, xem Claude Opus 4.8 là gì.

Bạn có gì với API Opus 4.8

Các thông số quan trọng khi tích hợp:

  • Model ID: claude-opus-4-8
  • Ngữ cảnh: đầu vào 1M token, đầu ra 128K token
  • Endpoint: vẫn dùng Messages API
  • effort: 5 cấp độ, từ low đến max
  • Adaptive thinking: mô hình tự quyết định mức suy luận
  • Giá tiêu chuẩn: 5 USD / 1 triệu input token, 25 USD / 1 triệu output token

Xem thêm hướng dẫn định giá Opus 4.8. Nếu bạn chưa có gói trả phí, xem hướng dẫn truy cập miễn phí.

Bước 1: Lấy Claude API key

  1. Truy cập console.anthropic.com
  2. Đăng nhập hoặc tạo tài khoản
  3. Mở SettingsAPI Keys
  4. Chọn Create Key, đặt tên và sao chép key

Lưu key vào biến môi trường:

export ANTHROPIC_API_KEY="sk-ant-..."
Enter fullscreen mode Exit fullscreen mode

Không hard-code API key trong source code, repo hoặc file log.

Bước 2: Cài SDK

Anthropic có SDK chính thức cho Python, TypeScript, Go, Java, C#, Ruby và PHP.

# Python
pip install anthropic

# Node.js / TypeScript
npm install @anthropic-ai/sdk
Enter fullscreen mode Exit fullscreen mode

Bạn cũng có thể gọi trực tiếp REST API bằng curl. Nếu cần kiểm tra kiểu dữ liệu, xem SDK Python của Anthropic.

Bước 3: Gọi request Opus 4.8 đầu tiên

Python

import anthropic

client = anthropic.Anthropic()  # đọc ANTHROPIC_API_KEY

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content": "Giải thích luồng OAuth 2.0 PKCE trong 3 đoạn văn ngắn."
        }
    ],
)

print(message.content[0].text)
Enter fullscreen mode Exit fullscreen mode

Node.js

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 4096,
  messages: [
    {
      role: "user",
      content: "Giải thích luồng OAuth 2.0 PKCE trong 3 đoạn văn ngắn.",
    },
  ],
});

console.log(message.content[0].text);
Enter fullscreen mode Exit fullscreen mode

curl

curl https://api.anthropic.com/v1/messages \
  --header "x-api-key: $ANTHROPIC_API_KEY" \
  --header "anthropic-version: 2023-06-01" \
  --header "content-type: application/json" \
  --data '{
    "model": "claude-opus-4-8",
    "max_tokens": 4096,
    "messages": [
      {
        "role": "user",
        "content": "Giải thích luồng OAuth 2.0 PKCE trong 3 đoạn văn ngắn."
      }
    ]
  }'
Enter fullscreen mode Exit fullscreen mode

Đây là request tối thiểu. Từ đây bạn có thể thêm effort, streaming, tools hoặc adaptive thinking.

Cấu hình effort

effort kiểm soát lượng token Opus 4.8 dùng cho toàn bộ phản hồi: văn bản, tool calls và suy luận. Tham số này nằm trong output_config.

Các giá trị hợp lệ:

  • low
  • medium
  • high
  • xhigh
  • max

Mặc định là high.

Python

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=8192,
    output_config={"effort": "xhigh"},
    messages=[
        {
            "role": "user",
            "content": "Tái cấu trúc module 600 dòng này để dễ kiểm thử."
        }
    ],
)
Enter fullscreen mode Exit fullscreen mode

Node.js

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 8192,
  output_config: { effort: "xhigh" },
  messages: [
    {
      role: "user",
      content: "Tái cấu trúc module 600 dòng này để dễ kiểm thử.",
    },
  ],
});
Enter fullscreen mode Exit fullscreen mode

Theo tài liệu về effort của Anthropic, bạn có thể chọn như sau:

Cấp độ Dùng cho
low Phân loại, tra cứu nhanh, tác vụ khối lượng lớn, subagents
medium Công việc agentic cân bằng giữa chất lượng và chi phí
high Mặc định; suy luận phức tạp khi ưu tiên chất lượng
xhigh Lập trình, tác vụ agentic dài; điểm khởi đầu được đề xuất
max Bài toán rất khó, khi bạn đã đo được giới hạn của xhigh

Quy tắc thực tế:

  • Bắt đầu với xhigh cho coding agents hoặc workflows nhiều bước.
  • Khi dùng xhigh hoặc max, đặt max_tokens đủ lớn. 64K là điểm khởi đầu hợp lý cho tác vụ agentic dài.
  • Sau khi đo usage thực tế, giảm max_tokens để kiểm soát chi phí.

Bật adaptive thinking

Opus 4.8 hỗ trợ adaptive thinking. Khi đặt thinking: { "type": "adaptive" }, mô hình tự quyết định khi nào cần suy luận sâu hơn.

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=16000,
    thinking={"type": "adaptive"},
    output_config={"effort": "xhigh"},
    messages=[
        {
            "role": "user",
            "content": "Tìm điều kiện chạy đua trong bộ lập lịch này."
        }
    ],
)

for block in message.content:
    if block.type == "thinking":
        print("[thinking]", block.thinking[:200])
    elif block.type == "text":
        print(block.text)
Enter fullscreen mode Exit fullscreen mode

Lưu ý khi migrate: Opus 4.8 không hỗ trợ budget_tokens cho extended thinking thủ công. Nếu request cũ còn trường này, API sẽ trả lỗi 400. Hãy xóa budget_tokens và dùng:

{
  "thinking": {
    "type": "adaptive"
  },
  "output_config": {
    "effort": "xhigh"
  }
}
Enter fullscreen mode Exit fullscreen mode

Streaming responses

Streaming giúp UI phản hồi nhanh hơn vì bạn có thể render từng phần output khi model đang sinh nội dung.

Python

with client.messages.stream(
    model="claude-opus-4-8",
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content": "Viết hướng dẫn 5 bước để viết một máy khách REST trong Go."
        }
    ],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
Enter fullscreen mode Exit fullscreen mode

Node.js

const stream = client.messages.stream({
  model: "claude-opus-4-8",
  max_tokens: 4096,
  messages: [
    {
      role: "user",
      content: "Viết hướng dẫn 5 bước để viết một máy khách REST trong Go.",
    },
  ],
});

for await (const event of stream) {
  if (
    event.type === "content_block_delta" &&
    event.delta.type === "text_delta"
  ) {
    process.stdout.write(event.delta.text);
  }
}
Enter fullscreen mode Exit fullscreen mode

Với REST API, thêm "stream": true vào request body và đọc Server-Sent Events.

{
  "model": "claude-opus-4-8",
  "max_tokens": 4096,
  "stream": true,
  "messages": [
    {
      "role": "user",
      "content": "Viết hướng dẫn 5 bước để viết một máy khách REST trong Go."
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Sử dụng tools và function calling

Bạn định nghĩa tool bằng input_schema. Khi Claude muốn gọi tool, response sẽ chứa block tool_use.

tools = [
    {
        "name": "get_weather",
        "description": "Lấy thời tiết hiện tại cho một thành phố.",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "Tên thành phố"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                },
            },
            "required": ["city"],
        },
    }
]

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    tools=tools,
    messages=[
        {
            "role": "user",
            "content": "Thời tiết ở Singapore hiện tại thế nào?"
        }
    ],
)

for block in message.content:
    if block.type == "tool_use":
        print(f"Call: {block.name}")
        print(f"Args: {block.input}")
Enter fullscreen mode Exit fullscreen mode

Luồng xử lý thường là:

  1. Gửi request kèm danh sách tools
  2. Nhận block tool_use
  3. Chạy tool ở backend của bạn
  4. Gửi lại kết quả dưới dạng tool_result
  5. Gọi tiếp Messages API để Claude tạo câu trả lời cuối

Nếu bạn xây hệ thống multi-agent, xem thêm managed agents vs Agent SDK.

System message giữa hội thoại

Opus 4.8 đi kèm thay đổi trong Messages API: bạn có thể đặt một entry hệ thống ở giữa mảng messages, không chỉ ở đầu. Điều này hữu ích khi bạn cần thêm instruction hoặc quyền mới trong lúc workflow đang chạy.

Mẫu này là nền tảng cho Dynamic Workflows của Claude Code. Xem phân tích Dynamic Workflows nếu bạn đang điều phối subagents qua API.

Kiểm thử tích hợp Opus 4.8 bằng Apidog

Một request SDK chạy được chưa đủ cho production. Bạn nên kiểm thử thêm:

  • Header xác thực
  • Request body với output_config
  • Streaming event blocks
  • Tool call payload
  • Adaptive thinking blocks
  • Response shape khi đổi effort
  • Error handling và retry

Apidog cho phép bạn lưu và kiểm thử toàn bộ request Messages API trong một workspace.

Cách thiết lập nhanh:

  1. Tạo request mới.
  2. Dùng endpoint:
https://api.anthropic.com/v1/messages
Enter fullscreen mode Exit fullscreen mode
  1. Thêm headers:
x-api-key: {{ANTHROPIC_API_KEY}}
anthropic-version: 2023-06-01
content-type: application/json
Enter fullscreen mode Exit fullscreen mode
  1. Dán body:
{
  "model": "claude-opus-4-8",
  "max_tokens": 4096,
  "output_config": {
    "effort": "xhigh"
  },
  "messages": [
    {
      "role": "user",
      "content": "Giải thích OAuth 2.0 PKCE trong 3 đoạn văn ngắn."
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
  1. Nhấn Send và kiểm tra response.

Bạn có thể dùng Apidog để:

  • Lưu endpoint Messages API thành request có thể chạy lại
  • Đổi claude-opus-4-7 sang claude-opus-4-8 và so sánh output
  • Kiểm tra streaming response theo từng block
  • Thêm assertions để phát hiện response shape thay đổi
  • Mock response Messages API để test code hạ nguồn mà không tốn token
  • Xây kịch bản nhiều bước cho agent loop và tool call validation

Để bắt đầu, tải xuống Apidog, tạo request trỏ đến Messages API và nhập đoạn curl ở trên. Quy trình tương tự cũng dùng được cho API Gemini 3.5API Qwen 3.7.

Xử lý lỗi và rate limit

Các lỗi thường gặp:

HTTP status Error type Nguyên nhân phổ biến
400 invalid_request_error Body sai format, còn budget_tokens, hoặc effort không hợp lệ
401 authentication_error API key sai hoặc thiếu
403 permission_error Key không có quyền truy cập model
429 rate_limit_error Vượt rate limit
500 api_error Lỗi phía server
529 overloaded_error API tạm thời quá tải

Bọc request bằng retry với exponential backoff:

import time
import anthropic

client = anthropic.Anthropic()

def call_with_retry(prompt, max_retries=4):
    for attempt in range(max_retries):
        try:
            return client.messages.create(
                model="claude-opus-4-8",
                max_tokens=4096,
                messages=[
                    {
                        "role": "user",
                        "content": prompt
                    }
                ],
            )
        except anthropic.RateLimitError:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)
Enter fullscreen mode Exit fullscreen mode

Bạn có thể mở rộng để retry thêm APIError hoặc OverloadedError, tùy cách SDK expose exception trong phiên bản bạn dùng.

Rate limit phụ thuộc cấp độ sử dụng. Với workload batch không yêu cầu độ trễ thời gian thực, Batch API có thể hỗ trợ output lên tới 300K token với beta header.

Di chuyển từ Opus 4.7 sang 4.8

Trong nhiều dự án, thay đổi chính là model string:

# Trước đây
model="claude-opus-4-7"

# Sau này
model="claude-opus-4-8"
Enter fullscreen mode Exit fullscreen mode

Checklist sau khi đổi model:

  1. Chạy lại evals với effort bạn dùng

    • Mặc định là high
    • Với coding agent, thử xhigh
  2. Kiểm tra thinking config

    • Xóa budget_tokens
    • Dùng thinking={"type": "adaptive"} nếu cần
  3. Kiểm tra tool schemas

    • Schema giữ nguyên
    • Vẫn nên chạy lại test cho tool usage
  4. Kiểm tra chi phí

    • Giá mỗi token giống Opus 4.7
    • Vẫn nên đo usage thực tế sau migration

FAQ

ID model của Claude Opus 4.8 là gì?

Trên Claude API và Vertex AI:

claude-opus-4-8
Enter fullscreen mode Exit fullscreen mode

Trên AWS Bedrock:

anthropic.claude-opus-4-8
Enter fullscreen mode Exit fullscreen mode

Có gói miễn phí cho API Opus 4.8 không?

Không có gói API miễn phí cố định, nhưng tài khoản mới có thể nhận tín dụng dùng thử. Xem hướng dẫn truy cập miễn phí.

Làm sao đặt cấp độ effort?

Thêm output_config vào request:

{
  "output_config": {
    "effort": "xhigh"
  }
}
Enter fullscreen mode Exit fullscreen mode

Các giá trị hợp lệ là low, medium, high, xhigh, max.

Vì sao request trả lỗi 400 liên quan đến budget_tokens?

Opus 4.8 không hỗ trợ extended thinking thủ công bằng budget_tokens. Hãy xóa trường đó và dùng:

{
  "thinking": {
    "type": "adaptive"
  },
  "output_config": {
    "effort": "xhigh"
  }
}
Enter fullscreen mode Exit fullscreen mode

Opus 4.8 có dùng được với SDK tương thích OpenAI không?

Anthropic cung cấp lớp tương thích cho OpenAI SDK. Bạn cần trỏ base URL sang endpoint của Anthropic, dùng Anthropic API key và giữ model là claude-opus-4-8.

Nên đặt max_tokens bao nhiêu cho agentic work?

Khi dùng xhigh hoặc max, bắt đầu với 64K để model có đủ không gian suy luận và gọi tools nhiều bước. Sau đó giảm xuống dựa trên usage thực tế.

Kiểm tra streaming response trong Apidog thế nào?

Mở request, thêm "stream": true vào body và gửi request. Apidog sẽ hiển thị các event blocks khi chúng đến, giúp bạn phát hiện response bị thiếu hoặc sai shape.

Top comments (0)