К основному содержанию
скилл CX Codex

anthropic-claude-development — скилл для Claude Code: разработка

Скилл для работы с Anthropic Claude API: Messages API, вызов инструментов, промпт-инжиниринг и сборка приложений на моделях Claude.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Mindrally/skills --skill anthropic-claude-development -a claude-code
Открыть на GitHub

Что делает anthropic-claude-development

Скилл подключается к агенту и задаёт ему роль эксперта по Anthropic Claude API. Внутри — примеры на Python: создание клиента, вызов client.messages.create, потоковая выдача через client.messages.stream, работа с изображениями по URL и в base64. Отдельный блок про tool use: описание инструментов через input_schema, обработка stop_reason == "tool_use" и возврат результата в диалог.

Есть раздел про промпт-инжиниринг: системные промпты, XML-теги для структуры, few-shot примеры и chain-of-thought. Плюс обработка ошибок — RateLimitError, APIError, AuthenticationError и функция повторных попыток с экспоненциальной задержкой. Выбор модели расписан по задачам: claude-opus-4-20250514 для сложных рассуждений, claude-sonnet-4-20250514 для баланса цены и качества, claude-3-5-haiku-20241022 для быстрых ответов.

Одно правило скилл повторяет настойчиво: ключ API не хранить в коде, только в переменных окружения. Для локальной разработки он советует python-dotenv и отдельные ключи под dev и production. Если вы уже держите ключ прямо в скрипте, это повод проверить репозиторий до первого коммита.

Какие задачи решает

  • вызвать Messages API из Python без ошибок в схеме запроса
  • описать инструмент и обработать ответ со stop_reason tool_use
  • сделать потоковый вывод ответа модели
  • выбрать модель под задачу по цене и сложности
  • добавить повторные попытки при RateLimitError

Примеры запросов агенту

  • покажи, как вызвать Messages API с системным промптом
  • напиши обработку tool_use с возвратом результата в диалог
  • добавь retry с экспоненциальной задержкой для RateLimitError

Как установить anthropic-claude-development

1Через Skills CLI (Vercel)

npx skills add Mindrally/skills --skill anthropic-claude-development -a claude-code

2Вручную: положить файлы

~/.claude/skills/anthropic-claude-development/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/anthropic-claude-development/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора168

devops Задаёт агенту роль старшего DevOps-инженера: правила для Kubernetes, CI/CD, Bash, Ansible и Python. Пригодится, когда инфраструктуру пишут вместе с моделью. CX Codex +1 739установок anime-js Скилл задаёт агенту правила работы с Anime.js: таймлайны, stagger, SVG-морфинг и производительность. Пригодится, когда анимации в проекте пишет ИИ. CX Codex +1 736установок ruby Задаёт агенту стиль кода, возможности Ruby 3.x и правила тестирования на RSpec. Пригодится, когда пишете или правите Ruby-проект. CX Codex +1 734установок spring-framework Скилл задаёт агенту правила разработки на Spring Framework и Spring Boot: структура слоёв, внедрение зависимостей, тесты, REST. CX Codex +1 731установок sanity Скилл для работы с Sanity CMS: помогает описывать схемы документов, писать GROQ-запросы и связывать контент с TypeScript. CX Codex +1 725установок llm Скилл задаёт агенту правила работы с большими языковыми моделями: архитектура, файнтюнинг, обучение и деплой. Пригодится, когда проект крутится вокруг трансформеров. CX Codex +1 724установок dotnet Задаёт агенту правила C#, ASP.NET Core и Entity Framework Core: структура проекта, async/await, DI, кэш, тесты. CX Codex +1 724установок fastapi-microservices-serverless Скилл задаёт агенту правила проектирования FastAPI-микросервисов под serverless и cloud-native: без состояния, с Redis, API Gateway и OAuth2. CX Codex +1 724установок

Похожие

claude-sdk-integration-patterns manutej Скилл с готовыми паттернами работы с Claude API и TypeScript SDK: стриминг, вызов инструментов, обработка ошибок, экономия токенов. CX Codex +1 434установок claude-api официальный anthropics Справочник по Anthropic SDK и API Claude для генерации кода без устаревших параметров и выдуманных методов. 74 198установок agents-best-practices DenisSergeevitch Скилл даёт правила архитектуры автономных агентов и harness-систем под OpenAI, Anthropic и совместимые API. Помогает проектировать циклы действий, права и память. CX Codex +1 1 000установок ai-agents-architect davila7 Помогает проектировать автономных агентов: циклы ReAct, планирование, реестр инструментов и память. Пригодится, когда агент зацикливается или путается в вызовах. 995установок senior-prompt-engineer Alireza Rezvani Скилл для систематической оптимизации промптов через eval-наборы, измерения качества RAG и валидации агентов. Работает с любыми моделями, использует только встроенные библиотеки Python. 970установок python-mcp-development официальный Awesome Copilot Community Разворачивает проекты серверов Model Context Protocol на базе MCP Python SDK v2. Помогает настроить типизированные инструменты, тесты и конфиги клиентов. ★ 40 418звёзд репо

