AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

writing-skills

Use when creating new skills, editing existing skills, or verifying skills work before deployment

Original source
obra
License
MIT
Pinned revision
2ce8aa15d05bd57213e6f746f953aafb7ded7a8b

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read obra--writing-skills at revision 2ce8aa15d05bd57213e6f746f953aafb7ded7a8b, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 8

references/anthropic-best-practices.md · 24000

## Document modification workflow

1. Determine the modification type:

   **Creating new content?** → Follow "Creation workflow" below
   **Editing existing content?** → Follow "Editing workflow" below

2. Creation workflow:
   - Use docx-js library
   - Build document from scratch
   - Export to .docx format

3. Editing workflow:
   - Unpack existing document
   - Modify XML directly
   - Validate after each change
   - Repack when complete

Evaluation and iteration

Build evaluations first

Create evaluations BEFORE writing extensive documentation. This ensures your Skill solves real problems rather than documenting imagined ones.

Evaluation-driven development:

  1. Identify gaps: Run your agent on representative tasks without a Skill. Document specific failures or missing context
  2. Create evaluations: Build three scenarios that test these gaps
  3. Establish baseline: Measure the agent's performance without the Skill
  4. Write minimal instructions: Create just enough content to address the gaps and pass evaluations
  5. Iterate: Execute evaluations, compare against baseline, and refine

This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.

Evaluation structure:

{
  "skills": ["pdf-processing"],
  "query": "Extract all text from this PDF file and save it to output.txt",
  "files": ["test-files/document.pdf"],
  "expected_behavior": [
    "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
    "Extracts text content from all pages in the document without missing any pages",
    "Saves the extracted text to a file named output.txt in a clear, readable format"
  ]
}

Develop Skills iteratively with the agent

The most effective Skill development process involves the agent itself. Work with one instance ("Agent A") to create a Skill that will be used by other instances ("Agent B"). Agent A helps you design and refine instructions, while Agent B tests them in real tasks. This works because the underlying models understand both how to write effective agent instructions and what information agents need.

Creating a new Skill:

  1. Complete a task without a Skill: Work through a problem with Agent A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.

  2. Identify the reusable pattern: After completing the task, identify what context you provided that would be useful for similar future tasks.

    Example: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.

  3. Ask Agent A to create a Skill: "Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts."

  4. Review for conciseness: Check that Agent A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - the agent already knows that."

  5. Improve information architecture: Ask Agent A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."

  6. Test on similar tasks: Use the Skill with Agent B (a fresh instance with the Skill loaded) on related use cases. Observe whether Agent B finds the right information, applies rules correctly, and handles the task successfully.

  7. Iterate based on observation: If Agent B struggles or misses something, return to Agent A with specifics: "When the agent used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"

Iterating on existing Skills:

The same hierarchical pattern continues when improving Skills. You alternate between:

  • Working with Agent A (the expert who helps refine the Skill)
  • Testing with Agent B (the agent using the Skill to perform real work)
  • Observing Agent B's behavior and bringing insights back to Agent A
  1. Use the Skill in real workflows: Give Agent B (with the Skill loaded) actual tasks, not test scenarios

  2. Observe Agent B's behavior: Note where it struggles, succeeds, or makes unexpected choices

    Example observation: "When I asked Agent B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."

  3. Return to Agent A for improvements: Share the current SKILL.md and describe what you observed. Ask: "I noticed Agent B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?"

  4. Review Agent A's suggestions: Agent A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.

  5. Apply and test changes: Update the Skill with Agent A's refinements, then test again with Agent B on similar requests

  6. Repeat based on usage: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.

Gathering team feedback:

  1. Share Skills with teammates and observe their usage
  2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
  3. Incorporate feedback to address blind spots in your own usage patterns

Why this approach works: Agent A understands agent needs, you provide domain expertise, Agent B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.

Observe how agents navigate Skills

As you iterate on Skills, pay attention to how agents actually use them in practice. Watch for:

  • Unexpected exploration paths: Does the agent read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
  • Missed connections: Does the agent fail to follow references to important files? Your links might need to be more explicit or prominent
  • Overreliance on certain sections: If the agent repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
  • Ignored content: If the agent never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions

Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Agents use these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.

