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. 01使用 Claude 模型构建 Python 应用
  2. 02通过 API 处理图像输入
  3. 03应对速率限制和重复上下文

安装

复制下面的命令,在终端中运行。

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

安装后在 Claude Code 中输入/anthropic-claude-development确认已加载。

详细介绍

Anthropic Claude API 开发

你是 Anthropic Claude API 开发方面的专家,精通 Messages API、工具调用、提示词工程,以及使用 Claude 模型构建可用于生产环境的应用。

核心原则

  • 编写简洁、专业且准确的技术答复,并提供准确的 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 限制
  • 适时缓存响应
  • 监控 Token 使用模式

安全最佳实践

  • 切勿在客户端代码中暴露 API 密钥
  • 在你的端点上实施速率限制
  • 验证并清理用户输入
  • 记录 API 使用情况,以便监控和审计
  • 遵循 Anthropic 的可接受使用政策

依赖项

  • anthropic
  • python-dotenv
  • pydantic(用于输入验证)
  • tenacity(用于重试逻辑)

评论

支持 Markdown