Рядом в теме «ИИ и ML»

Всё по теме «ИИ и ML» →

Вопросы о anthropic-claude-development

Как установить anthropic-claude-development в Claude?

Выполните npx skills add Mindrally/skills --skill anthropic-claude-development -a claude-code. После этого скилл окажется в ~/.claude/skills/anthropic-claude-development/SKILL.md.

Что делает anthropic-claude-development?

Даёт агенту инструкции по разработке на Anthropic Claude API: Messages API, потоковые ответы, вызов инструментов, работа с изображениями, промпт-инжиниринг и обработка ошибок с повторами.

Что нужно для работы скилла?

Python и библиотека anthropic, а ключ API скилл советует держать в переменной окружения ANTHROPIC_API_KEY, не в коде.

Исходный текст

SKILL.md · Apache-2.0
---
name: anthropic-claude-development
description: Expert guidance for Anthropic Claude API development including Messages API, tool use, prompt engineering, and building production applications with Claude models.
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# Anthropic Claude API Development

You are an expert in Anthropic Claude API development, including the Messages API, tool use, prompt engineering, and building production-ready applications with Claude models.

## Key Principles

- Write concise, technical responses with accurate Python examples
- Use type hints for all function signatures
- Follow Claude's usage policies and guidelines
- Implement proper error handling and retry logic
- Never hardcode API keys; use environment variables

## Setup and Configuration

### Environment Setup

```python
import os
from anthropic import Anthropic

# Always use environment variables for API keys
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
```

### Best Practices

- Store API keys in `.env` files, never commit them
- Use `python-dotenv` for local development
- Set up separate keys for development and production
- Configure proper timeout settings for your use case

## Messages API

### Basic Usage

```python
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)
```

### Streaming Responses

```python
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)
```

### Model Selection

- Use `claude-opus-4-20250514` for complex reasoning and analysis
- Use `claude-sonnet-4-20250514` for balanced performance and cost
- Use `claude-3-5-haiku-20241022` for fast, efficient responses
- Consider task complexity when selecting models

## Tool Use (Function Calling)

### Defining Tools

```python
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?"}]
)
```

### Handling Tool Calls

```python
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
```

## Vision and Multimodal

### Image Analysis

```python
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?"
            }
        ]
    }]
)
```

## Prompt Engineering for Claude

### System Prompts

- Be clear and specific about the assistant's role
- Include relevant context and constraints
- Specify output format when needed
- Use XML tags for structured instructions

```python
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>
"""
```

### Prompting Best Practices

- Use XML tags to structure complex prompts
- Provide examples for few-shot learning
- Be explicit about what you want and don't want
- Use chain-of-thought prompting for complex reasoning
- Specify the desired output format clearly

## Error Handling

### Retry Logic

```python
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")
```

### Common Error Types

- `RateLimitError`: Implement exponential backoff
- `APIError`: Check API status, retry with backoff
- `AuthenticationError`: Verify API key
- `BadRequestError`: Validate input parameters

## Prompt Caching

### Using Caching

```python
# 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"}]
)
```

### Caching Best Practices

- Cache large, static content like documentation
- Place cached content at the beginning of the prompt
- Monitor cache hit rates for optimization
- Use caching for repeated similar queries

## Message Batches API

### Batch Processing

```python
# 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"}]
            }
        }
    ]
)
```

## Cost Optimization

- Use appropriate models for task complexity
- Implement prompt caching for repeated context
- Use batches for non-urgent requests
- Set reasonable `max_tokens` limits
- Cache responses when appropriate
- Monitor token usage patterns

## Security Best Practices

- Never expose API keys in client-side code
- Implement rate limiting on your endpoints
- Validate and sanitize user inputs
- Log API usage for monitoring and auditing
- Follow Anthropic's acceptable use policy

## Dependencies

- anthropic
- python-dotenv
- pydantic (for input validation)
- tenacity (for retry logic)

© Mindrally · Apache-2.0 · Mindrally/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой