# Định dạng Anthropic

> Sử dụng Anthropic Messages API do LLMoxy cung cấp để gọi các mô hình Claude với hỗ trợ xác thực x-api-key.

LLMoxy cung cấp giao diện Anthropic Messages API hoàn toàn tương thích, được tối ưu hóa cho các mô hình dòng Claude. Người dùng SDK chính thức của Anthropic chỉ cần thay đổi `base_url` để chuyển đổi.

## URL cơ sở

```txt
https://llmoxy.com/v1
```

## Cách xác thực

Hỗ trợ hai cách xác thực：

### Cách 1: x-api-key (khuyến nghị)

```http
x-api-key: YOUR_API_KEY
```

### Cách 2: Authorization

```http
Authorization: Bearer YOUR_API_KEY
```

## Messages API

Giao diện hội thoại cốt lõi của Claude.

### URL yêu cầu

```txt
POST /v1/messages
```

### Ví dụ yêu cầu

```bash
curl https://llmoxy.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Viết thuật toán tìm kiếm nhị phân bằng Python"
}
]
}'
```

### Tham số yêu cầu

| Tham số | Kiểu | Bắt buộc | Mô tả |
| --- | --- | --- | --- |
| model | string | Có | Tên mô hình |
| messages | array | Có | Danh sách tin nhắn hội thoại |
| max_tokens | integer | Có | Số token tạo tối đa |
| system | string | Không | Lời nhắc hệ thống |
| temperature | number | Không | Tham số nhiệt độ, 0–1 |
| top_p | number | Không | Tham số nucleus sampling |
| stream | boolean | Không | Có bật đầu ra luồng hay không |
| stop_sequences | array | Không | Chuỗi dừng |

### Định dạng tin nhắn

Khác với OpenAI, định dạng Anthropic sử dụng tham số riêng cho lời nhắc hệ thống：

```json
{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"system": "Bạn là chuyên gia lập trình Python",
"messages": [
{
"role": "user",
"content": "Viết một quicksort"
},
{
"role": "assistant",
"content": "Được, tôi sẽ viết quicksort bằng Python..."
},
{
"role": "user",
"content": "Thêm chú thích chi tiết"
}
]
}
```

> **Lưu ý**
> - messages chỉ có thể chứa vai trò `user` và `assistant`
> - Phải bắt đầu bằng tin nhắn `user`
> - Tin nhắn `user` và `assistant` phải xen kẽ

### Định dạng phản hồi

```json
{
"id": "msg_123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Đây là nội dung phản hồi của Claude"
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 25,
"output_tokens": 150
}
}
```

## Đầu ra luồng

Đặt `stream: true` để bật đầu ra luồng：

```bash
curl https://llmoxy.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Xin chào"}],
"stream": true
}'
```

### Định dạng phản hồi luồng

```txt
event: message_start
data: {"type":"message_start","message":{"id":"msg_123",...}}

event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"X"}}

event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"i"}}

event: message_stop
data: {"type":"message_stop"}
```

## Các mô hình được hỗ trợ

| Mô hình | Mô tả | Nhóm khả dụng |
| --- | --- | --- |
| claude-fable-5-2 | Hiệu năng mạnh nhất | Claude |
| claude-opus-5-5 | Lựa chọn cân bằng | Claude |

