Loading...
    • Developer Guide
    • API Reference
    • MCP
    • Resources
    • Release Notes
    Search...
    ⌘K

    First steps

    Intro to ClaudeQuickstart

    Models & pricing

    Models overviewChoosing a modelWhat's new in Claude 4.5Migrating to Claude 4.5Model deprecationsPricing

    Build with Claude

    Features overviewUsing the Messages APIContext windowsPrompting best practices

    Capabilities

    Prompt cachingContext editingExtended thinkingStreaming MessagesBatch processingCitationsMultilingual supportToken countingEmbeddingsVisionPDF supportFiles APISearch resultsGoogle Sheets add-on

    Tools

    OverviewHow to implement tool useToken-efficient tool useFine-grained tool streamingBash toolCode execution toolComputer use toolText editor toolWeb fetch toolWeb search toolMemory tool

    Agent Skills

    OverviewQuickstartBest practicesUsing Skills with the API

    Agent SDK

    OverviewTypeScript SDKPython SDK

    Guides

    Streaming InputHandling PermissionsSession ManagementHosting the Agent SDKModifying system promptsMCP in the SDKCustom ToolsSubagents in the SDKSlash Commands in the SDKAgent Skills in the SDKTracking Costs and UsageTodo ListsPlugins in the SDK

    MCP in the API

    MCP connectorRemote MCP servers

    Claude on 3rd-party platforms

    Amazon BedrockVertex AI

    Prompt engineering

    OverviewPrompt generatorUse prompt templatesPrompt improverBe clear and directUse examples (multishot prompting)Let Claude think (CoT)Use XML tagsGive Claude a role (system prompts)Prefill Claude's responseChain complex promptsLong context tipsExtended thinking tips

    Test & evaluate

    Define success criteriaDevelop test casesUsing the Evaluation ToolReducing latency

    Strengthen guardrails

    Reduce hallucinationsIncrease output consistencyMitigate jailbreaksStreaming refusalsReduce prompt leakKeep Claude in character

    Administration and monitoring

    Admin API overviewUsage and Cost APIClaude Code Analytics API
    Console
    Guides

    Modifying system prompts

    Learn how to customize Claude's behavior by modifying system prompts using three approaches - output styles, systemPrompt with append, and custom system prompts.

    System prompts define Claude's behavior, capabilities, and response style. The Claude Agent SDK provides three ways to customize system prompts: using output styles (persistent, file-based configurations), appending to Claude Code's prompt, or using a fully custom prompt.

    Understanding system prompts

    A system prompt is the initial instruction set that shapes how Claude behaves throughout a conversation.

    Default behavior: The Agent SDK uses an empty system prompt by default for maximum flexibility. To use Claude Code's system prompt (tool instructions, code guidelines, etc.), specify systemPrompt: { preset: "claude_code" } in TypeScript or system_prompt="claude_code" in Python.

    Claude Code's system prompt includes:

    • Tool usage instructions and available tools
    • Code style and formatting guidelines
    • Response tone and verbosity settings
    • Security and safety instructions
    • Context about the current working directory and environment

    Methods of modification

    Method 1: CLAUDE.md files (project-level instructions)

    CLAUDE.md files provide project-specific context and instructions that are automatically read by the Agent SDK when it runs in a directory. They serve as persistent "memory" for your project.

    How CLAUDE.md works with the SDK

    Location and discovery:

    • Project-level: CLAUDE.md or .claude/CLAUDE.md in your working directory
    • User-level: ~/.claude/CLAUDE.md for global instructions across all projects

    IMPORTANT: The SDK only reads CLAUDE.md files when you explicitly configure settingSources (TypeScript) or setting_sources (Python):

    • Include 'project' to load project-level CLAUDE.md
    • Include 'user' to load user-level CLAUDE.md (~/.claude/CLAUDE.md)

    The claude_code system prompt preset does NOT automatically load CLAUDE.md - you must also specify setting sources.

    Content format: CLAUDE.md files use plain markdown and can contain:

    • Coding guidelines and standards
    • Project-specific context
    • Common commands or workflows
    • API conventions
    • Testing requirements

    Example CLAUDE.md

    # Project Guidelines
    
    ## Code Style
    
    - Use TypeScript strict mode
    - Prefer functional components in React
    - Always include JSDoc comments for public APIs
    
    ## Testing
    
    - Run `npm test` before committing
    - Maintain >80% code coverage
    - Use jest for unit tests, playwright for E2E
    
    ## Commands
    
    - Build: `npm run build`
    - Dev server: `npm run dev`
    - Type check: `npm run typecheck`

    Using CLAUDE.md with the SDK

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // IMPORTANT: You must specify settingSources to load CLAUDE.md
    // The claude_code preset alone does NOT load CLAUDE.md files
    const messages = [];
    
    for await (const message of query({
      prompt: "Add a new React component for user profiles",
      options: {
        systemPrompt: {
          type: "preset",
          preset: "claude_code", // Use Claude Code's system prompt
        },
        settingSources: ["project"], // Required to load CLAUDE.md from project
      },
    })) {
      messages.push(message);
    }
    
    // Now Claude has access to your project guidelines from CLAUDE.md

    When to use CLAUDE.md

    Best for:

    • Team-shared context - Guidelines everyone should follow
    • Project conventions - Coding standards, file structure, naming patterns
    • Common commands - Build, test, deploy commands specific to your project
    • Long-term memory - Context that should persist across all sessions
    • Version-controlled instructions - Commit to git so the team stays in sync

    Key characteristics:

    • ✅ Persistent across all sessions in a project
    • ✅ Shared with team via git
    • ✅ Automatic discovery (no code changes needed)
    • ⚠️ Requires loading settings via settingSources

    Method 2: Output styles (persistent configurations)

    Output styles are saved configurations that modify Claude's system prompt. They're stored as markdown files and can be reused across sessions and projects.

    Creating an output style

    import { writeFile, mkdir } from "fs/promises";
    import { join } from "path";
    import { homedir } from "os";
    
    async function createOutputStyle(
      name: string,
      description: string,
      prompt: string
    ) {
      // User-level: ~/.claude/output-styles
      // Project-level: .claude/output-styles
      const outputStylesDir = join(homedir(), ".claude", "output-styles");
    
      await mkdir(outputStylesDir, { recursive: true });
    
      const content = `---
    name: ${name}
    description: ${description}
    ---
    
    ${prompt}`;
    
      const filePath = join(
        outputStylesDir,
        `${name.toLowerCase().replace(/\s+/g, "-")}.md`
      );
      await writeFile(filePath, content, "utf-8");
    }
    
    // Example: Create a code review specialist
    await createOutputStyle(
      "Code Reviewer",
      "Thorough code review assistant",
      `You are an expert code reviewer.
    
    For every code submission:
    1. Check for bugs and security issues
    2. Evaluate performance
    3. Suggest improvements
    4. Rate code quality (1-10)`
    );

    Using output styles

    Once created, activate output styles via:

    • CLI: /output-style [style-name]
    • Settings: .claude/settings.local.json
    • Create new: /output-style:new [description]

    Note for SDK users: Output styles are loaded when you include settingSources: ['user'] or settingSources: ['project'] (TypeScript) / setting_sources=["user"] or setting_sources=["project"] (Python) in your options.

    Method 3: Using systemPrompt with append

    You can use the Claude Code preset with an append property to add your custom instructions while preserving all built-in functionality.

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const messages = [];
    
    for await (const message of query({
      prompt: "Help me write a Python function to calculate fibonacci numbers",
      options: {
        systemPrompt: {
          type: "preset",
          preset: "claude_code",
          append:
            "Always include detailed docstrings and type hints in Python code.",
        },
      },
    })) {
      messages.push(message);
      if (message.type === "assistant") {
        console.log(message.message.content);
      }
    }

    Method 4: Custom system prompts

    You can provide a custom string as systemPrompt to replace the default entirely with your own instructions.

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const customPrompt = `You are a Python coding specialist.
    Follow these guidelines:
    - Write clean, well-documented code
    - Use type hints for all functions
    - Include comprehensive docstrings
    - Prefer functional programming patterns when appropriate
    - Always explain your code choices`;
    
    const messages = [];
    
    for await (const message of query({
      prompt: "Create a data processing pipeline",
      options: {
        systemPrompt: customPrompt,
      },
    })) {
      messages.push(message);
      if (message.type === "assistant") {
        console.log(message.message.content);
      }
    }

    Comparison of all four approaches

    FeatureCLAUDE.mdOutput StylessystemPrompt with appendCustom systemPrompt
    PersistencePer-project fileSaved as filesSession onlySession only
    ReusabilityPer-projectAcross projectsCode duplicationCode duplication
    ManagementOn filesystemCLI + filesIn codeIn code
    Default toolsPreservedPreservedPreservedLost (unless included)
    Built-in safetyMaintainedMaintainedMaintainedMust be added
    Environment contextAutomaticAutomaticAutomaticMust be provided
    Customization levelAdditions onlyReplace defaultAdditions onlyComplete control
    Version controlWith projectYesWith codeWith code
    ScopeProject-specificUser or projectCode sessionCode session

    Note: "With append" means using systemPrompt: { type: "preset", preset: "claude_code", append: "..." } in TypeScript or system_prompt={"type": "preset", "preset": "claude_code", "append": "..."} in Python.

    Use cases and best practices

    When to use CLAUDE.md

    Best for:

    • Project-specific coding standards and conventions
    • Documenting project structure and architecture
    • Listing common commands (build, test, deploy)
    • Team-shared context that should be version controlled
    • Instructions that apply to all SDK usage in a project

    Examples:

    • "All API endpoints should use async/await patterns"
    • "Run npm run lint:fix before committing"
    • "Database migrations are in the migrations/ directory"

    Important: To load CLAUDE.md files, you must explicitly set settingSources: ['project'] (TypeScript) or setting_sources=["project"] (Python). The claude_code system prompt preset does NOT automatically load CLAUDE.md without this setting.

    When to use output styles

    Best for:

    • Persistent behavior changes across sessions
    • Team-shared configurations
    • Specialized assistants (code reviewer, data scientist, DevOps)
    • Complex prompt modifications that need versioning

    Examples:

    • Creating a dedicated SQL optimization assistant
    • Building a security-focused code reviewer
    • Developing a teaching assistant with specific pedagogy

    When to use systemPrompt with append

    Best for:

    • Adding specific coding standards or preferences
    • Customizing output formatting
    • Adding domain-specific knowledge
    • Modifying response verbosity
    • Enhancing Claude Code's default behavior without losing tool instructions

    When to use custom systemPrompt

    Best for:

    • Complete control over Claude's behavior
    • Specialized single-session tasks
    • Testing new prompt strategies
    • Situations where default tools aren't needed
    • Building specialized agents with unique behavior

    Combining approaches

    You can combine these methods for maximum flexibility:

    Example: Output style with session-specific additions

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // Assuming "Code Reviewer" output style is active (via /output-style)
    // Add session-specific focus areas
    const messages = [];
    
    for await (const message of query({
      prompt: "Review this authentication module",
      options: {
        systemPrompt: {
          type: "preset",
          preset: "claude_code",
          append: `
            For this review, prioritize:
            - OAuth 2.0 compliance
            - Token storage security
            - Session management
          `,
        },
      },
    })) {
      messages.push(message);
    }

    See also

    • Output styles - Complete output styles documentation
    • TypeScript SDK guide - Complete SDK usage guide
    • Configuration guide - General configuration options
    • Understanding system prompts
    • Methods of modification
    • Method 1: CLAUDE.md files (project-level instructions)
    • Method 2: Output styles (persistent configurations)
    • Method 3: Using with append
    • Method 4: Custom system prompts
    • Comparison of all four approaches
    • Use cases and best practices
    • When to use CLAUDE.md
    • When to use output styles
    • When to use with append
    • When to use custom
    • Combining approaches
    • Example: Output style with session-specific additions
    • See also
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC