SDK gốc
Anthropic SDK
Sử dụng Claude Messages thông qua TokenLab với Anthropic SDK
Tổng quan
Anthropic SDK có thể gọi các mô hình Claude thông qua Messages API của TokenLab. Chỉ cần thay đổi API key và base URL; các phương thức của SDK vẫn giữ nguyên.
Đối với Anthropic SDK, hãy sử dụng https://api.tokenlab.sh làm base URL, không cần tự thêm /v1 vào sau.
Cài đặt
pip install anthropicCấu hình Client
from anthropic import Anthropic
client = Anthropic(
api_key="sk-your-tokenlab-key",
base_url="https://api.tokenlab.sh",
)Cách sử dụng cơ bản
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Reply with: Connected to TokenLab."}
]
)
print(message.content[0].text)Streaming
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short poem about coding."}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)Vision (Thị giác máy tính)
import base64
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/image.jpg"
}
}
]
}]
)
with open("image.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode()
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image"},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
}
]
}]
)Sử dụng Tool
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "Get the weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}],
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
for block in message.content:
if block.type == "tool_use":
print(block.name)
print(block.input)Extended Thinking (Tư duy mở rộng)
message = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this complex problem step by step."}]
)
for block in message.content:
if block.type == "thinking":
print(block.thinking)
elif block.type == "text":
print(block.text)Chọn mô hình
Sao chép ID mô hình Claude hiện tại từ trang Models. Hãy so sánh các mô hình trên chính các prompt của bạn trước khi thiết lập mặc định.