·9 min 閱讀
Claude API 串接教學:在你的應用中整合 AI 能力
ClaudeAPIPythonTypeScript教學
為什麼選擇 Claude API
如果你想在自己的應用中加入 AI 能力,Claude API 是一個值得考慮的選項。相較於其他 AI API,Claude 的優勢包括:
- 200K token 的超長上下文視窗:可以一次處理整份文件或大量程式碼
- 優秀的指令遵循能力:輸出格式更可控,減少後處理的麻煩
- 多語言能力:中文理解和生成品質穩定
- Tool Use:讓 Claude 呼叫你定義的函式,實現更複雜的工作流程
快速開始
取得 API Key
- 前往 Anthropic Console(console.anthropic.com)
- 建立帳號並設定付款方式
- 在 API Keys 頁面建立新的金鑰
安裝 SDK
Claude API 提供 Python 和 TypeScript 兩種官方 SDK。
Python:
pip install anthropic
TypeScript / Node.js:
npm install @anthropic-ai/sdk
第一個 API 呼叫
Python 範例:
import anthropic
client = anthropic.Anthropic() # 自動讀取 ANTHROPIC_API_KEY 環境變數
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "用三句話解釋什麼是 ETL Pipeline"
}
]
)
print(message.content[0].text)
TypeScript 範例:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // 自動讀取 ANTHROPIC_API_KEY
const message = await client.messages.create({
model: "claude-sonnet-4-6-20250320",
max_tokens: 1024,
messages: [
{
role: "user",
content: "用三句話解釋什麼是 ETL Pipeline",
},
],
});
console.log(message.content[0].text);
核心概念
Messages API
Claude API 使用 Messages 格式,每次呼叫需要提供一組對話訊息:
messages = [
{"role": "user", "content": "你好"},
{"role": "assistant", "content": "你好!有什麼我可以幫你的嗎?"},
{"role": "user", "content": "幫我解釋 Python 的 generator"}
]
System Prompt
System prompt 用來設定 Claude 的行為和角色,與一般對話訊息分開設定:
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
system="你是一位資深的資料工程師,專精 Python 和 SQL。"
"回答問題時請提供程式碼範例,並用繁體中文回覆。",
messages=[
{"role": "user", "content": "如何用 Python 讀取大型 CSV 檔案?"}
]
)
串流回應
對使用者來說,等待 AI 的完整回應可能需要數秒。使用串流可以讓回應逐字出現,大幅改善體驗:
with client.messages.stream(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
messages=[{"role": "user", "content": "寫一首關於程式設計的詩"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
TypeScript 版本:
const stream = await client.messages.stream({
model: "claude-sonnet-4-6-20250320",
max_tokens: 1024,
messages: [{ role: "user", content: "寫一首關於程式設計的詩" }],
});
for await (const event of stream) {
if (
event.type === "content_block_delta" &&
event.delta.type === "text_delta"
) {
process.stdout.write(event.delta.text);
}
}
Tool Use(函式呼叫)
Tool Use 是 Claude API 最強大的功能之一。你可以定義一組「工具」,讓 Claude 在需要時呼叫它們。
基本範例:查詢天氣
import anthropic
import json
client = anthropic.Anthropic()
# 定義工具
tools = [
{
"name": "get_weather",
"description": "取得指定城市的目前天氣狀況",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名稱,例如「台北」"
}
},
"required": ["city"]
}
}
]
# 發送請求
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "台北現在天氣如何?"}
]
)
# 檢查 Claude 是否想呼叫工具
for block in message.content:
if block.type == "tool_use":
print(f"Claude 想呼叫: {block.name}")
print(f"參數: {json.dumps(block.input, ensure_ascii=False)}")
完整的 Tool Use 流程
Tool Use 是一個來回的過程:
- 你發送訊息和可用工具清單給 Claude
- Claude 決定是否需要使用工具,如果需要,回傳工具呼叫請求
- 你執行工具並把結果回傳給 Claude
- Claude 根據工具結果生成最終回應
# 步驟 1-2:Claude 決定使用工具
response = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "台北現在天氣如何?"}]
)
# 步驟 3:執行工具並回傳結果
tool_use_block = next(b for b in response.content if b.type == "tool_use")
# 你的工具實作(這裡用假資料示範)
weather_result = {"temperature": 26, "condition": "多雲", "humidity": 75}
# 步驟 4:把工具結果送回 Claude
final_response = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "台北現在天氣如何?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": json.dumps(weather_result, ensure_ascii=False)
}
]
}
]
)
print(final_response.content[0].text)
# 輸出類似:台北目前天氣多雲,氣溫 26°C,濕度 75%。
實際應用範例
範例一:自動化資料品質檢查
利用 Claude 分析資料集的品質問題:
import pandas as pd
def analyze_data_quality(df: pd.DataFrame) -> str:
# 取樣前 20 筆資料作為範例
sample = df.head(20).to_csv(index=False)
stats = df.describe(include="all").to_csv()
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=2048,
system="你是一位資料品質分析師。分析提供的資料集樣本,"
"找出潛在的品質問題並提供清洗建議。",
messages=[{
"role": "user",
"content": f"資料樣本:\n{sample}\n\n統計摘要:\n{stats}"
}]
)
return message.content[0].text
範例二:智慧客服機器人
結合 Tool Use 打造能查詢訂單的客服:
tools = [
{
"name": "lookup_order",
"description": "查詢訂單狀態",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "訂單編號"}
},
"required": ["order_id"]
}
},
{
"name": "get_faq",
"description": "搜尋常見問題",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "搜尋關鍵字"}
},
"required": ["query"]
}
}
]
# Claude 會自動判斷使用者的問題需要呼叫哪個工具
# 「我的訂單 A12345 到哪了?」→ 呼叫 lookup_order
# 「你們的退貨政策是什麼?」→ 呼叫 get_faq
費用控制
Token 計價
Claude API 按輸入和輸出的 token 數量計費。大致換算:
- 1 個中文字約等於 1-2 個 token
- 1 個英文單字約等於 1 個 token
省錢技巧
- 選擇適合的模型:不是每個任務都需要 Opus,大多數場景 Sonnet 就夠了
- 控制 max_tokens:根據預期的回應長度設定,避免浪費
- 快取常見回應:對重複性高的查詢做快取
- 精簡 system prompt:冗長的 system prompt 每次呼叫都會計費
- 使用 prompt caching:Anthropic 提供 prompt caching 功能,對重複的長前綴可以大幅降低成本
# 使用 prompt caching 的範例
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
system=[
{
"type": "text",
"text": "你是一位專業的客服人員...(很長的系統指令)",
"cache_control": {"type": "ephemeral"}
}
],
messages=[{"role": "user", "content": "你好"}]
)
錯誤處理
生產環境中,務必處理 API 可能回傳的錯誤:
import anthropic
client = anthropic.Anthropic()
try:
message = client.messages.create(
model="claude-sonnet-4-6-20250320",
max_tokens=1024,
messages=[{"role": "user", "content": "hello"}]
)
except anthropic.RateLimitError:
# 超過速率限制,等待後重試
print("Rate limited, retrying...")
except anthropic.APIStatusError as e:
print(f"API error: {e.status_code} - {e.message}")
Anthropic SDK 內建了自動重試機制,對 429(rate limit)和 5xx 錯誤會自動重試,通常不需要自己處理。
結語
Claude API 的串接並不複雜,但要在生產環境中用好它,需要注意費用控制、錯誤處理和 prompt 設計。建議先從一個小功能開始嘗試,確認效果後再逐步擴展使用範圍。
Tool Use 功能特別值得深入研究——它讓 Claude 不只是一個文字生成器,而是能真正與你的系統互動的智慧代理。