Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:16:46 +08:00
commit 3d2cb201f0
33 changed files with 2911 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
# Changelog
## 0.2.0
- Refactored to Anthropic progressive disclosure pattern
- Updated description with "Use PROACTIVELY when..." format
- Removed version/author/category/tags from frontmatter
## 0.1.0
- Initial release of Structured Outputs Advisor skill
- Requirements gathering workflow
- Mode selection logic (JSON outputs vs strict tool use)
- Decision matrix for common scenarios
- Delegation patterns to specialized skills
- Mode selection examples covering 8 common scenarios

View File

@@ -0,0 +1,59 @@
# Structured Outputs Advisor
Expert advisor skill for choosing between JSON outputs and strict tool use modes in Anthropic's structured outputs feature.
## Purpose
This skill serves as the **entry point** for implementing structured outputs. It analyzes your requirements and recommends the right mode:
- **JSON Outputs** (`output_format`) - For data extraction, classification, API formatting
- **Strict Tool Use** (`strict: true`) - For agentic workflows, validated tool parameters
Then delegates to specialized implementation skills.
## When to Use
Invoke this skill when you need:
- Guaranteed JSON schema compliance
- Validated tool input parameters
- Structured data extraction
- Type-safe API responses
- Reliable agentic workflows
## Quick Start
**Trigger phrases:**
- "implement structured outputs"
- "need guaranteed JSON schema"
- "extract structured data from..."
- "build reliable agent with validated tools"
The advisor will ask questions to understand your use case and recommend the appropriate mode.
## Workflow
1. **Requirements gathering** - Understand what you're building
2. **Mode selection** - JSON outputs vs strict tool use
3. **Delegation** - Hand off to specialized skill for implementation
## Related Skills
- [`json-outputs-implementer`](../json-outputs-implementer/) - Implements JSON outputs mode
- [`strict-tool-implementer`](../strict-tool-implementer/) - Implements strict tool use mode
## Examples
See [mode-selection-examples.md](./examples/mode-selection-examples.md) for detailed scenarios.
## Documentation
- [Official Structured Outputs Docs](https://docs.anthropic.com/en/docs/build-with-claude/structured-outputs)
- [JSON Schema Limitations](../reference/json-schema-limitations.md)
- [Best Practices](../reference/best-practices.md)
- [API Compatibility](../reference/api-compatibility.md)
## Version
Current version: 0.1.0
See [CHANGELOG.md](./CHANGELOG.md) for version history.

View File

@@ -0,0 +1,283 @@
---
name: structured-outputs-advisor
description: Use PROACTIVELY when users need guaranteed schema compliance or validated tool inputs from Anthropic's structured outputs feature. Expert advisor for choosing between JSON outputs (data extraction/formatting) and strict tool use (agentic workflows). Analyzes requirements, explains trade-offs, and delegates to specialized implementation skills. Not for simple text responses or unstructured outputs.
---
# Structured Outputs Advisor
## Overview
This skill serves as the entry point for implementing Anthropic's structured outputs feature. It helps developers choose between **JSON outputs** (for data extraction/formatting) and **strict tool use** (for agentic workflows), then delegates to specialized implementation skills. The advisor ensures developers select the right mode based on their use case and requirements.
**Two Modes Available:**
1. **JSON Outputs** (`output_format`) - Guaranteed JSON schema compliance for responses
2. **Strict Tool Use** (`strict: true`) - Validated tool parameters for function calls
**Specialized Implementation Skills:**
- `json-outputs-implementer` - For data extraction, classification, API formatting
- `strict-tool-implementer` - For agentic workflows, validated function calls
## When to Use This Skill
**Trigger Phrases:**
- "implement structured outputs"
- "need guaranteed JSON schema"
- "extract structured data from [source]"
- "validate tool inputs"
- "build reliable agentic workflow"
- "ensure type-safe responses"
- "help me with structured outputs"
**Use Cases:**
- Data extraction from text/images
- Classification with guaranteed output format
- API response formatting
- Agentic workflows with validated tools
- Type-safe database operations
- Complex tool parameter validation
## Response Style
- **Consultative**: Ask questions to understand requirements
- **Educational**: Explain both modes and when to use each
- **Decisive**: Recommend the right mode based on use case
- **Delegating**: Hand off to specialized skills for implementation
- **Concise**: Keep mode selection phase quick (<5 questions)
## Core Workflow
### Phase 1: Understand Requirements
**Questions to Ask:**
1. **What's your goal?**
- "What kind of output do you need Claude to produce?"
- Examples: Extract invoice data, validate function parameters, classify tickets
2. **What's the data source?**
- Text, images, API calls, user input, etc.
3. **What consumes the output?**
- Database, API endpoint, function call, agent workflow, etc.
4. **How critical is schema compliance?**
- Must be guaranteed vs. generally reliable
### Phase 2: Mode Selection
**Use JSON Outputs (`output_format`) when:**
- ✅ You need Claude's **response** in a specific format
- ✅ Extracting structured data from unstructured sources
- ✅ Generating reports, classifications, or API responses
- ✅ Formatting output for downstream processing
- ✅ Single-step operations
**Examples:**
- Extract contact info from emails → CRM database
- Classify support tickets → routing system
- Generate structured reports → API endpoint
- Parse invoices → accounting software
**Use Strict Tool Use (`strict: true`) when:**
- ✅ You need validated **tool input parameters**
- ✅ Building multi-step agentic workflows
- ✅ Ensuring type-safe function calls
- ✅ Complex tools with many/nested properties
- ✅ Critical operations requiring guaranteed types
**Examples:**
- Travel booking agent (flights + hotels + activities)
- Database operations with strict type requirements
- API orchestration with validated parameters
- Complex workflow automation
### Phase 3: Delegation
**After determining the mode, delegate to the specialized skill:**
**For JSON Outputs:**
```
I recommend using JSON outputs for your [use case].
I'm going to invoke the json-outputs-implementer skill to help you:
1. Design a production-ready JSON schema
2. Implement with SDK helpers (Pydantic/Zod)
3. Add validation and error handling
4. Optimize for production
[Launch json-outputs-implementer skill]
```
**For Strict Tool Use:**
```
I recommend using strict tool use for your [use case].
I'm going to invoke the strict-tool-implementer skill to help you:
1. Design validated tool schemas
2. Implement strict mode correctly
3. Build reliable agent workflows
4. Test and validate tool calls
[Launch strict-tool-implementer skill]
```
**For Both Modes (Hybrid):**
```
Your use case requires both modes:
- JSON outputs for [specific use case]
- Strict tool use for [specific use case]
I'll help you implement both, starting with [primary mode].
[Launch appropriate skill first, then the second one]
```
## Decision Matrix
| Requirement | JSON Outputs | Strict Tool Use |
|-------------|--------------|-----------------|
| Extract structured data | ✅ Primary use case | ❌ Not designed for this |
| Validate function parameters | ❌ Not designed for this | ✅ Primary use case |
| Multi-step agent workflows | ⚠️ Possible but not ideal | ✅ Designed for this |
| API response formatting | ✅ Ideal | ❌ Unnecessary |
| Database inserts (type safety) | ✅ Good fit | ⚠️ If via tool calls |
| Complex nested schemas | ✅ Supports this | ✅ Supports this |
| Classification tasks | ✅ Perfect fit | ❌ Overkill |
| Tool composition/chaining | ❌ Not applicable | ✅ Excellent |
## Feature Availability
**Models Supported:**
- ✅ Claude Sonnet 4.5 (`claude-sonnet-4-5`)
- ✅ Claude Opus 4.1 (`claude-opus-4-1`)
**Beta Header Required:**
```
anthropic-beta: structured-outputs-2025-11-13
```
**Incompatible Features:**
- ❌ Citations (with JSON outputs)
- ❌ Message Prefilling (with JSON outputs)
**Compatible Features:**
- ✅ Batch Processing (50% discount)
- ✅ Token Counting
- ✅ Streaming
- ✅ Both modes together in same request
## Common Scenarios
### Scenario 1: "I need to extract invoice data"
**Analysis**: Data extraction from unstructured text
**Mode**: JSON Outputs
**Delegation**: `json-outputs-implementer`
**Reason**: Single-step extraction with structured output format
### Scenario 2: "Building a travel booking agent"
**Analysis**: Multi-tool workflow (flights, hotels, activities)
**Mode**: Strict Tool Use
**Delegation**: `strict-tool-implementer`
**Reason**: Multiple validated tools in agent workflow
### Scenario 3: "Classify customer support tickets"
**Analysis**: Classification with guaranteed categories
**Mode**: JSON Outputs
**Delegation**: `json-outputs-implementer`
**Reason**: Single classification result, structured response
### Scenario 4: "Validate database insert parameters"
**Analysis**: Type-safe database operations
**Mode**: JSON Outputs (if direct) OR Strict Tool Use (if via tool)
**Delegation**: Depends on architecture
**Reason**: Both work - choose based on system architecture
### Scenario 5: "Generate API-ready responses"
**Analysis**: Format responses for API consumption
**Mode**: JSON Outputs
**Delegation**: `json-outputs-implementer`
**Reason**: Output formatting is primary goal
## Quick Start Examples
### JSON Outputs Example
```python
# Extract contact information
from pydantic import BaseModel
from anthropic import Anthropic
class Contact(BaseModel):
name: str
email: str
plan: str
client = Anthropic()
response = client.beta.messages.parse(
model="claude-sonnet-4-5",
betas=["structured-outputs-2025-11-13"],
messages=[{"role": "user", "content": "Extract contact info..."}],
output_format=Contact,
)
contact = response.parsed_output # Guaranteed schema match
```
### Strict Tool Use Example
```python
# Validated tool for agent workflow
response = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["structured-outputs-2025-11-13"],
messages=[{"role": "user", "content": "Book a flight..."}],
tools=[{
"name": "book_flight",
"strict": True, # Guarantees schema compliance
"input_schema": {
"type": "object",
"properties": {
"destination": {"type": "string"},
"passengers": {"type": "integer"}
},
"required": ["destination"],
"additionalProperties": False
}
}]
)
# Tool inputs guaranteed to match schema
```
## Success Criteria
- [ ] Requirements clearly understood
- [ ] Data source identified
- [ ] Output consumer identified
- [ ] Correct mode selected (JSON outputs vs strict tool use)
- [ ] Reasoning for mode selection explained
- [ ] Appropriate specialized skill invoked
- [ ] User understands next steps
## Important Reminders
1. **Ask before assuming** - Don't guess the mode, understand requirements first
2. **One mode is usually enough** - Most use cases need only one mode
3. **Delegate quickly** - Keep advisor phase short, let specialists handle implementation
4. **Both modes work together** - Can use both in same request if needed
5. **Model availability** - Confirm Sonnet 4.5 or Opus 4.1 is available
6. **Beta feature** - Requires beta header in API requests
## Next Steps After Mode Selection
Once mode is selected and you've delegated to the specialized skill, that skill will handle:
- ✅ Schema design (respecting JSON Schema limitations)
- ✅ SDK integration (Pydantic/Zod helpers)
- ✅ Implementation with error handling
- ✅ Testing and validation
- ✅ Production optimization
- ✅ Complete examples and documentation
---
**Official Documentation**: https://docs.anthropic.com/en/docs/build-with-claude/structured-outputs
**Related Skills**:
- `json-outputs-implementer` - Implement JSON outputs mode
- `strict-tool-implementer` - Implement strict tool use mode

View File

@@ -0,0 +1,234 @@
# Mode Selection Examples
Real-world scenarios showing how the advisor helps choose between JSON outputs and strict tool use.
## Example 1: Invoice Data Extraction
**User Request:**
> "I need to extract invoice data from PDF documents and store it in our PostgreSQL database. The invoices contain line items, tax information, and customer details."
**Advisor Analysis:**
- **Goal:** Extract structured data from documents
- **Source:** PDF documents (unstructured)
- **Consumer:** PostgreSQL database (needs type-safe inserts)
- **Complexity:** Single-step extraction
**Recommended Mode:** JSON Outputs
**Reasoning:**
- This is a data extraction task (primary use case for JSON outputs)
- Single-step operation (extract → database)
- No multi-step agent workflow needed
- Schema compliance ensures database insert succeeds
**Next Step:**
Delegate to `json-outputs-implementer` to design invoice schema with line items, tax calculations, and customer info fields.
---
## Example 2: Travel Booking Agent
**User Request:**
> "Build an agent that can help users book complete travel itineraries. It should search for flights, compare options, book the chosen flight, find hotels near their destination, and book accommodation."
**Advisor Analysis:**
- **Goal:** Multi-step booking workflow
- **Source:** User conversation
- **Consumer:** Multiple external APIs (flights, hotels, booking systems)
- **Complexity:** Multi-tool agent workflow with sequential dependencies
**Recommended Mode:** Strict Tool Use
**Reasoning:**
- Multi-step workflow (search → compare → book → search → book)
- Multiple tools that need validated parameters
- Tool composition (flight booking influences hotel search location)
- Type-safe API calls are critical (booking with wrong parameters could charge cards incorrectly)
**Next Step:**
Delegate to `strict-tool-implementer` to design tool schemas for `search_flights`, `book_flight`, `search_hotels`, `book_hotel` with strict parameter validation.
---
## Example 3: Support Ticket Classification
**User Request:**
> "We receive thousands of support tickets daily. I need to automatically classify them by category (billing, technical, sales), priority level, and route them to the right team."
**Advisor Analysis:**
- **Goal:** Classification with routing
- **Source:** Support ticket text
- **Consumer:** Routing system + metrics dashboard
- **Complexity:** Single classification operation
**Recommended Mode:** JSON Outputs
**Reasoning:**
- Classification task (perfect for JSON outputs)
- Fixed output schema (category, priority, team, confidence)
- Single-step operation
- No tool execution needed (just classification output)
**Next Step:**
Delegate to `json-outputs-implementer` to design classification schema with enums for category/priority, confidence scoring, and routing metadata.
---
## Example 4: Database Query Agent
**User Request:**
> "I want an agent that can answer questions about our sales data. It should translate natural language questions into SQL, execute the queries safely, and return formatted results."
**Advisor Analysis:**
- **Goal:** Natural language → SQL query execution
- **Source:** User questions in natural language
- **Consumer:** Database + user (formatted results)
- **Complexity:** Tool execution with type-safe parameters + structured output
**Recommended Mode:** Both (Hybrid Approach)
**Reasoning:**
- Tool use for SQL execution: Need `execute_sql` tool with validated query parameters (prevent SQL injection)
- JSON outputs for response: Want structured results formatted consistently
- Two distinct phases: query generation/execution → result formatting
**Next Step:**
1. First: Delegate to `strict-tool-implementer` for `execute_sql` tool with strict validation
2. Then: Delegate to `json-outputs-implementer` for result formatting schema
---
## Example 5: Resume Parser
**User Request:**
> "Parse resumes in various formats (PDF, DOCX, plain text) and extract structured information: personal details, work experience, education, skills. Store in our ATS database."
**Advisor Analysis:**
- **Goal:** Extract structured data from documents
- **Source:** Resume documents (various formats)
- **Consumer:** ATS (Applicant Tracking System) database
- **Complexity:** Single extraction operation
**Recommended Mode:** JSON Outputs
**Reasoning:**
- Data extraction from unstructured documents
- Well-defined output schema (resume has standard sections)
- No tool execution needed
- Database insertion requires type-safe data
**Next Step:**
Delegate to `json-outputs-implementer` to design resume schema with nested objects for work experience, education, and skills arrays.
---
## Example 6: API Response Formatter
**User Request:**
> "Our API needs to return consistent JSON responses. Sometimes Claude generates the response data, and I need it formatted exactly to our API spec with status, data, errors, and metadata fields."
**Advisor Analysis:**
- **Goal:** Format API responses consistently
- **Source:** Claude-generated content
- **Consumer:** API clients (web/mobile apps)
- **Complexity:** Response formatting
**Recommended Mode:** JSON Outputs
**Reasoning:**
- Response formatting task
- Fixed API schema that must be followed exactly
- No tool execution
- Consistency is critical for API clients
**Next Step:**
Delegate to `json-outputs-implementer` to design API response schema matching the spec, with proper error handling structure.
---
## Example 7: Research Assistant Agent
**User Request:**
> "Build an agent that researches topics by searching the web, reading articles, extracting key facts, cross-referencing sources, and generating a comprehensive research report."
**Advisor Analysis:**
- **Goal:** Multi-step research workflow
- **Source:** Web (via search tools, article fetchers)
- **Consumer:** User (research report)
- **Complexity:** Multi-tool workflow with sequential and parallel steps + structured output
**Recommended Mode:** Both (Hybrid Approach)
**Reasoning:**
- Research phase: Need tools (`search_web`, `fetch_article`, `extract_facts`) with strict validation
- Report phase: Need structured report output (JSON outputs)
- Complex workflow with multiple stages
**Next Step:**
1. First: Delegate to `strict-tool-implementer` for research tools
2. Then: Delegate to `json-outputs-implementer` for final report schema
---
## Example 8: Form Data Extraction
**User Request:**
> "Users upload scanned forms (insurance claims, applications, etc.). Extract all form fields into a structured format for processing."
**Advisor Analysis:**
- **Goal:** Extract form data
- **Source:** Scanned form images
- **Consumer:** Processing system
- **Complexity:** Single extraction
**Recommended Mode:** JSON Outputs
**Reasoning:**
- Image data extraction
- Form has known structure (predefined fields)
- No tool execution
- Type-safe data needed for downstream processing
**Next Step:**
Delegate to `json-outputs-implementer` to design form schema matching the expected fields with proper types.
---
## Decision Patterns Summary
| Scenario Type | Recommended Mode | Key Indicator |
|---------------|------------------|---------------|
| Data extraction | JSON Outputs | "Extract X from Y" |
| Classification | JSON Outputs | "Classify/categorize X" |
| API formatting | JSON Outputs | "Format response as X" |
| Report generation | JSON Outputs | "Generate report with X structure" |
| Multi-tool workflow | Strict Tool Use | "Search, then book, then..." |
| Agent with tools | Strict Tool Use | "Agent that can call X, Y, Z" |
| Type-safe function calls | Strict Tool Use | "Validate parameters for X" |
| Complex agents | Both | "Research then report" / "Query then format" |
---
## Common Misconceptions
### ❌ "I need reliable JSON, so I should use strict tool use"
**Correction:** Use JSON outputs for reliable JSON responses. Strict tool use is for tool **parameters**, not Claude's response format.
### ❌ "My agent just needs one tool, so I should use JSON outputs"
**Correction:** Even a single-tool agent benefits from strict tool use if the tool needs parameter validation. Mode choice is about **what** you're validating, not **how many** tools.
### ❌ "I can use both modes for the same thing"
**Correction:** Each mode has a specific purpose:
- JSON outputs: Claude's response format
- Strict tool use: Tool input validation
They solve different problems and can be combined when you need both.
---
**See Also:**
- [JSON Outputs Implementer Examples](../../json-outputs-implementer/examples/)
- [Strict Tool Implementer Examples](../../strict-tool-implementer/examples/)