Claude Code for Instructor: Structured LLM Outputs — Claude Skills 360 Blog
Blog / AI / Claude Code for Instructor: Structured LLM Outputs
AI

Claude Code for Instructor: Structured LLM Outputs

Published: October 6, 2027
Read time: 5 min read
By: Claude Skills 360

Instructor extracts structured data from LLMs using Pydantic schemas. pip install instructor. import instructor, from anthropic import Anthropic. Patch: client = instructor.from_anthropic(Anthropic()). Response model: from pydantic import BaseModel, Field, class User(BaseModel): name: str; email: str; age: int = Field(ge=0, le=120). Extract: user = client.messages.create(model="claude-sonnet-4-6", max_tokens=1024, messages=[{"role":"user","content":"Extract: John Doe, [email protected], age 30"}], response_model=User). Access: user.name, user.email. OpenAI: import openai; client = instructor.from_openai(openai.OpenAI()). Nested: class Address(BaseModel): street: str; city: str; country: str. class Person(BaseModel): name: str; address: Address. Classification with Literal: class Sentiment(BaseModel): label: Literal["positive","neutral","negative"]; confidence: float. List extraction with Iterable: from typing import Iterable, users = client.messages.create(..., response_model=Iterable[User]) — streams list of validated objects. Partial streaming: response = client.messages.create_partial(model=..., response_model=User, ...) — yields partial User as tokens arrive. Retry: client.messages.create(..., response_model=User, max_retries=3) — auto-retries with validation error feedback. Async: client = instructor.from_anthropic(anthropic.AsyncAnthropic()), user = await client.messages.create(...). instructor.Mode.ANTHROPIC_TOOLS uses tool calling instead of JSON for models that support it. ValidationContext for runtime cross-field validation. Claude Code generates Instructor extraction classes, nested Pydantic schemas, classification models, batch extractors, and async pipelines.

CLAUDE.md for Instructor

## Instructor Stack
- Version: instructor >= 1.6
- Patch: instructor.from_anthropic(Anthropic()) or from_openai(OpenAI())
- Extract: client.messages.create(..., response_model=MyModel) → validated Pydantic instance
- Schema: Pydantic BaseModel with Field(description=...) guides the LLM
- Retry: max_retries=3 — LLM sees validation errors and self-corrects
- List: response_model=Iterable[Model] for extracting arrays
- Async: instructor.from_anthropic(AsyncAnthropic()) → await client.messages.create()
- Mode: instructor.Mode.ANTHROPIC_TOOLS (default for Anthropic) or JSON

Structured Extraction Examples

# extraction/instructor_extract.py — structured LLM outputs with Instructor
from __future__ import annotations
import asyncio
import os
from enum import Enum
from typing import Iterable, Literal, Optional

import anthropic
import instructor
from pydantic import BaseModel, Field, field_validator, model_validator


# ── Patch the Anthropic client ────────────────────────────────────────────────

# Sync client
client = instructor.from_anthropic(
    anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", "")),
    mode=instructor.Mode.ANTHROPIC_TOOLS,  # Uses tool_use for reliable JSON
)

# Async client
async_client = instructor.from_anthropic(
    anthropic.AsyncAnthropic(),
    mode=instructor.Mode.ANTHROPIC_TOOLS,
)

MODEL = "claude-sonnet-4-6"


# ── 1. Simple entity extraction ───────────────────────────────────────────────

class ContactInfo(BaseModel):
    """Contact information extracted from unstructured text."""
    name:        str   = Field(description="Full name of the person")
    email:       Optional[str] = Field(None, description="Email address if present")
    phone:       Optional[str] = Field(None, description="Phone number if present")
    company:     Optional[str] = Field(None, description="Company or organization")
    role:        Optional[str] = Field(None, description="Job title or role")

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str | None) -> str | None:
        if v and "@" not in v:
            raise ValueError(f"Invalid email: {v}")
        return v


def extract_contact(text: str) -> ContactInfo:
    return client.messages.create(
        model=MODEL,
        max_tokens=512,
        messages=[{"role": "user", "content": f"Extract contact information:\n\n{text}"}],
        response_model=ContactInfo,
        max_retries=3,          # Auto-retry with validation errors fed back to LLM
    )


# ── 2. Nested schema extraction ───────────────────────────────────────────────

class LineItem(BaseModel):
    description: str
    quantity:    int   = Field(ge=1)
    unit_price:  float = Field(ge=0)
    total:       float = Field(ge=0)

    @model_validator(mode="after")
    def check_total(self) -> "LineItem":
        expected = round(self.quantity * self.unit_price, 2)
        if abs(self.total - expected) > 0.02:
            raise ValueError(f"Total {self.total} doesn't match qty * price = {expected}")
        return self


class Invoice(BaseModel):
    invoice_number: str
    vendor:         str
    date:           str = Field(description="Date in YYYY-MM-DD format")
    line_items:     list[LineItem]
    subtotal:       float
    tax_rate:       float = Field(ge=0, le=1, description="Tax rate as decimal (0.1 = 10%)")
    total:          float

    @property
    def calculated_total(self) -> float:
        return round(self.subtotal * (1 + self.tax_rate), 2)


def extract_invoice(ocr_text: str) -> Invoice:
    """Extract structured invoice data from OCR text."""
    return client.messages.create(
        model=MODEL,
        max_tokens=2048,
        messages=[{
            "role": "user",
            "content": f"Extract all invoice details from this text:\n\n{ocr_text}"
        }],
        response_model=Invoice,
        max_retries=4,
    )