Anti-patterns to avoid

Avoid Windows-style paths

Always use forward slashes in file paths, even on Windows:

  • ✓ Good: scripts/helper.py, reference/guide.md
  • ✗ Avoid: scripts\helper.py, reference\guide.md

Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.

Avoid offering too many options

Don't present multiple approaches unless necessary:

**Bad example: Too many choices** (confusing):
"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."

**Good example: Provide a default** (with escape hatch):
"Use pdfplumber for text extraction:
```python
import pdfplumber
```

For scanned PDFs requiring OCR, use pdf2image with pytesseract instead."

Advanced: Skills with executable code

The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to Checklist for effective Skills.

Solve, don't punt

When writing scripts for Skills, handle error conditions rather than punting to the agent.

Good example: Handle errors explicitly:

def process_file(path):
    """Process a file, creating it if it doesn't exist."""
    try:
        with open(path) as f:
            return f.read()
    except FileNotFoundError:
        # Create file with default content instead of failing
        print(f"File {path} not found, creating default")
        with open(path, 'w') as f:
            f.write('')
        return ''
    except PermissionError:
        # Provide alternative instead of failing
        print(f"Cannot access {path}, using default")
        return ''

Bad example: Punt to the agent:

def process_file(path):
    # Just fail and let the agent figure it out
    return open(path).read()

Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will the agent determine it?

Good example: Self-documenting:

# HTTP requests typically complete within 30 seconds
# Longer timeout accounts for slow connections
REQUEST_TIMEOUT = 30

# Three retries balances reliability vs speed
# Most intermittent failures resolve by the second retry
MAX_RETRIES = 3

Bad example: Magic numbers:

TIMEOUT = 47  # Why 47?
RETRIES = 5   # Why 5?

Provide utility scripts

Even if your agent could write a script, pre-made scripts offer advantages:

Benefits of utility scripts:

  • More reliable than generated code
  • Save tokens (no need to include code in context)
  • Save time (no code generation required)
  • Ensure consistency across uses

The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and the agent can execute it without loading its contents into context.

Important distinction: Make clear in your instructions whether the agent should:

  • Execute the script (most common): "Run analyze_form.py to extract fields"
  • Read it as reference (for complex logic): "See analyze_form.py for the field extraction algorithm"

For most utility scripts, execution is preferred because it's more reliable and efficient. See the Runtime environment section below for details on how script execution works.

Example:

## Utility scripts

**analyze_form.py**: Extract all form fields from PDF

```bash
python scripts/analyze_form.py input.pdf > fields.json
```

Output format:
```json
{
  "field_name": {"type": "text", "x": 100, "y": 200},
  "signature": {"type": "sig", "x": 150, "y": 500}
}
```

**validate_boxes.py**: Check for overlapping bounding boxes

```bash
python scripts/validate_boxes.py fields.json
# Returns: "OK" or lists conflicts
```

**fill_form.py**: Apply field values to PDF

```bash
python scripts/fill_form.py input.pdf fields.json output.pdf
```

Use visual analysis

When inputs can be rendered as images, have the agent analyze them:

## Form layout analysis

1. Convert PDF to images:
   ```bash
   python scripts/pdf_to_images.py form.pdf
   ```

2. Analyze each page image to identify form fields
3. The agent can see field locations and types visually

Agent vision capabilities help understand layouts and structures.

Create verifiable intermediate outputs

When agents perform complex, open-ended tasks, they can make mistakes. The "plan-validate-execute" pattern catches errors early by having the agent first create a plan in a structured format, then validate that plan with a script before executing it.

Example: Imagine asking the agent to update 50 form fields in a PDF based on a spreadsheet. Without validation, it might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.

Solution: Use the workflow pattern shown above (PDF form filling), but add an intermediate changes.json file that gets validated before applying changes. The workflow becomes: analyze → create plan file → validate plan → execute → verify.

Why this pattern works:

  • Catches errors early: Validation finds problems before changes are applied
  • Machine-verifiable: Scripts provide objective verification
  • Reversible planning: The agent can iterate on the plan without touching originals
  • Clear debugging: Error messages point to specific problems

