hive-skills 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/README.md +235 -0
- package/assets/LICENSE +32 -0
- package/assets/THIRD_PARTY_NOTICES.md +72 -0
- package/assets/manifest.json +1290 -0
- package/assets/skills/authored/code-review/composable/BUNDLE.md +192 -0
- package/assets/skills/authored/code-review/composable/INDEX.md +13 -0
- package/assets/skills/authored/code-review/composable/VERSION +1 -0
- package/assets/skills/authored/code-review/composable/mini/01-review-method.md +34 -0
- package/assets/skills/authored/code-review/composable/mini/02-security-review.md +20 -0
- package/assets/skills/authored/code-review/composable/mini/03-correctness-bugs.md +19 -0
- package/assets/skills/authored/code-review/composable/mini/04-concurrency.md +16 -0
- package/assets/skills/authored/code-review/composable/mini/05-error-handling.md +12 -0
- package/assets/skills/authored/code-review/composable/mini/06-performance.md +11 -0
- package/assets/skills/authored/code-review/composable/mini/07-api-design.md +20 -0
- package/assets/skills/authored/code-review/composable/mini/08-missing-tests.md +25 -0
- package/assets/skills/authored/code-review/composable/mini/09-refactoring-and-communication.md +32 -0
- package/assets/skills/authored/data-analysis/composable/BUNDLE.md +186 -0
- package/assets/skills/authored/data-analysis/composable/INDEX.md +13 -0
- package/assets/skills/authored/data-analysis/composable/VERSION +1 -0
- package/assets/skills/authored/data-analysis/composable/mini/01-data-quality-profiling.md +26 -0
- package/assets/skills/authored/data-analysis/composable/mini/02-aggregation-pitfalls.md +21 -0
- package/assets/skills/authored/data-analysis/composable/mini/03-time-series.md +19 -0
- package/assets/skills/authored/data-analysis/composable/mini/04-segmentation.md +23 -0
- package/assets/skills/authored/data-analysis/composable/mini/05-discount-pricing.md +17 -0
- package/assets/skills/authored/data-analysis/composable/mini/06-insight-generation.md +25 -0
- package/assets/skills/authored/data-analysis/composable/mini/07-executive-writing.md +26 -0
- package/assets/skills/authored/data-analysis/composable/mini/08-recommendations.md +20 -0
- package/assets/skills/authored/data-analysis/composable/mini/09-reproducibility-assumptions.md +20 -0
- package/assets/skills/authored/financial-analysis/composable/BUNDLE.md +1293 -0
- package/assets/skills/authored/financial-analysis/composable/INDEX.md +17 -0
- package/assets/skills/authored/financial-analysis/composable/VERSION +1 -0
- package/assets/skills/authored/financial-analysis/composable/mini/00-core.md +69 -0
- package/assets/skills/authored/financial-analysis/composable/mini/01-profitability-efficiency-ratios.md +173 -0
- package/assets/skills/authored/financial-analysis/composable/mini/02-liquidity-leverage-ratios.md +120 -0
- package/assets/skills/authored/financial-analysis/composable/mini/03-valuation-ratios-interpretation.md +107 -0
- package/assets/skills/authored/financial-analysis/composable/mini/04-dcf-projection-wacc.md +122 -0
- package/assets/skills/authored/financial-analysis/composable/mini/05-dcf-terminal-value-sensitivity.md +75 -0
- package/assets/skills/authored/financial-analysis/composable/mini/06-comparables-precedents.md +78 -0
- package/assets/skills/authored/financial-analysis/composable/mini/07-budget-variance-analysis.md +47 -0
- package/assets/skills/authored/financial-analysis/composable/mini/08-driver-based-forecasting-scenarios.md +111 -0
- package/assets/skills/authored/financial-analysis/composable/mini/09-rolling-forecasts-accuracy.md +114 -0
- package/assets/skills/authored/financial-analysis/composable/mini/10-reporting-exec-summary.md +58 -0
- package/assets/skills/authored/financial-analysis/composable/mini/11-industry-adaptations.md +130 -0
- package/assets/skills/authored/financial-analysis/composable/mini/12-toolkit-scripts-io.md +102 -0
- package/assets/skills/authored/python-api/composable/BUNDLE.md +389 -0
- package/assets/skills/authored/python-api/composable/INDEX.md +13 -0
- package/assets/skills/authored/python-api/composable/VERSION +1 -0
- package/assets/skills/authored/python-api/composable/mini/01-project-structure.md +44 -0
- package/assets/skills/authored/python-api/composable/mini/02-routing-and-app.md +38 -0
- package/assets/skills/authored/python-api/composable/mini/03-pydantic-models.md +45 -0
- package/assets/skills/authored/python-api/composable/mini/04-validation-and-errors.md +59 -0
- package/assets/skills/authored/python-api/composable/mini/05-dependencies-and-auth.md +60 -0
- package/assets/skills/authored/python-api/composable/mini/06-pagination-filtering.md +44 -0
- package/assets/skills/authored/python-api/composable/mini/07-async-performance.md +30 -0
- package/assets/skills/authored/python-api/composable/mini/08-testing.md +45 -0
- package/assets/skills/authored/python-api/composable/mini/09-middleware-observability.md +29 -0
- package/assets/skills/authored/tech-writing/composable/BUNDLE.md +220 -0
- package/assets/skills/authored/tech-writing/composable/INDEX.md +12 -0
- package/assets/skills/authored/tech-writing/composable/VERSION +1 -0
- package/assets/skills/authored/tech-writing/composable/mini/01-audience-analysis.md +26 -0
- package/assets/skills/authored/tech-writing/composable/mini/02-document-types.md +27 -0
- package/assets/skills/authored/tech-writing/composable/mini/03-readme-quickstart-changelog.md +22 -0
- package/assets/skills/authored/tech-writing/composable/mini/04-information-architecture.md +21 -0
- package/assets/skills/authored/tech-writing/composable/mini/05-style-clarity.md +29 -0
- package/assets/skills/authored/tech-writing/composable/mini/06-breaking-changes-migrations.md +33 -0
- package/assets/skills/authored/tech-writing/composable/mini/07-troubleshooting-security.md +30 -0
- package/assets/skills/authored/tech-writing/composable/mini/08-faq-voice-tone.md +32 -0
- package/assets/skills/converted/claude-api/composable/BUNDLE.md +14996 -0
- package/assets/skills/converted/claude-api/composable/INDEX.md +98 -0
- package/assets/skills/converted/claude-api/composable/VERSION +1 -0
- package/assets/skills/converted/claude-api/composable/mini/00-core.md +235 -0
- package/assets/skills/converted/claude-api/composable/mini/01-model-api-quick-reference.md +258 -0
- package/assets/skills/converted/claude-api/composable/mini/02-common-pitfalls.md +42 -0
- package/assets/skills/converted/claude-api/composable/mini/10-models.md +135 -0
- package/assets/skills/converted/claude-api/composable/mini/11-platform-availability.md +96 -0
- package/assets/skills/converted/claude-api/composable/mini/12-claude-platform-on-aws.md +59 -0
- package/assets/skills/converted/claude-api/composable/mini/13-live-sources.md +143 -0
- package/assets/skills/converted/claude-api/composable/mini/14-error-codes.md +256 -0
- package/assets/skills/converted/claude-api/composable/mini/15-prompt-caching.md +223 -0
- package/assets/skills/converted/claude-api/composable/mini/16-token-counting.md +56 -0
- package/assets/skills/converted/claude-api/composable/mini/17-tool-use-concepts.md +444 -0
- package/assets/skills/converted/claude-api/composable/mini/18-agent-design.md +101 -0
- package/assets/skills/converted/claude-api/composable/mini/19-anthropic-cli.md +246 -0
- package/assets/skills/converted/claude-api/composable/mini/20-model-migration.md +1301 -0
- package/assets/skills/converted/claude-api/composable/mini/30-managed-agents-overview.md +71 -0
- package/assets/skills/converted/claude-api/composable/mini/31-managed-agents-core.md +278 -0
- package/assets/skills/converted/claude-api/composable/mini/32-managed-agents-environments.md +219 -0
- package/assets/skills/converted/claude-api/composable/mini/33-managed-agents-tools.md +366 -0
- package/assets/skills/converted/claude-api/composable/mini/34-managed-agents-events.md +252 -0
- package/assets/skills/converted/claude-api/composable/mini/35-managed-agents-outcomes.md +106 -0
- package/assets/skills/converted/claude-api/composable/mini/36-managed-agents-multiagent.md +101 -0
- package/assets/skills/converted/claude-api/composable/mini/37-managed-agents-webhooks.md +123 -0
- package/assets/skills/converted/claude-api/composable/mini/38-managed-agents-memory.md +197 -0
- package/assets/skills/converted/claude-api/composable/mini/39-managed-agents-scheduled-deployments.md +146 -0
- package/assets/skills/converted/claude-api/composable/mini/40-managed-agents-client-patterns.md +211 -0
- package/assets/skills/converted/claude-api/composable/mini/41-managed-agents-onboarding.md +82 -0
- package/assets/skills/converted/claude-api/composable/mini/42-managed-agents-api-reference.md +441 -0
- package/assets/skills/converted/claude-api/composable/mini/43-managed-agents-self-hosted-sandboxes.md +174 -0
- package/assets/skills/converted/claude-api/composable/mini/50-python-readme.md +564 -0
- package/assets/skills/converted/claude-api/composable/mini/51-python-tool-use.md +590 -0
- package/assets/skills/converted/claude-api/composable/mini/52-python-streaming-batches-files.md +549 -0
- package/assets/skills/converted/claude-api/composable/mini/53-python-managed-agents.md +335 -0
- package/assets/skills/converted/claude-api/composable/mini/55-typescript-readme.md +404 -0
- package/assets/skills/converted/claude-api/composable/mini/56-typescript-tool-use.md +548 -0
- package/assets/skills/converted/claude-api/composable/mini/57-typescript-streaming-batches-files.md +384 -0
- package/assets/skills/converted/claude-api/composable/mini/58-typescript-managed-agents.md +358 -0
- package/assets/skills/converted/claude-api/composable/mini/60-csharp-readme.md +361 -0
- package/assets/skills/converted/claude-api/composable/mini/61-csharp-tool-use.md +163 -0
- package/assets/skills/converted/claude-api/composable/mini/62-csharp-streaming-batches-files.md +64 -0
- package/assets/skills/converted/claude-api/composable/mini/65-go-readme.md +185 -0
- package/assets/skills/converted/claude-api/composable/mini/66-go-tool-use.md +219 -0
- package/assets/skills/converted/claude-api/composable/mini/67-go-streaming-files.md +63 -0
- package/assets/skills/converted/claude-api/composable/mini/68-go-managed-agents.md +564 -0
- package/assets/skills/converted/claude-api/composable/mini/70-java-readme.md +237 -0
- package/assets/skills/converted/claude-api/composable/mini/71-java-tool-use.md +227 -0
- package/assets/skills/converted/claude-api/composable/mini/72-java-streaming-files.md +49 -0
- package/assets/skills/converted/claude-api/composable/mini/73-java-managed-agents.md +443 -0
- package/assets/skills/converted/claude-api/composable/mini/75-php-readme.md +173 -0
- package/assets/skills/converted/claude-api/composable/mini/76-php-tool-use.md +252 -0
- package/assets/skills/converted/claude-api/composable/mini/77-php-streaming-batches-files.md +53 -0
- package/assets/skills/converted/claude-api/composable/mini/78-php-managed-agents.md +443 -0
- package/assets/skills/converted/claude-api/composable/mini/80-ruby-readme.md +133 -0
- package/assets/skills/converted/claude-api/composable/mini/81-ruby-tool-use-streaming.md +56 -0
- package/assets/skills/converted/claude-api/composable/mini/82-ruby-managed-agents.md +394 -0
- package/assets/skills/converted/claude-api/composable/mini/85-curl-examples.md +255 -0
- package/assets/skills/converted/claude-api/composable/mini/86-curl-managed-agents.md +340 -0
- package/assets/skills/converted/claude-api/composable/presets/csharp.md +1151 -0
- package/assets/skills/converted/claude-api/composable/presets/curl.md +1154 -0
- package/assets/skills/converted/claude-api/composable/presets/go.md +1598 -0
- package/assets/skills/converted/claude-api/composable/presets/java.md +1523 -0
- package/assets/skills/converted/claude-api/composable/presets/php.md +1488 -0
- package/assets/skills/converted/claude-api/composable/presets/python.md +2605 -0
- package/assets/skills/converted/claude-api/composable/presets/ruby.md +1146 -0
- package/assets/skills/converted/claude-api/composable/presets/shared.md +6478 -0
- package/assets/skills/converted/claude-api/composable/presets/typescript.md +2261 -0
- package/assets/skills/converted/docx/composable/BUNDLE.md +617 -0
- package/assets/skills/converted/docx/composable/INDEX.md +12 -0
- package/assets/skills/converted/docx/composable/VERSION +1 -0
- package/assets/skills/converted/docx/composable/mini/00-core.md +26 -0
- package/assets/skills/converted/docx/composable/mini/01-reading-converting.md +36 -0
- package/assets/skills/converted/docx/composable/mini/02-creating-setup-layout.md +85 -0
- package/assets/skills/converted/docx/composable/mini/03-creating-elements.md +257 -0
- package/assets/skills/converted/docx/composable/mini/04-editing-existing.md +57 -0
- package/assets/skills/converted/docx/composable/mini/05-xml-reference.md +128 -0
- package/assets/skills/converted/internal-comms/composable/BUNDLE.md +220 -0
- package/assets/skills/converted/internal-comms/composable/INDEX.md +11 -0
- package/assets/skills/converted/internal-comms/composable/VERSION +1 -0
- package/assets/skills/converted/internal-comms/composable/mini/00-core.md +30 -0
- package/assets/skills/converted/internal-comms/composable/mini/01-3p-updates.md +49 -0
- package/assets/skills/converted/internal-comms/composable/mini/02-company-newsletter.md +67 -0
- package/assets/skills/converted/internal-comms/composable/mini/03-faq-answers.md +32 -0
- package/assets/skills/converted/internal-comms/composable/mini/04-general-comms.md +18 -0
- package/assets/skills/converted/mcp-builder/composable/BUNDLE.md +2460 -0
- package/assets/skills/converted/mcp-builder/composable/INDEX.md +23 -0
- package/assets/skills/converted/mcp-builder/composable/VERSION +1 -0
- package/assets/skills/converted/mcp-builder/composable/mini/00-core.md +43 -0
- package/assets/skills/converted/mcp-builder/composable/mini/01-workflow-research-planning.md +54 -0
- package/assets/skills/converted/mcp-builder/composable/mini/02-implementation-process.md +78 -0
- package/assets/skills/converted/mcp-builder/composable/mini/03-naming-conventions.md +33 -0
- package/assets/skills/converted/mcp-builder/composable/mini/04-response-formats.md +21 -0
- package/assets/skills/converted/mcp-builder/composable/mini/05-pagination.md +24 -0
- package/assets/skills/converted/mcp-builder/composable/mini/06-transport.md +47 -0
- package/assets/skills/converted/mcp-builder/composable/mini/07-annotations.md +20 -0
- package/assets/skills/converted/mcp-builder/composable/mini/08-security.md +35 -0
- package/assets/skills/converted/mcp-builder/composable/mini/09-error-handling.md +32 -0
- package/assets/skills/converted/mcp-builder/composable/mini/10-testing-and-documentation.md +21 -0
- package/assets/skills/converted/mcp-builder/composable/mini/11-python-implementation.md +432 -0
- package/assets/skills/converted/mcp-builder/composable/mini/12-python-advanced-and-checklist.md +233 -0
- package/assets/skills/converted/mcp-builder/composable/mini/13-node-implementation.md +717 -0
- package/assets/skills/converted/mcp-builder/composable/mini/14-node-advanced-and-checklist.md +200 -0
- package/assets/skills/converted/mcp-builder/composable/mini/15-evaluation-design.md +200 -0
- package/assets/skills/converted/mcp-builder/composable/mini/16-evaluation-running.md +198 -0
- package/assets/skills/converted/mcp-builder/composable/presets/node-server.md +1381 -0
- package/assets/skills/converted/mcp-builder/composable/presets/python-server.md +1129 -0
- package/assets/skills/converted/pdf/composable/BUNDLE.md +1284 -0
- package/assets/skills/converted/pdf/composable/INDEX.md +14 -0
- package/assets/skills/converted/pdf/composable/VERSION +1 -0
- package/assets/skills/converted/pdf/composable/mini/00-core.md +46 -0
- package/assets/skills/converted/pdf/composable/mini/01-creation.md +176 -0
- package/assets/skills/converted/pdf/composable/mini/02-extraction.md +178 -0
- package/assets/skills/converted/pdf/composable/mini/03-merge-split-manipulate.md +240 -0
- package/assets/skills/converted/pdf/composable/mini/04-images-ocr.md +168 -0
- package/assets/skills/converted/pdf/composable/mini/05-encryption.md +51 -0
- package/assets/skills/converted/pdf/composable/mini/06-forms.md +300 -0
- package/assets/skills/converted/pdf/composable/mini/07-libraries-reference.md +89 -0
- package/assets/skills/converted/pptx/composable/BUNDLE.md +911 -0
- package/assets/skills/converted/pptx/composable/INDEX.md +12 -0
- package/assets/skills/converted/pptx/composable/VERSION +1 -0
- package/assets/skills/converted/pptx/composable/mini/00-core.md +37 -0
- package/assets/skills/converted/pptx/composable/mini/01-reading.md +37 -0
- package/assets/skills/converted/pptx/composable/mini/02-creating-from-scratch.md +422 -0
- package/assets/skills/converted/pptx/composable/mini/03-editing-templates.md +207 -0
- package/assets/skills/converted/pptx/composable/mini/04-design.md +89 -0
- package/assets/skills/converted/pptx/composable/mini/05-qa-and-rendering.md +91 -0
- package/assets/skills/converted/pptx/composable/presets/creating.md +659 -0
- package/assets/skills/converted/pptx/composable/presets/editing.md +485 -0
- package/assets/skills/converted/skill-creator/composable/BUNDLE.md +1681 -0
- package/assets/skills/converted/skill-creator/composable/INDEX.md +21 -0
- package/assets/skills/converted/skill-creator/composable/VERSION +1 -0
- package/assets/skills/converted/skill-creator/composable/mini/00-core.md +59 -0
- package/assets/skills/converted/skill-creator/composable/mini/01-creating-a-skill.md +27 -0
- package/assets/skills/converted/skill-creator/composable/mini/02-skill-writing-guide.md +71 -0
- package/assets/skills/converted/skill-creator/composable/mini/03-test-cases.md +21 -0
- package/assets/skills/converted/skill-creator/composable/mini/04-running-and-evaluating.md +128 -0
- package/assets/skills/converted/skill-creator/composable/mini/05-improving-the-skill.md +30 -0
- package/assets/skills/converted/skill-creator/composable/mini/06-blind-comparison.md +5 -0
- package/assets/skills/converted/skill-creator/composable/mini/07-description-optimization.md +74 -0
- package/assets/skills/converted/skill-creator/composable/mini/08-packaging.md +11 -0
- package/assets/skills/converted/skill-creator/composable/mini/09-environment-specific.md +38 -0
- package/assets/skills/converted/skill-creator/composable/mini/10-scripts-and-references.md +34 -0
- package/assets/skills/converted/skill-creator/composable/mini/11-json-schemas.md +414 -0
- package/assets/skills/converted/skill-creator/composable/mini/12-agent-grader.md +225 -0
- package/assets/skills/converted/skill-creator/composable/mini/13-agent-comparator.md +204 -0
- package/assets/skills/converted/skill-creator/composable/mini/14-agent-analyzer.md +276 -0
- package/assets/skills/converted/skill-creator/composable/presets/authoring.md +198 -0
- package/assets/skills/converted/skill-creator/composable/presets/evaluating.md +1334 -0
- package/assets/skills/converted/skill-creator/composable/presets/optimizing.md +160 -0
- package/assets/skills/converted/skill-creator/composable/presets.json +5 -0
- package/assets/skills/meta/ccs-skill-creator/composable/BUNDLE.md +465 -0
- package/assets/skills/meta/ccs-skill-creator/composable/INDEX.md +8 -0
- package/assets/skills/meta/ccs-skill-creator/composable/VERSION +1 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/00-core.md +46 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/01-create-new-skill.md +167 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/02-convert-existing-skill.md +120 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/03-review-and-maintain.md +112 -0
- package/assets/skills/sources/anthropic/PROVENANCE.md +3 -0
- package/assets/skills/sources/anthropic/claude-api/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/docx/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/internal-comms/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/mcp-builder/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/pdf/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/pptx/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/skill-creator/LICENSE.txt +202 -0
- package/assets/skills/sources/financial-analyst/PROVENANCE.md +1 -0
- package/assets/tools/hive.py +728 -0
- package/dist/cli.js +7494 -0
- package/package.json +40 -0
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
# Claude API — Python
|
|
2
|
+
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install anthropic
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Client Initialization
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import anthropic
|
|
13
|
+
|
|
14
|
+
# Default — resolves credentials from the environment:
|
|
15
|
+
# ANTHROPIC_API_KEY, or ANTHROPIC_AUTH_TOKEN, or an `ant auth login` profile.
|
|
16
|
+
# Prefer this for local dev; don't hardcode a key.
|
|
17
|
+
client = anthropic.Anthropic()
|
|
18
|
+
|
|
19
|
+
# Explicit API key (only when you must inject a specific key)
|
|
20
|
+
client = anthropic.Anthropic(api_key="your-api-key")
|
|
21
|
+
|
|
22
|
+
# Async client
|
|
23
|
+
async_client = anthropic.AsyncAnthropic()
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## Client Configuration
|
|
29
|
+
|
|
30
|
+
### Per-request overrides
|
|
31
|
+
|
|
32
|
+
Use `with_options()` to override client settings for a single call without mutating the client:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
client.with_options(timeout=5.0, max_retries=5).messages.create(
|
|
36
|
+
model="claude-opus-4-8",
|
|
37
|
+
max_tokens=1024,
|
|
38
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
39
|
+
)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Timeouts
|
|
43
|
+
|
|
44
|
+
Default request timeout is 10 minutes. Pass a float (seconds) or an `httpx.Timeout` for granular control. On timeout the SDK raises `anthropic.APITimeoutError` (and retries per `max_retries`).
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import httpx
|
|
48
|
+
|
|
49
|
+
client = anthropic.Anthropic(timeout=20.0)
|
|
50
|
+
client = anthropic.Anthropic(
|
|
51
|
+
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
|
|
52
|
+
)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Retries
|
|
56
|
+
|
|
57
|
+
The SDK auto-retries connection errors, 408, 409, 429, and ≥500 with exponential backoff (default 2 retries). Set `max_retries` on the client or via `with_options()`; `max_retries=0` disables.
|
|
58
|
+
|
|
59
|
+
### Async performance (aiohttp backend)
|
|
60
|
+
|
|
61
|
+
For high-concurrency async workloads, install `anthropic[aiohttp]` and pass `DefaultAioHttpClient` instead of the default httpx backend:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from anthropic import AsyncAnthropic, DefaultAioHttpClient
|
|
65
|
+
|
|
66
|
+
async with AsyncAnthropic(http_client=DefaultAioHttpClient()) as client:
|
|
67
|
+
...
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Custom HTTP client (proxy, base URL)
|
|
71
|
+
|
|
72
|
+
Use `DefaultHttpxClient` / `DefaultAsyncHttpxClient` — not raw `httpx.Client` — so the SDK's default timeouts and connection limits are preserved:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from anthropic import Anthropic, DefaultHttpxClient
|
|
76
|
+
|
|
77
|
+
client = Anthropic(
|
|
78
|
+
base_url="http://my.test.server.example.com:8083", # or ANTHROPIC_BASE_URL env var
|
|
79
|
+
http_client=DefaultHttpxClient(proxy="http://my.test.proxy.example.com"),
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Logging
|
|
84
|
+
|
|
85
|
+
Set `ANTHROPIC_LOG=debug` (or `info`) to enable SDK logging via the standard `logging` module.
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Basic Message Request
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
response = client.messages.create(
|
|
93
|
+
model="claude-opus-4-8",
|
|
94
|
+
max_tokens=16000,
|
|
95
|
+
messages=[
|
|
96
|
+
{"role": "user", "content": "What is the capital of France?"}
|
|
97
|
+
]
|
|
98
|
+
)
|
|
99
|
+
# response.content is a list of content block objects (TextBlock, ThinkingBlock,
|
|
100
|
+
# ToolUseBlock, ...). Check .type before accessing .text.
|
|
101
|
+
for block in response.content:
|
|
102
|
+
if block.type == "text":
|
|
103
|
+
print(block.text)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## System Prompts
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
response = client.messages.create(
|
|
112
|
+
model="claude-opus-4-8",
|
|
113
|
+
max_tokens=16000,
|
|
114
|
+
system="You are a helpful coding assistant. Always provide examples in Python.",
|
|
115
|
+
messages=[{"role": "user", "content": "How do I read a JSON file?"}]
|
|
116
|
+
)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Mid-conversation system messages (model-gated)
|
|
120
|
+
|
|
121
|
+
For operator instructions that arrive mid-conversation (mode switches, injected state), append `{"role": "system", ...}` to `messages` instead of editing top-level `system` — this preserves the cached prefix and carries operator authority. Must follow a user message (or an `assistant` message ending in server-tool use), and must be either the last entry in `messages` or be followed by an `assistant` turn; cannot be `messages[0]`. Unsupported models return a 400 (`role 'system' is not supported on this model`). See `shared/prompt-caching.md` for when to use this vs. top-level `system`.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
response = client.messages.create(
|
|
125
|
+
model=MODEL_ID, # must support mid-conversation system messages
|
|
126
|
+
max_tokens=16000,
|
|
127
|
+
system=[{"type": "text", "text": STABLE_SYSTEM, "cache_control": {"type": "ephemeral"}}],
|
|
128
|
+
messages=history + [
|
|
129
|
+
{"role": "user", "content": user_message},
|
|
130
|
+
{"role": "system", "content": "Terse mode enabled — keep responses under 40 words."},
|
|
131
|
+
],
|
|
132
|
+
) # No beta header needed — use regular client.messages.create
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Vision (Images)
|
|
138
|
+
|
|
139
|
+
### Base64
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
import base64
|
|
143
|
+
|
|
144
|
+
with open("image.png", "rb") as f:
|
|
145
|
+
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
|
|
146
|
+
|
|
147
|
+
response = client.messages.create(
|
|
148
|
+
model="claude-opus-4-8",
|
|
149
|
+
max_tokens=16000,
|
|
150
|
+
messages=[{
|
|
151
|
+
"role": "user",
|
|
152
|
+
"content": [
|
|
153
|
+
{
|
|
154
|
+
"type": "image",
|
|
155
|
+
"source": {
|
|
156
|
+
"type": "base64",
|
|
157
|
+
"media_type": "image/png",
|
|
158
|
+
"data": image_data
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
{"type": "text", "text": "What's in this image?"}
|
|
162
|
+
]
|
|
163
|
+
}]
|
|
164
|
+
)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### URL
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
response = client.messages.create(
|
|
171
|
+
model="claude-opus-4-8",
|
|
172
|
+
max_tokens=16000,
|
|
173
|
+
messages=[{
|
|
174
|
+
"role": "user",
|
|
175
|
+
"content": [
|
|
176
|
+
{
|
|
177
|
+
"type": "image",
|
|
178
|
+
"source": {
|
|
179
|
+
"type": "url",
|
|
180
|
+
"url": "https://example.com/image.png"
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
{"type": "text", "text": "Describe this image"}
|
|
184
|
+
]
|
|
185
|
+
}]
|
|
186
|
+
)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
---
|
|
190
|
+
|
|
191
|
+
## Prompt Caching
|
|
192
|
+
|
|
193
|
+
Cache large context to reduce costs (up to 90% savings). **Caching is a prefix match** — any byte change anywhere in the prefix invalidates everything after it. For placement patterns, architectural guidance (frozen system prompt, deterministic tool order, where to put volatile content), and the silent-invalidator audit checklist, read `shared/prompt-caching.md`.
|
|
194
|
+
|
|
195
|
+
### Automatic Caching (Recommended)
|
|
196
|
+
|
|
197
|
+
Use top-level `cache_control` to automatically cache the last cacheable block in the request — no need to annotate individual content blocks:
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
response = client.messages.create(
|
|
201
|
+
model="claude-opus-4-8",
|
|
202
|
+
max_tokens=16000,
|
|
203
|
+
cache_control={"type": "ephemeral"}, # auto-caches the last cacheable block
|
|
204
|
+
system="You are an expert on this large document...",
|
|
205
|
+
messages=[{"role": "user", "content": "Summarize the key points"}]
|
|
206
|
+
)
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### Manual Cache Control
|
|
210
|
+
|
|
211
|
+
For fine-grained control, add `cache_control` to specific content blocks:
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
response = client.messages.create(
|
|
215
|
+
model="claude-opus-4-8",
|
|
216
|
+
max_tokens=16000,
|
|
217
|
+
system=[{
|
|
218
|
+
"type": "text",
|
|
219
|
+
"text": "You are an expert on this large document...",
|
|
220
|
+
"cache_control": {"type": "ephemeral"} # default TTL is 5 minutes
|
|
221
|
+
}],
|
|
222
|
+
messages=[{"role": "user", "content": "Summarize the key points"}]
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
# With explicit TTL (time-to-live)
|
|
226
|
+
response = client.messages.create(
|
|
227
|
+
model="claude-opus-4-8",
|
|
228
|
+
max_tokens=16000,
|
|
229
|
+
system=[{
|
|
230
|
+
"type": "text",
|
|
231
|
+
"text": "You are an expert on this large document...",
|
|
232
|
+
"cache_control": {"type": "ephemeral", "ttl": "1h"} # 1 hour TTL
|
|
233
|
+
}],
|
|
234
|
+
messages=[{"role": "user", "content": "Summarize the key points"}]
|
|
235
|
+
)
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### Verifying Cache Hits
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
print(response.usage.cache_creation_input_tokens) # tokens written to cache (~1.25x cost)
|
|
242
|
+
print(response.usage.cache_read_input_tokens) # tokens served from cache (~0.1x cost)
|
|
243
|
+
print(response.usage.input_tokens) # uncached tokens (full cost)
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
If `cache_read_input_tokens` is zero across repeated identical-prefix requests, a silent invalidator is at work — `datetime.now()` or a UUID in the system prompt, unsorted `json.dumps()`, or a varying tool set. See `shared/prompt-caching.md` for the full audit table.
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## Extended Thinking
|
|
251
|
+
|
|
252
|
+
> **Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6:** Use adaptive thinking. `budget_tokens` is removed on Fable 5, Opus 4.8, and 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.
|
|
253
|
+
> **Older models:** Use `thinking: {type: "enabled", budget_tokens: N}` (must be < `max_tokens`, min 1024).
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
# Fable 5 / Opus 4.8 / 4.7 / 4.6: adaptive thinking (recommended)
|
|
257
|
+
response = client.messages.create(
|
|
258
|
+
model="claude-opus-4-8",
|
|
259
|
+
max_tokens=16000,
|
|
260
|
+
thinking={"type": "adaptive", "display": "summarized"}, # display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Opus 4.8 / 4.7
|
|
261
|
+
output_config={"effort": "high"}, # low | medium | high | max
|
|
262
|
+
messages=[{"role": "user", "content": "Solve this step by step..."}]
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
# Access thinking and response
|
|
266
|
+
for block in response.content:
|
|
267
|
+
if block.type == "thinking":
|
|
268
|
+
print(f"Thinking: {block.thinking}")
|
|
269
|
+
elif block.type == "text":
|
|
270
|
+
print(f"Response: {block.text}")
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## Error Handling
|
|
276
|
+
|
|
277
|
+
```python
|
|
278
|
+
import anthropic
|
|
279
|
+
|
|
280
|
+
try:
|
|
281
|
+
response = client.messages.create(...)
|
|
282
|
+
except anthropic.BadRequestError as e:
|
|
283
|
+
print(f"Bad request: {e.message}")
|
|
284
|
+
except anthropic.AuthenticationError:
|
|
285
|
+
print("Invalid API key")
|
|
286
|
+
except anthropic.PermissionDeniedError:
|
|
287
|
+
print("API key lacks required permissions")
|
|
288
|
+
except anthropic.NotFoundError:
|
|
289
|
+
print("Invalid model or endpoint")
|
|
290
|
+
except anthropic.RateLimitError as e:
|
|
291
|
+
retry_after = int(e.response.headers.get("retry-after", "60"))
|
|
292
|
+
print(f"Rate limited. Retry after {retry_after}s.")
|
|
293
|
+
except anthropic.APIStatusError as e:
|
|
294
|
+
if e.status_code >= 500:
|
|
295
|
+
print(f"Server error ({e.status_code}). Retry later.")
|
|
296
|
+
else:
|
|
297
|
+
print(f"API error: {e.message}")
|
|
298
|
+
except anthropic.APIConnectionError:
|
|
299
|
+
print("Network error. Check internet connection.")
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## Response Helpers
|
|
305
|
+
|
|
306
|
+
Every response object exposes `_request_id` (populated from the `request-id` header) — log it when reporting failures to Anthropic. Despite the underscore prefix, this property is public.
|
|
307
|
+
|
|
308
|
+
```python
|
|
309
|
+
message = client.messages.create(...)
|
|
310
|
+
print(message._request_id) # req_018EeWyXxfu5pfWkrYcMdjWG
|
|
311
|
+
print(message.to_json()) # serialize the Pydantic model
|
|
312
|
+
print(message.to_dict()) # plain dict
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
To access raw headers or other response metadata, use `.with_raw_response`:
|
|
316
|
+
|
|
317
|
+
```python
|
|
318
|
+
raw = client.messages.with_raw_response.create(
|
|
319
|
+
model="claude-opus-4-8",
|
|
320
|
+
max_tokens=1024,
|
|
321
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
322
|
+
)
|
|
323
|
+
print(raw.headers.get("request-id"))
|
|
324
|
+
message = raw.parse() # the Message object messages.create() would have returned
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
## Multi-Turn Conversations
|
|
330
|
+
|
|
331
|
+
The API is stateless — send the full conversation history each time.
|
|
332
|
+
|
|
333
|
+
```python
|
|
334
|
+
class ConversationManager:
|
|
335
|
+
"""Manage multi-turn conversations with the Claude API."""
|
|
336
|
+
|
|
337
|
+
def __init__(self, client: anthropic.Anthropic, model: str, system: str = None):
|
|
338
|
+
self.client = client
|
|
339
|
+
self.model = model
|
|
340
|
+
self.system = system
|
|
341
|
+
self.messages = []
|
|
342
|
+
|
|
343
|
+
def send(self, user_message: str, **kwargs) -> str:
|
|
344
|
+
"""Send a message and get a response."""
|
|
345
|
+
self.messages.append({"role": "user", "content": user_message})
|
|
346
|
+
|
|
347
|
+
response = self.client.messages.create(
|
|
348
|
+
model=self.model,
|
|
349
|
+
max_tokens=kwargs.get("max_tokens", 16000),
|
|
350
|
+
system=self.system,
|
|
351
|
+
messages=self.messages,
|
|
352
|
+
**kwargs
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
assistant_message = next(
|
|
356
|
+
(b.text for b in response.content if b.type == "text"), ""
|
|
357
|
+
)
|
|
358
|
+
self.messages.append({"role": "assistant", "content": assistant_message})
|
|
359
|
+
|
|
360
|
+
return assistant_message
|
|
361
|
+
|
|
362
|
+
# Usage
|
|
363
|
+
conversation = ConversationManager(
|
|
364
|
+
client=anthropic.Anthropic(),
|
|
365
|
+
model="claude-opus-4-8",
|
|
366
|
+
system="You are a helpful assistant."
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
response1 = conversation.send("My name is Alice.")
|
|
370
|
+
response2 = conversation.send("What's my name?") # Claude remembers "Alice"
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
**Rules:**
|
|
374
|
+
|
|
375
|
+
- Consecutive same-role messages are allowed — the API combines them into a single turn
|
|
376
|
+
- First message must be `user`
|
|
377
|
+
- `role: "system"` messages are allowed mid-conversation on supporting models (no beta header needed) — see § Mid-conversation system messages above
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
### Compaction (long conversations)
|
|
382
|
+
|
|
383
|
+
> **Beta, Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6.** When conversations approach the 200K context window, compaction automatically summarizes earlier context server-side. The API returns a `compaction` block; you must pass it back on subsequent requests — append `response.content`, not just the text.
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
import anthropic
|
|
387
|
+
|
|
388
|
+
client = anthropic.Anthropic()
|
|
389
|
+
messages = []
|
|
390
|
+
|
|
391
|
+
def chat(user_message: str) -> str:
|
|
392
|
+
messages.append({"role": "user", "content": user_message})
|
|
393
|
+
|
|
394
|
+
response = client.beta.messages.create(
|
|
395
|
+
betas=["compact-2026-01-12"],
|
|
396
|
+
model="claude-opus-4-8",
|
|
397
|
+
max_tokens=16000,
|
|
398
|
+
messages=messages,
|
|
399
|
+
context_management={
|
|
400
|
+
"edits": [{"type": "compact_20260112"}]
|
|
401
|
+
}
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
# Append full content — compaction blocks must be preserved
|
|
405
|
+
messages.append({"role": "assistant", "content": response.content})
|
|
406
|
+
|
|
407
|
+
return next(block.text for block in response.content if block.type == "text")
|
|
408
|
+
|
|
409
|
+
# Compaction triggers automatically when context grows large
|
|
410
|
+
print(chat("Help me build a Python web scraper"))
|
|
411
|
+
print(chat("Add support for JavaScript-rendered pages"))
|
|
412
|
+
print(chat("Now add rate limiting and error handling"))
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
---
|
|
416
|
+
|
|
417
|
+
## Stop Reasons
|
|
418
|
+
|
|
419
|
+
The `stop_reason` field in the response indicates why the model stopped generating:
|
|
420
|
+
|
|
421
|
+
| Value | Meaning |
|
|
422
|
+
|-------|---------|
|
|
423
|
+
| `end_turn` | Claude finished its response naturally |
|
|
424
|
+
| `max_tokens` | Hit the `max_tokens` limit — increase it or use streaming |
|
|
425
|
+
| `stop_sequence` | Hit a custom stop sequence |
|
|
426
|
+
| `tool_use` | Claude wants to call a tool — execute it and continue |
|
|
427
|
+
| `pause_turn` | Model paused and can be resumed (agentic flows) |
|
|
428
|
+
| `refusal` | Claude refused for safety reasons — check `stop_details` |
|
|
429
|
+
|
|
430
|
+
### Structured Stop Details
|
|
431
|
+
|
|
432
|
+
When `stop_reason` is `"refusal"`, the response includes a `stop_details` object with structured information about the refusal:
|
|
433
|
+
|
|
434
|
+
```python
|
|
435
|
+
if response.stop_reason == "refusal" and response.stop_details:
|
|
436
|
+
print(f"Category: {response.stop_details.category}") # e.g. "cyber", "bio", "reasoning_extraction", "frontier_llm", or None — see docs for the full set
|
|
437
|
+
print(f"Explanation: {response.stop_details.explanation}")
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
### Refusal Fallbacks (Claude Fable 5) — opt in by default
|
|
441
|
+
|
|
442
|
+
Fallbacks are **opt-in**: without them a refused request simply stops. Include the server-side `fallbacks` parameter in `claude-fable-5` code by default — on a policy decline the API re-runs the same request on the fallback model inside the same call. A decline before any output isn't billed (a mid-stream decline bills the streamed partial); the rescue bills at the fallback model's own rates, with cache repricing applied automatically.
|
|
443
|
+
|
|
444
|
+
```python
|
|
445
|
+
response = client.beta.messages.create(
|
|
446
|
+
model="claude-fable-5",
|
|
447
|
+
max_tokens=16000,
|
|
448
|
+
betas=["server-side-fallback-2026-06-01"],
|
|
449
|
+
fallbacks=[{"model": "claude-opus-4-8"}],
|
|
450
|
+
messages=[{"role": "user", "content": "..."}],
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
# Switch points: one fallback block per model that ran and declined this turn
|
|
454
|
+
for block in response.content:
|
|
455
|
+
if block.type == "fallback":
|
|
456
|
+
print(f"{block.from_.model} declined; {block.to.model} continued")
|
|
457
|
+
|
|
458
|
+
# Served-by signal — covers sticky turns, which carry no fallback block.
|
|
459
|
+
# Pair with stop_reason: the fallback model can itself refuse.
|
|
460
|
+
fallback_ran = any(
|
|
461
|
+
entry.type == "fallback_message" for entry in response.usage.iterations or []
|
|
462
|
+
)
|
|
463
|
+
if fallback_ran and response.stop_reason != "refusal":
|
|
464
|
+
print(f"Served by {response.model}")
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
A `stop_reason: "refusal"` on the final response means the whole chain refused. The header must be exactly `server-side-fallback-2026-06-01`; the parameter is rejected on the Batches API and unavailable on Amazon Bedrock, Vertex AI, and Microsoft Foundry — register the client-side `BetaRefusalFallbackMiddleware` on the client there instead. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` → Migrating to Claude Fable 5 → `refusal` stop reason.
|
|
468
|
+
|
|
469
|
+
---
|
|
470
|
+
|
|
471
|
+
## Cost Optimization Strategies
|
|
472
|
+
|
|
473
|
+
### 1. Use Prompt Caching for Repeated Context
|
|
474
|
+
|
|
475
|
+
```python
|
|
476
|
+
# Automatic caching (simplest — caches the last cacheable block)
|
|
477
|
+
response = client.messages.create(
|
|
478
|
+
model="claude-opus-4-8",
|
|
479
|
+
max_tokens=16000,
|
|
480
|
+
cache_control={"type": "ephemeral"},
|
|
481
|
+
system=large_document_text, # e.g., 50KB of context
|
|
482
|
+
messages=[{"role": "user", "content": "Summarize the key points"}]
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
# First request: full cost
|
|
486
|
+
# Subsequent requests: ~90% cheaper for cached portion
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### 2. Choose the Right Model
|
|
490
|
+
|
|
491
|
+
```python
|
|
492
|
+
# Default to Opus for most tasks
|
|
493
|
+
response = client.messages.create(
|
|
494
|
+
model="claude-opus-4-8", # $5.00/$25.00 per 1M tokens
|
|
495
|
+
max_tokens=16000,
|
|
496
|
+
messages=[{"role": "user", "content": "Explain quantum computing"}]
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
# Use Sonnet for high-volume production workloads
|
|
500
|
+
standard_response = client.messages.create(
|
|
501
|
+
model="claude-sonnet-5", # $3.00/$15.00 per 1M tokens
|
|
502
|
+
max_tokens=16000,
|
|
503
|
+
messages=[{"role": "user", "content": "Summarize this document"}]
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
# Use Haiku only for simple, speed-critical tasks
|
|
507
|
+
simple_response = client.messages.create(
|
|
508
|
+
model="claude-haiku-4-5", # $1.00/$5.00 per 1M tokens
|
|
509
|
+
max_tokens=256,
|
|
510
|
+
messages=[{"role": "user", "content": "Classify this as positive or negative"}]
|
|
511
|
+
)
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
### 3. Use Token Counting Before Requests
|
|
515
|
+
|
|
516
|
+
```python
|
|
517
|
+
count_response = client.messages.count_tokens(
|
|
518
|
+
model="claude-opus-4-8",
|
|
519
|
+
messages=messages,
|
|
520
|
+
system=system
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
estimated_input_cost = count_response.input_tokens * 0.000005 # $5/1M tokens
|
|
524
|
+
print(f"Estimated input cost: ${estimated_input_cost:.4f}")
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
---
|
|
528
|
+
|
|
529
|
+
## Retry with Exponential Backoff
|
|
530
|
+
|
|
531
|
+
> **Note:** The Anthropic SDK automatically retries rate limit (429) and server errors (5xx) with exponential backoff. You can configure this with `max_retries` (default: 2). Only implement custom retry logic if you need behavior beyond what the SDK provides.
|
|
532
|
+
|
|
533
|
+
```python
|
|
534
|
+
import time
|
|
535
|
+
import random
|
|
536
|
+
import anthropic
|
|
537
|
+
|
|
538
|
+
def call_with_retry(
|
|
539
|
+
client: anthropic.Anthropic,
|
|
540
|
+
max_retries: int = 5,
|
|
541
|
+
base_delay: float = 1.0,
|
|
542
|
+
max_delay: float = 60.0,
|
|
543
|
+
**kwargs
|
|
544
|
+
):
|
|
545
|
+
"""Call the API with exponential backoff retry."""
|
|
546
|
+
last_exception = None
|
|
547
|
+
|
|
548
|
+
for attempt in range(max_retries):
|
|
549
|
+
try:
|
|
550
|
+
return client.messages.create(**kwargs)
|
|
551
|
+
except anthropic.RateLimitError as e:
|
|
552
|
+
last_exception = e
|
|
553
|
+
except anthropic.APIStatusError as e:
|
|
554
|
+
if e.status_code >= 500:
|
|
555
|
+
last_exception = e
|
|
556
|
+
else:
|
|
557
|
+
raise # Client errors (4xx except 429) should not be retried
|
|
558
|
+
|
|
559
|
+
delay = min(base_delay * (2 ** attempt) + random.uniform(0, 1), max_delay)
|
|
560
|
+
print(f"Retry {attempt + 1}/{max_retries} after {delay:.1f}s")
|
|
561
|
+
time.sleep(delay)
|
|
562
|
+
|
|
563
|
+
raise last_exception
|
|
564
|
+
```
|