# ── 3. Classification with confidence ─────────────────────────────────────────

class SentimentClass(str, Enum):
    POSITIVE = "positive"
    NEUTRAL  = "neutral"
    NEGATIVE = "negative"


class SentimentResult(BaseModel):
    label:      SentimentClass
    confidence: float = Field(ge=0, le=1, description="Confidence score between 0 and 1")
    rationale:  str   = Field(description="One-sentence explanation of the classification")


class TicketClassification(BaseModel):
    """Support ticket classification for routing."""
    priority:     Literal["critical", "high", "medium", "low"]
    category:     Literal["billing", "technical", "account", "feature_request", "other"]
    department:   Literal["support", "engineering", "billing", "product"]
    summary:      str = Field(max_length=100, description="One-line summary of the issue")
    requires_followup: bool


def classify_support_ticket(ticket_text: str) -> TicketClassification:
    return client.messages.create(
        model=MODEL,
        max_tokens=512,
        system="You are a support ticket classifier. Always classify accurately.",
        messages=[{"role": "user", "content": f"Classify this support ticket:\n\n{ticket_text}"}],
        response_model=TicketClassification,
    )


# ── 4. List / batch extraction ────────────────────────────────────────────────

class SkillMention(BaseModel):
    skill:       str
    level:       Optional[Literal["beginner", "intermediate", "advanced", "expert"]] = None
    years:       Optional[float] = Field(None, description="Years of experience")
    context:     str = Field(description="Short quote or context from resume")


def extract_skills_from_resume(resume_text: str) -> list[SkillMention]:
    """Extract all skills mentioned in a resume as a list."""
    skills = client.messages.create(
        model=MODEL,
        max_tokens=2000,
        messages=[{
            "role": "user",
            "content": f"Extract all technical skills from this resume. Return ALL skills mentioned:\n\n{resume_text}"
        }],
        response_model=Iterable[SkillMention],  # Returns generator of SkillMention
    )
    return list(skills)


# ── 5. Async extraction ───────────────────────────────────────────────────────

async def extract_batch_async(
    texts: list[str],
    response_model: type[BaseModel],
    concurrency: int = 5,
) -> list[BaseModel]:
    """Extract structured data from multiple texts concurrently."""
    semaphore = asyncio.Semaphore(concurrency)

    async def extract_one(text: str) -> BaseModel:
        async with semaphore:
            return await async_client.messages.create(
                model=MODEL,
                max_tokens=1024,
                messages=[{"role": "user", "content": text}],
                response_model=response_model,
                max_retries=2,
            )

    results = await asyncio.gather(*[extract_one(t) for t in texts], return_exceptions=True)
    return [r for r in results if not isinstance(r, Exception)]


# ── 6. Streaming partial extraction ──────────────────────────────────────────

def stream_extraction_demo():
    """Stream a partial model — yields incomplete but typed objects as tokens arrive."""
    print("Streaming extraction (partial objects):")
    for partial_contact in client.messages.create_partial(
        model=MODEL,
        max_tokens=512,
        messages=[{
            "role": "user",
            "content": "Extract: Alice Smith, [email protected], CTO at TechCorp, +1-555-0100"
        }],
        response_model=ContactInfo,
    ):
        # Partial object — fields may be None until fully generated
        print(f"  name={partial_contact.name!r:<25} email={partial_contact.email!r}")


# ── Usage examples ────────────────────────────────────────────────────────────

if __name__ == "__main__":
    # Extract contact
    contact = extract_contact("Please reach out to Sarah Connor at [email protected], she's the VP of Engineering at Skynet Inc, phone 555-1234.")
    print(f"Contact: {contact.name}, {contact.email}, {contact.role} @ {contact.company}")

    # Classify ticket
    ticket = classify_support_ticket(
        "URGENT: Our production API is returning 500 errors since the last deployment. "
        "Affecting all customers. Team is blocked."
    )
    print(f"Ticket: priority={ticket.priority}, dept={ticket.department}, summary={ticket.summary}")

    # Extract skills
    resume = "Senior Python engineer with 8 years experience. Expert in PyTorch, advanced Kubernetes, intermediate Go. Led 3 ML projects using scikit-learn and MLflow."
    skills = extract_skills_from_resume(resume)
    for s in skills:
        print(f"  - {s.skill} ({s.level}, {s.years}yr)")

    # Streaming
    stream_extraction_demo()

    # Async batch
    contacts_text = [
        "Bob Johnson, [email protected], Sales Manager",
        "Carol White, [email protected], Founder, +44-20-1234",
    ]
    contacts = asyncio.run(extract_batch_async(contacts_text, ContactInfo))
    for c in contacts:
        print(f"Async: {c.name}, {c.email}")

For the direct JSON mode (OpenAI response_format=json_object or Anthropic prefill technique) alternative when using a model without function calling support or wanting to avoid SDK dependencies — raw JSON prompting works but loses schema validation, retry logic, and the LLM-readable Pydantic field descriptions that guide extraction quality, whereas Instructor’s max_retries feeds validation errors back to the model so it can self-correct in 2-3 additional API calls. For the LangChain with_structured_output alternative when already using LangChain for chain composition — LangChain’s structured output works differently per model while Instructor uses the same Pydantic-first API across all providers (Anthropic, OpenAI, Gemini, Cohere, Ollama) making it easier to switch LLM providers without changing extraction logic. The Claude Skills 360 bundle includes Instructor skill sets covering entity extraction schemas, nested models, classification with Literal, list extraction, async batch processing, and streaming partial models. Start with the free tier to try structured LLM output generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free