Anthropic API
Description
Wraps the Anthropic Messages API for the four jobs an agent does most:
- Chat / completion with system prompts and message history.
- Tool use — the model returns
tool_use blocks; you execute and return tool_result.
- Streaming for token-by-token UX.
- Prompt caching to amortize the cost of large stable system prompts (docs, code, glossaries).
When to Use
- You want strong multi-step tool use with lower hallucinated-arg rates.
- You're feeding long stable context (full repo, manuals) and want prompt caching to drop cost ~85%.
- You need vision (Claude handles charts and diagrams strongly).
Inputs / Outputs
| Helper |
Input |
Output |
chat() |
messages, system, model |
assistant text |
tool_loop() |
tools registry + prompt |
final text after tool round-trips |
stream_chat() |
messages |
iterable of token chunks |
cached_chat() |
large system + messages |
text, with cache reuse on repeat calls |
Runnable Example
# pip install "anthropic>=0.39"
# export ANTHROPIC_API_KEY=...
from __future__ import annotations
import json
import time, random
from typing import Callable, Iterable
import anthropic
from anthropic import APIConnectionError, APIStatusError, RateLimitError
client = anthropic.Anthropic()
MODEL = "claude-opus-4-5"
# 1. Chat with retry ----------------------------------------------------------
def chat(messages: list[dict], *, system: str = "", model: str = MODEL,
max_attempts: int = 4) -> str:
for attempt in range(max_attempts):
try:
r = client.messages.create(
model=model, max_tokens=1024, system=system, messages=messages,
)
return r.content[0].text
except (RateLimitError, APIConnectionError):
if attempt == max_attempts - 1: raise
time.sleep(min(2 ** attempt, 10) + random.random())
except APIStatusError as e:
if 500 <= e.status_code < 600 and attempt < max_attempts - 1:
time.sleep(min(2 ** attempt, 10)); continue
raise
# 2. Tool loop ----------------------------------------------------------------
def get_weather(city: str) -> str:
return f"{city}: 24°C, clear."
REGISTRY: dict[str, Callable[..., str]] = {"get_weather": get_weather}
TOOLS = [{
"name": "get_weather",
"description": "Look up the current weather for a city.",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}]
def tool_loop(prompt: str, max_steps: int = 6) -> str:
messages: list[dict] = [{"role": "user", "content": prompt}]
for _ in range(max_steps):
r = client.messages.create(
model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages,
)
if r.stop_reason != "tool_use":
return "".join(b.text for b in r.content if b.type == "text")
messages.append({"role": "assistant", "content": r.content})
results = []
for block in r.content:
if block.type == "tool_use":
out = REGISTRY[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
messages.append({"role": "user", "content": results})
return "tool loop budget exhausted"
# 3. Streaming ----------------------------------------------------------------
def stream_chat(messages: list[dict], system: str = "") -> Iterable[str]:
with client.messages.stream(
model=MODEL, max_tokens=1024, system=system, messages=messages,
) as s:
for text in s.text_stream:
yield text
# 4. Prompt caching -----------------------------------------------------------
def cached_chat(big_system_doc: str, user_msg: str) -> str:
"""Mark a large stable system block as cacheable. Subsequent calls
that re-use the same block pay ~10% of its tokens."""
r = client.messages.create(
model=MODEL,
max_tokens=512,
system=[
{"type": "text", "text": "You answer questions about the attached doc."},
{"type": "text", "text": big_system_doc, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": user_msg}],
)
return r.content[0].text
if __name__ == "__main__":
print(chat([{"role": "user", "content": "One sentence on Skills Tree."}]))
print(tool_loop("What is the weather in Cairo?"))
Failure Modes
| Failure |
Cause |
Mitigation |
| Tool loop deadlock |
Model keeps emitting tool_use forever |
Hard max_steps cap (above) |
tool_result mismatch |
Forgot to attach the parent assistant message |
Always append the entire r.content block before tool results |
| Cache cold-start cost |
First call still pays full system tokens |
Warm the cache once at deploy time |
| Streaming + retry duplicates tokens |
Naive retry on the same stream |
Cancel the stream before retry; resume from the last yielded chunk |
| 529 overloaded errors |
Spike traffic |
Exponential backoff + lower max_tokens; consider Bedrock fallback |
| Wrong content extraction |
Model returned mixed text + tool_use |
Filter b.type == "text" blocks before joining |
Frameworks & Models
| Framework |
Use case |
anthropic SDK (above) |
Direct, lowest abstraction |
anthropic via Amazon Bedrock |
Same model, different control plane / quotas |
LangChain ChatAnthropic |
Drop-in for LangChain pipelines |
| LiteLLM |
Multi-provider abstraction with Anthropic support |
Model Comparison
| Capability |
claude-opus-4-5 |
claude-sonnet-4-5 |
claude-haiku-4-5 |
| Tool-use reliability |
5 |
5 |
4 |
| Long-context retrieval |
5 |
5 |
4 |
| Latency |
3 |
4 |
5 |
| Cost |
2 |
4 |
5 |
Related Skills
- OpenAI API — peer LLM provider
- Function Calling — pattern this builds on
- ReAct — uses tool-loop above
- Image Understanding — vision input
Changelog
| Date |
Version |
Change |
| 2025-03 |
v1 |
Initial entry |
| 2026-04 |
v3 |
Tool loop, streaming, prompt caching, retry, model comparison |
Evidence
The canonical skill file is the authoritative repository implementation. Repository schema, validation workflows, and the Agent Skills projection contract define structural conformance. Implementation guidance must remain traceable to supplied or independently verified authoritative sources; no benchmark claim is made without reproducible evidence.
1---2name: anthropic-api3description: Call Anthropic's Claude Messages API for chat, vision, tool use, and prompt-cached long context — with retry, streaming, and a typed tool dispatcher.4metadata:5 source: https://skillmd.com/skills/samotech/anthropic-api6 upstream: skills/07-tool-use/anthropic-api.md7 category: 07-tool-use8 version: "v3"9---10111213# Anthropic API1415## Description1617Wraps the Anthropic Messages API for the four jobs an agent does most:18191. **Chat / completion** with system prompts and message history.202. **Tool use** — the model returns `tool_use` blocks; you execute and return `tool_result`.213. **Streaming** for token-by-token UX.224. **Prompt caching** to amortize the cost of large stable system prompts (docs, code, glossaries).2324## When to Use2526- You want **strong multi-step tool use** with lower hallucinated-arg rates.27- You're feeding **long stable context** (full repo, manuals) and want prompt caching to drop cost ~85%.28- You need vision (Claude handles charts and diagrams strongly).2930## Inputs / Outputs3132| Helper | Input | Output |33|---|---|---|34| `chat()` | `messages`, `system`, `model` | assistant text |35| `tool_loop()` | tools registry + prompt | final text after tool round-trips |36| `stream_chat()` | `messages` | iterable of token chunks |37| `cached_chat()` | large system + messages | text, with cache reuse on repeat calls |3839## Runnable Example4041```python42# pip install "anthropic>=0.39"43# export ANTHROPIC_API_KEY=...44from __future__ import annotations45import json46import time, random47from typing import Callable, Iterable48import anthropic49from anthropic import APIConnectionError, APIStatusError, RateLimitError5051client = anthropic.Anthropic()52MODEL = "claude-opus-4-5"5354# 1. Chat with retry ----------------------------------------------------------55def chat(messages: list[dict], *, system: str = "", model: str = MODEL,56 max_attempts: int = 4) -> str:57 for attempt in range(max_attempts):58 try:59 r = client.messages.create(60 model=model, max_tokens=1024, system=system, messages=messages,61 )62 return r.content[0].text63 except (RateLimitError, APIConnectionError):64 if attempt == max_attempts - 1: raise65 time.sleep(min(2 ** attempt, 10) + random.random())66 except APIStatusError as e:67 if 500 <= e.status_code < 600 and attempt < max_attempts - 1:68 time.sleep(min(2 ** attempt, 10)); continue69 raise7071# 2. Tool loop ----------------------------------------------------------------72def get_weather(city: str) -> str:73 return f"{city}: 24°C, clear."7475REGISTRY: dict[str, Callable[..., str]] = {"get_weather": get_weather}7677TOOLS = [{78 "name": "get_weather",79 "description": "Look up the current weather for a city.",80 "input_schema": {81 "type": "object",82 "properties": {"city": {"type": "string"}},83 "required": ["city"],84 },85}]8687def tool_loop(prompt: str, max_steps: int = 6) -> str:88 messages: list[dict] = [{"role": "user", "content": prompt}]89 for _ in range(max_steps):90 r = client.messages.create(91 model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages,92 )93 if r.stop_reason != "tool_use":94 return "".join(b.text for b in r.content if b.type == "text")95 messages.append({"role": "assistant", "content": r.content})96 results = []97 for block in r.content:98 if block.type == "tool_use":99 out = REGISTRY[block.name](**block.input)100 results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})101 messages.append({"role": "user", "content": results})102 return "tool loop budget exhausted"103104# 3. Streaming ----------------------------------------------------------------105def stream_chat(messages: list[dict], system: str = "") -> Iterable[str]:106 with client.messages.stream(107 model=MODEL, max_tokens=1024, system=system, messages=messages,108 ) as s:109 for text in s.text_stream:110 yield text111112# 4. Prompt caching -----------------------------------------------------------113def cached_chat(big_system_doc: str, user_msg: str) -> str:114 """Mark a large stable system block as cacheable. Subsequent calls115 that re-use the same block pay ~10% of its tokens."""116 r = client.messages.create(117 model=MODEL,118 max_tokens=512,119 system=[120 {"type": "text", "text": "You answer questions about the attached doc."},121 {"type": "text", "text": big_system_doc, "cache_control": {"type": "ephemeral"}},122 ],123 messages=[{"role": "user", "content": user_msg}],124 )125 return r.content[0].text126127if __name__ == "__main__":128 print(chat([{"role": "user", "content": "One sentence on Skills Tree."}]))129 print(tool_loop("What is the weather in Cairo?"))130```131132## Failure Modes133134| Failure | Cause | Mitigation |135|---|---|---|136| Tool loop deadlock | Model keeps emitting `tool_use` forever | Hard `max_steps` cap (above) |137| `tool_result` mismatch | Forgot to attach the parent `assistant` message | Always append the entire `r.content` block before tool results |138| Cache cold-start cost | First call still pays full system tokens | Warm the cache once at deploy time |139| Streaming + retry duplicates tokens | Naive retry on the same stream | Cancel the stream before retry; resume from the last yielded chunk |140| 529 overloaded errors | Spike traffic | Exponential backoff + lower max_tokens; consider Bedrock fallback |141| Wrong content extraction | Model returned mixed text + tool_use | Filter `b.type == "text"` blocks before joining |142143## Frameworks & Models144145| Framework | Use case |146|---|---|147| `anthropic` SDK (above) | Direct, lowest abstraction |148| `anthropic` via Amazon Bedrock | Same model, different control plane / quotas |149| LangChain `ChatAnthropic` | Drop-in for LangChain pipelines |150| LiteLLM | Multi-provider abstraction with Anthropic support |151152## Model Comparison153154| Capability | claude-opus-4-5 | claude-sonnet-4-5 | claude-haiku-4-5 |155|---|---|---|---|156| Tool-use reliability | 5 | 5 | 4 |157| Long-context retrieval | 5 | 5 | 4 |158| Latency | 3 | 4 | 5 |159| Cost | 2 | 4 | 5 |160161## Related Skills162163- [OpenAI API](openai-api.md) — peer LLM provider164- [Function Calling](function-calling.md) — pattern this builds on165- [ReAct](../09-agentic-patterns/react.md) — uses tool-loop above166- [Image Understanding](../01-perception/image-understanding.md) — vision input167168## Changelog169170| Date | Version | Change |171|---|---|---|172| 2025-03 | v1 | Initial entry |173| 2026-04 | v3 | Tool loop, streaming, prompt caching, retry, model comparison |174175## Evidence176The canonical skill file is the authoritative repository implementation. Repository schema, validation workflows, and the Agent Skills projection contract define structural conformance. Implementation guidance must remain traceable to supplied or independently verified authoritative sources; no benchmark claim is made without reproducible evidence.