> **MẸO**
> Các mô hình khả dụng cụ thể vui lòng tham khảo [Quảng trường mô hình chính thức](https://llmoxy.com/).

## Hỗ trợ đa phương thức

Claude hỗ trợ đầu vào hình ảnh：

```json
{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
},
{
"type": "text",
"text": "Trong hình này có gì?"
}
]
}
]
}
```

Định dạng hình ảnh được hỗ trợ：JPEG、PNG、GIF、WebP. Tối đa 5MB mỗi hình.

## Ví dụ mã

### Python (SDK chính thức)

```python
from anthropic import Anthropic

client = Anthropic(
api_key="YOUR_API_KEY",
base_url="https://llmoxy.com/v1"
)

message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Viết một decorator Python"}
]
)

print(message.content[0].text)
```

### Python (Luồng)

```python
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Viết một bài báo"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
```

### Node.js (SDK chính thức)

```js
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://llmoxy.com/v1'
});

const message = await client.messages.create({
model: 'claude-opus-5-5',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Viết một quicksort' }
]
});

console.log(message.content[0].text);
```

### cURL

```bash
curl https://llmoxy.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, Claude!"}
]
}'
```

## Xử lý lỗi

### Định dạng phản hồi lỗi

```json
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "Mô tả lỗi"
}
}
```

### Các loại lỗi thường gặp

| Loại lỗi | Mô tả |
| --- | --- |
| invalid_request_error | Lỗi tham số yêu cầu |
| authentication_error | Xác thực thất bại |
| permission_error | Quyền không đủ |
| not_found_error | Tài nguyên không tồn tại |
| rate_limit_error | Tần suất yêu cầu vượt quá giới hạn |
| api_error | Lỗi nội bộ |
| overloaded_error | Dịch vụ quá tải |

### Ví dụ xử lý lỗi

```python
from anthropic import Anthropic, APIError

client = Anthropic(
api_key="YOUR_API_KEY",
base_url="https://llmoxy.com/v1"
)

try:
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
except APIError as e:
print(f"Loại lỗi: {e.type}")
print(f"Thông báo lỗi: {e.message}")
```

## Cách sử dụng nâng cao

### 1. Lời nhắc hệ thống

```python
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system="Bạn là chuyên gia Python, giỏi phân tích dữ liệu và học máy.",
messages=[
{"role": "user", "content": "Cách xử lý giá trị thiếu bằng pandas?"}
]
)
```

### 2. Hội thoại đa lượt

```python
conversation = [
{"role": "user", "content": "Viết một lớp người dùng"},
{"role": "assistant", "content": "Được, tôi sẽ viết lớp User..."},
{"role": "user", "content": "Thêm chức năng mã hóa mật khẩu"}
]

message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=conversation
)
```

### 3. Phân tích hình ảnh

```python
import base64

with open("image.jpg", "rb") as f:
image_data = base64.b64encode(f.read()).decode()

message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image_data
}
},
{
"type": "text",
"text": "Phân tích sơ đồ kiến trúc này"
}
]
}
]
)
```

## Thực hành tốt nhất

### 1. Đặt max_tokens hợp lý

Các mô hình có đầu ra tối đa khác nhau：Opus 32K、Sonnet 64K、Haiku 8K. Đặt theo nhu cầu thực tế để tránh lãng phí.

### 2. Sử dụng tham số system để đặt lời nhắc

Đặt định nghĩa vai trò trong tham số `system`, không phải trong messages：

```python
# ✅ Khuyến nghị
message = client.messages.create(
system="Bạn là chuyên gia Python",
messages=[{"role": "user", "content": "Viết mã"}],
...
)

# ❌ Không khuyến nghị
message = client.messages.create(
messages=[{"role": "user", "content": "Bạn là chuyên gia Python. Viết mã"}],
...
)
```

### 3. Xử lý hội thoại dài

Claude có cửa sổ ngữ cảnh 200K, nhưng nên định kỳ tóm tắt hội thoại và xóa các tin nhắn lịch sử không quan trọng để tiết kiệm token.

### 4. Triển khai cơ chế thử lại

```python
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def call_claude():
return client.messages.create(...)
```

## Bước tiếp theo

- [Nhóm và định giá](https://vi.llmoxy.com/docs/get-started/recharge-and-pricing) — tìm hiểu chi tiết phí
- [Nhận hỗ trợ](mailto:contact@llmoxy.com) — liên hệ nếu gặp vấn đề

Đây là bản markdown của https://vi.llmoxy.com/docs/api-reference/anthropic-format.
