outlines is a free, open source ai development platforms project written in Python and released under Apache-2.0. It has 15,825 GitHub stars, 880 forks and 166 open issues, and was last pushed 8 days ago. On this registry it ranks #43 of 61 tracked projects in AI Development Platforms, with 5 head-to-head comparisons available. It gained 17 stars over the last 3 tracked days.

What is outlines?

What it is

Outlines is a Python library for structured generation with large language models, released under the Apache-2.0 license and maintained by the team at .txt. It lives in the AI and machine learning ecosystem, specifically among AI development platforms and structured-generation tooling, and it is distributed through PyPI. The project describes itself as a way to guarantee structured outputs during generation rather than repairing them afterward, and its topic list places it alongside work on context-free grammars, regular expressions, JSON, prompt engineering, and symbolic AI.

The concrete problem it solves is the unpredictability of raw model output. Most approaches attempt to fix bad outputs after generation using parsing, regular expressions, or fragile code that breaks easily, which forces developers to write defensive glue around every call. Outlines instead constrains generation so that the returned data matches a declared type exactly, whether that type is a simple Literal["Yes", "No"], an int, or a full Pydantic model. The same code runs across OpenAI, Ollama, vLLM, and other backends, so switching providers does not require rewriting the output-handling layer.

Key capabilities

  • Guarantees valid structure during generation, removing the need for post-hoc parsing of broken JSON.
  • Accepts a desired output type directly through the model(prompt, output_type) call pattern.
  • Supports simple types such as Literal for classification and int for numerical extraction.
  • Supports complex nested structures defined with Pydantic models, including enums and lists.
  • Runs the same code across multiple providers, including OpenAI, Ollama, vLLM, and HuggingFace Transformers.
  • Integrates with local models through outlines.from_transformers with an AutoModelForCausalLM and AutoTokenizer.
  • Covers grammar- and regex-based constrained generation, as reflected in the project topics.

Who uses it and how

  • Customer support triage, where incoming messages are classified into defined categories.
  • E-commerce product categorization, mapping free-text product data into a fixed taxonomy.
  • Parsing event details from incomplete data, extracting structured fields from partial input.
  • Categorizing documents into predefined types for downstream routing or indexing.
  • Scheduling meetings through function calling, where the model must emit arguments in a valid shape.
  • Generating prompts dynamically from reusable templates.

Getting started

Install with pip install outlines, then connect a model of choice, for example through outlines.from_transformers with a HuggingFace checkpoint. Calls then pass the prompt and the desired output type, such as a Literal, an int, or a Pydantic model.

When to use it — and when not to

Outlines is the open-source option for teams that would otherwise reach for a hosted structured-output service, and the .txt API remains in early access, so the library is the available path today. A self-hoster must supply the model backend, whether that is a local Transformers checkpoint, Ollama, vLLM, or a paid provider API, since the library constrains generation rather than hosting inference. The repository carries 166 open issues, which is worth weighing against the maturity implied by its age and adoption.

project readme (upstream, from github) — read inline

🗒️ Structured outputs for LLMs 🗒️

Made with ❤👷️ by the team at .txt
Trusted by NVIDIA, Cohere, HuggingFace, vLLM, etc.

[![PyPI Version][pypi-version-badge]][pypi] [![Downloads][downloads-badge]][pypistats] [![Stars][stars-badge]][stars]

[![Discord][discord-badge]][discord] [![Blog][dottxt-blog-badge]][dottxt-blog] [![Twitter][twitter-badge]][twitter]


The .txt API is currently in early access. Request access here →

🚀 Building the future of structured generation

We're working with select partners to develop new interfaces to structured generation.

Need XML, FHIR, custom schemas or grammars? Let's talk.

Audit your schema: share one schema, we show you what breaks under generation, the constraints that fix it, and compliance rates before and after. Sign up here.

Table of Contents

Why Outlines?

LLMs are powerful but their outputs are unpredictable. Most solutions attempt to fix bad outputs after generation using parsing, regex, or fragile code that breaks easily.

Outlines guarantees structured outputs during generation — directly from any LLM.

  • Works with any model - Same code runs across OpenAI, Ollama, vLLM, and more
  • Simple integration - Just pass your desired output type: model(prompt, output_type)
  • Guaranteed valid structure - No more parsing headaches or broken JSON
  • Provider independence - Switch models without changing code

The Outlines Philosophy

Outlines follows a simple pattern that mirrors Python's own type system. Simply specify the desired output type, and Outlines will ensure your data matches that structure exactly:

  • For a yes/no response, use Literal["Yes", "No"]
  • For numerical values, use int
  • For complex objects, define a structure with a Pydantic model

Quickstart

Getting started with outlines is simple:

1. Install outlines

pip install outlines

2. Connect to your preferred model

