[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M758RH2AJCWDENNMM15CVM6S":3,"skill-same:01M758RH2AJCWDENNMM15CVM6S":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":53,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M758RH2AJCWDENNMM15CVM6S","instructor",null,"Structured LLM outputs validated with Pydantic.","lukemcqueen\u002Fsteadfaste-fleet","lukemcqueen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F405240?v=4","01M757MHPAGRXTJAT46SKZP98R","Luke McQueen","01M757MHPZ573KP8DT9GB8SBQ7",4,"MIT","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fmlops\u002Finstructor\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: instructor\ndescription: Structured LLM outputs validated with Pydantic.\nversion: 1.0.0\nauthor: Orchestra Research\nlicense: MIT\ndependencies: [instructor, pydantic, openai, anthropic]\nplatforms: [linux, macos, windows]\nmetadata:\n  hermes:\n    tags: [Prompt Engineering, Instructor, Structured Output, Pydantic, Data Extraction, JSON Parsing, Type Safety, Validation, Streaming, OpenAI, Anthropic]\n\n---\n\n# Instructor: Structured LLM Outputs\n\n## When to Use This Skill\n\nUse Instructor when you need to:\n- **Extract structured data** from LLM responses reliably\n- **Validate outputs** against Pydantic schemas automatically\n- **Retry failed extractions** with automatic error handling\n- **Parse complex JSON** with type safety and validation\n- **Stream partial results** for real-time processing\n- **Support multiple LLM providers** with consistent API\n\n**GitHub Stars**: 15,000+ | **Battle-tested**: 100,000+ developers\n\n## Installation\n\n```bash\n# Base installation\npip install instructor\n\n# With specific providers\npip install \"instructor[anthropic]\"  # Anthropic Claude\npip install \"instructor[openai]\"     # OpenAI\npip install \"instructor[all]\"        # All providers\n```\n\n## Quick Start\n\n### Basic Example: Extract User Data\n\n```python\nimport instructor\nfrom pydantic import BaseModel\nfrom anthropic import Anthropic\n\n# Define output structure\nclass User(BaseModel):\n    name: str\n    age: int\n    email: str\n\n# Create instructor client\nclient = instructor.from_anthropic(Anthropic())\n\n# Extract structured data\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"John Doe is 30 years old. His email is john@example.com\"\n    }],\n    response_model=User\n)\n\nprint(user.name)   # \"John Doe\"\nprint(user.age)    # 30\nprint(user.email)  # \"john@example.com\"\n```\n\n### With OpenAI\n\n```python\nfrom openai import OpenAI\n\nclient = instructor.from_openai(OpenAI())\n\nuser = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    response_model=User,\n    messages=[{\"role\": \"user\", \"content\": \"Extract: Alice, 25, alice@email.com\"}]\n)\n```\n\n## Core Concepts\n\n### 1. Response Models (Pydantic)\n\nResponse models define the structure and validation rules for LLM outputs.\n\n#### Basic Model\n\n```python\nfrom pydantic import BaseModel, Field\n\nclass Article(BaseModel):\n    title: str = Field(description=\"Article title\")\n    author: str = Field(description=\"Author name\")\n    word_count: int = Field(description=\"Number of words\", gt=0)\n    tags: list[str] = Field(description=\"List of relevant tags\")\n\narticle = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Analyze this article: [article text]\"\n    }],\n    response_model=Article\n)\n```\n\n**Benefits:**\n- Type safety with Python type hints\n- Automatic validation (word_count > 0)\n- Self-documenting with Field descriptions\n- IDE autocomplete support\n\n#### Nested Models\n\n```python\nclass Address(BaseModel):\n    street: str\n    city: str\n    country: str\n\nclass Person(BaseModel):\n    name: str\n    age: int\n    address: Address  # Nested model\n\nperson = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"John lives at 123 Main St, Boston, USA\"\n    }],\n    response_model=Person\n)\n\nprint(person.address.city)  # \"Boston\"\n```\n\n#### Optional Fields\n\n```python\nfrom typing import Optional\n\nclass Product(BaseModel):\n    name: str\n    price: float\n    discount: Optional[float] = None  # Optional\n    description: str = Field(default=\"No description\")  # Default value\n\n# LLM doesn't need to provide discount or description\n```\n\n#### Enums for Constraints\n\n```python\nfrom enum import Enum\n\nclass Sentiment(str, Enum):\n    POSITIVE = \"positive\"\n    NEGATIVE = \"negative\"\n    NEUTRAL = \"neutral\"\n\nclass Review(BaseModel):\n    text: str\n    sentiment: Sentiment  # Only these 3 values allowed\n\nreview = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"This product is amazing!\"\n    }],\n    response_model=Review\n)\n\nprint(review.sentiment)  # Sentiment.POSITIVE\n```\n\n### 2. Validation\n\nPydantic validates LLM outputs automatically. If validation fails, Instructor retries.\n\n#### Built-in Validators\n\n```python\nfrom pydantic import Field, EmailStr, HttpUrl\n\nclass Contact(BaseModel):\n    name: str = Field(min_length=2, max_length=100)\n    age: int = Field(ge=0, le=120)  # 0 \u003C= age \u003C= 120\n    email: EmailStr  # Validates email format\n    website: HttpUrl  # Validates URL format\n\n# If LLM provides invalid data, Instructor retries automatically\n```\n\n#### Custom Validators\n\n```python\nfrom pydantic import field_validator\n\nclass Event(BaseModel):\n    name: str\n    date: str\n    attendees: int\n\n    @field_validator('date')\n    def validate_date(cls, v):\n        \"\"\"Ensure date is in YYYY-MM-DD format.\"\"\"\n        import re\n        if not re.match(r'\\d{4}-\\d{2}-\\d{2}', v):\n            raise ValueError('Date must be YYYY-MM-DD format')\n        return v\n\n    @field_validator('attendees')\n    def validate_attendees(cls, v):\n        \"\"\"Ensure positive attendees.\"\"\"\n        if v \u003C 1:\n            raise ValueError('Must have at least 1 attendee')\n        return v\n```\n\n#### Model-Level Validation\n\n```python\nfrom pydantic import model_validator\n\nclass DateRange(BaseModel):\n    start_date: str\n    end_date: str\n\n    @model_validator(mode='after')\n    def check_dates(self):\n        \"\"\"Ensure end_date is after start_date.\"\"\"\n        from datetime import datetime\n        start = datetime.strptime(self.start_date, '%Y-%m-%d')\n        end = datetime.strptime(self.end_date, '%Y-%m-%d')\n\n        if end \u003C start:\n            raise ValueError('end_date must be after start_date')\n        return self\n```\n\n### 3. Automatic Retrying\n\nInstructor retries automatically when validation fails, providing error feedback to the LLM.\n\n```python\n# Retries up to 3 times if validation fails\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Extract user from: John, age unknown\"\n    }],\n    response_model=User,\n    max_retries=3  # Default is 3\n)\n\n# If age can't be extracted, Instructor tells the LLM:\n# \"Validation error: age - field required\"\n# LLM tries again with better extraction\n```\n\n**How it works:**\n1. LLM generates output\n2. Pydantic validates\n3. If invalid: Error message sent back to LLM\n4. LLM tries again with error feedback\n5. Repeats up to max_retries\n\n### 4. Streaming\n\nStream partial results for real-time processing.\n\n#### Streaming Partial Objects\n\n```python\nfrom instructor import Partial\n\nclass Story(BaseModel):\n    title: str\n    content: str\n    tags: list[str]\n\n# Stream partial updates as LLM generates\nfor partial_story in client.messages.create_partial(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Write a short sci-fi story\"\n    }],\n    response_model=Story\n):\n    print(f\"Title: {partial_story.title}\")\n    print(f\"Content so far: {partial_story.content[:100]}...\")\n    # Update UI in real-time\n```\n\n#### Streaming Iterables\n\n```python\nclass Task(BaseModel):\n    title: str\n    priority: str\n\n# Stream list items as they're generated\ntasks = client.messages.create_iterable(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Generate 10 project tasks\"\n    }],\n    response_model=Task\n)\n\nfor task in tasks:\n    print(f\"- {task.title} ({task.priority})\")\n    # Process each task as it arrives\n```\n\n## Provider Configuration\n\n### Anthropic Claude\n\n```python\nimport instructor\nfrom anthropic import Anthropic\n\nclient = instructor.from_anthropic(\n    Anthropic(api_key=\"your-api-key\")\n)\n\n# Use with Claude models\nresponse = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[...],\n    response_model=YourModel\n)\n```\n\n### OpenAI\n\n```python\nfrom openai import OpenAI\n\nclient = instructor.from_openai(\n    OpenAI(api_key=\"your-api-key\")\n)\n\nresponse = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    response_model=YourModel,\n    messages=[...]\n)\n```\n\n### Local Models (Ollama)\n\n```python\nfrom openai import OpenAI\n\n# Point to local Ollama server\nclient = instructor.from_openai(\n    OpenAI(\n        base_url=\"http:\u002F\u002Flocalhost:11434\u002Fv1\",\n        api_key=\"ollama\"  # Required but ignored\n    ),\n    mode=instructor.Mode.JSON\n)\n\nresponse = client.chat.completions.create(\n    model=\"llama3.1\",\n    response_model=YourModel,\n    messages=[...]\n)\n```\n\n## Common Patterns\n\n### Pattern 1: Data Extraction from Text\n\n```python\nclass CompanyInfo(BaseModel):\n    name: str\n    founded_year: int\n    industry: str\n    employees: int\n    headquarters: str\n\ntext = \"\"\"\nTesla, Inc. was founded in 2003. It operates in the automotive and energy\nindustry with approximately 140,000 employees. The company is headquartered\nin Austin, Texas.\n\"\"\"\n\ncompany = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Extract company information from: {text}\"\n    }],\n    response_model=CompanyInfo\n)\n```\n\n### Pattern 2: Classification\n\n```python\nclass Category(str, Enum):\n    TECHNOLOGY = \"technology\"\n    FINANCE = \"finance\"\n    HEALTHCARE = \"healthcare\"\n    EDUCATION = \"education\"\n    OTHER = \"other\"\n\nclass ArticleClassification(BaseModel):\n    category: Category\n    confidence: float = Field(ge=0.0, le=1.0)\n    keywords: list[str]\n\nclassification = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Classify this article: [article text]\"\n    }],\n    response_model=ArticleClassification\n)\n```\n\n### Pattern 3: Multi-Entity Extraction\n\n```python\nclass Person(BaseModel):\n    name: str\n    role: str\n\nclass Organization(BaseModel):\n    name: str\n    industry: str\n\nclass Entities(BaseModel):\n    people: list[Person]\n    organizations: list[Organization]\n    locations: list[str]\n\ntext = \"Tim Cook, CEO of Apple, announced at the event in Cupertino...\"\n\nentities = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Extract all entities from: {text}\"\n    }],\n    response_model=Entities\n)\n\nfor person in entities.people:\n    print(f\"{person.name} - {person.role}\")\n```\n\n### Pattern 4: Structured Analysis\n\n```python\nclass SentimentAnalysis(BaseModel):\n    overall_sentiment: Sentiment\n    positive_aspects: list[str]\n    negative_aspects: list[str]\n    suggestions: list[str]\n    score: float = Field(ge=-1.0, le=1.0)\n\nreview = \"The product works well but setup was confusing...\"\n\nanalysis = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Analyze this review: {review}\"\n    }],\n    response_model=SentimentAnalysis\n)\n```\n\n### Pattern 5: Batch Processing\n\n```python\ndef extract_person(text: str) -> Person:\n    return client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": f\"Extract person from: {text}\"\n        }],\n        response_model=Person\n    )\n\ntexts = [\n    \"John Doe is a 30-year-old engineer\",\n    \"Jane Smith, 25, works in marketing\",\n    \"Bob Johnson, age 40, software developer\"\n]\n\npeople = [extract_person(text) for text in texts]\n```\n\n## Advanced Features\n\n### Union Types\n\n```python\nfrom typing import Union\n\nclass TextContent(BaseModel):\n    type: str = \"text\"\n    content: str\n\nclass ImageContent(BaseModel):\n    type: str = \"image\"\n    url: HttpUrl\n    caption: str\n\nclass Post(BaseModel):\n    title: str\n    content: Union[TextContent, ImageContent]  # Either type\n\n# LLM chooses appropriate type based on content\n```\n\n### Dynamic Models\n\n```python\nfrom pydantic import create_model\n\n# Create model at runtime\nDynamicUser = create_model(\n    'User',\n    name=(str, ...),\n    age=(int, Field(ge=0)),\n    email=(EmailStr, ...)\n)\n\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[...],\n    response_model=DynamicUser\n)\n```\n\n### Custom Modes\n\n```python\n# For providers without native structured outputs\nclient = instructor.from_anthropic(\n    Anthropic(),\n    mode=instructor.Mode.JSON  # JSON mode\n)\n\n# Available modes:\n# - Mode.ANTHROPIC_TOOLS (recommended for Claude)\n# - Mode.JSON (fallback)\n# - Mode.TOOLS (OpenAI tools)\n```\n\n### Context Management\n\n```python\n# Single-use client\nwith instructor.from_anthropic(Anthropic()) as client:\n    result = client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[...],\n        response_model=YourModel\n    )\n    # Client closed automatically\n```\n\n## Error Handling\n\n### Handling Validation Errors\n\n```python\nfrom pydantic import ValidationError\n\ntry:\n    user = client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[...],\n        response_model=User,\n        max_retries=3\n    )\nexcept ValidationError as e:\n    print(f\"Failed after retries: {e}\")\n    # Handle gracefully\n\nexcept Exception as e:\n    print(f\"API error: {e}\")\n```\n\n### Custom Error Messages\n\n```python\nclass ValidatedUser(BaseModel):\n    name: str = Field(description=\"Full name, 2-100 characters\")\n    age: int = Field(description=\"Age between 0 and 120\", ge=0, le=120)\n    email: EmailStr = Field(description=\"Valid email address\")\n\n    class Config:\n        # Custom error messages\n        json_schema_extra = {\n            \"examples\": [\n                {\n                    \"name\": \"John Doe\",\n                    \"age\": 30,\n                    \"email\": \"john@example.com\"\n                }\n            ]\n        }\n```\n\n## Best Practices\n\n### 1. Clear Field Descriptions\n\n```python\n# ❌ Bad: Vague\nclass Product(BaseModel):\n    name: str\n    price: float\n\n# ✅ Good: Descriptive\nclass Product(BaseModel):\n    name: str = Field(description=\"Product name from the text\")\n    price: float = Field(description=\"Price in USD, without currency symbol\")\n```\n\n### 2. Use Appropriate Validation\n\n```python\n# ✅ Good: Constrain values\nclass Rating(BaseModel):\n    score: int = Field(ge=1, le=5, description=\"Rating from 1 to 5 stars\")\n    review: str = Field(min_length=10, description=\"Review text, at least 10 chars\")\n```\n\n### 3. Provide Examples in Prompts\n\n```python\nmessages = [{\n    \"role\": \"user\",\n    \"content\": \"\"\"Extract person info from: \"John, 30, engineer\"\n\nExample format:\n{\n  \"name\": \"John Doe\",\n  \"age\": 30,\n  \"occupation\": \"engineer\"\n}\"\"\"\n}]\n```\n\n### 4. Use Enums for Fixed Categories\n\n```python\n# ✅ Good: Enum ensures valid values\nclass Status(str, Enum):\n    PENDING = \"pending\"\n    APPROVED = \"approved\"\n    REJECTED = \"rejected\"\n\nclass Application(BaseModel):\n    status: Status  # LLM must choose from enum\n```\n\n### 5. Handle Missing Data Gracefully\n\n```python\nclass PartialData(BaseModel):\n    required_field: str\n    optional_field: Optional[str] = None\n    default_field: str = \"default_value\"\n\n# LLM only needs to provide required_field\n```\n\n## Comparison to Alternatives\n\n| Feature | Instructor | Manual JSON | LangChain | DSPy |\n|---------|------------|-------------|-----------|------|\n| Type Safety | ✅ Yes | ❌ No | ⚠️ Partial | ✅ Yes |\n| Auto Validation | ✅ Yes | ❌ No | ❌ No | ⚠️ Limited |\n| Auto Retry | ✅ Yes | ❌ No | ❌ No | ✅ Yes |\n| Streaming | ✅ Yes | ❌ No | ✅ Yes | ❌ No |\n| Multi-Provider | ✅ Yes | ⚠️ Manual | ✅ Yes | ✅ Yes |\n| Learning Curve | Low | Low | Medium | High |\n\n**When to choose Instructor:**\n- Need structured, validated outputs\n- Want type safety and IDE support\n- Require automatic retries\n- Building data extraction systems\n\n**When to choose alternatives:**\n- DSPy: Need prompt optimization\n- LangChain: Building complex chains\n- Manual: Simple, one-off extractions\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fpython.useinstructor.com\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fjxnl\u002Finstructor (15k+ stars)\n- **Cookbook**: https:\u002F\u002Fpython.useinstructor.com\u002Fexamples\n- **Discord**: Community support available\n\n## See Also\n\n- `references\u002Fvalidation.md` - Advanced validation patterns\n- `references\u002Fproviders.md` - Provider-specific configuration\n- `references\u002Fexamples.md` - Real-world use cases\n\n\n","# Instructor: Structured LLM Outputs\n\n## When to Use This Skill\n\nUse Instructor when you need to:\n- **Extract structured data** from LLM responses reliably\n- **Validate outputs** against Pydantic schemas automatically\n- **Retry failed extractions** with automatic error handling\n- **Parse complex JSON** with type safety and validation\n- **Stream partial results** for real-time processing\n- **Support multiple LLM providers** with consistent API\n\n**GitHub Stars**: 15,000+ | **Battle-tested**: 100,000+ developers\n\n## Installation\n\n```bash\n# Base installation\npip install instructor\n\n# With specific providers\npip install \"instructor[anthropic]\"  # Anthropic Claude\npip install \"instructor[openai]\"     # OpenAI\npip install \"instructor[all]\"        # All providers\n```\n\n## Quick Start\n\n### Basic Example: Extract User Data\n\n```python\nimport instructor\nfrom pydantic import BaseModel\nfrom anthropic import Anthropic\n\n# Define output structure\nclass User(BaseModel):\n    name: str\n    age: int\n    email: str\n\n# Create instructor client\nclient = instructor.from_anthropic(Anthropic())\n\n# Extract structured data\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"John Doe is 30 years old. His email is john@example.com\"\n    }],\n    response_model=User\n)\n\nprint(user.name)   # \"John Doe\"\nprint(user.age)    # 30\nprint(user.email)  # \"john@example.com\"\n```\n\n### With OpenAI\n\n```python\nfrom openai import OpenAI\n\nclient = instructor.from_openai(OpenAI())\n\nuser = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    response_model=User,\n    messages=[{\"role\": \"user\", \"content\": \"Extract: Alice, 25, alice@email.com\"}]\n)\n```\n\n## Core Concepts\n\n### 1. Response Models (Pydantic)\n\nResponse models define the structure and validation rules for LLM outputs.\n\n#### Basic Model\n\n```python\nfrom pydantic import BaseModel, Field\n\nclass Article(BaseModel):\n    title: str = Field(description=\"Article title\")\n    author: str = Field(description=\"Author name\")\n    word_count: int = Field(description=\"Number of words\", gt=0)\n    tags: list[str] = Field(description=\"List of relevant tags\")\n\narticle = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Analyze this article: [article text]\"\n    }],\n    response_model=Article\n)\n```\n\n**Benefits:**\n- Type safety with Python type hints\n- Automatic validation (word_count > 0)\n- Self-documenting with Field descriptions\n- IDE autocomplete support\n\n#### Nested Models\n\n```python\nclass Address(BaseModel):\n    street: str\n    city: str\n    country: str\n\nclass Person(BaseModel):\n    name: str\n    age: int\n    address: Address  # Nested model\n\nperson = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"John lives at 123 Main St, Boston, USA\"\n    }],\n    response_model=Person\n)\n\nprint(person.address.city)  # \"Boston\"\n```\n\n#### Optional Fields\n\n```python\nfrom typing import Optional\n\nclass Product(BaseModel):\n    name: str\n    price: float\n    discount: Optional[float] = None  # Optional\n    description: str = Field(default=\"No description\")  # Default value\n\n# LLM doesn't need to provide discount or description\n```\n\n#### Enums for Constraints\n\n```python\nfrom enum import Enum\n\nclass Sentiment(str, Enum):\n    POSITIVE = \"positive\"\n    NEGATIVE = \"negative\"\n    NEUTRAL = \"neutral\"\n\nclass Review(BaseModel):\n    text: str\n    sentiment: Sentiment  # Only these 3 values allowed\n\nreview = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"This product is amazing!\"\n    }],\n    response_model=Review\n)\n\nprint(review.sentiment)  # Sentiment.POSITIVE\n```\n\n### 2. Validation\n\nPydantic validates LLM outputs automatically. If validation fails, Instructor retries.\n\n#### Built-in Validators\n\n```python\nfrom pydantic import Field, EmailStr, HttpUrl\n\nclass Contact(BaseModel):\n    name: str = Field(min_length=2, max_length=100)\n    age: int = Field(ge=0, le=120)  # 0 \u003C= age \u003C= 120\n    email: EmailStr  # Validates email format\n    website: HttpUrl  # Validates URL format\n\n# If LLM provides invalid data, Instructor retries automatically\n```\n\n#### Custom Validators\n\n```python\nfrom pydantic import field_validator\n\nclass Event(BaseModel):\n    name: str\n    date: str\n    attendees: int\n\n    @field_validator('date')\n    def validate_date(cls, v):\n        \"\"\"Ensure date is in YYYY-MM-DD format.\"\"\"\n        import re\n        if not re.match(r'\\d{4}-\\d{2}-\\d{2}', v):\n            raise ValueError('Date must be YYYY-MM-DD format')\n        return v\n\n    @field_validator('attendees')\n    def validate_attendees(cls, v):\n        \"\"\"Ensure positive attendees.\"\"\"\n        if v \u003C 1:\n            raise ValueError('Must have at least 1 attendee')\n        return v\n```\n\n#### Model-Level Validation\n\n```python\nfrom pydantic import model_validator\n\nclass DateRange(BaseModel):\n    start_date: str\n    end_date: str\n\n    @model_validator(mode='after')\n    def check_dates(self):\n        \"\"\"Ensure end_date is after start_date.\"\"\"\n        from datetime import datetime\n        start = datetime.strptime(self.start_date, '%Y-%m-%d')\n        end = datetime.strptime(self.end_date, '%Y-%m-%d')\n\n        if end \u003C start:\n            raise ValueError('end_date must be after start_date')\n        return self\n```\n\n### 3. Automatic Retrying\n\nInstructor retries automatically when validation fails, providing error feedback to the LLM.\n\n```python\n# Retries up to 3 times if validation fails\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Extract user from: John, age unknown\"\n    }],\n    response_model=User,\n    max_retries=3  # Default is 3\n)\n\n# If age can't be extracted, Instructor tells the LLM:\n# \"Validation error: age - field required\"\n# LLM tries again with better extraction\n```\n\n**How it works:**\n1. LLM generates output\n2. Pydantic validates\n3. If invalid: Error message sent back to LLM\n4. LLM tries again with error feedback\n5. Repeats up to max_retries\n\n### 4. Streaming\n\nStream partial results for real-time processing.\n\n#### Streaming Partial Objects\n\n```python\nfrom instructor import Partial\n\nclass Story(BaseModel):\n    title: str\n    content: str\n    tags: list[str]\n\n# Stream partial updates as LLM generates\nfor partial_story in client.messages.create_partial(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Write a short sci-fi story\"\n    }],\n    response_model=Story\n):\n    print(f\"Title: {partial_story.title}\")\n    print(f\"Content so far: {partial_story.content[:100]}...\")\n    # Update UI in real-time\n```\n\n#### Streaming Iterables\n\n```python\nclass Task(BaseModel):\n    title: str\n    priority: str\n\n# Stream list items as they're generated\ntasks = client.messages.create_iterable(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Generate 10 project tasks\"\n    }],\n    response_model=Task\n)\n\nfor task in tasks:\n    print(f\"- {task.title} ({task.priority})\")\n    # Process each task as it arrives\n```\n\n## Provider Configuration\n\n### Anthropic Claude\n\n```python\nimport instructor\nfrom anthropic import Anthropic\n\nclient = instructor.from_anthropic(\n    Anthropic(api_key=\"your-api-key\")\n)\n\n# Use with Claude models\nresponse = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[...],\n    response_model=YourModel\n)\n```\n\n### OpenAI\n\n```python\nfrom openai import OpenAI\n\nclient = instructor.from_openai(\n    OpenAI(api_key=\"your-api-key\")\n)\n\nresponse = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    response_model=YourModel,\n    messages=[...]\n)\n```\n\n### Local Models (Ollama)\n\n```python\nfrom openai import OpenAI\n\n# Point to local Ollama server\nclient = instructor.from_openai(\n    OpenAI(\n        base_url=\"http:\u002F\u002Flocalhost:11434\u002Fv1\",\n        api_key=\"ollama\"  # Required but ignored\n    ),\n    mode=instructor.Mode.JSON\n)\n\nresponse = client.chat.completions.create(\n    model=\"llama3.1\",\n    response_model=YourModel,\n    messages=[...]\n)\n```\n\n## Common Patterns\n\n### Pattern 1: Data Extraction from Text\n\n```python\nclass CompanyInfo(BaseModel):\n    name: str\n    founded_year: int\n    industry: str\n    employees: int\n    headquarters: str\n\ntext = \"\"\"\nTesla, Inc. was founded in 2003. It operates in the automotive and energy\nindustry with approximately 140,000 employees. The company is headquartered\nin Austin, Texas.\n\"\"\"\n\ncompany = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Extract company information from: {text}\"\n    }],\n    response_model=CompanyInfo\n)\n```\n\n### Pattern 2: Classification\n\n```python\nclass Category(str, Enum):\n    TECHNOLOGY = \"technology\"\n    FINANCE = \"finance\"\n    HEALTHCARE = \"healthcare\"\n    EDUCATION = \"education\"\n    OTHER = \"other\"\n\nclass ArticleClassification(BaseModel):\n    category: Category\n    confidence: float = Field(ge=0.0, le=1.0)\n    keywords: list[str]\n\nclassification = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": \"Classify this article: [article text]\"\n    }],\n    response_model=ArticleClassification\n)\n```\n\n### Pattern 3: Multi-Entity Extraction\n\n```python\nclass Person(BaseModel):\n    name: str\n    role: str\n\nclass Organization(BaseModel):\n    name: str\n    industry: str\n\nclass Entities(BaseModel):\n    people: list[Person]\n    organizations: list[Organization]\n    locations: list[str]\n\ntext = \"Tim Cook, CEO of Apple, announced at the event in Cupertino...\"\n\nentities = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Extract all entities from: {text}\"\n    }],\n    response_model=Entities\n)\n\nfor person in entities.people:\n    print(f\"{person.name} - {person.role}\")\n```\n\n### Pattern 4: Structured Analysis\n\n```python\nclass SentimentAnalysis(BaseModel):\n    overall_sentiment: Sentiment\n    positive_aspects: list[str]\n    negative_aspects: list[str]\n    suggestions: list[str]\n    score: float = Field(ge=-1.0, le=1.0)\n\nreview = \"The product works well but setup was confusing...\"\n\nanalysis = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[{\n        \"role\": \"user\",\n        \"content\": f\"Analyze this review: {review}\"\n    }],\n    response_model=SentimentAnalysis\n)\n```\n\n### Pattern 5: Batch Processing\n\n```python\ndef extract_person(text: str) -> Person:\n    return client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": f\"Extract person from: {text}\"\n        }],\n        response_model=Person\n    )\n\ntexts = [\n    \"John Doe is a 30-year-old engineer\",\n    \"Jane Smith, 25, works in marketing\",\n    \"Bob Johnson, age 40, software developer\"\n]\n\npeople = [extract_person(text) for text in texts]\n```\n\n## Advanced Features\n\n### Union Types\n\n```python\nfrom typing import Union\n\nclass TextContent(BaseModel):\n    type: str = \"text\"\n    content: str\n\nclass ImageContent(BaseModel):\n    type: str = \"image\"\n    url: HttpUrl\n    caption: str\n\nclass Post(BaseModel):\n    title: str\n    content: Union[TextContent, ImageContent]  # Either type\n\n# LLM chooses appropriate type based on content\n```\n\n### Dynamic Models\n\n```python\nfrom pydantic import create_model\n\n# Create model at runtime\nDynamicUser = create_model(\n    'User',\n    name=(str, ...),\n    age=(int, Field(ge=0)),\n    email=(EmailStr, ...)\n)\n\nuser = client.messages.create(\n    model=\"claude-sonnet-4-5-20250929\",\n    max_tokens=1024,\n    messages=[...],\n    response_model=DynamicUser\n)\n```\n\n### Custom Modes\n\n```python\n# For providers without native structured outputs\nclient = instructor.from_anthropic(\n    Anthropic(),\n    mode=instructor.Mode.JSON  # JSON mode\n)\n\n# Available modes:\n# - Mode.ANTHROPIC_TOOLS (recommended for Claude)\n# - Mode.JSON (fallback)\n# - Mode.TOOLS (OpenAI tools)\n```\n\n### Context Management\n\n```python\n# Single-use client\nwith instructor.from_anthropic(Anthropic()) as client:\n    result = client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[...],\n        response_model=YourModel\n    )\n    # Client closed automatically\n```\n\n## Error Handling\n\n### Handling Validation Errors\n\n```python\nfrom pydantic import ValidationError\n\ntry:\n    user = client.messages.create(\n        model=\"claude-sonnet-4-5-20250929\",\n        max_tokens=1024,\n        messages=[...],\n        response_model=User,\n        max_retries=3\n    )\nexcept ValidationError as e:\n    print(f\"Failed after retries: {e}\")\n    # Handle gracefully\n\nexcept Exception as e:\n    print(f\"API error: {e}\")\n```\n\n### Custom Error Messages\n\n```python\nclass ValidatedUser(BaseModel):\n    name: str = Field(description=\"Full name, 2-100 characters\")\n    age: int = Field(description=\"Age between 0 and 120\", ge=0, le=120)\n    email: EmailStr = Field(description=\"Valid email address\")\n\n    class Config:\n        # Custom error messages\n        json_schema_extra = {\n            \"examples\": [\n                {\n                    \"name\": \"John Doe\",\n                    \"age\": 30,\n                    \"email\": \"john@example.com\"\n                }\n            ]\n        }\n```\n\n## Best Practices\n\n### 1. Clear Field Descriptions\n\n```python\n# ❌ Bad: Vague\nclass Product(BaseModel):\n    name: str\n    price: float\n\n# ✅ Good: Descriptive\nclass Product(BaseModel):\n    name: str = Field(description=\"Product name from the text\")\n    price: float = Field(description=\"Price in USD, without currency symbol\")\n```\n\n### 2. Use Appropriate Validation\n\n```python\n# ✅ Good: Constrain values\nclass Rating(BaseModel):\n    score: int = Field(ge=1, le=5, description=\"Rating from 1 to 5 stars\")\n    review: str = Field(min_length=10, description=\"Review text, at least 10 chars\")\n```\n\n### 3. Provide Examples in Prompts\n\n```python\nmessages = [{\n    \"role\": \"user\",\n    \"content\": \"\"\"Extract person info from: \"John, 30, engineer\"\n\nExample format:\n{\n  \"name\": \"John Doe\",\n  \"age\": 30,\n  \"occupation\": \"engineer\"\n}\"\"\"\n}]\n```\n\n### 4. Use Enums for Fixed Categories\n\n```python\n# ✅ Good: Enum ensures valid values\nclass Status(str, Enum):\n    PENDING = \"pending\"\n    APPROVED = \"approved\"\n    REJECTED = \"rejected\"\n\nclass Application(BaseModel):\n    status: Status  # LLM must choose from enum\n```\n\n### 5. Handle Missing Data Gracefully\n\n```python\nclass PartialData(BaseModel):\n    required_field: str\n    optional_field: Optional[str] = None\n    default_field: str = \"default_value\"\n\n# LLM only needs to provide required_field\n```\n\n## Comparison to Alternatives\n\n| Feature | Instructor | Manual JSON | LangChain | DSPy |\n|---------|------------|-------------|-----------|------|\n| Type Safety | ✅ Yes | ❌ No | ⚠️ Partial | ✅ Yes |\n| Auto Validation | ✅ Yes | ❌ No | ❌ No | ⚠️ Limited |\n| Auto Retry | ✅ Yes | ❌ No | ❌ No | ✅ Yes |\n| Streaming | ✅ Yes | ❌ No | ✅ Yes | ❌ No |\n| Multi-Provider | ✅ Yes | ⚠️ Manual | ✅ Yes | ✅ Yes |\n| Learning Curve | Low | Low | Medium | High |\n\n**When to choose Instructor:**\n- Need structured, validated outputs\n- Want type safety and IDE support\n- Require automatic retries\n- Building data extraction systems\n\n**When to choose alternatives:**\n- DSPy: Need prompt optimization\n- LangChain: Building complex chains\n- Manual: Simple, one-off extractions\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fpython.useinstructor.com\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fjxnl\u002Finstructor (15k+ stars)\n- **Cookbook**: https:\u002F\u002Fpython.useinstructor.com\u002Fexamples\n- **Discord**: Community support available\n\n## See Also\n\n- `references\u002Fvalidation.md` - Advanced validation patterns\n- `references\u002Fproviders.md` - Provider-specific configuration\n- `references\u002Fexamples.md` - Real-world use cases\n\n\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"platforms":40,"description":7,"dependencies":44},"Orchestra Research","1.0.0",{"hermes":27},{"tags":28},[29,30,31,32,33,34,35,36,37,38,39],"Prompt Engineering","Instructor","Structured Output","Pydantic","Data Extraction","JSON Parsing","Type Safety","Validation","Streaming","OpenAI","Anthropic",[41,42,43],"linux","macos","windows",[5,45,46,47],"pydantic","openai","anthropic","main","2e6aa8d15ab0a366c90be54f61bf9c6e97015e83","skills\u002Fmlops\u002Finstructor",1,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet","steadfaste.com","https:\u002F\u002Fgithub.com\u002Flukemcqueen","AI Architect | Building Hermes Cortex: governed multi-agent AI for autonomous software engineering | Enterprise Tech Consultant","2026-11-14 22:33:34",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill instructor",{"tool":63,"command":64},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill instructor",{"tool":66,"command":67},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill instructor","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fmlops\u002Finstructor\u002FSKILL.md",true,[],[72,80,87,94,101,108],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":79},"01M7DXY4G8NSVB59K8B6S2AQNP","macbook-linux-maintenance","Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fmacbook-linux-maintenance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":79},"01M7DXXYJCXFJ3TGB84ZQ8KFE6","governance-regression-triage","Triage a host's governance issues: what changed.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fgovernance-regression-triage\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":79},"01M7DXXSAP1G8FDRJAMXQGBBMK","enforcement-immutability","Use when enforcement files lose their immutable flag.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fenforcement-immutability\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":79},"01M78SSDQVRYX64Y16X32TC0NS","steadfaste-fleet-repo-deploy","Use when committing to the steadfaste-fleet repo.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-repo-deploy\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":79},"01M78SS928F3R2RJAYVW4E30CE","steadfaste-fleet-maintenance","Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-maintenance\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":79},"01M78SP1CHW0T0BWE5ZT6JBPX8","fleet-preflight","DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its \"Repo-Specific Pre-Flight\" section covers git search, Hermes boundary, and deployment verification.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-preflight\u002FSKILL.md",[],[]]