mcpField
O
outlines

outlines

github.com/orchestra-research開発14.1k959 回インストール19 週間前に更新
リポジトリ

outlines について

Outlinesは、LLMの生成を構造化テキストに制約するPythonライブラリです。指定形式の出力を必要とする開発者向けで、トークン単位の制約によりJSON、正規表現、型付きデータに対応し、複数のモデルバックエンドを利用できます。

主な機能

  1. 01スキーマに沿った生成制約
  2. 02PydanticとJSON Schema対応
  3. 03正規表現に合うテキスト生成
  4. 04選択肢・数値ジェネレーター
  5. 05複数モデルバックエンド対応

活用シーン

  1. 01テキストから型付き項目を抽出
  2. 02スキーマに沿ったJSON生成
  3. 03内容を定められた選択肢に分類

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/orchestra-research/ai-research-skills --skill outlines

インストール後、Claude Code で/outlinesを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
backends.md
examples.md
json_generation.md

詳細

Outlines: 構造化テキスト生成

このスキルを使うタイミング

Outlines は次のような場合に使用します:

  • 生成時に 有効な JSON/XML/コード の構造を保証したい
  • 型安全な出力のために Pydantic モデル を使いたい
  • ローカルモデル(Transformers、llama.cpp、vLLM)をサポートしたい
  • ゼロオーバーヘッドの構造化生成で 推論速度を最大化 したい
  • JSON スキーマに基づいて 自動的に生成したい
  • 文法レベルで トークンサンプリングを制御 したい

GitHub Stars: 8,000+ | 開発元: dottxt.ai(旧 .txt)

インストール

# Base installation
pip install outlines

# With specific backends
pip install outlines transformers  # Hugging Face models
pip install outlines llama-cpp-python  # llama.cpp
pip install outlines vllm  # vLLM for high-throughput

クイックスタート

基本例: 分類
import outlines
from typing import Literal

# Load model
model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")

# Generate with type constraint
prompt = "Sentiment of 'This product is amazing!': "
generator = outlines.generate.choice(model, ["positive", "negative", "neutral"])
sentiment = generator(prompt)

print(sentiment)  # "positive" (guaranteed one of these)
Pydantic モデルの利用
from pydantic import BaseModel
import outlines

class User(BaseModel):
    name: str
    age: int
    email: str

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")

# Generate structured output
prompt = "Extract user: John Doe, 30 years old, [email protected]"
generator = outlines.generate.json(model, User)
user = generator(prompt)

print(user.name)   # "John Doe"
print(user.age)    # 30
print(user.email)  # "[email protected]"

コアコンセプト

1. 制約付きトークンサンプリング

Outlines は有限状態機械(FSM)を使い、ロジットレベルでトークン生成を制約します。

仕組み:

  1. スキーマ(JSON/Pydantic/正規表現)を文脈自由文法(CFG)に変換する
  2. CFG を有限状態機械(FSM)に変換する
  3. 生成中、各ステップで無効なトークンをフィルタリングする
  4. 有効なトークンが1つしかない場合は早送りする

利点:

  • ゼロオーバーヘッド: フィルタリングはトークン単位で行われる
  • 速度向上: 決定的なパスを早送りする
  • 妥当性の保証: 無効な出力は発生しない
import outlines

# Pydantic model -> JSON schema -> CFG -> FSM
class Person(BaseModel):
    name: str
    age: int

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")

# Behind the scenes:
# 1. Person -> JSON schema
# 2. JSON schema -> CFG
# 3. CFG -> FSM
# 4. FSM filters tokens during generation

generator = outlines.generate.json(model, Person)
result = generator("Generate person: Alice, 25")
2. 構造化ジェネレーター

Outlines は出力の種類ごとに専用のジェネレーターを提供します。

Choice ジェネレーター
# Multiple choice selection
generator = outlines.generate.choice(
    model,
    ["positive", "negative", "neutral"]
)

sentiment = generator("Review: This is great!")
# Result: One of the three choices
JSON ジェネレーター
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    price: float
    in_stock: bool

# Generate valid JSON matching schema
generator = outlines.generate.json(model, Product)
product = generator("Extract: iPhone 15, $999, available")

# Guaranteed valid Product instance
print(type(product))  # <class '__main__.Product'>
正規表現ジェネレーター
# Generate text matching regex
generator = outlines.generate.regex(
    model,
    r"[0-9]{3}-[0-9]{3}-[0-9]{4}"  # Phone number pattern
)

phone = generator("Generate phone number:")
# Result: "555-123-4567" (guaranteed to match pattern)
整数/浮動小数点ジェネレーター
# Generate specific numeric types
int_generator = outlines.generate.integer(model)
age = int_generator("Person's age:")  # Guaranteed integer

float_generator = outlines.generate.float(model)
price = float_generator("Product price:")  # Guaranteed float
3. モデルバックエンド

Outlines は複数のローカルおよび API ベースのバックエンドをサポートします。

Transformers(Hugging Face)
import outlines

# Load from Hugging Face
model = outlines.models.transformers(
    "microsoft/Phi-3-mini-4k-instruct",
    device="cuda"  # Or "cpu"
)