import outlines
from transformers import AutoTokenizer, AutoModelForCausalLM


MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
model = outlines.from_transformers(
    AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
    AutoTokenizer.from_pretrained(MODEL_NAME)
)

3. Start with simple structured outputs

from typing import Literal
from pydantic import BaseModel


# Simple classification
sentiment = model(
    "Analyze: 'This product completely changed my life!'",
    Literal["Positive", "Negative", "Neutral"]
)
print(sentiment)  # "Positive"

# Extract specific types
temperature = model("What's the boiling point of water in Celsius?", int)
print(temperature)  # 100

4. Create complex structures

from pydantic import BaseModel
from enum import Enum

class Rating(Enum):
    poor = 1
    fair = 2
    good = 3
    excellent = 4

class ProductReview(BaseModel):
    rating: Rating
    pros: list[str]
    cons: list[str]
    summary: str

review = model(
    "Review: The XPS 13 has great battery life and a stunning display, but it runs hot and the webcam is poor quality.",
    ProductReview,
    max_new_tokens=200,
)

review = ProductReview.model_validate_json(review)
print(f"Rating: {review.rating.name}")  # "Rating: good"
print(f"Pros: {review.pros}")           # "Pros: ['great battery life', 'stunning display']"
print(f"Summary: {review.summary}")     # "Summary: Good laptop with great display but thermal issues"

Real-world examples

Here are production-ready examples showing how Outlines solves common problems:

🙋‍♂️ Customer Support Triage
This example shows how to convert a free-form customer email into a structured service ticket. By parsing attributes like priority, category, and escalation flags, the code enables automated routing and handling of support issues.
import outlines
from enum import Enum
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
from typing import List


MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
model = outlines.from_transformers(
    AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
    AutoTokenizer.from_pretrained(MODEL_NAME)
)


def alert_manager(ticket):
    print("Alert!", ticket)


class TicketPriority(str, Enum):
    low = "low"
    medium = "medium"
    high = "high"
    urgent = "urgent"

class ServiceTicket(BaseModel):
    priority: TicketPriority
    category: str
    requires_manager: bool
    summary: str
    action_items: List[str]


customer_email = """
Subject: URGENT - Cannot access my account after payment

I paid for the premium plan 3 hours ago and still can't access any features.
I've tried logging out and back in multiple times. This is unacceptable as I
have a client presentation in an hour and need the analytics dashboard.
Please fix this immediately or refund my payment.
"""

prompt = f"""
<|im_start|>user
Analyze this customer email:

{customer_email}
<|im_end|>
<|im_start|>assistant
"""

ticket = model(
    prompt,
    ServiceTicket,
    max_new_tokens=500
)

# Use structured data to route the ticket
ticket = ServiceTicket.model_validate_json(ticket)
if ticket.priority == "urgent" or ticket.requires_manager:
    alert_manager(ticket)
📦 E-commerce product categorization
This use case demonstrates how outlines can transform product descriptions into structured categorization data (e.g., main category, sub-category, and attributes) to streamline tasks such as inventory management. Each product description is processed automatically, reducing manual categorization overhead.
import outlines
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
from typing import List, Optional


MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
model = outlines.from_transformers(
    AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
    AutoTokenizer.from_pretrained(MODEL_NAME)
)


def update_inventory(product, category, sub_category):
    print(f"Updated {product.split(',')[0]} in category {category}/{sub_category}")


class ProductCategory(BaseModel):
    main_category: str
    sub_category: str
    attributes: List[str]
    brand_match: Optional[str]

# Process product descriptions in batches
product_descriptions = [
    "Apple iPhone 15 Pro Max 256GB Titanium, 6.7-inch Super Retina XDR display with ProMotion",
    "Organic Cotton T-Shirt, Men's Medium, Navy Blue, 100% Sustainable Materials",
    "KitchenAid Stand Mixer, 5 Quart, Red, 10-Speed Settings with Dough Hook Attachment"
]

template = outlines.Template.from_string("""
<|im_start|>user
Categorize this product:

{{ description }}
<|im_end|>
<|im_start|>assistant
""")

# Get structured categorization for all products
categories = model(
    [template(description=desc) for desc in product_descriptions],
    ProductCategory,
    max_new_tokens=200
)

# Use categorization for inventory management
categories = [
    ProductCategory.model_validate_json(category) for category in categories
]
for product, category in zip(product_descriptions, categories):
    update_inventory(product, category.main_category, category.sub_category)

readme truncated — read the full docs on github

Frequently asked questions

Is outlines free to use?

outlines is open source under the Apache-2.0 licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does outlines do?

Structured Outputs

What is outlines written in?

outlines is primarily written in Python. Its source is publicly available at https://github.com/dottxt-ai/outlines, and it has 15,825 GitHub stars.