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

Claude Code for Outlines: Guaranteed Structured LLM Outputs

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

Outlines generates guaranteed structured output from local LLMs at the token level. pip install outlines. import outlines. Load model: model = outlines.models.transformers("meta-llama/Llama-3.2-3B-Instruct", device="cuda"). JSON generation with Pydantic: from pydantic import BaseModel; class User(BaseModel): name: str; age: int. generator = outlines.generate.json(model, User), user = generator("Extract: John Doe, age 30") — returns validated User instance. JSON Schema: generator = outlines.generate.json(model, {"type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"}}}). Regex: generator = outlines.generate.regex(model, r"\d{3}-\d{2}-\d{4}"), ssn = generator("My SSN is: "). Choice: generator = outlines.generate.choice(model, ["positive","neutral","negative"]), label = generator("Sentiment of: great product!"). Text: generator = outlines.generate.text(model), text = generator("Write a haiku:"). Type: generator = outlines.generate.format(model, int), n = generator("How many planets?"). Batch: users = generator(["Extract info from Alice, 25", "Extract info from Bob, 30"]). Sampling: generator = outlines.generate.json(model, User, sampler=outlines.samplers.greedy()) or multinomial(samples=3, temperature=0.7). vLLM backend: model = outlines.models.vllm("meta-llama/Llama-3.2-3B-Instruct"). llama.cpp: model = outlines.models.llamacpp("model.gguf"). Outlines works by constructing a finite state machine from the schema and applying it as a token-level mask during generation — no post-processing, no retries, guaranteed valid output every time. Claude Code generates Outlines schemas, constrained decoders, extraction pipelines, and classification generators for local LLM inference.

CLAUDE.md for Outlines

## Outlines Stack
- Version: outlines >= 0.1.0
- Load: outlines.models.transformers(hf_model_id) | vllm(model_id) | llamacpp(gguf_path)
- JSON: outlines.generate.json(model, PydanticModel | json_schema_dict)
- Regex: outlines.generate.regex(model, r"pattern") — guaranteed match
- Choice: outlines.generate.choice(model, ["opt1","opt2"]) — always one of the options
- Format: outlines.generate.format(model, int | float | bool) — typed scalars
- Sampler: greedy() | multinomial(samples=N, temperature=T)
- Guarantee: token-level FSM mask — no post-processing or retries needed

Outlines Structured Generation

# generation/outlines_generate.py — constrained local LLM generation
from __future__ import annotations
import re
from enum import Enum
from typing import Optional

import outlines
from pydantic import BaseModel, Field


# ── 1. Load model (shared across all generators) ─────────────────────────────

def get_model(
    model_id: str  = "microsoft/Phi-3.5-mini-instruct",
    device:   str  = "cuda",
    dtype:    str  = "float16",
):
    """Load a HuggingFace model for constrained generation."""
    return outlines.models.transformers(
        model_id,
        device=device,
        model_kwargs={"torch_dtype": dtype},
    )


# ── 2. JSON generation with Pydantic schemas ──────────────────────────────────

class ContactInfo(BaseModel):
    name:    str
    email:   Optional[str] = None
    phone:   Optional[str] = None
    company: Optional[str] = None


class Invoice(BaseModel):
    vendor:      str
    amount:      float = Field(ge=0)
    currency:    str  = Field(pattern=r"[A-Z]{3}")    # ISO currency code
    date:        str  = Field(pattern=r"\d{4}-\d{2}-\d{2}")
    description: str


class MedicalEntity(BaseModel):
    """Named entity from clinical text."""
    text:        str
    entity_type: str  = Field(description="MEDICATION|CONDITION|PROCEDURE|DOSAGE")
    start:       int
    end:         int
    confidence:  float = Field(ge=0.0, le=1.0)


def extract_contact(model, text: str) -> ContactInfo:
    """Extract contact info — guaranteed valid ContactInfo every time."""
    generator = outlines.generate.json(model, ContactInfo)
    prompt    = f"Extract contact information from this text:\n{text}\n\nContact:"
    return generator(prompt)


def extract_invoice(model, ocr_text: str) -> Invoice:
    """Extract invoice fields — no post-processing needed."""
    generator = outlines.generate.json(model, Invoice)
    prompt    = f"Extract invoice details:\n{ocr_text}\n\nInvoice:"
    return generator(prompt)


def extract_entities_batch(
    model,
    texts: list[str],
) -> list[list[MedicalEntity]]:
    """Batch entity extraction — one call per text."""
    generator = outlines.generate.json(model, list[MedicalEntity])
    prompts   = [f"Extract medical entities:\n{t}\n\nEntities:" for t in texts]
    return generator(prompts)   # Batched inference


# ── 3. Regex-constrained generation ──────────────────────────────────────────

def extract_phone_number(model, text: str) -> str:
    """Extract phone number matching US format exactly."""
    generator = outlines.generate.regex(
        model,
        r"\+?1?\s*\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}",
    )
    return generator(f"Extract the phone number from: {text}\nPhone:")


