agentleFS
andreab67andreab67/agent-skills/messages-api-sdk/SKILL.md

messages-api-sdk

Skill1 starsChanged 2 months agoBSD-3-ClauseView on GitHub

Expert help with the Anthropic Python SDK (anthropic package) and Claude API: Messages API calls, tool use / function calling, streaming, prompt caching, count_tokens pre-flight checks, vision input, cost estimation, and model selection (Sonnet 5, Opus 5.5, Fable 5.1, Haiku 4.5). Use when calling Claude models directly via the Anthropic API, implementing tool-use loops, streaming responses, estimating token costs before a call, choosing between current Claude models, or debugging stop_reason/usage/content-block responses. Do NOT use for Claude Code CLI configuration, the OpenAI Python SDK, or the OpenRouter/Kilo gateways - those have their own skills.

  • Reads credentials
  • Installs packages

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before writing any API code, verify these in order:

    line 22
  2. Distinctive:

    Coding recommendation: Start with Sonnet 5 for general coding, PRs, and review.

    line 166
  3. Very specific:

    If stop_reason is max_tokens at any turn: the response was cut — increase max_tokens or split the task.

    line 303
  4. Distinctive:

    Cache system prompts: when the same large context is reused across calls

    line 309

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Anthropic Claude SDK

Expert assistance with the Anthropic Python SDK (anthropic package) and Claude API. Covers the Messages API, tool use, streaming, prompt caching, cost estimation, and model selection for coding workloads.

When to Use This Skill

  • Calling Claude models directly via the Anthropic API
  • Implementing tool use / function calling with Claude
  • Streaming responses for real-time UX
  • Estimating token costs before making a call
  • Choosing between Fable 5.1, Opus 5.5, Sonnet 5, and Haiku 4.5
  • Setting up prompt caching for long repeated contexts
  • Debugging stop_reason, usage, and content block responses

Pre-flight Checklist

Before writing any API code, verify these in order:

  1. Key present: echo $ANTHROPIC_API_KEY returns a value starting with sk-ant-
  2. SDK installed: python -c "import anthropic; print(anthropic.__version__)" succeeds
  3. Model ID correct: copy from the table below — do not guess; model IDs include version suffixes
  4. max_tokens set: there is no default; every call needs an explicit value or it will error
  5. Tool schema valid: input_schema must use "type": "object" at the top level — bare arrays fail

Quick Reference

Installation

pip install anthropic
export ANTHROPIC_API_KEY='sk-ant-...'

Basic Messages Call (Python)

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system="You are a Python expert.",
    messages=[{"role": "user", "content": "Write a quicksort."}],
)
print(message.content[0].text)
print(f"Tokens used: {message.usage.input_tokens} in / {message.usage.output_tokens} out")

Streaming

with client.messages.stream(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain async/await"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Tool Use (Function Calling)

tools = [
    {
        "name": "run_sql",
        "description": "Execute a SQL query and return results",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "SQL query to execute"},
                "database": {"type": "string", "enum": ["prod", "staging"]}
            },
            "required": ["query"]
        }
    }
]

messages = [{"role": "user", "content": "Show me all users created this week"}]
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    tools=tools,
    messages=messages,
)

while response.stop_reason == "tool_use":
    tool_block = next(b for b in response.content if b.type == "tool_use")
    result = execute_tool(tool_block.name, tool_block.input)  # your impl

    messages.append({"role": "assistant", "content": response.content})
    messages.append({
        "role": "user",
        "content": [{"type": "tool_result", "tool_use_id": tool_block.id, "content": str(result)}]
    })
    response = client.messages.create(model="claude-sonnet-5", max_tokens=1024, tools=tools, messages=messages)

print(response.content[0].text)

Count Tokens (pre-flight, no generation)

count = client.messages.count_tokens(
    model="claude-sonnet-5",
    messages=[{"role": "user", "content": "Your prompt here"}],
)
print(f"Input tokens: {count.input_tokens}")

This is a separate API request — it POSTs to /v1/messages/count_tokens (network round-trip, needs your API key) and returns the token count without generating a completion.

Prompt Caching (Long Repeated Context)

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": "<large system prompt or document>",
        "cache_control": {"type": "ephemeral"}  # cache for 5 min
    }],
    messages=[{"role": "user", "content": "Summarize the key points"}],
)
# usage.cache_creation_input_tokens — first call writes cache
# usage.cache_read_input_tokens — subsequent calls read at 90% discount

Vision (Image Input)

import base64
with open("screenshot.png", "rb") as f:
    img_b64 = base64.standard_b64encode(f.read()).decode()

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": img_b64}},
            {"type": "text", "text": "What bug do you see in this screenshot?"}
        ]
    }]
)

Model Selection

ModelIDInput $/MtokOutput $/MtokContextBest For
claude-fable-5.1claude-fable-5-1$10$501MAutonomous long-horizon tasks, agentic workflows
claude-opus-5.5claude-opus-5-5$4$201MComplex reasoning, architecture decisions, hard bugs
claude-sonnet-5claude-sonnet-5$2$101MGeneral coding, PRs, code review — best value
claude-haiku-4.5claude-haiku-4-5-20251001$1$5200KFast completions, autocomplete, simple edits (retirement not sooner than 2026-10-15)

Older, still-active models:

ModelIDInput $/MtokOutput $/Mtok
claude-opus-4.8claude-opus-4-8$5$25
claude-sonnet-4.6claude-sonnet-4-6$3$15
claude-fable-5claude-fable-5$10$50

