mcpField
A
anthropic-claude-development

anthropic-claude-development

github.com/mindrally開発287732 回インストール3 週間前に更新
リポジトリ

anthropic-claude-development について

Anthropic Claude APIを使うアプリケーション開発向けのスキルです。Messages API、ツール利用、プロンプト、マルチモーダル入力、Pythonでの運用を扱います。

主な機能

  1. 01Messages APIとストリーミング
  2. 02ツール呼び出しの処理
  3. 03画像認識と画像分析
  4. 04プロンプト設計とキャッシュ
  5. 05リトライとバッチリクエスト
  6. 06APIのセキュリティとコスト管理

活用シーン

  1. 01Claudeモデルを使ったPythonアプリの構築
  2. 02API経由での画像入力処理
  3. 03レート制限と繰り返し使うコンテキストへの対応

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mindrally/skills --skill anthropic-claude-development

インストール後、Claude Code で/anthropic-claude-developmentを入力して読み込まれたか確認します。

詳細

Anthropic Claude API 開発

Messages API、ツールの使用、プロンプトエンジニアリング、Claude モデルを使用した本番環境対応アプリケーションの構築など、Anthropic Claude API 開発のエキスパートです。

重要な原則

  • 正確な Python の例を用いて、簡潔で技術的な回答を作成してください
  • すべての関数シグネチャに型ヒントを使用してください
  • Claude の利用ポリシーとガイドラインに従ってください
  • 適切なエラー処理と再試行ロジックを実装してください
  • API キーをハードコードせず、環境変数を使用してください

セットアップと構成

環境のセットアップ
import os
from anthropic import Anthropic

# Always use environment variables for API keys
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
ベストプラクティス
  • API キーは .env ファイルに保存し、決してコミットしないでください
  • ローカル開発には python-dotenv を使用してください
  • 開発環境用と本番環境用に別々のキーを設定してください
  • 用途に応じて適切なタイムアウト設定を行ってください

Messages API

基本的な使い方
from anthropic import Anthropic

client = Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)

print(message.content[0].text)
ストリーミング応答
with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
モデルの選択
  • 複雑な推論や分析には claude-opus-4-20250514 を使用してください
  • 性能とコストのバランスを取るには claude-sonnet-4-20250514 を使用してください
  • 高速で効率的な応答には claude-3-5-haiku-20241022 を使用してください
  • モデルを選択する際は、タスクの複雑さを考慮してください

ツールの使用(関数呼び出し)

ツールの定義
tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g., San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The unit of temperature"
                }
            },
            "required": ["location"]
        }
    }
]

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in London?"}]
)
ツール呼び出しの処理
import json

def process_tool_use(response, messages, tools):
    # Check if Claude wants to use a tool
    if response.stop_reason == "tool_use":
        tool_use_block = next(
            block for block in response.content
            if block.type == "tool_use"
        )

        tool_name = tool_use_block.name
        tool_input = tool_use_block.input

        # Execute the tool
        tool_result = execute_tool(tool_name, tool_input)

        # Continue the conversation
        messages.append({"role": "assistant", "content": response.content})
        messages.append({
            "role": "user",
            "content": [{
                "type": "tool_result",
                "tool_use_id": tool_use_block.id,
                "content": json.dumps(tool_result)
            }]
        })

        # Get final response
        return client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=1024,
            tools=tools,
            messages=messages
        )

    return response

ビジョンとマルチモーダル

画像分析
import base64

# From URL
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "url",
                    "url": "https://example.com/image.jpg"
                }
            },
            {
                "type": "text",
                "text": "Describe this image in detail."
            }
        ]
    }]
)

# From base64
with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": image_data
                }
            },
            {
                "type": "text",
                "text": "What do you see?"
            }
        ]
    }]
)

Claude 向けプロンプトエンジニアリング

システムプロンプト
  • アシスタントの役割を明確かつ具体的にしてください
  • 関連するコンテキストと制約を含めてください
  • 必要に応じて出力形式を指定してください
  • 構造化された指示には XML タグを使用してください
system_prompt = """You are a technical documentation writer.

<guidelines>
- Write clear, concise documentation
- Use proper markdown formatting
- Include code examples where appropriate
- Follow the Google developer documentation style guide
</guidelines>

<output_format>
Always structure your response with:
1. Overview
2. Prerequisites
3. Step-by-step instructions
4. Examples
5. Troubleshooting
</output_format>
"""
プロンプト作成のベストプラクティス
  • 複雑なプロンプトを構造化するには XML タグを使用してください
  • 少数ショット学習の例を提示してください
  • 求める内容と求めない内容を明確にしてください
  • 複雑な推論には思考の連鎖を用いたプロンプトを使用してください
  • 希望する出力形式を明確に指定してください

エラー処理

再試行ロジック
from anthropic import RateLimitError, APIError
import time

def call_with_retry(func, max_retries=3, base_delay=1):
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError:
            delay = base_delay * (2 ** attempt)
            print(f"Rate limited. Retrying in {delay}s...")
            time.sleep(delay)
        except APIError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(base_delay)
    raise Exception("Max retries exceeded")
一般的なエラーの種類
  • RateLimitError:指数バックオフを実装してください
  • APIError:API のステータスを確認し、バックオフを伴って再試行してください
  • AuthenticationError:API キーを確認してください
  • BadRequestError:入力パラメーターを検証してください

プロンプトキャッシュ

キャッシュの使用
# Enable caching for frequently used context
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": "Large context that should be cached...",
        "cache_control": {"type": "ephemeral"}
    }],
    messages=[{"role": "user", "content": "Question about the context"}]
)
キャッシュのベストプラクティス
  • ドキュメントなど、大きくて静的なコンテンツをキャッシュしてください
  • キャッシュするコンテンツはプロンプトの先頭に配置してください
  • 最適化のためにキャッシュヒット率を監視してください
  • 類似したクエリを繰り返す場合はキャッシュを使用してください

Message Batches API

バッチ処理
# Create a batch for non-time-sensitive requests
batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": "request-1",
            "params": {
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": "Question 1"}]
            }
        },
        {
            "custom_id": "request-2",
            "params": {
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": "Question 2"}]
            }
        }
    ]
)

コストの最適化

  • タスクの複雑さに応じたモデルを使用してください
  • 繰り返し使用するコンテキストにはプロンプトキャッシュを実装してください
  • 緊急でないリクエストにはバッチを使用してください
  • 適切な max_tokens の上限を設定してください
  • 適切な場合は応答をキャッシュしてください
  • トークン使用パターンを監視してください

セキュリティのベストプラクティス

  • クライアント側のコードで API キーを公開しないでください
  • エンドポイントにレート制限を実装してください
  • ユーザー入力を検証してサニタイズしてください
  • 監視と監査のために API の使用状況を記録してください
  • Anthropic の利用規定に従ってください

依存関係

  • anthropic
  • python-dotenv
  • pydantic(入力検証用)
  • tenacity(再試行ロジック用)

コメント