When to use: Batch operations, destructive changes, complex validation rules, high-stakes operations.

Implementation tip: Make validation scripts verbose with specific error messages like "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" to help the agent fix issues.

Package dependencies

Skills run in the code execution environment with platform-specific limitations:

  • claude.ai: Can install packages from npm and PyPI and pull from GitHub repositories
  • Anthropic API: Has no network access and no runtime package installation

List required packages in your SKILL.md and verify they're available in the code execution tool documentation.

Runtime environment

Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see The Skills architecture in the overview.

How this affects your authoring:

How agents access Skills:

  1. Metadata pre-loaded: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt
  2. Files read on-demand: Agents use their file-reading tools to access SKILL.md and other files from the filesystem when needed
  3. Scripts executed efficiently: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens
  4. No context penalty for large files: Reference files, data, or documentation don't consume context tokens until actually read
  • File paths matter: Agents navigate your skill directory like a filesystem. Use forward slashes (reference/guide.md), not backslashes
  • Name files descriptively: Use names that indicate content: form_validation_rules.md, not doc2.md
  • Organize for discovery: Structure directories by domain or feature
    • Good: reference/finance.md, reference/sales.md
    • Bad: docs/file1.md, docs/file2.md
  • Bundle comprehensive resources: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
  • Prefer scripts for deterministic operations: Write validate_form.py rather than asking the agent to generate validation code
  • Make execution intent clear:
    • "Run analyze_form.py to extract fields" (execute)
    • "See analyze_form.py for the extraction algorithm" (read as reference)
  • Test file access patterns: Verify the agent can navigate your directory structure by testing with real requests

Example:

bigquery-skill/
├── SKILL.md (overview, points to reference files)
└── reference/
    ├── finance.md (revenue metrics)
    ├── sales.md (pipeline data)
    └── product.md (usage analytics)

When the user asks about revenue, the agent reads SKILL.md, sees the reference to reference/finance.md, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Agents can navigate and selectively load exactly what each task requires.

For complete details on the technical architecture, see How Skills work in the Skills overview.

MCP tool references

If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.

Format: ServerName:tool_name

Example:

Use the BigQuery:bigquery_schema tool to retrieve table schemas.
Use the GitHub:create_issue tool to create issues.

Where:

  • BigQuery and GitHub are MCP server names
  • bigquery_schema and create_issue are the tool names within those servers

Without the server prefix, agents may fail to locate the tool, especially when multiple MCP servers are available.

Avoid assuming tools are installed

Don't assume packages are available:

**Bad example: Assumes installation**:
"Use the pdf library to process the file."

**Good example: Explicit about dependencies**:
"Install required package: `pip install pypdf`

Then use it:
```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"

Technical notes

YAML frontmatter requirements

The SKILL.md frontmatter requires name (64 characters max) and description (1024 characters max) fields. See the Skills overview for complete structure details.

Token budgets

Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the Skills overview.

Checklist for effective Skills

Before sharing a Skill, verify:

Core quality

  • [ ] Description is specific and includes key terms
  • [ ] Description includes both what the Skill does and when to use it
  • [ ] SKILL.md body is under 500 lines
  • [ ] Additional details are in separate files (if needed)
  • [ ] No time-sensitive information (or in "old patterns" section)
  • [ ] Consistent terminology throughout
  • [ ] Examples are concrete, not abstract
  • [ ] File references are one level deep
  • [ ] Progressive disclosure used appropriately
  • [ ] Workflows have clear steps

Code and scripts

  • [ ] Scripts solve problems rather than punt to the agent
  • [ ] Error handling is explicit and helpful
  • [ ] No "voodoo constants" (all values justified)
  • [ ] Required packages listed in instructions and verified as available
  • [ ] Scripts have clear documentation
  • [ ] No Windows-style paths (all forward slashes)
  • [ ] Validation/verification steps for critical operations
  • [ ] Feedback loops included for quality-critical tasks

Testing

  • [ ] At least three evaluations created
  • [ ] Tested with Haiku, Sonnet, and Opus
  • [ ] Tested with real usage scenarios
  • [ ] Team feedback incorporated (if applicable)

Next steps