outlines
You are an expert in Outlines, the Python library for reliable structured text generation with LLMs. You help developers generate guaranteed-valid JSON, regex-matching text, and grammar-constrained output from open-source models — using finite state machine guided generation that constrains the token sampling process to produce only valid output on the first try.
What this skill does
# Outlines — Structured Text Generation
You are an expert in Outlines, the Python library for reliable structured text generation with LLMs. You help developers generate guaranteed-valid JSON, regex-matching text, and grammar-constrained output from open-source models — using finite state machine guided generation that constrains the token sampling process to produce only valid output on the first try.
## Core Capabilities
### Structured Generation
```python
import outlines
from pydantic import BaseModel, Field
from enum import Enum
# Load model
model = outlines.models.transformers("meta-llama/Llama-3.1-8B-Instruct")
# JSON generation with Pydantic schema
class Sentiment(str, Enum):
positive = "positive"
negative = "negative"
neutral = "neutral"
class ReviewAnalysis(BaseModel):
sentiment: Sentiment
score: float = Field(ge=0, le=1)
topics: list[str] = Field(min_length=1, max_length=5)
summary: str = Field(max_length=200)
generator = outlines.generate.json(model, ReviewAnalysis)
result = generator(
"Analyze this review: 'Great product, fast shipping, but packaging could be better'"
)
# result is a validated ReviewAnalysis instance — guaranteed to match schema
print(result.sentiment) # Sentiment.positive
print(result.score) # 0.85
print(result.topics) # ["product quality", "shipping", "packaging"]
# Regex-constrained generation
phone_gen = outlines.generate.regex(model, r"\(\d{3}\) \d{3}-\d{4}")
phone = phone_gen("Generate a US phone number:")
# phone = "(415) 555-0123" — always matches the regex
# Choice (classification)
classifier = outlines.generate.choice(model, ["spam", "ham", "uncertain"])
result = classifier("Is this spam? 'You won $1000000!!!'")
# result = "spam"
# Format-constrained (date, number, etc.)
date_gen = outlines.generate.format(model, datetime.date)
date = date_gen("When was Python created?")
# date = datetime.date(1991, 2, 20) — always a valid date object
```
### Batch Processing
```python
# Batch inference for throughput
generator = outlines.generate.json(model, ReviewAnalysis)
reviews = [
"Amazing quality, will buy again!",
"Terrible customer service, never ordering here.",
"It's okay, nothing special.",
]
prompts = [f"Analyze: '{r}'" for r in reviews]
results = generator(prompts, max_tokens=200)
# results is a list of ReviewAnalysis objects — all guaranteed valid
```
### Grammar-Constrained
```python
# Custom grammar (CFG)
arithmetic_grammar = r"""
?start: expression
?expression: term (("+" | "-") term)*
?term: factor (("*" | "/") factor)*
?factor: NUMBER | "(" expression ")"
NUMBER: /[0-9]+(\.[0-9]+)?/
"""
calc_gen = outlines.generate.cfg(model, arithmetic_grammar)
expr = calc_gen("Generate a math expression that equals 42:")
# expr = "(6 * 7)" — always valid arithmetic
```
### With vLLM
```python
# Use with vLLM for production throughput
model = outlines.models.vllm("meta-llama/Llama-3.1-8B-Instruct",
tensor_parallel_size=1, gpu_memory_utilization=0.9)
generator = outlines.generate.json(model, ReviewAnalysis)
# Combines Outlines' constrained generation with vLLM's batching + PagedAttention
```
## Installation
```bash
pip install outlines
```
## Best Practices
1. **Pydantic schemas** — Define output with Pydantic models; Outlines compiles to FSM for guaranteed compliance
2. **Regex for patterns** — Use `generate.regex()` for dates, emails, IDs; output always matches the pattern
3. **Choice for classification** — Use `generate.choice()` instead of free text; constrained to exact options
4. **vLLM for production** — Combine with vLLM backend for high-throughput constrained generation
5. **Batch for efficiency** — Pass lists of prompts; Outlines batches efficiently with the model
6. **Field constraints** — Use Pydantic's `ge`, `le`, `min_length`, `max_length`; further constrains output
7. **Grammar for DSLs** — Use CFG grammars for domain-specific output (SQL, code, formulas)
8. **First-try guarantee** — Unlike retry-based approaches, Outlines gets valid output on the first generation
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.