Coding recommendation: Start with Sonnet 5 for general coding, PRs, and review. Escalate to Opus 5.5 when Sonnet 5 fails on hard reasoning or architecture problems. Use Fable 5.1 for long-horizon autonomous/agentic work. Use Haiku 4.5 for high-volume simple tasks (autocomplete, classification, linting) where cost per call dominates.

Pricing pages change — verify current numbers at https://platform.claude.com/docs/en/about-claude/pricing before quoting a price to a user.

Cost Estimation

def estimate_cost(input_tokens: int, output_tokens: int, model: str = "claude-sonnet-5") -> float:
    prices = {
        # current models
        "claude-fable-5-1":            (10.00, 50.00),
        "claude-opus-5-5":              (4.00,  20.00),
        "claude-sonnet-5":              (2.00,  10.00),
        "claude-haiku-4-5-20251001":    (1.00,   5.00),
        # older, still-active models
        "claude-opus-4-8":              (5.00,  25.00),
        "claude-sonnet-4-6":            (3.00,  15.00),
        "claude-fable-5":               (10.00, 50.00),
    }
    if model not in prices:
        raise ValueError(f"unknown model {model!r}; add it to prices")
    in_price, out_price = prices[model]
    return (input_tokens * in_price + output_tokens * out_price) / 1_000_000

Key Parameters

ParameterDefaultNotes
max_tokensRequiredAlways set; use 0 to pre-warm cache only
temperature1.00.0–0.3 for coding/analysis; 0.7+ for creative
top_p1.0Nucleus sampling; lower = more focused
stop_sequences[]Stop generation at these strings
tool_choice"auto""any" forces tool use; "none" disables

Error Handling

import anthropic

try:
    response = client.messages.create(...)
except anthropic.RateLimitError:
    time.sleep(60)  # back off and retry
except anthropic.APIStatusError as e:
    print(f"Status {e.status_code}: {e.message}")
except anthropic.APIConnectionError:
    print("Network error — check connectivity")

Anti-patterns

These all look reasonable but will silently fail or produce wrong results:

  1. Omitting max_tokens — the parameter is required; the API errors immediately, not gracefully.
  2. Building the tool loop with a for instead of while — a tool can chain into another tool call, so a fixed-iteration loop truncates the agent mid-task. Always loop on stop_reason == "tool_use".
  3. Placing cache_control on a short or frequently-changing block — caching costs 25% more per token on creation; blocks under ~1000 tokens or that change per-call will never recoup the premium.
  4. Using client.messages.create() without appending the assistant's content block before the tool_result — the API requires the assistant turn with the tool_use block before the tool_result user turn; skipping it returns a 400.
  5. Passing temperature on a reasoning-optimised model — some extended-thinking Claude variants ignore temperature; check the model docs before relying on low-temp determinism.
  6. Guessing model IDs — claude-opus-4 (no suffix) is not a valid ID; always use the versioned string from the table above. Wrong IDs return a 404, not a fallback.
  7. Calling count_tokens() with the full tools list omitted — token counts for tool-augmented prompts exclude the tool-schema overhead unless you pass tools= to count_tokens() as well.

Worked Example — Tool Use Loop with Triage Decisions

Scenario: build a two-tool SQL assistant that can query a DB and format results.

import anthropic
import json

client = anthropic.Anthropic()

tools = [
    {
        "name": "run_sql",
        "description": "Execute a read-only SQL query and return rows as JSON",
        "input_schema": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
        },
    },
    {
        "name": "format_table",
        "description": "Format a list of dicts as a markdown table",
        "input_schema": {
            "type": "object",
            "properties": {"rows": {"type": "array", "items": {"type": "object"}}},
            "required": ["rows"],
        },
    },
]

messages = [{"role": "user", "content": "Show me the top 5 users by signup date as a table."}]

# Pre-flight: count tokens before sending
token_count = client.messages.count_tokens(
    model="claude-sonnet-5", tools=tools, messages=messages
)
print(f"Pre-flight: {token_count.input_tokens} input tokens")  # guard against runaway prompts

response = client.messages.create(
    model="claude-sonnet-5", max_tokens=1024, tools=tools, messages=messages
)

# Tool loop — WHILE, not for
while response.stop_reason == "tool_use":
    tool_block = next(b for b in response.content if b.type == "tool_use")

    if tool_block.name == "run_sql":
        result = run_query(tool_block.input["query"])  # your DB call
    elif tool_block.name == "format_table":
        result = build_markdown_table(tool_block.input["rows"])  # your formatter
    else:
        result = f"Unknown tool: {tool_block.name}"

    # Append BOTH turns — assistant's tool_use block, then tool_result
    messages.append({"role": "assistant", "content": response.content})
    messages.append({
        "role": "user",
        "content": [{"type": "tool_result", "tool_use_id": tool_block.id, "content": str(result)}],
    })
    response = client.messages.create(
        model="claude-sonnet-5", max_tokens=1024, tools=tools, messages=messages
    )

print(response.content[0].text)

What the loop triage table looks like in practice:

Turnstop_reasonAction
1tool_use → run_sqlExecute DB query, append result, loop
2tool_use → format_tableFormat rows, append result, loop
3end_turnPrint content[0].text — done

If stop_reason is max_tokens at any turn: the response was cut — increase max_tokens or split the task.

Best Practices

  1. Always set max_tokens — no default, unbounded responses are expensive
  2. Use Sonnet 5 as the default; escalate to Opus 5.5 only when needed
  3. Cache system prompts when the same large context is reused across calls
  4. Count tokens first (count_tokens) before expensive batch jobs — pass tools= too
  5. Temperature 0.0–0.2 for deterministic code generation and analysis
  6. Check stop_reason — "tool_use" means continue the loop; "max_tokens" means response was cut
  7. Log usage on every call in production to track spend

Official Docs

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.