def extract_date(model, text: str) -> str:
    """Extract date in ISO format — guaranteed YYYY-MM-DD."""
    generator = outlines.generate.regex(model, r"\d{4}-\d{2}-\d{2}")
    return generator(f"What is the date mentioned in: {text}\nDate:")


def extract_price(model, text: str) -> str:
    """Extract price — guaranteed format like $123.45."""
    generator = outlines.generate.regex(model, r"\$\d{1,6}\.\d{2}")
    return generator(f"Extract the price from: {text}\nPrice:")


# ── 4. Classification with choice ────────────────────────────────────────────

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


def classify_sentiment(model, text: str) -> str:
    """Classify sentiment — always returns one of the three labels."""
    generator = outlines.generate.choice(model, ["positive", "neutral", "negative"])
    return generator(f"Sentiment of the following text:\n\"{text}\"\n\nSentiment:")


def classify_priority(model, text: str) -> str:
    """Classify support ticket priority — guaranteed valid value."""
    generator = outlines.generate.choice(model, ["critical", "high", "medium", "low"])
    return generator(f"Priority of this support ticket:\n\"{text}\"\n\nPriority:")


def batch_classify(
    model,
    texts: list[str],
    labels: list[str],
) -> list[str]:
    """Batch classification — all results guaranteed to be in labels."""
    generator = outlines.generate.choice(model, labels)
    prompts   = [f"Classify: \"{t}\"\nLabel:" for t in texts]
    return generator(prompts)


# ── 5. Typed scalar extraction ────────────────────────────────────────────────

def extract_count(model, text: str) -> int:
    """Extract a numeric count from text — guaranteed integer output."""
    generator = outlines.generate.format(model, int)
    return generator(f"How many items are mentioned in: \"{text}\"\nCount:")


def extract_score(model, text: str) -> float:
    """Extract a score between 0 and 1 — guaranteed float output."""
    generator = outlines.generate.format(model, float)
    return generator(f"On a scale of 0.0 to 1.0, rate the quality of: \"{text}\"\nScore:")


# ── 6. Complex nested schema ──────────────────────────────────────────────────

class ProductReview(BaseModel):
    product_name: str
    rating:       int   = Field(ge=1, le=5)
    pros:         list[str] = Field(min_length=1, max_length=5)
    cons:         list[str] = Field(min_length=0, max_length=5)
    verdict:      str  = Field(pattern="(buy|skip|wait)")
    summary:      str  = Field(max_length=200)


def analyze_review(model, review_text: str) -> ProductReview:
    """Parse a product review into structured fields."""
    generator = outlines.generate.json(model, ProductReview)
    prompt    = f"Analyze this product review:\n{review_text}\n\nAnalysis:"
    return generator(prompt)


# ── 7. Custom grammar (EBNF) ──────────────────────────────────────────────────

ARITHMETIC_GRAMMAR = r"""
    ?start: expr
    ?expr: term (("+" | "-") term)*
    ?term: factor (("*" | "/") factor)*
    ?factor: NUMBER | "(" expr ")"
    NUMBER: /\d+(\.\d+)?/
    %ignore /\s+/
"""


def generate_arithmetic_expression(model, description: str) -> str:
    """Generate valid arithmetic expressions using EBNF grammar."""
    generator = outlines.generate.cfg(model, ARITHMETIC_GRAMMAR)
    return generator(f"Write an arithmetic expression for: {description}\nExpression:")


# ── Demo ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("Loading model...")
    model = get_model("microsoft/Phi-3.5-mini-instruct")

    # Contact extraction
    contact = extract_contact(model, "Call Sarah at [email protected] or +1-555-867-5309")
    print(f"Contact: {contact.name}, {contact.email}, {contact.phone}")

    # Classification
    label = classify_sentiment(model, "This product exceeded all my expectations!")
    print(f"Sentiment: {label}")

    priority = classify_priority(model, "Production is down, all users affected!")
    print(f"Priority: {priority}")

    # Regex
    phone = extract_phone_number(model, "My number is 415-555-1234, please call anytime.")
    print(f"Phone: {phone}")

    # Typed scalar
    count = extract_count(model, "I bought three apples, two oranges, and a banana.")
    print(f"Count: {count}")

    # Complex nested
    review = analyze_review(model, "The MacBook Pro is incredibly fast and has great battery life, though it's expensive and ports are limited. Overall a premium laptop.")
    print(f"Review: rating={review.rating}/5, verdict={review.verdict}")

For the Instructor (with API models) alternative when using hosted LLM APIs like Anthropic or OpenAI where token-level control is unavailable — Instructor uses Pydantic validation + retry loops (2-3 extra API calls on failure) while Outlines applies FSM-based constraints directly during token sampling, making it impossible for a local model to produce invalid output without any retries. For the LMQL/guidance alternative when needing interleaved code execution within generation or multi-part constrained programs that branch based on generated values — LMQL provides a full programming language for generation control while Outlines focuses specifically on output type constraints (JSON/regex/choice) with a simpler API that covers the vast majority of structured extraction use cases. The Claude Skills 360 bundle includes Outlines skill sets covering JSON Pydantic generation, regex constraint, choice classification, typed scalars, batch inference, and custom EBNF grammars. Start with the free tier to try constrained LLM code 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