2.1 基本構成
Basic Architecture
アーキテクチャ概要
Guardrails AIは、LLMの入出力を制御するための複数のコンポーネントで構成される。中核となるのはGuardオブジェクトであり、スキーマ定義・バリデーター・LLM呼び出しを統合的に管理する。
設計思想
Guardrails AIは「宣言的な定義」と「自動的な検証・修正」を組み合わせ、開発者が出力品質を意識せずにLLMを活用できることを目指している。
主要コンポーネント
Guard
Guardrails AIの中心となるオブジェクト。以下の責務を持つ。
| 責務 | 説明 |
|---|---|
| スキーマ管理 | 期待する出力構造の定義を保持 |
| LLM呼び出し | 各種LLM APIのラッパーとして機能 |
| バリデーション実行 | 登録されたValidatorを順次実行 |
| リトライ制御 | 検証失敗時の再生成ロジックを管理 |
from guardrails import Guard from pydantic import BaseModel class Output(BaseModel): answer: str confidence: float # Guardの作成方法 guard = Guard.from_pydantic(Output) # Pydanticから guard = Guard.from_rail("schema.rail") # RAILファイルから guard = Guard.from_rail_string(rail_string) # RAIL文字列から
Validator
出力の各フィールドに適用される検証ルール。組み込みバリデーターとカスタムバリデーターがある。
from guardrails.validators import ( ValidLength, ValidRange, ValidChoices, RegexMatch ) from pydantic import BaseModel, Field from typing import Annotated class Product(BaseModel): name: Annotated[str, ValidLength(min=1, max=100)] price: Annotated[int, ValidRange(min=0, max=1000000)] category: Annotated[str, ValidChoices(["電子機器", "食品", "衣類"])]
RAIL(Reliable AI Language)
XMLベースのDSLでスキーマとバリデーションルールを定義する形式。複雑なスキーマの可読性が高い。
<!-- example.rail -->
<rail version="0.1">
<output>
<object name="user_profile">
<string name="name"
description="ユーザー名"
validators="length: 1 100" />
<integer name="age"
description="年齢"
validators="range: 0 150" />
<string name="email"
description="メールアドレス"
validators="regex: ^[\w\.-]+@[\w\.-]+\.\w+$" />
</object>
</output>
</rail>
コンポーネント間の関係
各コンポーネントは以下のように連携する。
連携の流れ
1. スキーマ定義(Pydantic / RAIL)→ Guardに登録
2. Validator → スキーマの各フィールドに紐付け
3. Guard → LLM呼び出し時にValidator群を実行
4. 検証結果 → 成功なら出力、失敗ならReask
Guard作成のパターン
パターン1: Pydanticモデルから
最も一般的なパターン。型ヒントとバリデーターをPythonコードで定義。
from guardrails import Guard from pydantic import BaseModel, Field class Summary(BaseModel): title: str = Field(description="要約のタイトル") content: str = Field(description="要約本文") keywords: list[str] = Field(description="キーワードリスト") guard = Guard.from_pydantic(Summary)
パターン2: RAILファイルから
スキーマを外部ファイルとして管理したい場合。
guard = Guard.from_rail("./schemas/summary.rail")
パターン3: 動的なスキーマ定義
実行時にスキーマを構築する場合。
rail_string = """
<rail version="0.1">
<output>
<string name="result" />
</output>
</rail>
"""
guard = Guard.from_rail_string(rail_string)
参考文献
[1] Guardrails AI - Guard Object - https://docs.guardrailsai.com/concepts/guard/
[2] Guardrails AI - RAIL Specification - https://docs.guardrailsai.com/concepts/rail/
[1] Guardrails AI - Guard Object - https://docs.guardrailsai.com/concepts/guard/
[2] Guardrails AI - RAIL Specification - https://docs.guardrailsai.com/concepts/rail/