[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EPS3EVSFNPMZ6RKJVSW85F":3,"skill-same:01M7EPS3EVSFNPMZ6RKJVSW85F":79},{"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":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M7EPS3EVSFNPMZ6RKJVSW85F","prompt-engineering-instructor",null,"Extract structured data from LLM responses with Pydantic validation, retry failed extractions automatically, parse complex JSON with type safety, and stream partial results with Instructor - battle-tested structured output library","TanNhatCMS\u002Fjarvis","TanNhatCMS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F113796420?v=4","01M753MV17KG5CD3152G3WQEQY","KietNT","01M7EKEDYVYQ6PWVJJMZ911VMX",0,"MIT","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-prompt-engineering-instructor\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: prompt-engineering-instructor\ndescription: Extract structured data from LLM responses with Pydantic validation, retry failed extractions automatically, parse complex JSON with type safety, and stream partial results with Instructor - battle-tested structured output library\nversion: 1.0.0\nauthor: Orchestra Research\nlicense: MIT\ntags: [Prompt Engineering, Instructor, Structured Output, Pydantic, Data Extraction, JSON Parsing, Type Safety, Validation, Streaming, OpenAI, Anthropic]\ndependencies: [instructor, pydantic, openai, anthropic]\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,"tags":24,"author":36,"license":15,"version":37,"description":7,"dependencies":38},[25,26,27,28,29,30,31,32,33,34,35],"Prompt Engineering","Instructor","Structured Output","Pydantic","Data Extraction","JSON Parsing","Type Safety","Validation","Streaming","OpenAI","Anthropic","Orchestra Research","1.0.0",[39,40,41,42],"instructor","pydantic","openai","anthropic","main","af388a77c2fe5e0b4fd879cca4300a0ffa9a6579","skills\u002Fams-imp-prompt-engineering-instructor",1,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis","https:\u002F\u002Fgithub.com\u002FTanNhatCMS","https:\u002F\u002Fmrkiet.name.vn","2026-11-07 14:23:08",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add TanNhatCMS\u002Fjarvis --skill prompt-engineering-instructor",{"tool":57,"command":58},"bunx","bunx skills add TanNhatCMS\u002Fjarvis --skill prompt-engineering-instructor",{"tool":60,"command":61},"pnpm","pnpm dlx skills add TanNhatCMS\u002Fjarvis --skill prompt-engineering-instructor","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-prompt-engineering-instructor\u002FSKILL.md",true,[65,71,75],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fexamples.md","REFERENCE","参考文档",2320,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-prompt-engineering-instructor\u002Freferences\u002Fexamples.md",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fproviders.md",1329,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-prompt-engineering-instructor\u002Freferences\u002Fproviders.md",{"path":76,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fvalidation.md",15306,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-prompt-engineering-instructor\u002Freferences\u002Fvalidation.md",[80,87,95,102,109,116],{"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":19},"01M7EWYJR0J8DARY7E59Z6Y9MV","web-scrape","Turn web pages into LLM-ready markdown via the Firecrawl API (renders JS, anti-bot handling). Use when browser_open\u002Ffetch fails on JS-heavy pages, or when you need clean markdown\u002Fstructured extraction from a site. Requires FIRECRAWL_API_KEY.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fweb-scrape\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":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7EWYBN5P6F2AJG3FR24T9BP","design-taste-frontend","tasteskill v2, the anti-slop frontend skill. Art direction for websites, distilled from a study of 247 curated gallery sites (One Page Love, Awwwards Sites of the Day). Deals researched directions (idea, composition, type, palette, photographs, section blueprints) from a library, enforces a strict no-slop house style with a real-browser inspector, and runs a look-and-fix loop on screenshots. Use this whenever you build, design, redesign, restyle, polish or review a landing page, marketing site, portfolio, product page, one-pager, hero or any public-facing web page, in any stack (HTML\u002FCSS, React, Next.js, Vue, Svelte, Astro, Tailwind) — also when the user says a page looks generic, templated, \"AI-made\", sloppy, or asks to make it look designed, premium, award-level or less like every other site. Not for dashboards or app screens.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7EWY8FQFNQ2GB7NZZWGSSDX","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-tdd\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7EWY5SHBFRH1HDHVWM9K7TV","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-debugging\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M7EWY3NM0Z0JAKS7HDZ24K66","requesting-code-review","Use when completing tasks, implementing major features, or before merging to verify work meets requirements","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-code-review\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":19},"01M7EWY0WRMWX4M9ZFY0WKC593","brainstorming","You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-brainstorming\u002FSKILL.md",[],[]]