# Use with any generator
generator = outlines.generate.json(model, YourModel)
llama.cpp
# Load GGUF model
model = outlines.models.llamacpp(
    "./models/llama-3.1-8b-instruct.Q4_K_M.gguf",
    n_gpu_layers=35
)

generator = outlines.generate.json(model, YourModel)
vLLM(高スループット)
# For production deployments
model = outlines.models.vllm(
    "meta-llama/Llama-3.1-8B-Instruct",
    tensor_parallel_size=2  # Multi-GPU
)

generator = outlines.generate.json(model, YourModel)
OpenAI(限定サポート)
# Basic OpenAI support
model = outlines.models.openai(
    "gpt-4o-mini",
    api_key="your-api-key"
)

# Note: Some features limited with API models
generator = outlines.generate.json(model, YourModel)
4. Pydantic 連携

Outlines は自動的なスキーマ変換を備えた、第一級の Pydantic サポートを提供します。

基本モデル
from pydantic import BaseModel, Field

class Article(BaseModel):
    title: str = Field(description="Article title")
    author: str = Field(description="Author name")
    word_count: int = Field(description="Number of words", gt=0)
    tags: list[str] = Field(description="List of tags")

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = outlines.generate.json(model, Article)

article = generator("Generate article about AI")
print(article.title)
print(article.word_count)  # Guaranteed > 0
ネストされたモデル
class Address(BaseModel):
    street: str
    city: str
    country: str

class Person(BaseModel):
    name: str
    age: int
    address: Address  # Nested model

generator = outlines.generate.json(model, Person)
person = generator("Generate person in New York")

print(person.address.city)  # "New York"
列挙型とリテラル
from enum import Enum
from typing import Literal

