[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MA9T2W5D3PM82XSPA0PJ3P":3,"skill-same:01M6MA9T2W5D3PM82XSPA0PJ3P":122},{"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":28,"publishedAt":57,"linkOnly":58,"markdownContent":59,"markdownBody":60,"frontMatter":61,"refName":68,"commitSha":69,"skillDirectory":70,"forksCount":71,"repositoryHtmlUrl":72,"repositoryHomepageUrl":73,"ownerHtmlUrl":74,"ownerBlogUrl":75,"ownerDescription":76,"updatedAt":77,"install":78,"resources":91},"01M6MA9T2W5D3PM82XSPA0PJ3P","instructor",null,"Extracts structured, validated data from LLM responses using the Instructor Python library with Pydantic response models, including nested models, enums, custom validators, automatic retries with validation error feedback, and streaming of partial objects or iterables. Works with Anthropic, OpenAI, and local Ollama models. Use when pulling typed fields or entities out of free text, when classifying text into fixed categories, when an LLM must return JSON that passes schema validation, when failed extractions need automatic retry, or when streaming partial structured results. Not for prompt optimization (use DSPy) or building multi-step chains (use LangChain).","hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1559,"MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[5,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56],"entities","python","automatic","custom","for","schema validation","categories","retry","Prompt Optimization","retries","error","structured output","free","local","objects","dspy","use","langchain","ollama","text","applications","Safety","Type Safety","Pydantic","data","library","streaming","openai","2026-11-10 10:12:30",false,"---\nname: instructor\ndescription: Extracts structured, validated data from LLM responses using the Instructor Python library with Pydantic response models, including nested models, enums, custom validators, automatic retries with validation error feedback, and streaming of partial objects or iterables. Works with Anthropic, OpenAI, and local Ollama models. Use when pulling typed fields or entities out of free text, when classifying text into fixed categories, when an LLM must return JSON that passes schema validation, when failed extractions need automatic retry, or when streaming partial structured results. Not for prompt optimization (use DSPy) or building multi-step chains (use LangChain).\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: llm-applications\n  maintainer: Kalaris Labs\n  tags: Prompt Engineering, Instructor, Structured Output, Pydantic, Data Extraction, JSON Parsing, Type Safety, Validation, Streaming, OpenAI, Anthropic\n  dependencies: 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\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\nDetails, code examples and parameter tables: [references\u002Fprovider-configuration.md](references\u002Fprovider-configuration.md). Read it when this step applies.\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Advanced Features\n\nDetails, code examples and parameter tables: [references\u002Fadvanced-features.md](references\u002Fadvanced-features.md). Read it when this step applies.\n\n## Error Handling\n\nDetails, code examples and parameter tables: [references\u002Ferror-handling.md](references\u002Ferror-handling.md). Read it when this step applies.\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\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## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\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\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\nDetails, code examples and parameter tables: [references\u002Fprovider-configuration.md](references\u002Fprovider-configuration.md). Read it when this step applies.\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Advanced Features\n\nDetails, code examples and parameter tables: [references\u002Fadvanced-features.md](references\u002Fadvanced-features.md). Read it when this step applies.\n\n## Error Handling\n\nDetails, code examples and parameter tables: [references\u002Ferror-handling.md](references\u002Ferror-handling.md). Read it when this step applies.\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\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## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n",{"name":5,"license":15,"metadata":62,"description":7},{"tags":63,"version":64,"category":65,"maintainer":66,"dependencies":67},"Prompt Engineering, Instructor, Structured Output, Pydantic, Data Extraction, JSON Parsing, Type Safety, Validation, Streaming, OpenAI, Anthropic","1.0.0","llm-applications","Kalaris Labs","instructor, pydantic, openai, anthropic","main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor",474,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-11 14:40:14",{"source":8,"skillName":5,"commands":79,"prompt":89,"zipAvailable":90},[80,83,86],{"tool":81,"command":82},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill instructor",{"tool":84,"command":85},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill instructor",{"tool":87,"command":88},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill instructor","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002FSKILL.md",true,[92,98,102,106,110,114,118],{"path":93,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fadvanced-features.md","REFERENCE","参考文档",1369,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fadvanced-features.md",{"path":99,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":100,"sourceHtmlUrl":101},"references\u002Fcommon-patterns.md",2972,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fcommon-patterns.md",{"path":103,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Ferror-handling.md",998,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Ferror-handling.md",{"path":107,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":108,"sourceHtmlUrl":109},"references\u002Fexamples.md",2320,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fexamples.md",{"path":111,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":112,"sourceHtmlUrl":113},"references\u002Fprovider-configuration.md",1002,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fprovider-configuration.md",{"path":115,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":116,"sourceHtmlUrl":117},"references\u002Fproviders.md",1329,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fproviders.md",{"path":119,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":120,"sourceHtmlUrl":121},"references\u002Fvalidation.md",15306,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Finstructor\u002Freferences\u002Fvalidation.md",[123,132,139,146,172,197],{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":131},"01M746ZWACVKMZ1BJXJZHYJSSX","migrate-to-e2e","Moves an existing Playwright, Cypress, Selenium, Appium, Detox, Maestro, or TesterArmy suite to e2e one slice at a time, with the old suite running beside the new one until each ported test is proven. Keeps a MIGRATION.md progress file so any later session resumes where the last stopped. Optionally plants a defect to show both suites catch it. Use for \u002Fmigrate-to-e2e, \"migrate our tests to e2e\", \"port these Maestro flows\", \"move our TesterArmy tests\", or when a project has an e2e config and an older suite still running.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fmigrate-to-e2e\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":131},"01M746ZPTAX1Q0FBKAB1CYND7E","e2e","Writes, runs, and debugs end-to-end tests for web and mobile apps with e2e, the agentic test runner, which mixes agent.act goals with exact locator assertions on a Playwright browser or an iOS or Android device. Also drives a project's running app live over the e2e MCP server to look at a screen, check a UI change, take a screenshot or record a video, and try a locator; and runs bug bashes, parallel e2e explore runs with each bug proven by a repro test. Use when a project depends on e2e or has an e2e.config.ts, when asked for end-to-end, browser, mobile, or agentic UI tests, to check a change in the running app, to QA or bug bash an app or branch, or when an e2e run fails.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fe2e\u002FSKILL.md",[],[],{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":131},"01M746ZJN784HVHMDP9MQGCSGG","create-verification-skill","Generate a project-local verify-\u003Capp> skill on top of e2e, so any coding agent can launch the app, check it is worth driving, exercise a feature the way a user does, keep evidence, and bug bash it. Writes the skill, a feature map with one explore charter per feature, and proves it once. Use for \u002Fcreate-verification-skill, \"make a verification skill for this repo\", or when a project has no scripted way to prove UI behavior.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fcreate-verification-skill\u002FSKILL.md",[],[],{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":57},"01M716A6ETNB9B1SQ3GXZC75VR","deja-search","deja-vu memory — search the user's past AI coding sessions with the deja CLI. Holds what they already settled and never wrote into the repo (naming rules, banned or already-tried tools, required checks before merge, preferred values, who owns what). Use before your first edit in a task, before you call a change done or ready to merge, before you recommend a tool, library, design or reviewer, before re-debugging an error that may already be solved, when they say 'didn't we fix this before', 'what did we decide about X' or 'I already have that', and before telling them something on this machine does not exist.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-search\u002FSKILL.md",[],[153,154,155,39,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171],"search","deja search","never","ready","memory","re","decide","fix","design","debugging","when","you","done","reviewer","io","change","cli","merge","past",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":178,"publishedAt":57},"01M716A3J2W5SENSE9VGMXB375","deja-reflect","End-of-session reflection and memory curation with deja-vu. Review what was decided, what commands broke and what repaired them, and record durable project rules or decisions with deja remember so the next session starts with them.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-reflect\u002FSKILL.md",[],[179,180,181,167,182,183,184,185,186,187,188,189,190,191,157,192,193,194,195,196],"deja reflect","reflect","review","with","record","github","next","https","node","Rules","decisions","brew","remember","project rules","project","session","end","reflection",{"skillNo":198,"name":199,"nameZh":6,"description":200,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":127,"licenseFileUrl":6,"sourceHtmlUrl":201,"categories":202,"keywords":210,"publishedAt":57},"01M715T3RR4BAYSR57HPPTJ0PF","revid","Make, edit, export and post AI videos with Revid (revid.ai) through the Revid MCP server. Use whenever the user wants a short-form or long-form video made (from an idea, a script, a URL, an article, a PDF, a tweet, a product page, their own clips, or a song), wants to find what is going viral on TikTok, YouTube, Instagram or X before making something, wants to edit or re-export an existing Revid project, generate a standalone AI image or clip, make a series episode, or publish and schedule a finished video to connected social accounts. Covers setup (hosted MCP with OAuth, or an API key), the 36 tools, credits, polling and the rules for publishing. Routes to the more specific revid-* skills when one fits.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftmakersas\u002Frevid-skills\u002Fskills\u002Frevid\u002FSKILL.md",[203,206,207],{"categoryNo":204,"categoryName":205,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":208,"categoryName":209,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口",[199,211,212,213,214,215,216,193,217,158,218,219,220,221,163,222,223,224,225,226],"URL","Video","short-form","standalone","PDF","viral","tiktok","short","social","MCP","song","image","mcp server","schedule","api","publish"]