Claude API Python 教學指南 2026 | APIMaster.ai
如何使用 Python 操作 Claude API。透過 APIMaster.ai 提供使用 Anthropic SDK 及相容 OpenAI 的用戶端進行聊天、串流、視覺與函式呼叫的完整範例。
Claude API Python 教學指南
本指南涵蓋如何在 Python 中使用 Claude API,包含原生 Anthropic SDK 以及相容 OpenAI 的用戶端。所有範例皆可搭配 APIMaster.ai 使用 —— 只需換上自己的基礎 URL 與 API 金鑰即可。
安裝
pip install anthropic # 原生 Anthropic SDK
pip install openai # 相容 OpenAI(可選)
基本設定
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai", # Anthropic SDK 不需加 /v1
)
或者使用 OpenAI SDK(如果已在使用 OpenAI,則更簡單):
from openai import OpenAI
client = OpenAI(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai/v1",
)
你的第一次 Claude API 呼叫
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain the difference between lists and tuples in Python."}
],
)
print(message.content[0].text)
系統提示詞
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
system="You are a senior Python engineer. Be concise and use code examples.",
messages=[
{"role": "user", "content": "What's the fastest way to flatten a nested list?"}
],
)
print(response.content[0].text)
多輪對話
conversation = []
def chat(user_message):
conversation.append({"role": "user", "content": user_message})
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=conversation,
)
assistant_message = response.content[0].text
conversation.append({"role": "assistant", "content": assistant_message})
return assistant_message
print(chat("What is a decorator in Python?"))
print(chat("Can you show me a practical example?"))
串流回應
串流模式會逐 token 回傳結果 —— 適合長輸出以獲得更好的使用者體驗:
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a Python web scraper using requests and BeautifulSoup."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() # 結尾換行
視覺功能:分析圖片
Claude Sonnet 和 Opus 支援圖片輸入(Base64 或 URL):
import base64
with open("chart.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data,
},
},
{"type": "text", "text": "Summarize what this chart shows."},
],
}
],
)
print(response.content[0].text)
工具使用(函式呼叫)
tools = [
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
},
"required": ["city"],
},
}
]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
# Check if Claude wants to call a tool
if response.stop_reason == "tool_use":
tool_call = next(b for b in response.content if b.type == "tool_use")
print(f"Tool: {tool_call.name}, Input: {tool_call.input}")
非同步使用
import asyncio
import anthropic
async def main():
client = anthropic.AsyncAnthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "Hello!"}],
)
print(response.content[0].text)
asyncio.run(main())
錯誤處理
import anthropic
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.AuthenticationError:
print("Invalid API key")
except anthropic.RateLimitError:
print("Rate limit—add retry logic")
except anthropic.APIStatusError as e:
print(f"API error {e.status_code}: {e.message}")
為 Python 專案選擇合適的 Claude 模型
| 任務 | 模型 | 原因 |
|---|---|---|
| 聊天機器人、問答 | claude-haiku-4-5 | 快速且便宜 |
| 程式碼生成 | claude-sonnet-4-6 | 最佳平衡 |
| 複雜推理 | claude-opus-4-8 | 最高準確度 |
| 文件分析 | claude-sonnet-4-6 | 100 萬上下文 |
取得 Claude API 存取權
常見問題
如何安裝 Claude API Python 函式庫?
執行 pip install anthropic 安裝官方 SDK,或執行 pip install openai 透過 APIMaster 的 OpenAI 相容端點使用 Claude 模型。
該使用哪個 Python SDK 來操作 Claude API?
anthropic SDK 為官方選擇,支援所有 Claude 專屬功能(工具使用、視覺、串流)。openai SDK 則可透過 APIMaster 的相容層使用 —— 若你已在使用 OpenAI 且想切換模型,這會很方便。
如何在 Python 中串流 Claude API 回應?
使用 openai 函式庫時傳入 stream=True,或使用 anthropic SDK 的 client.messages.stream()。請參考上方串流範例。
Claude API 是否支援函式呼叫(工具使用)?
是的 —— Claude 在原生的 Anthropic SDK 中支援工具使用,也可透過 APIMaster 的 OpenAI 相容端點使用標準的 tools 參數。
Claude 在 Python 中的最大上下文視窗是多少?
Claude Sonnet 4.6 和 Opus 4.8 各支援 100 萬個 token。你可以直接在 messages 陣列中傳入非常長的文件。
在 APIMaster.ai 註冊 即可透過統一的端點取得 Claude API 存取權,並享有即時定價與指紋驗證資料。
另請參閱:Claude API 定價 · 如何取得 Claude API 金鑰