mirror of
https://github.com/Piebald-AI/claude-code-system-prompts.git
synced 2026-05-30 05:35:24 +08:00
v2.1.73 (+13,443 tokens)
This commit is contained in:
parent
840a27ba8a
commit
c02a840ffd
42
README.md
42
README.md
@ -34,7 +34,7 @@ Download it and try it out for free! **https://piebald.ai/**
|
|||||||
> [!important]
|
> [!important]
|
||||||
> **NEW (January 23, 2026): We've added all of Claude Code's ~40 system reminders to this list—see [System Reminders](#system-reminders).**
|
> **NEW (January 23, 2026): We've added all of Claude Code's ~40 system reminders to this list—see [System Reminders](#system-reminders).**
|
||||||
|
|
||||||
This repository contains an up-to-date list of all Claude Code's various system prompts and their associated token counts as of **[Claude Code v2.1.72](https://www.npmjs.com/package/@anthropic-ai/claude-code/v/2.1.72) (March 9th, 2026).** It also contains a [**CHANGELOG.md**](./CHANGELOG.md) for the system prompts across 122 versions since v2.0.14. From the team behind [<img src="https://github.com/Piebald-AI/piebald/raw/main/assets/logo.svg" width="15"> **Piebald.**](https://piebald.ai/)
|
This repository contains an up-to-date list of all Claude Code's various system prompts and their associated token counts as of **[Claude Code v2.1.73](https://www.npmjs.com/package/@anthropic-ai/claude-code/v/2.1.73) (March 11th, 2026).** It also contains a [**CHANGELOG.md**](./CHANGELOG.md) for the system prompts across 123 versions since v2.0.14. From the team behind [<img src="https://github.com/Piebald-AI/piebald/raw/main/assets/logo.svg" width="15"> **Piebald.**](https://piebald.ai/)
|
||||||
|
|
||||||
**This repository is updated within minutes of each Claude Code release. See the [changelog](./CHANGELOG.md), and follow [@PiebaldAI](https://x.com/PiebaldAI) on X for a summary of the system prompt changes in each release.**
|
**This repository is updated within minutes of each Claude Code release. See the [changelog](./CHANGELOG.md), and follow [@PiebaldAI](https://x.com/PiebaldAI) on X for a summary of the system prompt changes in each release.**
|
||||||
|
|
||||||
@ -120,31 +120,32 @@ Sub-agents and utilities.
|
|||||||
|
|
||||||
The content of various template files embedded in Claude Code.
|
The content of various template files embedded in Claude Code.
|
||||||
|
|
||||||
- [Data: Agent SDK patterns — Python](./system-prompts/data-agent-sdk-patterns-python.md) (**2500** tks) - Python Agent SDK patterns including custom tools, hooks, subagents, MCP integration, and session resumption.
|
- [Data: Agent SDK patterns — Python](./system-prompts/data-agent-sdk-patterns-python.md) (**2495** tks) - Python Agent SDK patterns including custom tools, hooks, subagents, MCP integration, and session resumption.
|
||||||
- [Data: Agent SDK patterns — TypeScript](./system-prompts/data-agent-sdk-patterns-typescript.md) (**1250** tks) - TypeScript Agent SDK patterns including basic agents, hooks, subagents, and MCP integration.
|
- [Data: Agent SDK patterns — TypeScript](./system-prompts/data-agent-sdk-patterns-typescript.md) (**1250** tks) - TypeScript Agent SDK patterns including basic agents, hooks, subagents, and MCP integration.
|
||||||
- [Data: Agent SDK reference — Python](./system-prompts/data-agent-sdk-reference-python.md) (**3207** tks) - Python Agent SDK reference including installation, quick start, custom tools via MCP, and hooks.
|
- [Data: Agent SDK reference — Python](./system-prompts/data-agent-sdk-reference-python.md) (**3104** tks) - Python Agent SDK reference including installation, quick start, custom tools via MCP, and hooks.
|
||||||
- [Data: Agent SDK reference — TypeScript](./system-prompts/data-agent-sdk-reference-typescript.md) (**2774** tks) - TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks.
|
- [Data: Agent SDK reference — TypeScript](./system-prompts/data-agent-sdk-reference-typescript.md) (**2921** tks) - TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks.
|
||||||
- [Data: Claude API reference — C#](./system-prompts/data-claude-api-reference-c.md) (**550** tks) - C# SDK reference including installation, client initialization, basic requests, streaming, and tool use.
|
- [Data: Claude API reference — C#](./system-prompts/data-claude-api-reference-c.md) (**4703** tks) - C# SDK reference including installation, client initialization, basic requests, streaming, and tool use.
|
||||||
- [Data: Claude API reference — Go](./system-prompts/data-claude-api-reference-go.md) (**2864** tks) - Go SDK reference.
|
- [Data: Claude API reference — Go](./system-prompts/data-claude-api-reference-go.md) (**4341** tks) - Go SDK reference.
|
||||||
- [Data: Claude API reference — Java](./system-prompts/data-claude-api-reference-java.md) (**1225** tks) - Java SDK reference including installation, client initialization, basic requests, streaming, and beta tool use.
|
- [Data: Claude API reference — Java](./system-prompts/data-claude-api-reference-java.md) (**4356** tks) - Java SDK reference including installation, client initialization, basic requests, streaming, and beta tool use.
|
||||||
- [Data: Claude API reference — PHP](./system-prompts/data-claude-api-reference-php.md) (**586** tks) - PHP SDK reference.
|
- [Data: Claude API reference — PHP](./system-prompts/data-claude-api-reference-php.md) (**2381** tks) - PHP SDK reference.
|
||||||
- [Data: Claude API reference — Python](./system-prompts/data-claude-api-reference-python.md) (**3511** tks) - Python SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation.
|
- [Data: Claude API reference — Python](./system-prompts/data-claude-api-reference-python.md) (**3518** tks) - Python SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation.
|
||||||
- [Data: Claude API reference — Ruby](./system-prompts/data-claude-api-reference-ruby.md) (**696** tks) - Ruby SDK reference including installation, client initialization, basic requests, streaming, and beta tool runner.
|
- [Data: Claude API reference — Ruby](./system-prompts/data-claude-api-reference-ruby.md) (**696** tks) - Ruby SDK reference including installation, client initialization, basic requests, streaming, and beta tool runner.
|
||||||
- [Data: Claude API reference — TypeScript](./system-prompts/data-claude-api-reference-typescript.md) (**2809** tks) - TypeScript SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation.
|
- [Data: Claude API reference — TypeScript](./system-prompts/data-claude-api-reference-typescript.md) (**2837** tks) - TypeScript SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation.
|
||||||
- [Data: Claude model catalog](./system-prompts/data-claude-model-catalog.md) (**1542** tks) - Catalog of current and legacy Claude models with exact model IDs, aliases, context windows, and pricing.
|
- [Data: Claude API reference — cURL](./system-prompts/data-claude-api-reference-curl.md) (**1996** tks) - Raw API reference for Claude API for use with cURL or else Raw HTTP.
|
||||||
- [Data: Files API reference — Python](./system-prompts/data-files-api-reference-python.md) (**1300** tks) - Python Files API reference including file upload, listing, deletion, and usage in messages.
|
- [Data: Claude model catalog](./system-prompts/data-claude-model-catalog.md) (**1558** tks) - Catalog of current and legacy Claude models with exact model IDs, aliases, context windows, and pricing.
|
||||||
|
- [Data: Files API reference — Python](./system-prompts/data-files-api-reference-python.md) (**1334** tks) - Python Files API reference including file upload, listing, deletion, and usage in messages.
|
||||||
- [Data: Files API reference — TypeScript](./system-prompts/data-files-api-reference-typescript.md) (**797** tks) - TypeScript Files API reference including file upload, listing, deletion, and usage in messages.
|
- [Data: Files API reference — TypeScript](./system-prompts/data-files-api-reference-typescript.md) (**797** tks) - TypeScript Files API reference including file upload, listing, deletion, and usage in messages.
|
||||||
- [Data: GitHub Actions workflow for @claude mentions](./system-prompts/data-github-actions-workflow-for-claude-mentions.md) (**527** tks) - GitHub Actions workflow template for triggering Claude Code via @claude mentions.
|
- [Data: GitHub Actions workflow for @claude mentions](./system-prompts/data-github-actions-workflow-for-claude-mentions.md) (**527** tks) - GitHub Actions workflow template for triggering Claude Code via @claude mentions.
|
||||||
- [Data: GitHub App installation PR description](./system-prompts/data-github-app-installation-pr-description.md) (**424** tks) - Template for PR description when installing Claude Code GitHub App integration.
|
- [Data: GitHub App installation PR description](./system-prompts/data-github-app-installation-pr-description.md) (**424** tks) - Template for PR description when installing Claude Code GitHub App integration.
|
||||||
- [Data: HTTP error codes reference](./system-prompts/data-http-error-codes-reference.md) (**1891** tks) - Reference for HTTP error codes returned by the Claude API with common causes and handling strategies.
|
- [Data: HTTP error codes reference](./system-prompts/data-http-error-codes-reference.md) (**1922** tks) - Reference for HTTP error codes returned by the Claude API with common causes and handling strategies.
|
||||||
- [Data: Live documentation sources](./system-prompts/data-live-documentation-sources.md) (**2336** tks) - WebFetch URLs for fetching current Claude API and Agent SDK documentation from official sources.
|
- [Data: Live documentation sources](./system-prompts/data-live-documentation-sources.md) (**2336** tks) - WebFetch URLs for fetching current Claude API and Agent SDK documentation from official sources.
|
||||||
- [Data: Message Batches API reference — Python](./system-prompts/data-message-batches-api-reference-python.md) (**1501** tks) - Python Batches API reference including batch creation, status polling, and result retrieval at 50% cost.
|
- [Data: Message Batches API reference — Python](./system-prompts/data-message-batches-api-reference-python.md) (**1544** tks) - Python Batches API reference including batch creation, status polling, and result retrieval at 50% cost.
|
||||||
- [Data: Session memory template](./system-prompts/data-session-memory-template.md) (**292** tks) - Template structure for session memory `summary.md` files.
|
- [Data: Session memory template](./system-prompts/data-session-memory-template.md) (**292** tks) - Template structure for session memory `summary.md` files.
|
||||||
- [Data: Streaming reference — Python](./system-prompts/data-streaming-reference-python.md) (**1528** tks) - Python streaming reference including sync/async streaming and handling different content types.
|
- [Data: Streaming reference — Python](./system-prompts/data-streaming-reference-python.md) (**1528** tks) - Python streaming reference including sync/async streaming and handling different content types.
|
||||||
- [Data: Streaming reference — TypeScript](./system-prompts/data-streaming-reference-typescript.md) (**1703** tks) - TypeScript streaming reference including basic streaming and handling different content types.
|
- [Data: Streaming reference — TypeScript](./system-prompts/data-streaming-reference-typescript.md) (**1703** tks) - TypeScript streaming reference including basic streaming and handling different content types.
|
||||||
- [Data: Tool use concepts](./system-prompts/data-tool-use-concepts.md) (**3932** tks) - Conceptual foundations of tool use with the Claude API including tool definitions, tool choice, and best practices.
|
- [Data: Tool use concepts](./system-prompts/data-tool-use-concepts.md) (**3932** tks) - Conceptual foundations of tool use with the Claude API including tool definitions, tool choice, and best practices.
|
||||||
- [Data: Tool use reference — Python](./system-prompts/data-tool-use-reference-python.md) (**5056** tks) - Python tool use reference including tool runner, manual agentic loop, code execution, and structured outputs.
|
- [Data: Tool use reference — Python](./system-prompts/data-tool-use-reference-python.md) (**5106** tks) - Python tool use reference including tool runner, manual agentic loop, code execution, and structured outputs.
|
||||||
- [Data: Tool use reference — TypeScript](./system-prompts/data-tool-use-reference-typescript.md) (**4114** tks) - TypeScript tool use reference including tool runner, manual agentic loop, code execution, and structured outputs.
|
- [Data: Tool use reference — TypeScript](./system-prompts/data-tool-use-reference-typescript.md) (**5033** tks) - TypeScript tool use reference including tool runner, manual agentic loop, code execution, and structured outputs.
|
||||||
|
|
||||||
### System Prompt
|
### System Prompt
|
||||||
|
|
||||||
@ -157,7 +158,6 @@ Parts of the main system prompt.
|
|||||||
- [System Prompt: Analysis instructions for full compact prompt (minimal and via feature flag)](./system-prompts/system-prompt-analysis-instructions-for-full-compact-prompt-minimal-and-via-feature-flag.md) (**157** tks) - System prompt for the analysis instructions. Part of the compaction instructions. Lean version - experimental.
|
- [System Prompt: Analysis instructions for full compact prompt (minimal and via feature flag)](./system-prompts/system-prompt-analysis-instructions-for-full-compact-prompt-minimal-and-via-feature-flag.md) (**157** tks) - System prompt for the analysis instructions. Part of the compaction instructions. Lean version - experimental.
|
||||||
- [System Prompt: Analysis instructions for full compact prompt (recent messages)](./system-prompts/system-prompt-analysis-instructions-for-full-compact-prompt-recent-messages.md) (**178** tks) - System prompt for the analysis instructions. Part of the compaction instructions. Recent messages only.
|
- [System Prompt: Analysis instructions for full compact prompt (recent messages)](./system-prompts/system-prompt-analysis-instructions-for-full-compact-prompt-recent-messages.md) (**178** tks) - System prompt for the analysis instructions. Part of the compaction instructions. Recent messages only.
|
||||||
- [System Prompt: Auto mode](./system-prompts/system-prompt-auto-mode.md) (**188** tks) - Continuous task execution, akin to a background agent.
|
- [System Prompt: Auto mode](./system-prompts/system-prompt-auto-mode.md) (**188** tks) - Continuous task execution, akin to a background agent.
|
||||||
- [System Prompt: Brief mode](./system-prompts/system-prompt-brief-mode.md) (**230** tks) - Codex-like way of executing tasks - short status updates and then launching in to the work.
|
|
||||||
- [System Prompt: Censoring assistance with malicious activities](./system-prompts/system-prompt-censoring-assistance-with-malicious-activities.md) (**98** tks) - Guidelines for assisting with authorized security testing, defensive security, CTF challenges, and educational contexts while censoring requests for malicious activities.
|
- [System Prompt: Censoring assistance with malicious activities](./system-prompts/system-prompt-censoring-assistance-with-malicious-activities.md) (**98** tks) - Guidelines for assisting with authorized security testing, defensive security, CTF challenges, and educational contexts while censoring requests for malicious activities.
|
||||||
- [System Prompt: Chrome browser MCP tools](./system-prompts/system-prompt-chrome-browser-mcp-tools.md) (**156** tks) - Instructions for loading Chrome browser MCP tools via MCPSearch before use.
|
- [System Prompt: Chrome browser MCP tools](./system-prompts/system-prompt-chrome-browser-mcp-tools.md) (**156** tks) - Instructions for loading Chrome browser MCP tools via MCPSearch before use.
|
||||||
- [System Prompt: Claude in Chrome browser automation](./system-prompts/system-prompt-claude-in-chrome-browser-automation.md) (**759** tks) - Instructions for using Claude in Chrome browser automation tools effectively.
|
- [System Prompt: Claude in Chrome browser automation](./system-prompts/system-prompt-claude-in-chrome-browser-automation.md) (**759** tks) - Instructions for using Claude in Chrome browser automation tools effectively.
|
||||||
@ -180,6 +180,7 @@ Parts of the main system prompt.
|
|||||||
- [System Prompt: Fork usage guidelines](./system-prompts/system-prompt-fork-usage-guidelines.md) (**339** tks) - Instructions for when to fork subagents and rules against reading fork output mid-flight or fabricating fork results.
|
- [System Prompt: Fork usage guidelines](./system-prompts/system-prompt-fork-usage-guidelines.md) (**339** tks) - Instructions for when to fork subagents and rules against reading fork output mid-flight or fabricating fork results.
|
||||||
- [System Prompt: Git status](./system-prompts/system-prompt-git-status.md) (**97** tks) - System prompt for displaying the current git status at the start of the conversation.
|
- [System Prompt: Git status](./system-prompts/system-prompt-git-status.md) (**97** tks) - System prompt for displaying the current git status at the start of the conversation.
|
||||||
- [System Prompt: Hooks Configuration](./system-prompts/system-prompt-hooks-configuration.md) (**1461** tks) - System prompt for hooks configuration. Used for above Claude Code config skill.
|
- [System Prompt: Hooks Configuration](./system-prompts/system-prompt-hooks-configuration.md) (**1461** tks) - System prompt for hooks configuration. Used for above Claude Code config skill.
|
||||||
|
- [System Prompt: How to use the SendUserMessage tool](./system-prompts/system-prompt-how-to-use-the-sendusermessage-tool.md) (**283** tks) - Instructions for using the SendUserMessage tool.
|
||||||
- [System Prompt: Insights at a glance summary](./system-prompts/system-prompt-insights-at-a-glance-summary.md) (**569** tks) - Generates a concise 4-part summary (what's working, hindrances, quick wins, ambitious workflows) for the insights report.
|
- [System Prompt: Insights at a glance summary](./system-prompts/system-prompt-insights-at-a-glance-summary.md) (**569** tks) - Generates a concise 4-part summary (what's working, hindrances, quick wins, ambitious workflows) for the insights report.
|
||||||
- [System Prompt: Insights friction analysis](./system-prompts/system-prompt-insights-friction-analysis.md) (**139** tks) - Analyzes aggregated usage data to identify friction patterns and categorize recurring issues.
|
- [System Prompt: Insights friction analysis](./system-prompts/system-prompt-insights-friction-analysis.md) (**139** tks) - Analyzes aggregated usage data to identify friction patterns and categorize recurring issues.
|
||||||
- [System Prompt: Insights on the horizon](./system-prompts/system-prompt-insights-on-the-horizon.md) (**148** tks) - Identifies ambitious future workflows and opportunities for autonomous AI-assisted development.
|
- [System Prompt: Insights on the horizon](./system-prompts/system-prompt-insights-on-the-horizon.md) (**148** tks) - Identifies ambitious future workflows and opportunities for autonomous AI-assisted development.
|
||||||
@ -191,7 +192,7 @@ Parts of the main system prompt.
|
|||||||
- [System Prompt: Option previewer](./system-prompts/system-prompt-option-previewer.md) (**151** tks) - System prompt for previewing UI options in a side-by-side layout.
|
- [System Prompt: Option previewer](./system-prompts/system-prompt-option-previewer.md) (**151** tks) - System prompt for previewing UI options in a side-by-side layout.
|
||||||
- [System Prompt: Output efficiency](./system-prompts/system-prompt-output-efficiency.md) (**177** tks) - Instructs Claude to be concise and direct in text output, leading with answers over reasoning and limiting responses to essential information.
|
- [System Prompt: Output efficiency](./system-prompts/system-prompt-output-efficiency.md) (**177** tks) - Instructs Claude to be concise and direct in text output, leading with answers over reasoning and limiting responses to essential information.
|
||||||
- [System Prompt: Parallel tool call note (part of "Tool usage policy")](./system-prompts/system-prompt-parallel-tool-call-note-part-of-tool-usage-policy.md) (**102** tks) - System prompt for telling Claude to using parallel tool calls.
|
- [System Prompt: Parallel tool call note (part of "Tool usage policy")](./system-prompts/system-prompt-parallel-tool-call-note-part-of-tool-usage-policy.md) (**102** tks) - System prompt for telling Claude to using parallel tool calls.
|
||||||
- [System Prompt: Post checkpoints](./system-prompts/system-prompt-post-checkpoints.md) (**471** tks) - How to post the checkpoints.
|
- [System Prompt: Phase four of plan mode](./system-prompts/system-prompt-phase-four-of-plan-mode.md) (**142** tks) - Phase four of plan mode.
|
||||||
- [System Prompt: Scratchpad directory](./system-prompts/system-prompt-scratchpad-directory.md) (**170** tks) - Instructions for using a dedicated scratchpad directory for temporary files.
|
- [System Prompt: Scratchpad directory](./system-prompts/system-prompt-scratchpad-directory.md) (**170** tks) - Instructions for using a dedicated scratchpad directory for temporary files.
|
||||||
- [System Prompt: Skillify Current Session](./system-prompts/system-prompt-skillify-current-session.md) (**1882** tks) - System prompt for converting the current session in to a skill.
|
- [System Prompt: Skillify Current Session](./system-prompts/system-prompt-skillify-current-session.md) (**1882** tks) - System prompt for converting the current session in to a skill.
|
||||||
- [System Prompt: Subagent delegation examples](./system-prompts/system-prompt-subagent-delegation-examples.md) (**588** tks) - Provides example interactions showing how a coordinator agent should delegate tasks to subagents, handle waiting states, and report results.
|
- [System Prompt: Subagent delegation examples](./system-prompts/system-prompt-subagent-delegation-examples.md) (**588** tks) - Provides example interactions showing how a coordinator agent should delegate tasks to subagents, handle waiting states, and report results.
|
||||||
@ -244,7 +245,7 @@ Text for large system reminders.
|
|||||||
- [System Reminder: New diagnostics detected](./system-prompts/system-reminder-new-diagnostics-detected.md) (**35** tks) - Notification about new diagnostic issues.
|
- [System Reminder: New diagnostics detected](./system-prompts/system-reminder-new-diagnostics-detected.md) (**35** tks) - Notification about new diagnostic issues.
|
||||||
- [System Reminder: Output style active](./system-prompts/system-reminder-output-style-active.md) (**32** tks) - Notification that an output style is active.
|
- [System Reminder: Output style active](./system-prompts/system-reminder-output-style-active.md) (**32** tks) - Notification that an output style is active.
|
||||||
- [System Reminder: Plan file reference](./system-prompts/system-reminder-plan-file-reference.md) (**62** tks) - Reference to an existing plan file.
|
- [System Reminder: Plan file reference](./system-prompts/system-reminder-plan-file-reference.md) (**62** tks) - Reference to an existing plan file.
|
||||||
- [System Reminder: Plan mode is active (5-phase)](./system-prompts/system-reminder-plan-mode-is-active-5-phase.md) (**1437** tks) - Enhanced plan mode system reminder with parallel exploration and multi-agent planning.
|
- [System Reminder: Plan mode is active (5-phase)](./system-prompts/system-reminder-plan-mode-is-active-5-phase.md) (**1297** tks) - Enhanced plan mode system reminder with parallel exploration and multi-agent planning.
|
||||||
- [System Reminder: Plan mode is active (iterative)](./system-prompts/system-reminder-plan-mode-is-active-iterative.md) (**919** tks) - Iterative plan mode system reminder for main agent with user interviewing workflow.
|
- [System Reminder: Plan mode is active (iterative)](./system-prompts/system-reminder-plan-mode-is-active-iterative.md) (**919** tks) - Iterative plan mode system reminder for main agent with user interviewing workflow.
|
||||||
- [System Reminder: Plan mode is active (subagent)](./system-prompts/system-reminder-plan-mode-is-active-subagent.md) (**307** tks) - Simplified plan mode system reminder for sub agents.
|
- [System Reminder: Plan mode is active (subagent)](./system-prompts/system-reminder-plan-mode-is-active-subagent.md) (**307** tks) - Simplified plan mode system reminder for sub agents.
|
||||||
- [System Reminder: Plan mode re-entry](./system-prompts/system-reminder-plan-mode-re-entry.md) (**236** tks) - System reminder sent when the user enters Plan mode after having previously exited it either via shift+tab or by approving Claude's plan.
|
- [System Reminder: Plan mode re-entry](./system-prompts/system-reminder-plan-mode-re-entry.md) (**236** tks) - System reminder sent when the user enters Plan mode after having previously exited it either via shift+tab or by approving Claude's plan.
|
||||||
@ -335,6 +336,7 @@ Text for large system reminders.
|
|||||||
- [Tool Description: Bash (timeout)](./system-prompts/tool-description-bash-timeout.md) (**83** tks) - Bash tool instruction: optional timeout configuration.
|
- [Tool Description: Bash (timeout)](./system-prompts/tool-description-bash-timeout.md) (**83** tks) - Bash tool instruction: optional timeout configuration.
|
||||||
- [Tool Description: Bash (verify parent directory)](./system-prompts/tool-description-bash-verify-parent-directory.md) (**38** tks) - Bash tool instruction: verify parent directory before creating files.
|
- [Tool Description: Bash (verify parent directory)](./system-prompts/tool-description-bash-verify-parent-directory.md) (**38** tks) - Bash tool instruction: verify parent directory before creating files.
|
||||||
- [Tool Description: Bash (working directory)](./system-prompts/tool-description-bash-working-directory.md) (**37** tks) - Bash tool note about working directory persistence and shell state.
|
- [Tool Description: Bash (working directory)](./system-prompts/tool-description-bash-working-directory.md) (**37** tks) - Bash tool note about working directory persistence and shell state.
|
||||||
|
- [Tool Description: SendMessageTool (non-agent-teams)](./system-prompts/tool-description-sendmessagetool-non-agent-teams.md) (**133** tks) - Send a message the user will read, describes this tool well.
|
||||||
- [Tool Description: TaskList (teammate workflow)](./system-prompts/tool-description-tasklist-teammate-workflow.md) (**133** tks) - Conditional section appended to TaskList tool description.
|
- [Tool Description: TaskList (teammate workflow)](./system-prompts/tool-description-tasklist-teammate-workflow.md) (**133** tks) - Conditional section appended to TaskList tool description.
|
||||||
- [Tool Description: ToolSearch (second part)](./system-prompts/tool-description-toolsearch-second-part.md) (**202** tks) - The bulk of the tool description.
|
- [Tool Description: ToolSearch (second part)](./system-prompts/tool-description-toolsearch-second-part.md) (**202** tks) - The bulk of the tool description.
|
||||||
- [Tool Parameter: Computer action](./system-prompts/tool-parameter-computer-action.md) (**251** tks) - Action parameter options for the Chrome browser computer tool.
|
- [Tool Parameter: Computer action](./system-prompts/tool-parameter-computer-action.md) (**251** tks) - Action parameter options for the Chrome browser computer tool.
|
||||||
@ -345,7 +347,7 @@ Built-in skill prompts for specialized tasks.
|
|||||||
|
|
||||||
- [Skill: /loop slash command](./system-prompts/skill-loop-slash-command.md) (**984** tks) - Parses user input into an interval and prompt, converts the interval to a cron expression, and schedules a recurring task.
|
- [Skill: /loop slash command](./system-prompts/skill-loop-slash-command.md) (**984** tks) - Parses user input into an interval and prompt, converts the interval to a cron expression, and schedules a recurring task.
|
||||||
- [Skill: Build with Claude API (reference guide)](./system-prompts/skill-build-with-claude-api-reference-guide.md) (**410** tks) - Template for presenting language-specific reference documentation with quick task navigation.
|
- [Skill: Build with Claude API (reference guide)](./system-prompts/skill-build-with-claude-api-reference-guide.md) (**410** tks) - Template for presenting language-specific reference documentation with quick task navigation.
|
||||||
- [Skill: Build with Claude API](./system-prompts/skill-build-with-claude-api.md) (**5137** tks) - Main routing guide for building LLM-powered applications with Claude, including language detection, surface selection, and architecture overview.
|
- [Skill: Build with Claude API](./system-prompts/skill-build-with-claude-api.md) (**5144** tks) - Main routing guide for building LLM-powered applications with Claude, including language detection, surface selection, and architecture overview.
|
||||||
- [Skill: Create verifier skills](./system-prompts/skill-create-verifier-skills.md) (**2625** tks) - Prompt for creating verifier skills for the Verify agent to automatically verify code changes.
|
- [Skill: Create verifier skills](./system-prompts/skill-create-verifier-skills.md) (**2625** tks) - Prompt for creating verifier skills for the Verify agent to automatically verify code changes.
|
||||||
- [Skill: Debugging](./system-prompts/skill-debugging.md) (**412** tks) - Instructions for debugging an issue that the user is encountering in the Claude Code session.
|
- [Skill: Debugging](./system-prompts/skill-debugging.md) (**412** tks) - Instructions for debugging an issue that the user is encountering in the Claude Code session.
|
||||||
- [Skill: Simplify](./system-prompts/skill-simplify.md) (**822** tks) - Instructions for simplifying code.
|
- [Skill: Simplify](./system-prompts/skill-simplify.md) (**822** tks) - Instructions for simplifying code.
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Agent SDK patterns — Python'
|
name: 'Data: Agent SDK patterns — Python'
|
||||||
description: Python Agent SDK patterns including custom tools, hooks, subagents, MCP integration, and session resumption
|
description: Python Agent SDK patterns including custom tools, hooks, subagents, MCP integration, and session resumption
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Agent SDK Patterns — Python
|
# Agent SDK Patterns — Python
|
||||||
|
|
||||||
@ -29,7 +29,7 @@ anyio.run(main)
|
|||||||
|
|
||||||
## Custom Tools
|
## Custom Tools
|
||||||
|
|
||||||
Custom tools require an MCP server. Use \`ClaudeSDKClient\` for full control, or pass the server to \`query()\` via \`mcp_servers\`.
|
Custom tools require an MCP server. Use \`ClaudeSDKClient\` for full control (custom SDK MCP tools require \`ClaudeSDKClient\` — \`query()\` only supports external stdio/http MCP servers).
|
||||||
|
|
||||||
\`\`\`python
|
\`\`\`python
|
||||||
import anyio
|
import anyio
|
||||||
@ -221,8 +221,7 @@ async def main():
|
|||||||
prompt="Set up the development environment",
|
prompt="Set up the development environment",
|
||||||
options=ClaudeAgentOptions(
|
options=ClaudeAgentOptions(
|
||||||
allowed_tools=["Bash", "Write"],
|
allowed_tools=["Bash", "Write"],
|
||||||
permission_mode="bypassPermissions",
|
permission_mode="bypassPermissions"
|
||||||
allow_dangerously_skip_permissions=True
|
|
||||||
)
|
)
|
||||||
):
|
):
|
||||||
pass
|
pass
|
||||||
@ -283,7 +282,7 @@ async def main():
|
|||||||
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"])
|
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"])
|
||||||
):
|
):
|
||||||
if isinstance(message, SystemMessage) and message.subtype == "init":
|
if isinstance(message, SystemMessage) and message.subtype == "init":
|
||||||
session_id = message.session_id
|
session_id = message.data.get("session_id")
|
||||||
|
|
||||||
# Resume with full context from the first query
|
# Resume with full context from the first query
|
||||||
async for message in query(
|
async for message in query(
|
||||||
@ -301,22 +300,18 @@ anyio.run(main)
|
|||||||
## Session History
|
## Session History
|
||||||
|
|
||||||
\`\`\`python
|
\`\`\`python
|
||||||
import anyio
|
|
||||||
from claude_agent_sdk import list_sessions, get_session_messages
|
from claude_agent_sdk import list_sessions, get_session_messages
|
||||||
|
|
||||||
async def main():
|
# List past sessions (sync function — no await)
|
||||||
# List past sessions
|
sessions = list_sessions()
|
||||||
sessions = await list_sessions()
|
for session in sessions:
|
||||||
for session in sessions:
|
print(f"Session {session.session_id} in {session.cwd}")
|
||||||
print(f"Session {session.session_id} in {session.cwd}")
|
|
||||||
|
|
||||||
# Retrieve messages from the most recent session
|
# Retrieve messages from the most recent session (sync function — no await)
|
||||||
if sessions:
|
if sessions:
|
||||||
messages = await get_session_messages(session_id=sessions[0].session_id)
|
messages = get_session_messages(session_id=sessions[0].session_id)
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
print(msg)
|
print(msg)
|
||||||
|
|
||||||
anyio.run(main)
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Agent SDK reference — Python'
|
name: 'Data: Agent SDK reference — Python'
|
||||||
description: Python Agent SDK reference including installation, quick start, custom tools via MCP, and hooks
|
description: Python Agent SDK reference including installation, quick start, custom tools via MCP, and hooks
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Agent SDK — Python
|
# Agent SDK — Python
|
||||||
|
|
||||||
@ -120,8 +120,7 @@ Permission modes:
|
|||||||
- \`"default"\`: Prompt for dangerous operations
|
- \`"default"\`: Prompt for dangerous operations
|
||||||
- \`"plan"\`: Planning only, no execution
|
- \`"plan"\`: Planning only, no execution
|
||||||
- \`"acceptEdits"\`: Auto-accept file edits
|
- \`"acceptEdits"\`: Auto-accept file edits
|
||||||
- \`"dontAsk"\`: Don't prompt (useful for CI/CD)
|
- \`"bypassPermissions"\`: Skip all prompts (use with caution)
|
||||||
- \`"bypassPermissions"\`: Skip all prompts (requires \`allow_dangerously_skip_permissions=True\` in options)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -171,7 +170,7 @@ async for message in query(
|
|||||||
|
|
||||||
Hook callback inputs for tool-lifecycle events (\`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`) include \`agent_id\` and \`agent_type\` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.
|
Hook callback inputs for tool-lifecycle events (\`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`) include \`agent_id\` and \`agent_type\` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.
|
||||||
|
|
||||||
Available hook events: \`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`, \`Notification\`, \`UserPromptSubmit\`, \`SessionStart\`, \`SessionEnd\`, \`Stop\`, \`SubagentStart\`, \`SubagentStop\`, \`PreCompact\`, \`PermissionRequest\`, \`Setup\`, \`TeammateIdle\`, \`TaskCompleted\`, \`ConfigChange\`
|
Available hook events: \`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`, \`UserPromptSubmit\`, \`Stop\`, \`SubagentStop\`, \`PreCompact\`, \`Notification\`, \`SubagentStart\`, \`PermissionRequest\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -190,7 +189,6 @@ async for message in query(prompt="...", options=ClaudeAgentOptions(...)):
|
|||||||
| \`tools\` | list | Built-in tools to make available (restricts the default set) |
|
| \`tools\` | list | Built-in tools to make available (restricts the default set) |
|
||||||
| \`disallowed_tools\` | list | Tools to explicitly disallow |
|
| \`disallowed_tools\` | list | Tools to explicitly disallow |
|
||||||
| \`permission_mode\` | string | How to handle permission prompts |
|
| \`permission_mode\` | string | How to handle permission prompts |
|
||||||
| \`allow_dangerously_skip_permissions\`| bool | Must be \`True\` to use \`permission_mode="bypassPermissions"\` |
|
|
||||||
| \`mcp_servers\` | dict | MCP servers to connect to |
|
| \`mcp_servers\` | dict | MCP servers to connect to |
|
||||||
| \`hooks\` | dict | Hooks for customizing behavior |
|
| \`hooks\` | dict | Hooks for customizing behavior |
|
||||||
| \`system_prompt\` | string | Custom system prompt |
|
| \`system_prompt\` | string | Custom system prompt |
|
||||||
@ -219,13 +217,13 @@ async for message in query(
|
|||||||
print(message.result)
|
print(message.result)
|
||||||
print(f"Stop reason: {message.stop_reason}") # e.g., "end_turn", "max_turns"
|
print(f"Stop reason: {message.stop_reason}") # e.g., "end_turn", "max_turns"
|
||||||
elif isinstance(message, SystemMessage) and message.subtype == "init":
|
elif isinstance(message, SystemMessage) and message.subtype == "init":
|
||||||
session_id = message.session_id # Capture for resuming later
|
session_id = message.data.get("session_id") # Capture for resuming later
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
Typed task message subclasses are available for better type safety when handling subagent task events:
|
Typed task message subclasses are available for better type safety when handling subagent task events:
|
||||||
- \`TaskStarted\` — emitted when a subagent task is registered
|
- \`TaskStartedMessage\` — emitted when a subagent task is registered
|
||||||
- \`TaskProgress\` — real-time progress updates with cumulative usage metrics
|
- \`TaskProgressMessage\` — real-time progress updates with cumulative usage metrics
|
||||||
- \`TaskNotification\` — task completion notifications
|
- \`TaskNotificationMessage\` — task completion notifications
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -280,13 +278,13 @@ Retrieve past session data with top-level functions:
|
|||||||
\`\`\`python
|
\`\`\`python
|
||||||
from claude_agent_sdk import list_sessions, get_session_messages
|
from claude_agent_sdk import list_sessions, get_session_messages
|
||||||
|
|
||||||
# List all past sessions
|
# List all past sessions (sync function — no await)
|
||||||
sessions = await list_sessions()
|
sessions = list_sessions()
|
||||||
for session in sessions:
|
for session in sessions:
|
||||||
print(f"{session.session_id}: {session.cwd}")
|
print(f"{session.session_id}: {session.cwd}")
|
||||||
|
|
||||||
# Get messages from a specific session
|
# Get messages from a specific session (sync function — no await)
|
||||||
messages = await get_session_messages(session_id="...")
|
messages = get_session_messages(session_id="...")
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
print(msg)
|
print(msg)
|
||||||
\`\`\`
|
\`\`\`
|
||||||
@ -299,14 +297,14 @@ Manage MCP servers at runtime using \`ClaudeSDKClient\`:
|
|||||||
|
|
||||||
\`\`\`python
|
\`\`\`python
|
||||||
async with ClaudeSDKClient(options=options) as client:
|
async with ClaudeSDKClient(options=options) as client:
|
||||||
# Add a new MCP server during the session
|
# Reconnect a disconnected MCP server
|
||||||
await client.add_mcp_server("my-server", {"command": "npx", "args": ["my-server"]})
|
await client.reconnect_mcp_server("my-server")
|
||||||
|
|
||||||
# Remove an MCP server
|
# Toggle an MCP server on/off
|
||||||
await client.remove_mcp_server("my-server")
|
await client.toggle_mcp_server("my-server", enabled=False)
|
||||||
|
|
||||||
# Check MCP server status (returns typed McpServerStatus)
|
# Get status of all MCP servers
|
||||||
status = await client.get_mcp_status()
|
status = await client.get_mcp_status() # returns McpStatusResponse
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Agent SDK reference — TypeScript'
|
name: 'Data: Agent SDK reference — TypeScript'
|
||||||
description: TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks
|
description: TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Agent SDK — TypeScript
|
# Agent SDK — TypeScript
|
||||||
|
|
||||||
@ -68,7 +68,7 @@ Permission modes:
|
|||||||
- \`"default"\`: Prompt for dangerous operations
|
- \`"default"\`: Prompt for dangerous operations
|
||||||
- \`"plan"\`: Planning only, no execution
|
- \`"plan"\`: Planning only, no execution
|
||||||
- \`"acceptEdits"\`: Auto-accept file edits
|
- \`"acceptEdits"\`: Auto-accept file edits
|
||||||
- \`"dontAsk"\`: Don't prompt (useful for CI/CD)
|
- \`"dontAsk"\`: Don't prompt — **denies** anything not pre-approved (not an auto-approve mode)
|
||||||
- \`"bypassPermissions"\`: Skip all prompts (requires \`allowDangerouslySkipPermissions: true\` in options)
|
- \`"bypassPermissions"\`: Skip all prompts (requires \`allowDangerouslySkipPermissions: true\` in options)
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -144,7 +144,7 @@ for await (const message of query({
|
|||||||
|
|
||||||
Hook event inputs for tool-lifecycle events (\`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`) include \`agent_id\` and \`agent_type\` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.
|
Hook event inputs for tool-lifecycle events (\`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`) include \`agent_id\` and \`agent_type\` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.
|
||||||
|
|
||||||
Available hook events: \`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`, \`Notification\`, \`UserPromptSubmit\`, \`SessionStart\`, \`SessionEnd\`, \`Stop\`, \`SubagentStart\`, \`SubagentStop\`, \`PreCompact\`, \`PermissionRequest\`, \`Setup\`, \`TeammateIdle\`, \`TaskCompleted\`, \`ConfigChange\`
|
Available hook events: \`PreToolUse\`, \`PostToolUse\`, \`PostToolUseFailure\`, \`Notification\`, \`UserPromptSubmit\`, \`SessionStart\`, \`SessionEnd\`, \`Stop\`, \`SubagentStart\`, \`SubagentStop\`, \`PreCompact\`, \`PermissionRequest\`, \`Setup\`, \`TeammateIdle\`, \`TaskCompleted\`, \`ConfigChange\`, \`Elicitation\`, \`ElicitationResult\`, \`WorktreeCreate\`, \`WorktreeRemove\`, \`InstructionsLoaded\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -160,13 +160,13 @@ query({ prompt: "...", options: { ... } })
|
|||||||
| ----------------------------------- | ------ | -------------------------------------------------------------------------- |
|
| ----------------------------------- | ------ | -------------------------------------------------------------------------- |
|
||||||
| \`cwd\` | string | Working directory for file operations |
|
| \`cwd\` | string | Working directory for file operations |
|
||||||
| \`allowedTools\` | array | Tools the agent can use (e.g., \`["Read", "Edit", "Bash"]\`) |
|
| \`allowedTools\` | array | Tools the agent can use (e.g., \`["Read", "Edit", "Bash"]\`) |
|
||||||
| \`tools\` | array | Built-in tools to make available (restricts the default set) |
|
| \`tools\` | array \\| preset | Built-in tools to make available (\`string[]\` or \`{type:'preset', preset:'claude_code'}\`) |
|
||||||
| \`disallowedTools\` | array | Tools to explicitly disallow |
|
| \`disallowedTools\` | array | Tools to explicitly disallow |
|
||||||
| \`permissionMode\` | string | How to handle permission prompts |
|
| \`permissionMode\` | string | How to handle permission prompts |
|
||||||
| \`allowDangerouslySkipPermissions\` | bool | Must be \`true\` to use \`permissionMode: "bypassPermissions"\` |
|
| \`allowDangerouslySkipPermissions\` | bool | Must be \`true\` to use \`permissionMode: "bypassPermissions"\` |
|
||||||
| \`mcpServers\` | object | MCP servers to connect to |
|
| \`mcpServers\` | object | MCP servers to connect to |
|
||||||
| \`hooks\` | object | Hooks for customizing behavior |
|
| \`hooks\` | object | Hooks for customizing behavior |
|
||||||
| \`systemPrompt\` | string | Custom system prompt |
|
| \`systemPrompt\` | string \\| preset | Custom system prompt (\`string\` or \`{type:'preset', preset:'claude_code', append?:string}\`) |
|
||||||
| \`maxTurns\` | number | Maximum agent turns before stopping |
|
| \`maxTurns\` | number | Maximum agent turns before stopping |
|
||||||
| \`maxBudgetUsd\` | number | Maximum budget in USD for the query |
|
| \`maxBudgetUsd\` | number | Maximum budget in USD for the query |
|
||||||
| \`model\` | string | Model ID (default: determined by CLI) |
|
| \`model\` | string | Model ID (default: determined by CLI) |
|
||||||
@ -210,7 +210,7 @@ for await (const message of query({
|
|||||||
})) {
|
})) {
|
||||||
if ("result" in message) {
|
if ("result" in message) {
|
||||||
console.log(message.result);
|
console.log(message.result);
|
||||||
console.log(\`Stop reason: \${message.stop_reason}\`); // e.g., "end_turn", "max_turns"
|
console.log(\`Stop reason: \${message.stop_reason}\`); // e.g., "end_turn", "tool_use", "max_tokens"
|
||||||
} else if (message.type === "system" && message.subtype === "init") {
|
} else if (message.type === "system" && message.subtype === "init") {
|
||||||
const sessionId = message.session_id; // Capture for resuming later
|
const sessionId = message.session_id; // Capture for resuming later
|
||||||
}
|
}
|
||||||
@ -255,10 +255,13 @@ Manage MCP servers at runtime on a running query:
|
|||||||
await queryHandle.reconnectMcpServer("my-server");
|
await queryHandle.reconnectMcpServer("my-server");
|
||||||
|
|
||||||
// Toggle an MCP server on/off
|
// Toggle an MCP server on/off
|
||||||
await queryHandle.toggleMcpServer("my-server");
|
await queryHandle.toggleMcpServer("my-server", false); // (name, enabled) — both required
|
||||||
|
|
||||||
// Check MCP server status (returns typed McpServerStatus with config, scope, tools, and error fields)
|
// Get status of ALL configured MCP servers — returns an ARRAY
|
||||||
const status = await queryHandle.mcpServerStatus();
|
const statuses: McpServerStatus[] = await queryHandle.mcpServerStatus();
|
||||||
|
for (const s of statuses) {
|
||||||
|
console.log(s.name, s.scope, s.tools.length, s.error);
|
||||||
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — C#'
|
name: 'Data: Claude API reference — C#'
|
||||||
description: C# SDK reference including installation, client initialization, basic requests, streaming, and tool use
|
description: C# SDK reference including installation, client initialization, basic requests, streaming, and tool use
|
||||||
ccVersion: 2.1.51
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — C#
|
# Claude API — C#
|
||||||
|
|
||||||
@ -40,8 +40,15 @@ var parameters = new MessageCreateParams
|
|||||||
MaxTokens = 1024,
|
MaxTokens = 1024,
|
||||||
Messages = [new() { Role = Role.User, Content = "What is the capital of France?" }]
|
Messages = [new() { Role = Role.User, Content = "What is the capital of France?" }]
|
||||||
};
|
};
|
||||||
var message = await client.Messages.Create(parameters);
|
var response = await client.Messages.Create(parameters);
|
||||||
Console.WriteLine(message);
|
|
||||||
|
// ContentBlock is a union wrapper. .Value unwraps to the variant object,
|
||||||
|
// then OfType<T> filters to the type you want. Or use the TryPick* idiom
|
||||||
|
// shown in the Thinking section below.
|
||||||
|
foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())
|
||||||
|
{
|
||||||
|
Console.WriteLine(text.Text);
|
||||||
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -68,8 +75,331 @@ await foreach (RawMessageStreamEvent streamEvent in client.Messages.CreateStream
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
|
**\`RawMessageStreamEvent\` TryPick methods** (naming drops the \`Message\`/\`Raw\` prefix): \`TryPickStart\`, \`TryPickDelta\`, \`TryPickStop\`, \`TryPickContentBlockStart\`, \`TryPickContentBlockDelta\`, \`TryPickContentBlockStop\`. There is no \`TryPickMessageStop\` — use \`TryPickStop\`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Tool Use (Manual Loop)
|
## Thinking
|
||||||
|
|
||||||
The C# SDK supports raw tool definitions via JSON schema. See the [shared tool use concepts](../shared/tool-use-concepts.md) for the tool definition format and agentic loop pattern.
|
**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using Anthropic.Models.Messages;
|
||||||
|
|
||||||
|
var response = await client.Messages.Create(new MessageCreateParams
|
||||||
|
{
|
||||||
|
Model = Model.ClaudeOpus4_6,
|
||||||
|
MaxTokens = 16000,
|
||||||
|
// ThinkingConfigParam? implicitly converts from the concrete variant classes —
|
||||||
|
// no wrapper needed.
|
||||||
|
Thinking = new ThinkingConfigAdaptive(),
|
||||||
|
Messages =
|
||||||
|
[
|
||||||
|
new() { Role = Role.User, Content = "Solve: 27 * 453" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// ThinkingBlock(s) precede TextBlock in Content. TryPick* narrows the union.
|
||||||
|
foreach (var block in response.Content)
|
||||||
|
{
|
||||||
|
if (block.TryPickThinking(out ThinkingBlock? t))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[thinking] {t.Thinking}");
|
||||||
|
}
|
||||||
|
else if (block.TryPickText(out TextBlock? text))
|
||||||
|
{
|
||||||
|
Console.WriteLine(text.Text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
> **Deprecated:** \`new ThinkingConfigEnabled { BudgetTokens = N }\` (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.
|
||||||
|
|
||||||
|
Alternative to \`TryPick*\`: \`.Select(b => b.Value).OfType<ThinkingBlock>()\` (same LINQ pattern as the Basic Message example).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tool Use
|
||||||
|
|
||||||
|
### Defining a tool
|
||||||
|
|
||||||
|
\`Tool\` (NOT \`ToolParam\`) with an \`InputSchema\` record. \`InputSchema.Type\` is auto-set to \`"object"\` by the constructor — don't set it. \`ToolUnion\` has an implicit conversion from \`Tool\`, triggered by the collection expression \`[...]\`.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anthropic.Models.Messages;
|
||||||
|
|
||||||
|
var parameters = new MessageCreateParams
|
||||||
|
{
|
||||||
|
Model = Model.ClaudeSonnet4_6,
|
||||||
|
MaxTokens = 1024,
|
||||||
|
Tools = [
|
||||||
|
new Tool {
|
||||||
|
Name = "get_weather",
|
||||||
|
Description = "Get the current weather in a given location",
|
||||||
|
InputSchema = new() {
|
||||||
|
Properties = new Dictionary<string, JsonElement> {
|
||||||
|
["location"] = JsonSerializer.SerializeToElement(
|
||||||
|
new { type = "string", description = "City name" }),
|
||||||
|
},
|
||||||
|
Required = ["location"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
Messages = [new() { Role = Role.User, Content = "Weather in Paris?" }],
|
||||||
|
};
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Derived from \`anthropic-sdk-csharp/src/Anthropic/Models/Messages/Tool.cs\` and \`ToolUnion.cs:799\` (implicit conversion).
|
||||||
|
|
||||||
|
See [shared tool use concepts](../shared/tool-use-concepts.md) for the loop pattern.
|
||||||
|
### Converting response content to the follow-up assistant message
|
||||||
|
|
||||||
|
When echoing Claude's response back in the assistant turn, **there is no \`.ToParam()\` helper** — manually reconstruct each \`ContentBlock\` variant as its \`*Param\` counterpart. Do NOT use \`new ContentBlockParam(block.Json)\`: it compiles and serializes, but \`.Value\` stays \`null\` so \`TryPick*\`/\`Validate()\` fail (degraded JSON pass-through, not the typed path).
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using Anthropic.Models.Messages;
|
||||||
|
|
||||||
|
Message response = await client.Messages.Create(parameters);
|
||||||
|
|
||||||
|
// No .ToParam() — reconstruct per variant. Implicit conversions from each
|
||||||
|
// *Param type to ContentBlockParam mean no explicit wrapper.
|
||||||
|
List<ContentBlockParam> assistantContent = [];
|
||||||
|
List<ContentBlockParam> toolResults = [];
|
||||||
|
foreach (ContentBlock block in response.Content)
|
||||||
|
{
|
||||||
|
if (block.TryPickText(out TextBlock? text))
|
||||||
|
{
|
||||||
|
assistantContent.Add(new TextBlockParam { Text = text.Text });
|
||||||
|
}
|
||||||
|
else if (block.TryPickThinking(out ThinkingBlock? thinking))
|
||||||
|
{
|
||||||
|
// Signature MUST be preserved — the API rejects tampering
|
||||||
|
assistantContent.Add(new ThinkingBlockParam
|
||||||
|
{
|
||||||
|
Thinking = thinking.Thinking,
|
||||||
|
Signature = thinking.Signature,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else if (block.TryPickRedactedThinking(out RedactedThinkingBlock? redacted))
|
||||||
|
{
|
||||||
|
assistantContent.Add(new RedactedThinkingBlockParam { Data = redacted.Data });
|
||||||
|
}
|
||||||
|
else if (block.TryPickToolUse(out ToolUseBlock? toolUse))
|
||||||
|
{
|
||||||
|
// ToolUseBlock has required Caller; ToolUseBlockParam.Caller is optional — don't copy it
|
||||||
|
assistantContent.Add(new ToolUseBlockParam
|
||||||
|
{
|
||||||
|
ID = toolUse.ID,
|
||||||
|
Name = toolUse.Name,
|
||||||
|
Input = toolUse.Input,
|
||||||
|
});
|
||||||
|
// Execute the tool; collect ONE result per tool_use block — the API
|
||||||
|
// rejects the follow-up if any tool_use ID lacks a matching tool_result.
|
||||||
|
string result = ExecuteYourTool(toolUse.Name, toolUse.Input);
|
||||||
|
toolResults.Add(new ToolResultBlockParam
|
||||||
|
{
|
||||||
|
ToolUseID = toolUse.ID,
|
||||||
|
Content = result,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Follow-up: prior messages + assistant echo + user tool_result(s)
|
||||||
|
List<MessageParam> followUpMessages =
|
||||||
|
[
|
||||||
|
.. parameters.Messages,
|
||||||
|
new() { Role = Role.Assistant, Content = assistantContent },
|
||||||
|
new() { Role = Role.User, Content = toolResults },
|
||||||
|
];
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`ToolResultBlockParam\` has no tuple constructor — use the object initializer. \`Content\` is a string-or-list union; a plain \`string\` implicitly converts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context Editing / Compaction (Beta)
|
||||||
|
|
||||||
|
**Beta-namespace prefix is inconsistent** (source-verified against \`src/Anthropic/Models/Beta/Messages/*.cs\` @ 12.8.0). No prefix: \`MessageCreateParams\`, \`MessageCountTokensParams\`, \`Role\`. **Everything else has the \`Beta\` prefix**: \`BetaMessageParam\`, \`BetaMessage\`, \`BetaContentBlock\`, \`BetaToolUseBlock\`, all block param types. The unprefixed \`Role\` WILL collide with \`Anthropic.Models.Messages.Role\` if you import both namespaces (CS0104). Safest: import only Beta; if mixing, alias the beta \`Role\`:
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using Anthropic.Models.Beta.Messages;
|
||||||
|
using NonBeta = Anthropic.Models.Messages; // only if you also need non-beta types
|
||||||
|
// Now: MessageCreateParams, BetaMessageParam, Role (beta's), NonBeta.Role (if needed)
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
|
||||||
|
\`BetaMessage.Content\` is \`IReadOnlyList<BetaContentBlock>\` — a 15-variant discriminated union. Narrow with \`TryPick*\`. **Response \`BetaContentBlock\` is NOT assignable to param \`BetaContentBlockParam\`** — there's no \`.ToParam()\` in C#. Round-trip by converting each block:
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using Anthropic.Models.Beta.Messages;
|
||||||
|
|
||||||
|
var betaParams = new MessageCreateParams // no Beta prefix — one of only 2 unprefixed
|
||||||
|
{
|
||||||
|
Model = Model.ClaudeOpus4_6,
|
||||||
|
MaxTokens = 1024,
|
||||||
|
Betas = ["compact-2026-01-12"],
|
||||||
|
ContextManagement = new BetaContextManagementConfig
|
||||||
|
{
|
||||||
|
Edits = [new BetaCompact20260112Edit()],
|
||||||
|
},
|
||||||
|
Messages = messages,
|
||||||
|
};
|
||||||
|
BetaMessage resp = await client.Beta.Messages.Create(betaParams);
|
||||||
|
|
||||||
|
foreach (BetaContentBlock block in resp.Content)
|
||||||
|
{
|
||||||
|
if (block.TryPickCompaction(out BetaCompactionBlock? compaction))
|
||||||
|
{
|
||||||
|
// Content is nullable — compaction can fail server-side
|
||||||
|
Console.WriteLine($"compaction summary: {compaction.Content}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Context-edit metadata lives on a separate nullable field
|
||||||
|
if (resp.ContextManagement is { } ctx)
|
||||||
|
{
|
||||||
|
foreach (var edit in ctx.AppliedEdits)
|
||||||
|
Console.WriteLine($"cleared {edit.ClearedInputTokens} tokens");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ROUND-TRIP: BetaMessageParam.Content is BetaMessageParamContent (a string|list
|
||||||
|
// union). It implicit-converts from List<BetaContentBlockParam>, NOT from the
|
||||||
|
// response's IReadOnlyList<BetaContentBlock>. Convert each block:
|
||||||
|
List<BetaContentBlockParam> paramBlocks = [];
|
||||||
|
foreach (var b in resp.Content)
|
||||||
|
{
|
||||||
|
if (b.TryPickText(out var t)) paramBlocks.Add(new BetaTextBlockParam { Text = t.Text });
|
||||||
|
else if (b.TryPickCompaction(out var c)) paramBlocks.Add(new BetaCompactionBlockParam { Content = c.Content });
|
||||||
|
// ... other variants as needed
|
||||||
|
}
|
||||||
|
messages.Add(new BetaMessageParam { Role = Role.Assistant, Content = paramBlocks });
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
All 15 \`BetaContentBlock.TryPick*\` variants: \`Text\`, \`Thinking\`, \`RedactedThinking\`, \`ToolUse\`, \`ServerToolUse\`, \`WebSearchToolResult\`, \`WebFetchToolResult\`, \`CodeExecutionToolResult\`, \`BashCodeExecutionToolResult\`, \`TextEditorCodeExecutionToolResult\`, \`ToolSearchToolResult\`, \`McpToolUse\`, \`McpToolResult\`, \`ContainerUpload\`, \`Compaction\`.
|
||||||
|
|
||||||
|
**\`BetaToolUseBlock.Input\` is \`IReadOnlyDictionary<string, JsonElement>\`** — index by key then call the \`JsonElement\` extractor:
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
if (block.TryPickToolUse(out BetaToolUseBlock? tu))
|
||||||
|
{
|
||||||
|
int a = tu.Input["a"].GetInt32();
|
||||||
|
string s = tu.Input["name"].GetString()!;
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Effort Parameter
|
||||||
|
|
||||||
|
Effort is nested under \`OutputConfig\`, NOT a top-level property. \`ApiEnum<string, Effort>\` has an implicit conversion from the enum, so assign \`Effort.High\` directly.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
OutputConfig = new OutputConfig { Effort = Effort.High },
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Values: \`Effort.Low\`, \`Effort.Medium\`, \`Effort.High\`, \`Effort.Max\`. Combine with \`Thinking = new ThinkingConfigAdaptive()\` for cost-quality control.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prompt Caching
|
||||||
|
|
||||||
|
\`System\` takes \`MessageCreateParamsSystem?\` — a union of \`string\` or \`List<TextBlockParam>\`. There is no \`SystemTextBlockParam\`; use plain \`TextBlockParam\`. The implicit conversion needs the concrete \`List<TextBlockParam>\` type (array literals won't convert).
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
System = new List<TextBlockParam> {
|
||||||
|
new() {
|
||||||
|
Text = longSystemPrompt,
|
||||||
|
CacheControl = new CacheControlEphemeral(), // auto-sets Type = "ephemeral"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Optional \`Ttl\` on \`CacheControlEphemeral\`: \`new() { Ttl = Ttl.Ttl1h }\` or \`Ttl.Ttl5m\`. \`CacheControl\` also exists on \`Tool.CacheControl\` and top-level \`MessageCreateParams.CacheControl\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Token Counting
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
MessageTokensCount result = await client.Messages.CountTokens(new MessageCountTokensParams {
|
||||||
|
Model = Model.ClaudeOpus4_6,
|
||||||
|
Messages = [new() { Role = Role.User, Content = "Hello" }],
|
||||||
|
});
|
||||||
|
long tokens = result.InputTokens;
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`MessageCountTokensParams.Tools\` uses a different union type (\`MessageCountTokensTool\`) than \`MessageCreateParams.Tools\` (\`ToolUnion\`) — if you're passing tools, the compiler will tell you when it matters.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Structured Output
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
OutputConfig = new OutputConfig {
|
||||||
|
Format = new JsonOutputFormat {
|
||||||
|
Schema = new Dictionary<string, JsonElement> {
|
||||||
|
["type"] = JsonSerializer.SerializeToElement("object"),
|
||||||
|
["properties"] = JsonSerializer.SerializeToElement(
|
||||||
|
new { name = new { type = "string" } }),
|
||||||
|
["required"] = JsonSerializer.SerializeToElement(new[] { "name" }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`JsonOutputFormat.Type\` is auto-set to \`"json_schema"\` by the constructor. \`Schema\` is \`required\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PDF / Document Input
|
||||||
|
|
||||||
|
\`DocumentBlockParam\` takes a \`DocumentBlockParamSource\` union: \`Base64PdfSource\` / \`UrlPdfSource\` / \`PlainTextSource\` / \`ContentBlockSource\`. \`Base64PdfSource\` auto-sets \`MediaType = "application/pdf"\` and \`Type = "base64"\`.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
new MessageParam {
|
||||||
|
Role = Role.User,
|
||||||
|
Content = new List<ContentBlockParam> {
|
||||||
|
new DocumentBlockParam { Source = new Base64PdfSource { Data = base64String } },
|
||||||
|
new TextBlockParam { Text = "Summarize this PDF" },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Server-Side Tools
|
||||||
|
|
||||||
|
Web search, bash, text editor, and code execution are built-in server tools. Type names are version-suffixed; constructors auto-set \`name\`/\`type\`. All implicit-convert to \`ToolUnion\`.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
Tools = [
|
||||||
|
new WebSearchTool20260209(),
|
||||||
|
new ToolBash20250124(),
|
||||||
|
new ToolTextEditor20250728(),
|
||||||
|
new CodeExecutionTool20260120(),
|
||||||
|
],
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Also available: \`WebFetchTool20260209\`, \`MemoryTool20250818\`. \`WebSearchTool20260209\` optionals: \`AllowedDomains\`, \`BlockedDomains\`, \`MaxUses\`, \`UserLocation\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files API (Beta)
|
||||||
|
|
||||||
|
Files live under \`client.Beta.Files\` (namespace \`Anthropic.Models.Beta.Files\`). \`BinaryContent\` implicit-converts from \`Stream\` and \`byte[]\`.
|
||||||
|
|
||||||
|
\`\`\`csharp
|
||||||
|
using Anthropic.Models.Beta.Files;
|
||||||
|
using Anthropic.Models.Beta.Messages;
|
||||||
|
|
||||||
|
FileMetadata meta = await client.Beta.Files.Upload(
|
||||||
|
new FileUploadParams { File = File.OpenRead("doc.pdf") });
|
||||||
|
|
||||||
|
// Referencing the uploaded file requires Beta message types:
|
||||||
|
new BetaRequestDocumentBlock {
|
||||||
|
Source = new BetaFileDocumentSource { FileID = meta.ID },
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
The non-beta \`DocumentBlockParamSource\` union has no file-ID variant — file references need \`client.Beta.Messages.Create()\`.
|
||||||
|
|||||||
198
system-prompts/data-claude-api-reference-curl.md
Normal file
198
system-prompts/data-claude-api-reference-curl.md
Normal file
@ -0,0 +1,198 @@
|
|||||||
|
<!--
|
||||||
|
name: 'Data: Claude API reference — cURL'
|
||||||
|
description: Raw API reference for Claude API for use with cURL or else Raw HTTP
|
||||||
|
ccVersion: 2.1.73
|
||||||
|
-->
|
||||||
|
# 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": "{{OPUS_ID}}",
|
||||||
|
"max_tokens": 1024,
|
||||||
|
"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":"{{OPUS_ID}}","max_tokens":1024,"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": "{{OPUS_ID}}",
|
||||||
|
"max_tokens": 1024,
|
||||||
|
"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": "{{OPUS_ID}}",
|
||||||
|
"max_tokens": 1024,
|
||||||
|
"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": "{{OPUS_ID}}",
|
||||||
|
"max_tokens": 1024,
|
||||||
|
"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"}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extended Thinking
|
||||||
|
|
||||||
|
> **Opus 4.6 and Sonnet 4.6:** Use adaptive thinking. \`budget_tokens\` is deprecated on both Opus 4.6 and Sonnet 4.6.
|
||||||
|
> **Older models:** Use \`"type": "enabled"\` with \`"budget_tokens": N\` (must be < \`max_tokens\`, min 1024).
|
||||||
|
|
||||||
|
\`\`\`bash
|
||||||
|
# Opus 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": "{{OPUS_ID}}",
|
||||||
|
"max_tokens": 16000,
|
||||||
|
"thinking": {
|
||||||
|
"type": "adaptive"
|
||||||
|
},
|
||||||
|
"output_config": {
|
||||||
|
"effort": "high"
|
||||||
|
},
|
||||||
|
"messages": [{"role": "user", "content": "Solve this step by step..."}]
|
||||||
|
}'
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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 |
|
||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — Go'
|
name: 'Data: Claude API reference — Go'
|
||||||
description: Go SDK reference
|
description: Go SDK reference
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — Go
|
# Claude API — Go
|
||||||
|
|
||||||
@ -81,6 +81,19 @@ if err := stream.Err(); err != nil {
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
|
**Accumulating the final message** (there is no \`GetFinalMessage()\` on the stream):
|
||||||
|
|
||||||
|
\`\`\`go
|
||||||
|
stream := client.Messages.NewStreaming(ctx, params)
|
||||||
|
message := anthropic.Message{}
|
||||||
|
for stream.Next() {
|
||||||
|
message.Accumulate(stream.Current())
|
||||||
|
}
|
||||||
|
if err := stream.Err(); err != nil { log.Fatal(err) }
|
||||||
|
// message.Content now has the complete response
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Tool Use
|
## Tool Use
|
||||||
@ -140,7 +153,16 @@ message, err := runner.RunToCompletion(context.Background())
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
fmt.Println(message.Content[0].Text)
|
|
||||||
|
// RunToCompletion returns *BetaMessage; content is []BetaContentBlockUnion.
|
||||||
|
// Narrow via AsAny() switch — note the Beta-namespace types (BetaTextBlock,
|
||||||
|
// not TextBlock):
|
||||||
|
for _, block := range message.Content {
|
||||||
|
switch block := block.AsAny().(type) {
|
||||||
|
case anthropic.BetaTextBlock:
|
||||||
|
fmt.Println(block.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
**Key features of the Go tool runner:**
|
**Key features of the Go tool runner:**
|
||||||
@ -255,36 +277,133 @@ func main() {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Extended Thinking
|
## Thinking
|
||||||
|
|
||||||
Enable Claude's internal reasoning by setting \`Thinking\` in \`MessageNewParams\`. The response will contain \`ThinkingBlock\` content before the final \`TextBlock\`.
|
Enable Claude's internal reasoning by setting \`Thinking\` in \`MessageNewParams\`. The response will contain \`ThinkingBlock\` content before the final \`TextBlock\`.
|
||||||
|
|
||||||
Derived from \`anthropic-sdk-go/message.go:6316\` (\`ThinkingConfigParamOfEnabled\`).
|
**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think. Combine with the \`effort\` parameter for cost-quality control.
|
||||||
|
|
||||||
|
Derived from \`anthropic-sdk-go/message.go\` (\`ThinkingConfigParamUnion\`, \`NewThinkingConfigAdaptiveParam\`).
|
||||||
|
|
||||||
\`\`\`go
|
\`\`\`go
|
||||||
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
|
// There is no ThinkingConfigParamOfAdaptive helper — construct the union
|
||||||
|
// struct-literal directly and take the address of the variant.
|
||||||
|
adaptive := anthropic.NewThinkingConfigAdaptiveParam()
|
||||||
|
params := anthropic.MessageNewParams{
|
||||||
Model: anthropic.ModelClaudeSonnet4_6,
|
Model: anthropic.ModelClaudeSonnet4_6,
|
||||||
MaxTokens: 16000, // must be > budget_tokens
|
MaxTokens: 16000,
|
||||||
// ThinkingConfigParamOfEnabled(budgetTokens) is the helper constructor.
|
Thinking: anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive},
|
||||||
// budgetTokens must be >= 1024 and < MaxTokens.
|
|
||||||
Thinking: anthropic.ThinkingConfigParamOfEnabled(5000),
|
|
||||||
Messages: []anthropic.MessageParam{
|
Messages: []anthropic.MessageParam{
|
||||||
anthropic.NewUserMessage(anthropic.NewTextBlock("How many r's in strawberry?")),
|
anthropic.NewUserMessage(anthropic.NewTextBlock("How many r's in strawberry?")),
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
|
|
||||||
|
resp, err := client.Messages.New(context.Background(), params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Thinking blocks come before text blocks in Content
|
// ThinkingBlock(s) precede TextBlock in content
|
||||||
for _, block := range resp.Content {
|
for _, block := range resp.Content {
|
||||||
switch variant := block.AsAny().(type) {
|
switch b := block.AsAny().(type) {
|
||||||
case anthropic.ThinkingBlock:
|
case anthropic.ThinkingBlock:
|
||||||
fmt.Println("[thinking]", variant.Thinking)
|
fmt.Println("[thinking]", b.Thinking)
|
||||||
case anthropic.TextBlock:
|
case anthropic.TextBlock:
|
||||||
fmt.Println("[response]", variant.Text)
|
fmt.Println(b.Text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
To disable: \`anthropic.NewThinkingConfigDisabledParam()\`. For adaptive thinking (model decides budget): \`anthropic.NewThinkingConfigAdaptiveParam()\`.
|
> **Deprecated:** \`ThinkingConfigParamOfEnabled(budgetTokens)\` (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.
|
||||||
|
|
||||||
|
To disable: \`anthropic.ThinkingConfigParamUnion{OfDisabled: &anthropic.ThinkingConfigDisabledParam{}}\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Server-Side Tools
|
||||||
|
|
||||||
|
Version-suffixed struct names with \`Param\` suffix. \`Name\`/\`Type\` are \`constant.*\` types — zero value marshals correctly, so \`{}\` works. Wrap in \`ToolUnionParam\` with the matching \`Of*\` field.
|
||||||
|
|
||||||
|
\`\`\`go
|
||||||
|
Tools: []anthropic.ToolUnionParam{
|
||||||
|
{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},
|
||||||
|
{OfBashTool20250124: &anthropic.ToolBash20250124Param{}},
|
||||||
|
{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
|
||||||
|
{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
|
||||||
|
},
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Also available: \`WebFetchTool20260209Param\`, \`MemoryTool20250818Param\`, \`ToolSearchToolBm25_20251119Param\`, \`ToolSearchToolRegex20251119Param\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PDF / Document Input
|
||||||
|
|
||||||
|
\`NewDocumentBlock\` generic helper accepts any source type. \`MediaType\`/\`Type\` are auto-set.
|
||||||
|
|
||||||
|
\`\`\`go
|
||||||
|
b64 := base64.StdEncoding.EncodeToString(pdfBytes)
|
||||||
|
|
||||||
|
msg := anthropic.NewUserMessage(
|
||||||
|
anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: b64}),
|
||||||
|
anthropic.NewTextBlock("Summarize this document"),
|
||||||
|
)
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Other sources: \`URLPDFSourceParam{URL: "https://..."}\`, \`PlainTextSourceParam{Data: "..."}\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files API (Beta)
|
||||||
|
|
||||||
|
Under \`client.Beta.Files\`. Method is **\`Upload\`** (NOT \`New\`/\`Create\`), params struct is \`BetaFileUploadParams\`. The \`File\` field takes an \`io.Reader\`; use \`anthropic.File()\` to attach a filename + content-type for the multipart encoding.
|
||||||
|
|
||||||
|
\`\`\`go
|
||||||
|
f, _ := os.Open("./upload_me.txt")
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
meta, err := client.Beta.Files.Upload(ctx, anthropic.BetaFileUploadParams{
|
||||||
|
File: anthropic.File(f, "upload_me.txt", "text/plain"),
|
||||||
|
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14},
|
||||||
|
})
|
||||||
|
// meta.ID is the file_id to reference in subsequent message requests
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Other \`Beta.Files\` methods: \`List\`, \`Delete\`, \`Download\`, \`GetMetadata\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context Editing / Compaction (Beta)
|
||||||
|
|
||||||
|
Use \`Beta.Messages.New\` with \`ContextManagement\` on \`BetaMessageNewParams\`. There is no \`NewBetaAssistantMessage\` — use \`.ToParam()\` for the round-trip.
|
||||||
|
|
||||||
|
\`\`\`go
|
||||||
|
params := anthropic.BetaMessageNewParams{
|
||||||
|
Model: anthropic.ModelClaudeOpus4_6, // also supported: ModelClaudeSonnet4_6
|
||||||
|
MaxTokens: 1024,
|
||||||
|
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
|
||||||
|
ContextManagement: anthropic.BetaContextManagementConfigParam{
|
||||||
|
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
|
||||||
|
{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Messages: []anthropic.BetaMessageParam{ /* ... */ },
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := client.Beta.Messages.New(ctx, params)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Round-trip: append response to history via .ToParam()
|
||||||
|
params.Messages = append(params.Messages, resp.ToParam())
|
||||||
|
|
||||||
|
// Read compaction blocks from the response
|
||||||
|
for _, block := range resp.Content {
|
||||||
|
if c, ok := block.AsAny().(anthropic.BetaCompactionBlock); ok {
|
||||||
|
fmt.Println("compaction summary:", c.Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Other edit types: \`BetaClearToolUses20250919EditParam\`, \`BetaClearThinking20251015EditParam\`.
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — Java'
|
name: 'Data: Claude API reference — Java'
|
||||||
description: Java SDK reference including installation, client initialization, basic requests, streaming, and beta tool use
|
description: Java SDK reference including installation, client initialization, basic requests, streaming, and beta tool use
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — Java
|
# Claude API — Java
|
||||||
|
|
||||||
@ -85,6 +85,35 @@ try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().cr
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Thinking
|
||||||
|
|
||||||
|
**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think. The builder has a direct \`.thinking(ThinkingConfigAdaptive)\` overload — no manual union wrapping.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.ContentBlock;
|
||||||
|
import com.anthropic.models.messages.MessageCreateParams;
|
||||||
|
import com.anthropic.models.messages.Model;
|
||||||
|
import com.anthropic.models.messages.ThinkingConfigAdaptive;
|
||||||
|
|
||||||
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
|
.model(Model.CLAUDE_SONNET_4_6)
|
||||||
|
.maxTokens(16000L)
|
||||||
|
.thinking(ThinkingConfigAdaptive.builder().build())
|
||||||
|
.addUserMessage("Solve this step by step: 27 * 453")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
for (ContentBlock block : client.messages().create(params).content()) {
|
||||||
|
block.thinking().ifPresent(t -> System.out.println("[thinking] " + t.thinking()));
|
||||||
|
block.text().ifPresent(t -> System.out.println(t.text()));
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
> **Deprecated:** \`ThinkingConfigEnabled.builder().budgetTokens(N)\` (and the \`.enabledThinking(N)\` shortcut) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.
|
||||||
|
|
||||||
|
\`ContentBlock\` narrowing: \`.thinking()\` / \`.text()\` return \`Optional<T>\` — use \`.ifPresent(...)\` or \`.stream().flatMap(...)\`. Alternative: \`isThinking()\` / \`asThinking()\` boolean+unwrap pairs (throws on wrong variant).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Tool Use (Beta)
|
## Tool Use (Beta)
|
||||||
|
|
||||||
The Java SDK supports beta tool use with annotated classes. Tool classes implement \`Supplier<String>\` for automatic execution via \`BetaToolRunner\`.
|
The Java SDK supports beta tool use with annotated classes. Tool classes implement \`Supplier<String>\` for automatic execution via \`BetaToolRunner\`.
|
||||||
@ -124,10 +153,248 @@ for (BetaMessage message : toolRunner) {
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Non-Beta Tool Use
|
### Non-Beta Tool Declaration (manual JSON schema)
|
||||||
|
|
||||||
Tool use is also available through the non-beta \`com.anthropic.models.messages.MessageCreateParams\` with \`addTool(Tool)\` for manually defined JSON schemas, without needing the beta namespace. The beta namespace is only needed for the class-annotation convenience layer (\`@JsonClassDescription\`, \`BetaToolRunner\`).
|
\`Tool.InputSchema.Properties\` is a freeform \`Map<String, JsonValue>\` wrapper — build property schemas via \`putAdditionalProperty\`. \`type: "object"\` is the default. The builder has a direct \`.addTool(Tool)\` overload that wraps in \`ToolUnion\` automatically.
|
||||||
|
|
||||||
### Manual Loop
|
\`\`\`java
|
||||||
|
import com.anthropic.core.JsonValue;
|
||||||
|
import com.anthropic.models.messages.Tool;
|
||||||
|
|
||||||
For manual tool loops, define tools as JSON schema in the request, handle \`tool_use\` blocks in the response, send \`tool_result\` back, and loop until \`stop_reason\` is \`"end_turn"\`. See the [shared tool use concepts](../shared/tool-use-concepts.md) for the agentic loop pattern.
|
Tool tool = Tool.builder()
|
||||||
|
.name("get_weather")
|
||||||
|
.description("Get the current weather in a given location")
|
||||||
|
.inputSchema(Tool.InputSchema.builder()
|
||||||
|
.properties(Tool.InputSchema.Properties.builder()
|
||||||
|
.putAdditionalProperty("location", JsonValue.from(Map.of("type", "string")))
|
||||||
|
.build())
|
||||||
|
.required(List.of("location"))
|
||||||
|
.build())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
|
.model(Model.CLAUDE_SONNET_4_6)
|
||||||
|
.maxTokens(1024L)
|
||||||
|
.addTool(tool)
|
||||||
|
.addUserMessage("Weather in Paris?")
|
||||||
|
.build();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
For manual tool loops, handle \`tool_use\` blocks in the response, send \`tool_result\` back, loop until \`stop_reason\` is \`"end_turn"\`. See [shared tool use concepts](../shared/tool-use-concepts.md).
|
||||||
|
|
||||||
|
### Building \`MessageParam\` with Content Blocks (Tool Result Round-Trip)
|
||||||
|
|
||||||
|
\`MessageParam.Content\` is an inner union class (string | list). Use the builder's \`.contentOfBlockParams(List<ContentBlockParam>)\` alias — there is NO separate \`MessageParamContent\` class with a static \`ofBlockParams\`:
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.MessageParam;
|
||||||
|
import com.anthropic.models.messages.ContentBlockParam;
|
||||||
|
import com.anthropic.models.messages.ToolResultBlockParam;
|
||||||
|
|
||||||
|
List<ContentBlockParam> results = List.of(
|
||||||
|
ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
|
||||||
|
.toolUseId(toolUseBlock.id())
|
||||||
|
.content(yourResultString)
|
||||||
|
.build())
|
||||||
|
);
|
||||||
|
|
||||||
|
MessageParam toolResultMsg = MessageParam.builder()
|
||||||
|
.role(MessageParam.Role.USER)
|
||||||
|
.contentOfBlockParams(results) // builder alias for Content.ofBlockParams(...)
|
||||||
|
.build();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Effort Parameter
|
||||||
|
|
||||||
|
Effort is nested inside \`OutputConfig\` — there is NO \`.effort()\` directly on \`MessageCreateParams.Builder\`.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.OutputConfig;
|
||||||
|
|
||||||
|
.outputConfig(OutputConfig.builder()
|
||||||
|
.effort(OutputConfig.Effort.HIGH) // or LOW, MEDIUM, MAX
|
||||||
|
.build())
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Combine with \`Thinking = ThinkingConfigAdaptive\` for cost-quality control.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prompt Caching
|
||||||
|
|
||||||
|
System message as a list of \`TextBlockParam\` with \`CacheControlEphemeral\`. Use \`.systemOfTextBlockParams(...)\` — the plain \`.system(String)\` overload can't carry cache control.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.TextBlockParam;
|
||||||
|
import com.anthropic.models.messages.CacheControlEphemeral;
|
||||||
|
|
||||||
|
.systemOfTextBlockParams(List.of(
|
||||||
|
TextBlockParam.builder()
|
||||||
|
.text(longSystemPrompt)
|
||||||
|
.cacheControl(CacheControlEphemeral.builder()
|
||||||
|
.ttl(CacheControlEphemeral.Ttl.TTL_1H) // optional; also TTL_5M
|
||||||
|
.build())
|
||||||
|
.build()))
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
There's also a top-level \`.cacheControl(CacheControlEphemeral)\` on \`MessageCreateParams.Builder\` and on \`Tool.builder()\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Token Counting
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.MessageCountTokensParams;
|
||||||
|
|
||||||
|
long tokens = client.messages().countTokens(
|
||||||
|
MessageCountTokensParams.builder()
|
||||||
|
.model(Model.CLAUDE_SONNET_4_6)
|
||||||
|
.addUserMessage("Hello")
|
||||||
|
.build()
|
||||||
|
).inputTokens();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Structured Output
|
||||||
|
|
||||||
|
The class-based overload auto-derives the JSON schema from your POJO and gives you a typed \`.text()\` return — no manual schema, no manual parsing.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.StructuredMessageCreateParams;
|
||||||
|
|
||||||
|
record Book(String title, String author) {}
|
||||||
|
record BookList(List<Book> books) {}
|
||||||
|
|
||||||
|
StructuredMessageCreateParams<BookList> params = MessageCreateParams.builder()
|
||||||
|
.model(Model.CLAUDE_SONNET_4_6)
|
||||||
|
.maxTokens(2048L)
|
||||||
|
.outputConfig(BookList.class) // returns a typed builder
|
||||||
|
.addUserMessage("List 3 classic novels")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
client.messages().create(params).content().stream()
|
||||||
|
.flatMap(cb -> cb.text().stream())
|
||||||
|
.forEach(typed -> {
|
||||||
|
// typed.text() returns BookList, not String
|
||||||
|
for (Book b : typed.text().books()) System.out.println(b.title());
|
||||||
|
});
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Supports Jackson annotations: \`@JsonPropertyDescription\`, \`@JsonIgnore\`, \`@ArraySchema(minItems=...)\`. Manual schema path: \`OutputConfig.builder().format(JsonOutputFormat.builder().schema(...).build())\`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PDF / Document Input
|
||||||
|
|
||||||
|
\`DocumentBlockParam\` builder has source shortcuts. Wrap in \`ContentBlockParam.ofDocument()\` and pass via \`.addUserMessageOfBlockParams()\`.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.DocumentBlockParam;
|
||||||
|
import com.anthropic.models.messages.ContentBlockParam;
|
||||||
|
import com.anthropic.models.messages.TextBlockParam;
|
||||||
|
|
||||||
|
DocumentBlockParam doc = DocumentBlockParam.builder()
|
||||||
|
.base64Source(base64String) // or .urlSource("https://...") or .textSource("...")
|
||||||
|
.title("My Document") // optional
|
||||||
|
.build();
|
||||||
|
|
||||||
|
.addUserMessageOfBlockParams(List.of(
|
||||||
|
ContentBlockParam.ofDocument(doc),
|
||||||
|
ContentBlockParam.ofText(TextBlockParam.builder().text("Summarize this").build())))
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Server-Side Tools
|
||||||
|
|
||||||
|
Version-suffixed types; \`name\`/\`type\` auto-set by builder. Direct \`.addTool()\` overloads exist for every type — no manual \`ToolUnion\` wrapping.
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.messages.WebSearchTool20260209;
|
||||||
|
import com.anthropic.models.messages.ToolBash20250124;
|
||||||
|
import com.anthropic.models.messages.ToolTextEditor20250728;
|
||||||
|
import com.anthropic.models.messages.CodeExecutionTool20260120;
|
||||||
|
|
||||||
|
.addTool(WebSearchTool20260209.builder()
|
||||||
|
.maxUses(5L) // optional
|
||||||
|
.allowedDomains(List.of("example.com")) // optional
|
||||||
|
.build())
|
||||||
|
.addTool(ToolBash20250124.builder().build())
|
||||||
|
.addTool(ToolTextEditor20250728.builder().build())
|
||||||
|
.addTool(CodeExecutionTool20260120.builder().build())
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Also available: \`WebFetchTool20260209\`, \`MemoryTool20250818\`, \`ToolSearchToolBm25_20251119\`.
|
||||||
|
|
||||||
|
### Beta namespace (MCP, compaction)
|
||||||
|
|
||||||
|
For beta-only features use \`com.anthropic.models.beta.messages.*\` — class names have a \`Beta\` prefix AND live in the beta package. The beta \`MessageCreateParams.Builder\` has direct \`.addTool(BetaToolBash20250124)\` overloads AND \`.addMcpServer()\`:
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.beta.messages.MessageCreateParams;
|
||||||
|
import com.anthropic.models.beta.messages.BetaToolBash20250124;
|
||||||
|
import com.anthropic.models.beta.messages.BetaCodeExecutionTool20260120;
|
||||||
|
import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;
|
||||||
|
|
||||||
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
|
.model(Model.CLAUDE_OPUS_4_6)
|
||||||
|
.maxTokens(1024L)
|
||||||
|
.addBeta("mcp-client-2025-11-20")
|
||||||
|
.addTool(BetaToolBash20250124.builder().build())
|
||||||
|
.addTool(BetaCodeExecutionTool20260120.builder().build())
|
||||||
|
.addMcpServer(BetaRequestMcpServerUrlDefinition.builder()
|
||||||
|
.name("my-server")
|
||||||
|
.url("https://example.com/mcp")
|
||||||
|
.build())
|
||||||
|
.addUserMessage("...")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
client.beta().messages().create(params);
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`BetaTool*\` types are NOT interchangeable with non-beta \`Tool*\` — pick one namespace per request.
|
||||||
|
|
||||||
|
**Reading server-tool blocks in the response:** \`ServerToolUseBlock\` has \`.id()\`, \`.name()\` (enum), and \`._input()\` returning raw \`JsonValue\` — there is NO typed \`.input()\`. For code execution results, unwrap two levels:
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
for (ContentBlock block : response.content()) {
|
||||||
|
block.serverToolUse().ifPresent(stu -> {
|
||||||
|
System.out.println("tool: " + stu.name() + " input: " + stu._input());
|
||||||
|
});
|
||||||
|
block.codeExecutionToolResult().ifPresent(r -> {
|
||||||
|
r.content().resultBlock().ifPresent(result -> {
|
||||||
|
System.out.println("stdout: " + result.stdout());
|
||||||
|
System.out.println("stderr: " + result.stderr());
|
||||||
|
System.out.println("exit: " + result.returnCode());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files API (Beta)
|
||||||
|
|
||||||
|
Under \`client.beta().files()\`. File references in messages need the beta message types (non-beta \`DocumentBlockParam.Source\` has no file-ID variant).
|
||||||
|
|
||||||
|
\`\`\`java
|
||||||
|
import com.anthropic.models.beta.files.FileUploadParams;
|
||||||
|
import com.anthropic.models.beta.files.FileMetadata;
|
||||||
|
import com.anthropic.models.beta.messages.BetaRequestDocumentBlock;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
FileMetadata meta = client.beta().files().upload(
|
||||||
|
FileUploadParams.builder()
|
||||||
|
.file(Paths.get("/path/to/doc.pdf")) // or .file(InputStream) or .file(byte[])
|
||||||
|
.build());
|
||||||
|
|
||||||
|
// Reference in a beta message:
|
||||||
|
BetaRequestDocumentBlock doc = BetaRequestDocumentBlock.builder()
|
||||||
|
.fileSource(meta.id())
|
||||||
|
.build();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Other methods: \`.list()\`, \`.delete(String fileId)\`, \`.download(String fileId)\`, \`.retrieveMetadata(String fileId)\`.
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — PHP'
|
name: 'Data: Claude API reference — PHP'
|
||||||
description: PHP SDK reference
|
description: PHP SDK reference
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — PHP
|
# Claude API — PHP
|
||||||
|
|
||||||
@ -25,20 +25,20 @@ $client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
|
|||||||
### Amazon Bedrock
|
### Amazon Bedrock
|
||||||
|
|
||||||
\`\`\`php
|
\`\`\`php
|
||||||
use Anthropic\\BedrockClient;
|
use Anthropic\\Bedrock;
|
||||||
|
|
||||||
$client = new BedrockClient(
|
// Constructor is private — use the static factory. Reads AWS credentials from env.
|
||||||
region: 'us-east-1',
|
$client = Bedrock\\Client::fromEnvironment(region: 'us-east-1');
|
||||||
);
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Google Vertex AI
|
### Google Vertex AI
|
||||||
|
|
||||||
\`\`\`php
|
\`\`\`php
|
||||||
use Anthropic\\VertexClient;
|
use Anthropic\\Vertex;
|
||||||
|
|
||||||
$client = new VertexClient(
|
// Constructor is private. Parameter is \`location\`, not \`region\`.
|
||||||
region: 'us-east5',
|
$client = Vertex\\Client::fromEnvironment(
|
||||||
|
location: 'us-east5',
|
||||||
projectId: 'my-project-id',
|
projectId: 'my-project-id',
|
||||||
);
|
);
|
||||||
\`\`\`
|
\`\`\`
|
||||||
@ -46,10 +46,12 @@ $client = new VertexClient(
|
|||||||
### Anthropic Foundry
|
### Anthropic Foundry
|
||||||
|
|
||||||
\`\`\`php
|
\`\`\`php
|
||||||
use Anthropic\\FoundryClient;
|
use Anthropic\\Foundry;
|
||||||
|
|
||||||
$client = new FoundryClient(
|
// Constructor is private. baseUrl or resource is required.
|
||||||
authToken: getenv("ANTHROPIC_AUTH_TOKEN"),
|
$client = Foundry\\Client::withCredentials(
|
||||||
|
authToken: getenv('ANTHROPIC_FOUNDRY_AUTH_TOKEN'),
|
||||||
|
baseUrl: 'https://<resource>.services.ai.azure.com/anthropic',
|
||||||
);
|
);
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
@ -65,14 +67,39 @@ $message = $client->messages->create(
|
|||||||
['role' => 'user', 'content' => 'What is the capital of France?'],
|
['role' => 'user', 'content' => 'What is the capital of France?'],
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
echo $message->content[0]->text;
|
|
||||||
|
// content is an array of polymorphic blocks (TextBlock, ToolUseBlock,
|
||||||
|
// ThinkingBlock). Accessing ->text on content[0] without checking the block
|
||||||
|
// type will throw if the first block is not a TextBlock (e.g., when extended
|
||||||
|
// thinking is enabled and a ThinkingBlock comes first). Always guard:
|
||||||
|
foreach ($message->content as $block) {
|
||||||
|
if ($block->type === 'text') {
|
||||||
|
echo $block->text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
If you only want the first text block:
|
||||||
|
|
||||||
|
\`\`\`php
|
||||||
|
foreach ($message->content as $block) {
|
||||||
|
if ($block->type === 'text') {
|
||||||
|
echo $block->text;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Streaming
|
## Streaming
|
||||||
|
|
||||||
|
> **Requires SDK v0.5.0+.** v0.4.0 and earlier used a single \`$params\` array; calling with named parameters throws \`Unknown named parameter $model\`. Upgrade: \`composer require "anthropic-ai/sdk:^0.6"\`
|
||||||
|
|
||||||
\`\`\`php
|
\`\`\`php
|
||||||
|
use Anthropic\\Messages\\RawContentBlockDeltaEvent;
|
||||||
|
use Anthropic\\Messages\\TextDelta;
|
||||||
|
|
||||||
$stream = $client->messages->createStream(
|
$stream = $client->messages->createStream(
|
||||||
model: '{{OPUS_ID}}',
|
model: '{{OPUS_ID}}',
|
||||||
maxTokens: 1024,
|
maxTokens: 1024,
|
||||||
@ -82,7 +109,9 @@ $stream = $client->messages->createStream(
|
|||||||
);
|
);
|
||||||
|
|
||||||
foreach ($stream as $event) {
|
foreach ($stream as $event) {
|
||||||
echo $event;
|
if ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) {
|
||||||
|
echo $event->delta->text;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
@ -90,4 +119,128 @@ foreach ($stream as $event) {
|
|||||||
|
|
||||||
## Tool Use (Manual Loop)
|
## Tool Use (Manual Loop)
|
||||||
|
|
||||||
The PHP SDK supports raw tool definitions via JSON schema. See the [shared tool use concepts](../shared/tool-use-concepts.md) for the tool definition format and agentic loop pattern.
|
Tools are passed as arrays. **The SDK uses camelCase keys** (\`inputSchema\`, \`toolUseID\`, \`stopReason\`) and auto-maps to the API's snake_case on the wire — since v0.5.0. See [shared tool use concepts](../shared/tool-use-concepts.md) for the loop pattern.
|
||||||
|
|
||||||
|
\`\`\`php
|
||||||
|
use Anthropic\\Messages\\ToolUseBlock;
|
||||||
|
|
||||||
|
$tools = [
|
||||||
|
[
|
||||||
|
'name' => 'get_weather',
|
||||||
|
'description' => 'Get the current weather in a given location',
|
||||||
|
'inputSchema' => [ // camelCase, not input_schema
|
||||||
|
'type' => 'object',
|
||||||
|
'properties' => [
|
||||||
|
'location' => ['type' => 'string', 'description' => 'City and state'],
|
||||||
|
],
|
||||||
|
'required' => ['location'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
$messages = [['role' => 'user', 'content' => 'What is the weather in SF?']];
|
||||||
|
|
||||||
|
$response = $client->messages->create(
|
||||||
|
model: '{{OPUS_ID}}',
|
||||||
|
maxTokens: 1024,
|
||||||
|
tools: $tools,
|
||||||
|
messages: $messages,
|
||||||
|
);
|
||||||
|
|
||||||
|
while ($response->stopReason === 'tool_use') { // camelCase property
|
||||||
|
$toolResults = [];
|
||||||
|
foreach ($response->content as $block) {
|
||||||
|
if ($block instanceof ToolUseBlock) {
|
||||||
|
// $block->name : string — tool name to dispatch on
|
||||||
|
// $block->input : array<string,mixed> — parsed JSON input
|
||||||
|
// $block->id : string — pass back as toolUseID
|
||||||
|
$result = executeYourTool($block->name, $block->input);
|
||||||
|
$toolResults[] = [
|
||||||
|
'type' => 'tool_result',
|
||||||
|
'toolUseID' => $block->id, // camelCase, not tool_use_id
|
||||||
|
'content' => $result,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append assistant turn + user turn with tool results
|
||||||
|
$messages[] = ['role' => 'assistant', 'content' => $response->content];
|
||||||
|
$messages[] = ['role' => 'user', 'content' => $toolResults];
|
||||||
|
|
||||||
|
$response = $client->messages->create(
|
||||||
|
model: '{{OPUS_ID}}',
|
||||||
|
maxTokens: 1024,
|
||||||
|
tools: $tools,
|
||||||
|
messages: $messages,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Final text response
|
||||||
|
foreach ($response->content as $block) {
|
||||||
|
if ($block->type === 'text') {
|
||||||
|
echo $block->text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`$block->type === 'tool_use'\` also works; \`instanceof ToolUseBlock\` narrows for PHPStan.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extended Thinking
|
||||||
|
|
||||||
|
**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think.
|
||||||
|
|
||||||
|
\`\`\`php
|
||||||
|
use Anthropic\\Messages\\ThinkingBlock;
|
||||||
|
|
||||||
|
$message = $client->messages->create(
|
||||||
|
model: '{{OPUS_ID}}',
|
||||||
|
maxTokens: 16000,
|
||||||
|
thinking: ['type' => 'adaptive'],
|
||||||
|
messages: [
|
||||||
|
['role' => 'user', 'content' => 'Solve: 27 * 453'],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ThinkingBlock(s) precede TextBlock in content
|
||||||
|
foreach ($message->content as $block) {
|
||||||
|
if ($block instanceof ThinkingBlock) {
|
||||||
|
echo "Thinking:\\n{$block->thinking}\\n\\n";
|
||||||
|
// $block->signature is an opaque string — preserve verbatim if
|
||||||
|
// passing thinking blocks back in multi-turn conversations
|
||||||
|
} elseif ($block->type === 'text') {
|
||||||
|
echo "Answer: {$block->text}\\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
> **Deprecated:** \`['type' => 'enabled', 'budgetTokens' => N]\` (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.
|
||||||
|
|
||||||
|
\`$block->type === 'thinking'\` also works for the check; \`instanceof\` narrows for PHPStan.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Beta Features & Server-Side Tools
|
||||||
|
|
||||||
|
**\`betas:\` is NOT a param on \`$client->messages->create()\`** — it only exists on the beta namespace. Use it for features that need an explicit opt-in header:
|
||||||
|
|
||||||
|
\`\`\`php
|
||||||
|
use Anthropic\\Beta\\Messages\\BetaRequestMCPServerURLDefinition;
|
||||||
|
|
||||||
|
$response = $client->beta->messages->create(
|
||||||
|
model: '{{OPUS_ID}}',
|
||||||
|
maxTokens: 1024,
|
||||||
|
mcpServers: [
|
||||||
|
BetaRequestMCPServerURLDefinition::with(
|
||||||
|
name: 'my-server',
|
||||||
|
url: 'https://example.com/mcp',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
betas: ['mcp-client-2025-11-20'], // only valid on ->beta->messages
|
||||||
|
messages: [['role' => 'user', 'content' => 'Use the MCP tools']],
|
||||||
|
);
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
**Server-side tools** (bash, web_search, text_editor, code_execution) are GA and work on both paths — \`Anthropic\\Messages\\ToolBash20250124\` / \`WebSearchTool20260209\` / \`ToolTextEditor20250728\` / \`CodeExecutionTool20260120\` for non-beta, \`Anthropic\\Beta\\Messages\\BetaToolBash20250124\` / \`BetaWebSearchTool20260209\` / \`BetaToolTextEditor20250728\` / \`BetaCodeExecutionTool20260120\` for beta. No \`betas:\` header needed for these.
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — Python'
|
name: 'Data: Claude API reference — Python'
|
||||||
description: Python SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation
|
description: Python SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — Python
|
# Claude API — Python
|
||||||
|
|
||||||
@ -270,7 +270,7 @@ response2 = conversation.send("What's my name?") # Claude remembers "Alice"
|
|||||||
|
|
||||||
### Compaction (long conversations)
|
### Compaction (long conversations)
|
||||||
|
|
||||||
> **Beta, Opus 4.6 only.** 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.
|
> **Beta, 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.
|
||||||
|
|
||||||
\`\`\`python
|
\`\`\`python
|
||||||
import anthropic
|
import anthropic
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude API reference — TypeScript'
|
name: 'Data: Claude API reference — TypeScript'
|
||||||
description: TypeScript SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation
|
description: TypeScript SDK reference including installation, client initialization, basic requests, thinking, and multi-turn conversation
|
||||||
ccVersion: 2.1.71
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude API — TypeScript
|
# Claude API — TypeScript
|
||||||
|
|
||||||
@ -233,7 +233,7 @@ const response = await client.messages.create({
|
|||||||
|
|
||||||
**Rules:**
|
**Rules:**
|
||||||
|
|
||||||
- Messages must alternate between \`user\` and \`assistant\`
|
- Consecutive same-role messages are allowed — the API combines them into a single turn
|
||||||
- First message must be \`user\`
|
- First message must be \`user\`
|
||||||
- Use SDK types (\`Anthropic.MessageParam\`, \`Anthropic.Message\`, \`Anthropic.Tool\`, etc.) for all API data structures — don't redefine equivalent interfaces
|
- Use SDK types (\`Anthropic.MessageParam\`, \`Anthropic.Message\`, \`Anthropic.Tool\`, etc.) for all API data structures — don't redefine equivalent interfaces
|
||||||
|
|
||||||
@ -241,7 +241,7 @@ const response = await client.messages.create({
|
|||||||
|
|
||||||
### Compaction (long conversations)
|
### Compaction (long conversations)
|
||||||
|
|
||||||
> **Beta, Opus 4.6 only.** 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.
|
> **Beta, 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.
|
||||||
|
|
||||||
\`\`\`typescript
|
\`\`\`typescript
|
||||||
import Anthropic from "@anthropic-ai/sdk";
|
import Anthropic from "@anthropic-ai/sdk";
|
||||||
@ -265,7 +265,9 @@ async function chat(userMessage: string): Promise<string> {
|
|||||||
// Append full content — compaction blocks must be preserved
|
// Append full content — compaction blocks must be preserved
|
||||||
messages.push({ role: "assistant", content: response.content });
|
messages.push({ role: "assistant", content: response.content });
|
||||||
|
|
||||||
const textBlock = response.content.find((block) => block.type === "text");
|
const textBlock = response.content.find(
|
||||||
|
(b): b is Anthropic.Beta.BetaTextBlock => b.type === "text",
|
||||||
|
);
|
||||||
return textBlock?.text ?? "";
|
return textBlock?.text ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Claude model catalog'
|
name: 'Data: Claude model catalog'
|
||||||
description: Catalog of current and legacy Claude models with exact model IDs, aliases, context windows, and pricing
|
description: Catalog of current and legacy Claude models with exact model IDs, aliases, context windows, and pricing
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Claude Model Catalog
|
# Claude Model Catalog
|
||||||
|
|
||||||
@ -33,9 +33,9 @@ ccVersion: 2.1.63
|
|||||||
|
|
||||||
## Deprecated Models (retiring soon)
|
## Deprecated Models (retiring soon)
|
||||||
|
|
||||||
| Friendly Name | Alias (use this) | Full ID | Status |
|
| Friendly Name | Alias (use this) | Full ID | Status | Retires |
|
||||||
|-------------------|---------------------|-------------------------------|------------|
|
|-------------------|---------------------|-------------------------------|------------|--------------|
|
||||||
| Claude Haiku 3 | — | \`claude-3-haiku-20240307\` | Deprecated |
|
| Claude Haiku 3 | — | \`claude-3-haiku-20240307\` | Deprecated | Apr 19, 2026 |
|
||||||
|
|
||||||
## Retired Models (no longer available)
|
## Retired Models (no longer available)
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Files API reference — Python'
|
name: 'Data: Files API reference — Python'
|
||||||
description: Python Files API reference including file upload, listing, deletion, and usage in messages
|
description: Python Files API reference including file upload, listing, deletion, and usage in messages
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Files API — Python
|
# Files API — Python
|
||||||
|
|
||||||
@ -57,7 +57,9 @@ response = client.beta.messages.create(
|
|||||||
}],
|
}],
|
||||||
betas=["files-api-2025-04-14"],
|
betas=["files-api-2025-04-14"],
|
||||||
)
|
)
|
||||||
print(response.content[0].text)
|
for block in response.content:
|
||||||
|
if block.type == "text":
|
||||||
|
print(block.text)
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Image
|
### Image
|
||||||
@ -160,7 +162,8 @@ for question in questions:
|
|||||||
betas=["files-api-2025-04-14"],
|
betas=["files-api-2025-04-14"],
|
||||||
)
|
)
|
||||||
print(f"\\nQ: {question}")
|
print(f"\\nQ: {question}")
|
||||||
print(f"A: {response.content[0].text[:200]}")
|
text = next((b.text for b in response.content if b.type == "text"), "")
|
||||||
|
print(f"A: {text[:200]}")
|
||||||
|
|
||||||
# 3. Clean up when done
|
# 3. Clean up when done
|
||||||
client.beta.files.delete(uploaded.id)
|
client.beta.files.delete(uploaded.id)
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: HTTP error codes reference'
|
name: 'Data: HTTP error codes reference'
|
||||||
description: Reference for HTTP error codes returned by the Claude API with common causes and handling strategies
|
description: Reference for HTTP error codes returned by the Claude API with common causes and handling strategies
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# HTTP Error Codes Reference
|
# HTTP Error Codes Reference
|
||||||
|
|
||||||
@ -40,7 +40,8 @@ This file documents HTTP error codes returned by the Claude API, their common ca
|
|||||||
"error": {
|
"error": {
|
||||||
"type": "invalid_request_error",
|
"type": "invalid_request_error",
|
||||||
"message": "messages: roles must alternate between \"user\" and \"assistant\""
|
"message": "messages: roles must alternate between \"user\" and \"assistant\""
|
||||||
}
|
},
|
||||||
|
"request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Message Batches API reference — Python'
|
name: 'Data: Message Batches API reference — Python'
|
||||||
description: Python Batches API reference including batch creation, status polling, and result retrieval at 50% cost
|
description: Python Batches API reference including batch creation, status polling, and result retrieval at 50% cost
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Message Batches API — Python
|
# Message Batches API — Python
|
||||||
|
|
||||||
@ -80,7 +80,9 @@ print(f"Errored: {batch.request_counts.errored}")
|
|||||||
for result in client.messages.batches.results(message_batch.id):
|
for result in client.messages.batches.results(message_batch.id):
|
||||||
match result.result.type:
|
match result.result.type:
|
||||||
case "succeeded":
|
case "succeeded":
|
||||||
print(f"[{result.custom_id}] {result.result.message.content[0].text[:100]}")
|
msg = result.result.message
|
||||||
|
text = next((b.text for b in msg.content if b.type == "text"), "")
|
||||||
|
print(f"[{result.custom_id}] {text[:100]}")
|
||||||
case "errored":
|
case "errored":
|
||||||
if result.result.error.type == "invalid_request":
|
if result.result.error.type == "invalid_request":
|
||||||
print(f"[{result.custom_id}] Validation error - fix request and retry")
|
print(f"[{result.custom_id}] Validation error - fix request and retry")
|
||||||
@ -180,7 +182,8 @@ while True:
|
|||||||
results = {}
|
results = {}
|
||||||
for result in client.messages.batches.results(batch.id):
|
for result in client.messages.batches.results(batch.id):
|
||||||
if result.result.type == "succeeded":
|
if result.result.type == "succeeded":
|
||||||
results[result.custom_id] = result.result.message.content[0].text
|
msg = result.result.message
|
||||||
|
results[result.custom_id] = next((b.text for b in msg.content if b.type == "text"), "")
|
||||||
|
|
||||||
for custom_id, classification in sorted(results.items()):
|
for custom_id, classification in sorted(results.items()):
|
||||||
print(f"{custom_id}: {classification}")
|
print(f"{custom_id}: {classification}")
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Tool use reference — Python'
|
name: 'Data: Tool use reference — Python'
|
||||||
description: Python tool use reference including tool runner, manual agentic loop, code execution, and structured outputs
|
description: Python tool use reference including tool runner, manual agentic loop, code execution, and structured outputs
|
||||||
ccVersion: 2.1.69
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Tool Use — Python
|
# Tool Use — Python
|
||||||
|
|
||||||
@ -75,7 +75,8 @@ async with stdio_client(StdioServerParameters(command="mcp-server")) as (read, w
|
|||||||
await mcp_client.initialize()
|
await mcp_client.initialize()
|
||||||
|
|
||||||
tools_result = await mcp_client.list_tools()
|
tools_result = await mcp_client.list_tools()
|
||||||
runner = await client.beta.messages.tool_runner(
|
# tool_runner is sync — returns the runner, not a coroutine
|
||||||
|
runner = client.beta.messages.tool_runner(
|
||||||
model="{{OPUS_ID}}",
|
model="{{OPUS_ID}}",
|
||||||
max_tokens=1024,
|
max_tokens=1024,
|
||||||
messages=[{"role": "user", "content": "Use the available tools"}],
|
messages=[{"role": "user", "content": "Use the available tools"}],
|
||||||
@ -525,7 +526,9 @@ response = client.messages.create(
|
|||||||
)
|
)
|
||||||
|
|
||||||
import json
|
import json
|
||||||
data = json.loads(response.content[0].text)
|
# output_config.format guarantees the first block is text with valid JSON
|
||||||
|
text = next(b.text for b in response.content if b.type == "text")
|
||||||
|
data = json.loads(text)
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Strict Tool Use
|
### Strict Tool Use
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Data: Tool use reference — TypeScript'
|
name: 'Data: Tool use reference — TypeScript'
|
||||||
description: TypeScript tool use reference including tool runner, manual agentic loop, code execution, and structured outputs
|
description: TypeScript tool use reference including tool runner, manual agentic loop, code execution, and structured outputs
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Tool Use — TypeScript
|
# Tool Use — TypeScript
|
||||||
|
|
||||||
@ -74,12 +74,9 @@ while (true) {
|
|||||||
|
|
||||||
if (response.stop_reason === "end_turn") break;
|
if (response.stop_reason === "end_turn") break;
|
||||||
|
|
||||||
// Server-side tool hit iteration limit; re-send to continue
|
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
|
||||||
if (response.stop_reason === "pause_turn") {
|
if (response.stop_reason === "pause_turn") {
|
||||||
messages = [
|
messages.push({ role: "assistant", content: response.content });
|
||||||
{ role: "user", content: userInput },
|
|
||||||
{ role: "assistant", content: response.content },
|
|
||||||
];
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,12 +130,9 @@ while (true) {
|
|||||||
|
|
||||||
if (message.stop_reason === "end_turn") break;
|
if (message.stop_reason === "end_turn") break;
|
||||||
|
|
||||||
// Server-side tool hit iteration limit; re-send to continue
|
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
|
||||||
if (message.stop_reason === "pause_turn") {
|
if (message.stop_reason === "pause_turn") {
|
||||||
messages = [
|
messages.push({ role: "assistant", content: message.content });
|
||||||
{ role: "user", content: userInput },
|
|
||||||
{ role: "assistant", content: message.content },
|
|
||||||
];
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -219,6 +213,45 @@ const response = await client.messages.create({
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Server-Side Tools
|
||||||
|
|
||||||
|
Version-suffixed \`type\` literals; \`name\` is fixed per interface. Pass plain object literals — the \`ToolUnion\` type is satisfied structurally. **The \`name\`/\`type\` pair must match the interface**: mixing \`str_replace_based_edit_tool\` (20250728 name) with \`text_editor_20250124\` (which expects \`str_replace_editor\`) is a TS2322.
|
||||||
|
|
||||||
|
**Don't type-annotate as \`Tool[]\`** — \`Tool\` is just the custom-tool variant. Let structural typing infer from the \`tools\` param, or annotate as \`Anthropic.Messages.ToolUnion[]\` if you must:
|
||||||
|
|
||||||
|
\`\`\`typescript
|
||||||
|
// ✓ let inference work — no annotation
|
||||||
|
const response = await client.messages.create({
|
||||||
|
model: "{{OPUS_ID}}",
|
||||||
|
max_tokens: 1024,
|
||||||
|
tools: [
|
||||||
|
{ type: "text_editor_20250728", name: "str_replace_based_edit_tool" },
|
||||||
|
{ type: "bash_20250124", name: "bash" },
|
||||||
|
{ type: "web_search_20260209", name: "web_search" },
|
||||||
|
{ type: "code_execution_20260120", name: "code_execution" },
|
||||||
|
],
|
||||||
|
messages: [{ role: "user", content: "..." }],
|
||||||
|
});
|
||||||
|
|
||||||
|
// ✗ this is a TS2352 — Tool is the CUSTOM tool variant only
|
||||||
|
// const tools: Anthropic.Tool[] = [{ type: "text_editor_20250728", ... }]
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
| Interface | \`name\` | \`type\` |
|
||||||
|
|---|---|---|
|
||||||
|
| \`ToolTextEditor20250124\` | \`str_replace_editor\` | \`text_editor_20250124\` |
|
||||||
|
| \`ToolTextEditor20250429\` | \`str_replace_based_edit_tool\` | \`text_editor_20250429\` |
|
||||||
|
| \`ToolTextEditor20250728\` | \`str_replace_based_edit_tool\` | \`text_editor_20250728\` |
|
||||||
|
| \`ToolBash20250124\` | \`bash\` | \`bash_20250124\` |
|
||||||
|
| \`WebSearchTool20260209\` | \`web_search\` | \`web_search_20260209\` |
|
||||||
|
| \`WebFetchTool20260209\` | \`web_fetch\` | \`web_fetch_20260209\` |
|
||||||
|
| \`CodeExecutionTool20260120\` | \`code_execution\` | \`code_execution_20260120\` |
|
||||||
|
|
||||||
|
**Don't mix beta and non-beta types**: if you call \`client.beta.messages.create()\`, the response \`content\` is \`BetaContentBlock[]\` — you cannot pass that to a non-beta \`ContentBlockParam[]\` without narrowing each element.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
## Code Execution
|
## Code Execution
|
||||||
|
|
||||||
### Basic Usage
|
### Basic Usage
|
||||||
@ -242,6 +275,21 @@ const response = await client.messages.create({
|
|||||||
});
|
});
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
|
### Reading Local Files (ESM note)
|
||||||
|
|
||||||
|
\`__dirname\` doesn't exist in ES modules. For script-relative paths use \`import.meta.url\`:
|
||||||
|
|
||||||
|
\`\`\`typescript
|
||||||
|
import { readFileSync } from "fs";
|
||||||
|
import { fileURLToPath } from "url";
|
||||||
|
import { dirname, join } from "path";
|
||||||
|
|
||||||
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const pdfBytes = readFileSync(join(__dirname, "sample.pdf"));
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Or use a CWD-relative path if the script runs from a known directory: \`readFileSync("./sample.pdf")\`.
|
||||||
|
|
||||||
### Upload Files for Analysis
|
### Upload Files for Analysis
|
||||||
|
|
||||||
\`\`\`typescript
|
\`\`\`typescript
|
||||||
@ -300,8 +348,8 @@ for (const block of response.content) {
|
|||||||
const metadata = await client.beta.files.retrieveMetadata(
|
const metadata = await client.beta.files.retrieveMetadata(
|
||||||
fileRef.file_id,
|
fileRef.file_id,
|
||||||
);
|
);
|
||||||
const response = await client.beta.files.download(fileRef.file_id);
|
const downloadResponse = await client.beta.files.download(fileRef.file_id);
|
||||||
const fileBytes = Buffer.from(await response.arrayBuffer());
|
const fileBytes = Buffer.from(await downloadResponse.arrayBuffer());
|
||||||
const safeName = path.basename(metadata.filename);
|
const safeName = path.basename(metadata.filename);
|
||||||
if (!safeName || safeName === "." || safeName === "..") {
|
if (!safeName || safeName === "." || safeName === "..") {
|
||||||
console.warn(\`Skipping invalid filename: \${metadata.filename}\`);
|
console.warn(\`Skipping invalid filename: \${metadata.filename}\`);
|
||||||
@ -334,7 +382,8 @@ const response1 = await client.messages.create({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Reuse container
|
// Reuse container
|
||||||
const containerId = response1.container.id;
|
// container is nullable — set only when using server-side code execution
|
||||||
|
const containerId = response1.container!.id;
|
||||||
|
|
||||||
const response2 = await client.messages.create({
|
const response2 = await client.messages.create({
|
||||||
container: containerId,
|
container: containerId,
|
||||||
@ -443,7 +492,8 @@ const response = await client.messages.parse({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(response.parsed_output.name); // "Jane Doe"
|
// parsed_output is null if parsing failed — assert or guard
|
||||||
|
console.log(response.parsed_output!.name); // "Jane Doe"
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Strict Tool Use
|
### Strict Tool Use
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'Skill: Build with Claude API'
|
name: 'Skill: Build with Claude API'
|
||||||
description: Main routing guide for building LLM-powered applications with Claude, including language detection, surface selection, and architecture overview
|
description: Main routing guide for building LLM-powered applications with Claude, including language detection, surface selection, and architecture overview
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
-->
|
-->
|
||||||
# Building LLM-Powered Applications with Claude
|
# Building LLM-Powered Applications with Claude
|
||||||
|
|
||||||
@ -159,7 +159,7 @@ A note: if any of the model strings above look unfamiliar to you, that's to be e
|
|||||||
|
|
||||||
## Compaction (Quick Reference)
|
## Compaction (Quick Reference)
|
||||||
|
|
||||||
**Beta, Opus 4.6 only.** For long-running conversations that may exceed the 200K context window, enable server-side compaction. The API automatically summarizes earlier context when it approaches the trigger threshold (default: 150K tokens). Requires beta header \`compact-2026-01-12\`.
|
**Beta, Opus 4.6 and Sonnet 4.6.** For long-running conversations that may exceed the 200K context window, enable server-side compaction. The API automatically summarizes earlier context when it approaches the trigger threshold (default: 150K tokens). Requires beta header \`compact-2026-01-12\`.
|
||||||
|
|
||||||
**Critical:** Append \`response.content\` (not just the text) back to your messages on every turn. Compaction blocks in the response must be preserved — the API uses them to replace the compacted history on the next request. Extracting only the text string and appending that will silently lose the compaction state.
|
**Critical:** Append \`response.content\` (not just the text) back to your messages on every turn. Compaction blocks in the response must be preserved — the API uses them to replace the compacted history on the next request. Extracting only the text string and appending that will silently lose the compaction state.
|
||||||
|
|
||||||
|
|||||||
@ -1,17 +0,0 @@
|
|||||||
<!--
|
|
||||||
name: 'System Prompt: Brief mode'
|
|
||||||
description: Codex-like way of executing tasks - short status updates and then launching in to the work.
|
|
||||||
ccVersion: 2.1.72
|
|
||||||
-->
|
|
||||||
## Communicating with the user
|
|
||||||
|
|
||||||
Write your text output normally — it's the walkthrough. Call ${"SendUserMessage"} at checkpoints: to acknowledge a request, mark a result, flag a decision or blocker, or ask for input.
|
|
||||||
|
|
||||||
Think of it like posting to a thread while you work async. Each post marks where things stand. Someone reading only the thread (compact view) gets the arc; someone watching you work live sees the posts as beats between the detail, not recaps of it.
|
|
||||||
|
|
||||||
Call ${"SendUserMessage"} to:
|
|
||||||
- Acknowledge a request before starting work that will take more than a few seconds — otherwise the user sees only a spinner
|
|
||||||
- Mark results at phase boundaries during long work
|
|
||||||
- Ask when you need input to continue
|
|
||||||
|
|
||||||
One call caps a quick reply — ack and result in one. For longer work, the shape is: ack up front, checkpoint at phase boundaries, final result. If there's nothing meaningful to say between those, keep working — don't narrate each step or send "still working."
|
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
<!--
|
||||||
|
name: 'System Prompt: How to use the SendUserMessage tool'
|
||||||
|
description: Instructions for using the SendUserMessage tool
|
||||||
|
ccVersion: 2.1.73
|
||||||
|
-->
|
||||||
|
## Talking to the user
|
||||||
|
|
||||||
|
${"SendUserMessage"} is where your replies go. Text outside it is visible if the user expands the detail view, but most won't — assume unread. Anything you want them to actually see goes through ${"SendUserMessage"}. The failure mode: the real answer lives in plain text while ${"SendUserMessage"} just says "done!" — they see "done!" and miss everything.
|
||||||
|
|
||||||
|
So: every time the user says something, the reply they actually read comes through ${"SendUserMessage"}. Even for "hi". Even for "thanks".
|
||||||
|
|
||||||
|
If you can answer right away, send the answer. If you need to go look — run a command, read files, check something — ack first in one line ("On it — checking the test output"), then work, then send the result. Without the ack they're staring at a spinner.
|
||||||
|
|
||||||
|
For longer work: ack → work → result. Between those, send a checkpoint when something useful happened — a decision you made, a surprise you hit, a phase boundary. Skip the filler ("running tests...") — a checkpoint earns its place by carrying information.
|
||||||
|
|
||||||
|
Keep messages tight — the decision, the file:line, the PR number. Second person always ("your config"), never third.
|
||||||
13
system-prompts/system-prompt-phase-four-of-plan-mode.md
Normal file
13
system-prompts/system-prompt-phase-four-of-plan-mode.md
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<!--
|
||||||
|
name: 'System Prompt: Phase four of plan mode'
|
||||||
|
description: Phase four of plan mode.
|
||||||
|
ccVersion: 2.1.73
|
||||||
|
-->
|
||||||
|
### Phase 4: Final Plan
|
||||||
|
Goal: Write your final plan to the plan file (the only file you can edit).
|
||||||
|
- Do NOT write a Context, Background, or Overview section. The user just told you what they want.
|
||||||
|
- Do NOT restate the user's request. Do NOT write prose paragraphs.
|
||||||
|
- List the paths of files to be modified and what changes in each (one bullet per file)
|
||||||
|
- Reference existing functions to reuse, with file:line
|
||||||
|
- End with the single verification command
|
||||||
|
- **Hard limit: 40 lines.** If the plan is longer, delete prose — not file paths.
|
||||||
@ -1,21 +0,0 @@
|
|||||||
<!--
|
|
||||||
name: 'System Prompt: Post checkpoints'
|
|
||||||
description: How to post the checkpoints.
|
|
||||||
ccVersion: 2.1.72
|
|
||||||
-->
|
|
||||||
Post a checkpoint to the user. The user may be reading only these messages (compact view) or reading them interleaved with your full text and tool calls. Write for both: each message should stand on its own given your prior ${"SendUserMessage"} calls, and land naturally after the text that preceded it — don't open with "To summarize" or refer back ("as I mentioned above").
|
|
||||||
|
|
||||||
If the task will take more than a few seconds, acknowledge it before you start. The user is on a compact view — without an ack they see only a spinner and don't know whether you received the request or understood it. One line: confirm what you're doing, then go.
|
|
||||||
|
|
||||||
Good messages are concise and outcome-focused — like a commit message, not a recap:
|
|
||||||
- "On it — pulling the PR and running the failing test locally." (ack)
|
|
||||||
- "PR #1234 opened — adds retry logic to the upload endpoint. Ready for review." (result)
|
|
||||||
- "Blocked: the auth test fails because the staging API key is expired. Can you rotate it?" (blocker)
|
|
||||||
|
|
||||||
Include enough specifics (file:line, PR number, the decision made) that each message is useful alone. Don't narrate process ("I'm going to read the file now"). Don't pad with filler. Say what matters and get back to work.
|
|
||||||
|
|
||||||
When referring to the user, write in second person ("you're in meetings until 2pm"), never third ("he's in meetings").
|
|
||||||
|
|
||||||
Attachments: pass file paths in the \`attachments\` array to share photos, screenshots, diffs, or logs alongside your message. Paths can be absolute or relative to the current working directory. Only attach files that help the user — don't attach every file you touched.
|
|
||||||
|
|
||||||
Set \`status\` on every call. Use \`proactive\` when you're initiating — the user is away or hasn't asked, and you want this to reach their phone (task done, blocker hit, question you need answered to continue). Use \`normal\` when you're replying to something the user just said — they're already here, no push needed.
|
|
||||||
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
name: 'System Reminder: Plan mode is active (5-phase)'
|
name: 'System Reminder: Plan mode is active (5-phase)'
|
||||||
description: Enhanced plan mode system reminder with parallel exploration and multi-agent planning
|
description: Enhanced plan mode system reminder with parallel exploration and multi-agent planning
|
||||||
ccVersion: 2.1.63
|
ccVersion: 2.1.73
|
||||||
variables:
|
variables:
|
||||||
- PLAN_FILE_INFO_BLOCK
|
- PLAN_FILE_INFO_BLOCK
|
||||||
- EDIT_TOOL
|
- EDIT_TOOL
|
||||||
@ -11,6 +11,7 @@ variables:
|
|||||||
- PLAN_SUBAGENT
|
- PLAN_SUBAGENT
|
||||||
- PLAN_V2_PLAN_AGENT_COUNT
|
- PLAN_V2_PLAN_AGENT_COUNT
|
||||||
- ASK_USER_QUESTION_TOOL_NAME
|
- ASK_USER_QUESTION_TOOL_NAME
|
||||||
|
- GET_PHASE_FOUR_FN
|
||||||
- EXIT_PLAN_MODE_TOOL
|
- EXIT_PLAN_MODE_TOOL
|
||||||
-->
|
-->
|
||||||
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received.
|
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received.
|
||||||
@ -66,14 +67,7 @@ Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's inten
|
|||||||
2. Ensure that the plans align with the user's original request
|
2. Ensure that the plans align with the user's original request
|
||||||
3. Use ${ASK_USER_QUESTION_TOOL_NAME} to clarify any remaining questions with the user
|
3. Use ${ASK_USER_QUESTION_TOOL_NAME} to clarify any remaining questions with the user
|
||||||
|
|
||||||
### Phase 4: Final Plan
|
${GET_PHASE_FOUR_FN()}
|
||||||
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
||||||
- Begin with a **Context** section: explain why this change is being made — the problem or need it addresses, what prompted it, and the intended outcome
|
|
||||||
- Include only your recommended approach, not all alternatives
|
|
||||||
- Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
|
|
||||||
- Include the paths of critical files to be modified
|
|
||||||
- Reference existing functions and utilities you found that should be reused, with their file paths
|
|
||||||
- Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
|
|
||||||
|
|
||||||
### Phase 5: Call ${EXIT_PLAN_MODE_TOOL.name}
|
### Phase 5: Call ${EXIT_PLAN_MODE_TOOL.name}
|
||||||
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ${EXIT_PLAN_MODE_TOOL.name} to indicate to the user that you are done planning.
|
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ${EXIT_PLAN_MODE_TOOL.name} to indicate to the user that you are done planning.
|
||||||
|
|||||||
@ -0,0 +1,10 @@
|
|||||||
|
<!--
|
||||||
|
name: 'Tool Description: SendMessageTool (non-agent-teams)'
|
||||||
|
description: Send a message the user will read, describes this tool well.
|
||||||
|
ccVersion: 2.1.73
|
||||||
|
-->
|
||||||
|
Send a message the user will read. Text outside this tool is visible in the detail view, but most won't open it — the answer lives here.
|
||||||
|
|
||||||
|
`message` supports markdown. `attachments` takes file paths (absolute or cwd-relative) for images, diffs, logs.
|
||||||
|
|
||||||
|
`status` labels intent: 'normal' when replying to what they just asked; 'proactive' when you're initiating — a scheduled task finished, a blocker surfaced during background work, you need input on something they haven't asked about. Set it honestly; downstream routing uses it.
|
||||||
Loading…
x
Reference in New Issue
Block a user