初始化项目版本

This commit is contained in:
Axhub Make
2026-07-29 16:04:39 +08:00
commit 4305a1082b
2629 changed files with 760590 additions and 0 deletions

View File

@@ -0,0 +1,256 @@
# Claude API — cURL / Raw HTTP
Use these examples when the user needs raw HTTP requests or is working in a language without an official SDK.
## Setup
```bash
export ANTHROPIC_API_KEY="your-api-key"
```
---
## Basic Message Request
```bash
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 16000,
"messages": [
{"role": "user", "content": "What is the capital of France?"}
]
}'
```
### Parsing the response
Use `jq` to extract fields from the JSON response. Do not use `grep`/`sed`
JSON strings can contain any character and regex parsing will break on quotes,
escapes, or multi-line content.
```bash
# Capture the response, then extract fields
response=$(curl -s https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{"model":"claude-opus-5","max_tokens":16000,"messages":[{"role":"user","content":"Hello"}]}')
# Print the first text block (-r strips the JSON quotes)
echo "$response" | jq -r '.content[0].text'
# Read usage fields
input_tokens=$(echo "$response" | jq -r '.usage.input_tokens')
output_tokens=$(echo "$response" | jq -r '.usage.output_tokens')
# Read stop reason (for tool-use loops)
stop_reason=$(echo "$response" | jq -r '.stop_reason')
# Extract all text blocks (content is an array; filter to type=="text")
echo "$response" | jq -r '.content[] | select(.type == "text") | .text'
```
---
## Streaming (SSE)
```bash
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 64000,
"stream": true,
"messages": [{"role": "user", "content": "Write a haiku"}]
}'
```
The response is a stream of Server-Sent Events:
```
event: message_start
data: {"type":"message_start","message":{"id":"msg_...","type":"message",...}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12}}
event: message_stop
data: {"type":"message_stop"}
```
---
## Tool Use
```bash
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 16000,
"tools": [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}],
"messages": [{"role": "user", "content": "What is the weather in Paris?"}]
}'
```
When Claude responds with a `tool_use` block, send the result back:
```bash
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 16000,
"tools": [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}],
"messages": [
{"role": "user", "content": "What is the weather in Paris?"},
{"role": "assistant", "content": [
{"type": "text", "text": "Let me check the weather."},
{"type": "tool_use", "id": "toolu_abc123", "name": "get_weather", "input": {"location": "Paris"}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_abc123", "content": "72°F and sunny"}
]}
]
}'
```
---
## Prompt Caching
Put `cache_control` on the last block of the stable prefix. See `shared/prompt-caching.md` for placement patterns and the silent-invalidator audit checklist.
```bash
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 16000,
"system": [
{"type": "text", "text": "<large shared prompt...>", "cache_control": {"type": "ephemeral"}}
],
"messages": [{"role": "user", "content": "Summarize the key points"}]
}'
```
For 1-hour TTL: `"cache_control": {"type": "ephemeral", "ttl": "1h"}`. Top-level `"cache_control"` on the request body auto-places on the last cacheable block. Verify hits via the response `usage.cache_creation_input_tokens` / `usage.cache_read_input_tokens` fields.
---
## Extended Thinking
> **Fable 5, Claude Opus 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6:** Use adaptive thinking. `budget_tokens` is removed on Fable 5, Claude Opus 5, Opus 4.8, and 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.
> **Claude Opus 5:** thinking is on by default — omitting `"thinking"` runs adaptive (`{"type": "adaptive"}` is equivalent), unlike Opus 4.8/4.7 where omitting it meant no thinking. `{"type": "disabled"}` is accepted only at effort `high` or lower; pairing it with `xhigh`/`max` returns a 400.
> **Older models:** Use `"type": "enabled"` with `"budget_tokens": N` (must be < `max_tokens`, min 1024).
```bash
# Fable 5 / Claude Opus 5 / Opus 4.8 / 4.7 / 4.6: adaptive thinking (recommended)
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 16000,
"thinking": {
"type": "adaptive",
"display": "summarized"
},
"output_config": {
"effort": "high"
},
"messages": [{"role": "user", "content": "Solve this step by step..."}]
}'
```
---
## Refusal Fallbacks (Claude Fable 5) — opt in by default
On `claude-fable-5`, safety classifiers may decline a request (HTTP 200 with `stop_reason: "refusal"`). Fallbacks are **opt-in**: without them the request simply stops. Include the `fallbacks` parameter and its beta header 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.
```bash
response=$(curl -s https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: server-side-fallback-2026-06-01" \
-d '{
"model": "claude-fable-5",
"max_tokens": 16000,
"fallbacks": [{"model": "claude-opus-4-8"}],
"messages": [{"role": "user", "content": "Hello"}]
}')
# Which model produced the message
echo "$response" | jq -r '.model'
# Refusal on the final response means the whole chain refused
echo "$response" | jq -r '.stop_reason'
# Switch points: one fallback block per model that ran and declined this turn
echo "$response" | jq -r '.content[] | select(.type == "fallback") | "\(.from.model) declined; \(.to.model) continued"'
# Served-by signal — covers sticky turns, which carry no fallback block.
# Pair with stop_reason: the fallback model can itself refuse.
if [ "$(echo "$response" | jq -r '.stop_reason')" != "refusal" ] && \
echo "$response" | jq -e '[.usage.iterations[]? | select(.type == "fallback_message")] | length > 0' > /dev/null; then
echo "fallback model served this turn"
fi
```
The header must be exactly `server-side-fallback-2026-06-01` **for this array form**; the newer `fallbacks: "default"` scalar form uses `server-side-fallback-2026-07-01` instead (see `shared/model-migration.md` → Migrating to Claude Opus 5 → New API features), and pairing either header with the other form returns a 400. The parameter is rejected on the Batches API and unavailable on Amazon Bedrock, Vertex AI, and Microsoft Foundry. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` → Migrating to Claude Fable 5 → `refusal` stop reason.
---
## Required Headers
| Header | Value | Description |
| ------------------- | ------------------ | -------------------------- |
| `Content-Type` | `application/json` | Required |
| `x-api-key` | Your API key | Authentication |
| `anthropic-version` | `2023-06-01` | API version |
| `anthropic-beta` | Beta feature IDs | Required for beta features |

View File

@@ -0,0 +1,340 @@
# Managed Agents — cURL / Raw HTTP
Use these examples when the user needs raw HTTP requests or is working without an SDK.
## Setup
```bash
export ANTHROPIC_API_KEY="your-api-key"
# Common headers
HEADERS=(
-H "Content-Type: application/json"
-H "x-api-key: $ANTHROPIC_API_KEY"
-H "anthropic-version: 2023-06-01"
-H "anthropic-beta: managed-agents-2026-04-01"
)
```
---
## Create an Environment
```bash
curl -X POST https://api.anthropic.com/v1/environments \
"${HEADERS[@]}" \
-d '{
"name": "my-dev-env",
"config": {
"type": "cloud",
"networking": { "type": "unrestricted" }
}
}'
```
### With restricted networking
```bash
curl -X POST https://api.anthropic.com/v1/environments \
"${HEADERS[@]}" \
-d '{
"name": "restricted-env",
"config": {
"type": "cloud",
"networking": {
"type": "limited",
"allow_package_managers": true,
"allow_mcp_servers": true,
"allowed_hosts": ["api.example.com"]
}
}
}'
```
---
## Create an Agent (required first step)
> ⚠️ **There is no inline agent config.** Under `managed-agents-2026-04-01`, `model`/`system`/`tools` are top-level fields on `POST /v1/agents`, not on the session. Always create the agent first — the session only takes `"agent": {"type": "agent", "id": "..."}`.
### Minimal
```bash
# 1. Create the agent
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Coding Assistant",
"model": "claude-opus-5",
"tools": [{ "type": "agent_toolset_20260401" }]
}'
# → { "id": "agent_abc123", ... }
# 2. Start a session
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": { "type": "agent", "id": "agent_abc123", "version": "1772585501101368014" },
"environment_id": "env_abc123"
}'
# → { "id": "sesn_abc123", ... }
# Trace: https://platform.claude.com/workspaces/default/sessions/sesn_abc123 (swap 'default' for your workspace ID if the API key is not in the Default workspace)
```
### With system prompt, custom tools, and GitHub repo
```bash
# 1. Create the agent
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Code Reviewer",
"model": "claude-opus-5",
"system": "You are a senior code reviewer. Be thorough and constructive.",
"tools": [
{ "type": "agent_toolset_20260401" },
{
"type": "custom",
"name": "run_linter",
"description": "Run the project linter on a file",
"input_schema": {
"type": "object",
"properties": {
"file_path": { "type": "string", "description": "Path to lint" }
},
"required": ["file_path"]
}
}
]
}'
# 2. Start a session with the repo mounted
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": { "type": "agent", "id": "agent_abc123", "version": "1772585501101368014" },
"environment_id": "env_abc123",
"title": "Code review session",
"resources": [
{
"type": "github_repository",
"url": "https://github.com/owner/repo",
"mount_path": "/workspace/repo",
"authorization_token": "ghp_...",
"branch": "feature-branch"
}
]
}'
```
---
## Send a User Message
```bash
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "user.message",
"content": [{ "type": "text", "text": "Review the auth module for security issues" }]
}
]
}'
```
---
## Stream Events (SSE)
```bash
curl -N https://api.anthropic.com/v1/sessions/$SESSION_ID/events/stream \
"${HEADERS[@]}"
```
Response format:
```
event: session.status_running
data: {"type":"session.status_running","id":"sevt_...","processed_at":"..."}
event: agent.message
data: {"type":"agent.message","id":"sevt_...","content":[{"type":"text","text":"I'll review..."}],"processed_at":"..."}
event: session.status_idle
data: {"type":"session.status_idle","id":"sevt_...","processed_at":"..."}
```
---
## Poll Events
```bash
# Get all events
curl https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}"
# Paginated — get next page of events
curl "https://api.anthropic.com/v1/sessions/$SESSION_ID/events?page=page_abc123" \
"${HEADERS[@]}"
```
---
## Provide Custom Tool Result
When the agent calls a custom tool, send the result back:
```bash
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "user.custom_tool_result",
"custom_tool_use_id": "sevt_abc123",
"content": [{ "type": "text", "text": "No linting errors found." }]
}
]
}'
```
---
## Interrupt a Running Session
```bash
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "user.interrupt"
}
]
}'
```
---
## Get Session Details
```bash
curl https://api.anthropic.com/v1/sessions/$SESSION_ID \
"${HEADERS[@]}"
```
---
## List Sessions
```bash
curl https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}"
```
---
## Delete a Session
```bash
curl -X DELETE https://api.anthropic.com/v1/sessions/$SESSION_ID \
"${HEADERS[@]}"
```
---
## Upload a File
```bash
curl -X POST https://api.anthropic.com/v1/files \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14" \
-F "file=@path/to/file.txt"
```
---
## List and Download Session Files
List files the agent wrote to `/mnt/session/outputs/` during a session, then download them.
```bash
# List files associated with a session
curl "https://api.anthropic.com/v1/files?scope_id=$SESSION_ID" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14,managed-agents-2026-04-01"
# Download a specific file
curl "https://api.anthropic.com/v1/files/$FILE_ID/content" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14,managed-agents-2026-04-01" \
-o downloaded_file.txt
```
---
## List Agents
```bash
curl https://api.anthropic.com/v1/agents \
"${HEADERS[@]}"
```
---
## MCP Server Integration
```bash
# 1. Agent declares MCP server (no auth here — auth goes in a vault)
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "MCP Agent",
"model": "claude-opus-5",
"mcp_servers": [
{ "type": "url", "name": "my-tools", "url": "https://my-mcp-server.example.com/sse" }
],
"tools": [
{ "type": "agent_toolset_20260401" },
{ "type": "mcp_toolset", "mcp_server_name": "my-tools" }
]
}'
# 2. Session attaches vault containing credentials for that MCP server URL
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": "agent_abc123",
"environment_id": "env_abc123",
"vault_ids": ["vlt_abc123"]
}'
```
See `shared/managed-agents-tools.md` §Vaults for creating vaults and adding credentials.
---
## Tool Configuration
```bash
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Restricted Agent",
"model": "claude-opus-5",
"tools": [
{
"type": "agent_toolset_20260401",
"default_config": { "enabled": true },
"configs": [
{ "name": "bash", "enabled": false }
]
}
]
}'
```