claude-api
Anthropic Claude APIのPythonおよびTypeScriptの使用パターンについて説明します。Messages API、ストリーミング、ツール使用、ビジョン機能、拡張思考、バッチ処理、プロンプトキャッシング、Claude Agent SDKなどの機能を網羅しています。Claude APIまたはAnthropic SDKを使用してアプリケーションを構築する場面で活用できます。
description の原文を見る
Anthropic Claude API 的 Python 和 TypeScript 使用模式。涵盖 Messages API、流式处理、工具使用、视觉功能、扩展思维、批量处理、提示缓存和 Claude Agent SDK。适用于使用 Claude API 或 Anthropic SDK 构建应用程序的场景。
SKILL.md 本文
Claude API
Anthropic Claude API と SDK を使用してアプリケーションを構築します。
アクティベーション条件
- Claude API を呼び出すアプリケーションを構築している
- コードが
anthropic(Python) または@anthropic-ai/sdk(TypeScript) をインポートしている - ユーザーが Claude API パターン、ツール使用、ストリーミング、またはビジョン機能について質問している
- Claude Agent SDK を使用してエージェント ワークフローを実装している
- API コスト、トークン使用量、またはレイテンシーを最適化する必要がある
モデル選択
| モデル | ID | 最適な用途 |
|---|---|---|
| Opus 4.1 | claude-opus-4-1 | 複雑な推論、アーキテクチャ設計、研究 |
| Sonnet 4 | claude-sonnet-4-0 | バランスの取れたコーディング タスク、ほとんどの開発作業 |
| Haiku 3.5 | claude-3-5-haiku-latest | 高速レスポンス、高スループット、コスト重視 |
デフォルトでは Sonnet 4 を使用します。タスクが深い推論を必要とする場合は Opus、速度またはコスト最適化が必要な場合は Haiku を使用してください。本番環境では、エイリアスではなく固定のスナップショット ID を優先的に使用してください。
Python SDK
インストール
pip install anthropic
基本的なメッセージ
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from env
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain async/await in Python"}
]
)
print(message.content[0].text)
ストリーミング
with client.messages.stream(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
システム プロンプト
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system="You are a senior Python developer. Be concise.",
messages=[{"role": "user", "content": "Review this function"}]
)
TypeScript SDK
インストール
npm install @anthropic-ai/sdk
基本的なメッセージ
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env
const message = await client.messages.create({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain async/await in TypeScript" }
],
});
console.log(message.content[0].text);
ストリーミング
const stream = client.messages.stream({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku" }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
ツール使用
ツールを定義して Claude に呼び出させます:
tools = [
{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in SF?"}]
)
# Handle tool use response
for block in message.content:
if block.type == "tool_use":
# Execute the tool with block.input
result = get_weather(**block.input)
# Send result back
follow_up = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in SF?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": block.id, "content": str(result)}
]}
]
)
ビジョン機能
分析用に画像を送信します:
import base64
with open("diagram.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}},
{"type": "text", "text": "Describe this diagram"}
]
}]
)
拡張思考
複雑な推論タスク向け:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this math problem step by step..."}]
)
for block in message.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "text":
print(f"Answer: {block.text}")
プロンプト キャッシング
大型のシステム プロンプトまたはコンテキストをキャッシュしてコストを削減します:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system=[
{"type": "text", "text": large_system_prompt, "cache_control": {"type": "ephemeral"}}
],
messages=[{"role": "user", "content": "Question about the cached context"}]
)
# Check cache usage
print(f"Cache read: {message.usage.cache_read_input_tokens}")
print(f"Cache creation: {message.usage.cache_creation_input_tokens}")
バッチ API
50% のコスト削減で大量データを非同期処理します:
import time
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"request-{i}",
"params": {
"model": "claude-sonnet-4-0",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}]
}
}
for i, prompt in enumerate(prompts)
]
)
# Poll for completion
while True:
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
break
time.sleep(30)
# Get results
for result in client.messages.batches.results(batch.id):
print(result.result.message.content[0].text)
Claude Agent SDK
マルチステップ エージェントを構築します:
# Note: Agent SDK API surface may change — check official docs
import anthropic
# Define tools as functions
tools = [{
"name": "search_codebase",
"description": "Search the codebase for relevant code",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}]
# Run an agentic loop with tool use
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Review the auth module for security issues"}]
while True:
response = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break
# Handle tool calls and continue the loop
messages.append({"role": "assistant", "content": response.content})
# ... execute tools and append tool_result messages
コスト最適化
| 戦略 | 節減額 | 使用するタイミング |
|---|---|---|
| プロンプト キャッシング | キャッシュ トークン コスト最大 90% 削減 | 繰り返される system プロンプトまたはコンテキスト |
| バッチ API | 50% | 時間制約のない大量処理 |
| Haiku を Sonnet の代わりに使用 | 約 75% | シンプルなタスク、分類、抽出 |
| max_tokens を短縮 | 可変 | 出力が短いことがわかっている場合 |
| ストリーミング | なし(コスト同じ) | ユーザー体験の向上、価格は同じ |
エラー ハンドリング
import time
from anthropic import APIError, RateLimitError, APIConnectionError
try:
message = client.messages.create(...)
except RateLimitError:
# Back off and retry
time.sleep(60)
except APIConnectionError:
# Network issue, retry with backoff
pass
except APIError as e:
print(f"API error {e.status_code}: {e.message}")
環境設定
# Required
export ANTHROPIC_API_KEY="your-api-key-here"
# Optional: set default model
export ANTHROPIC_MODEL="claude-sonnet-4-0"
API キーをハードコードしないでください。常に環境変数を使用してください。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- ComeOnOliver
- ライセンス
- MIT
- 最終更新
- 2026/5/11
Source: https://github.com/ComeOnOliver/skillshub / ライセンス: MIT