class Status(str, Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"

class Application(BaseModel):
    applicant: str
    status: Status  # Must be one of enum values
    priority: Literal["low", "medium", "high"]  # Must be one of literals

generator = outlines.generate.json(model, Application)
app = generator("Generate application")

print(app.status)  # Status.PENDING (or APPROVED/REJECTED)

よくあるパターン

パターン 1: データ抽出
from pydantic import BaseModel
import outlines

class CompanyInfo(BaseModel):
    name: str
    founded_year: int
    industry: str
    employees: int

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = outlines.generate.json(model, CompanyInfo)

text = """
Apple Inc. was founded in 1976 in the technology industry.
The company employs approximately 164,000 people worldwide.
"""

prompt = f"Extract company information:\n{text}\n\nCompany:"
company = generator(prompt)

print(f"Name: {company.name}")
print(f"Founded: {company.founded_year}")
print(f"Industry: {company.industry}")
print(f"Employees: {company.employees}")
パターン 2: 分類
from typing import Literal
import outlines

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")

# Binary classification
generator = outlines.generate.choice(model, ["spam", "not_spam"])
result = generator("Email: Buy now! 50% off!")

# Multi-class classification
categories = ["technology", "business", "sports", "entertainment"]
category_gen = outlines.generate.choice(model, categories)
category = category_gen("Article: Apple announces new iPhone...")

# With confidence
class Classification(BaseModel):
    label: Literal["positive", "negative", "neutral"]
    confidence: float

classifier = outlines.generate.json(model, Classification)
result = classifier("Review: This product is okay, nothing special")
パターン 3: 構造化フォーム
class UserProfile(BaseModel):
    full_name: str
    age: int
    email: str
    phone: str
    country: str
    interests: list[str]

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = outlines.generate.json(model, UserProfile)

prompt = """
Extract user profile from:
Name: Alice Johnson
Age: 28
Email: [email protected]
Phone: 555-0123
Country: USA
Interests: hiking, photography, cooking
"""

profile = generator(prompt)
print(profile.full_name)
print(profile.interests)  # ["hiking", "photography", "cooking"]
パターン 4: 複数エンティティの抽出
class Entity(BaseModel):
    name: str
    type: Literal["PERSON", "ORGANIZATION", "LOCATION"]

class DocumentEntities(BaseModel):
    entities: list[Entity]

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = outlines.generate.json(model, DocumentEntities)

text = "Tim Cook met with Satya Nadella at Microsoft headquarters in Redmond."
prompt = f"Extract entities from: {text}"

result = generator(prompt)
for entity in result.entities:
    print(f"{entity.name} ({entity.type})")
パターン 5: コード生成
class PythonFunction(BaseModel):
    function_name: str
    parameters: list[str]
    docstring: str
    body: str

model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = outlines.generate.json(model, PythonFunction)

prompt = "Generate a Python function to calculate factorial"
func = generator(prompt)

print(f"def {func.function_name}({', '.join(func.parameters)}):")
print(f'    """{func.docstring}"""')
print(f"    {func.body}")
パターン 6: バッチ処理
def batch_extract(texts: list[str], schema: type[BaseModel]):
    """Extract structured data from multiple texts."""
    model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")
    generator = outlines.generate.json(model, schema)

    results = []
    for text in texts:
        result = generator(f"Extract from: {text}")
        results.append(result)

    return results

class Person(BaseModel):
    name: str
    age: int

texts = [
    "John is 30 years old",
    "Alice is 25 years old",
    "Bob is 40 years old"
]

people = batch_extract(texts, Person)
for person in people:
    print(f"{person.name}: {person.age}")

バックエンドの設定

Transformers
import outlines

# Basic usage
model = outlines.models.transformers("microsoft/Phi-3-mini-4k-instruct")

# GPU configuration
model = outlines.models.transformers(
    "microsoft/Phi-3-mini-4k-instruct",
    device="cuda",
    model_kwargs={"torch_dtype": "float16"}
)

# Popular models
model = outlines.models.transformers("meta-llama/Llama-3.1-8B-Instruct")
model = outlines.models.transformers("mistralai/Mistral-7B-Instruct-v0.3")
model = outlines.models.transformers("Qwen/Qwen2.5-7B-Instruct")
llama.cpp
# Load GGUF model
model = outlines.models.llamacpp(
    "./models/llama-3.1-8b.Q4_K_M.gguf",
    n_ctx=4096,         # Context window
    n_gpu_layers=35,    # GPU layers
    n_threads=8         # CPU threads
)

# Full GPU offload
model = outlines.models.llamacpp(
    "./models/model.gguf",
    n_gpu_layers=-1  # All layers on GPU
)
vLLM(本番環境)
# Single GPU
model = outlines.models.vllm("meta-llama/Llama-3.1-8B-Instruct")

# Multi-GPU
model = outlines.models.vllm(
    "meta-llama/Llama-3.1-70B-Instruct",
    tensor_parallel_size=4  # 4 GPUs
)

# With quantization
model = outlines.models.vllm(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization="awq"  # Or "gptq"
)

ベストプラクティス

1. 具体的な型を使う
# ✅ Good: Specific types
class Product(BaseModel):
    name: str
    price: float  # Not str
    quantity: int  # Not str
    in_stock: bool  # Not str

# ❌ Bad: Everything as string
class Product(BaseModel):
    name: str
    price: str  # Should be float
    quantity: str  # Should be int
2. 制約を追加する
from pydantic import Field

# ✅ Good: With constraints
class User(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=0, le=120)
    email: str = Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")

# ❌ Bad: No constraints
class User(BaseModel):
    name: str
    age: int
    email: str
3. カテゴリには列挙型を使う
# ✅ Good: Enum for fixed set
class Priority(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"

class Task(BaseModel):
    title: str
    priority: Priority

# ❌ Bad: Free-form string
class Task(BaseModel):
    title: str
    priority: str  # Can be anything
4. プロンプトにコンテキストを含める
# ✅ Good: Clear context
prompt = """
Extract product information from the following text.
Text: iPhone 15 Pro costs $999 and is currently in stock.
Product:
"""

# ❌ Bad: Minimal context
prompt = "iPhone 15 Pro costs $999 and is currently in stock."
5. オプションのフィールドを処理する
from typing import Optional

# ✅ Good: Optional fields for incomplete data
class Article(BaseModel):
    title: str  # Required
    author: Optional[str] = None  # Optional
    date: Optional[str] = None  # Optional
    tags: list[str] = []  # Default empty list

# Can succeed even if author/date missing

代替手段との比較

機能OutlinesInstructorGuidanceLMQL
Pydantic サポート✅ ネイティブ✅ ネイティブ❌ なし❌ なし
JSON スキーマ✅ あり✅ あり⚠️ 限定的✅ あり
正規表現制約✅ あり❌ なし✅ あり✅ あり
ローカルモデル✅ 完全⚠️ 限定的✅ 完全✅ 完全
API モデル⚠️ 限定的✅ 完全✅ 完全✅ 完全
ゼロオーバーヘッド✅ あり❌ なし⚠️ 部分的✅ あり
自動リトライ❌ なし✅ あり❌ なし❌ なし
学習コスト低低低高

Outlines を選ぶべき場合:

  • ローカルモデル(Transformers、llama.cpp、vLLM)を使用している
  • 最大の推論速度が必要である
  • Pydantic モデルのサポートが欲しい
  • ゼロオーバーヘッドの構造化生成が必要である
  • トークンサンプリングの過程を制御したい

代替手段を選ぶべき場合:

  • Instructor: 自動リトライを備えた API モデルが必要な場合
  • Guidance: トークンヒーリングや複雑なワークフローが必要な場合
  • LMQL: 宣言的なクエリ構文を好む場合

パフォーマンス特性

速度:

  • ゼロオーバーヘッド: 構造化生成は制約なしの生成と同程度に高速
  • 早送り最適化: 決定的なトークンをスキップする
  • 生成後の検証方式より 1.2〜2 倍高速

メモリ:

  • FSM はスキーマごとに一度だけコンパイルされる(キャッシュされる)
  • 実行時のオーバーヘッドは最小限
  • vLLM と組み合わせると高スループットで効率的

精度:

  • 100% 有効な出力(FSM により保証)
  • リトライループは不要
  • 決定的なトークンフィルタリング

リソース

関連項目

  • references/json_generation.md - JSON と Pydantic の包括的なパターン
  • references/backends.md - バックエンド固有の設定
  • references/examples.md - 本番環境に対応した例

コメント