2.3 主要コンポーネント
Core Components
コンポーネント一覧
| コンポーネント | 役割 | 主なクラス/関数 |
|---|---|---|
| Guard | メインの制御オブジェクト | Guard |
| Validator | 検証ルールの定義 | Validator, 各種組み込みValidator |
| Schema | 出力構造の定義 | Pydantic BaseModel, RAIL |
| History | 実行履歴の管理 | GuardHistory |
| Actions | 検証失敗時の動作 | OnFailAction |
Guard詳細
Guardの作成方法
from guardrails import Guard # 方法1: Pydanticモデルから guard = Guard.from_pydantic(MyModel) # 方法2: RAILファイルから guard = Guard.from_rail("schema.rail") # 方法3: RAIL文字列から guard = Guard.from_rail_string(rail_str) # 方法4: 空のGuard(後からスキーマ設定) guard = Guard()
Guardの設定オプション
guard = Guard.from_pydantic(
MyModel,
num_reasks=3, # リトライ回数
output_schema=schema, # 追加スキーマ
)
# 呼び出し時の設定
result = guard(
llm_api=openai.chat.completions.create,
model="gpt-4",
messages=[...],
num_reasks=2, # 呼び出し時にも設定可
full_schema_reask=True # 全スキーマでリトライ
)
Validator詳細
Validatorの基本構造
from guardrails.validators import Validator, register_validator from guardrails.validators import PassResult, FailResult @register_validator(name="my-validator", data_type="string") class MyValidator(Validator): def validate(self, value, metadata) -> PassResult | FailResult: if self._is_valid(value): return PassResult() return FailResult( error_message=f"値 '{value}' は無効です", fix_value=self._fix(value) # 修正値(オプション) )
OnFailActionの種類
検証失敗時の動作を指定できる。
| Action | 動作 |
|---|---|
REASK |
LLMに再生成を依頼 |
FIX |
Validatorのfix_valueで修正 |
FILTER |
該当フィールドを除外 |
REFRAIN |
出力全体を破棄 |
NOOP |
何もしない(警告のみ) |
EXCEPTION |
例外を発生 |
from guardrails.validators import ValidLength from guardrails import OnFailAction class MyModel(BaseModel): name: Annotated[ str, ValidLength(min=1, max=100, on_fail=OnFailAction.REASK) ]
History詳細
Guardは実行履歴を保持し、デバッグや分析に活用できる。
result = guard(...) # 履歴へのアクセス for call in guard.history: print("入力:", call.inputs) print("出力:", call.output) print("検証結果:", call.validation_response) print("---") # 履歴のクリア guard.history.clear()
履歴の活用例
# リトライ回数の統計 total_reasks = sum( len(call.iterations) - 1 for call in guard.history ) print(f"平均リトライ回数: {total_reasks / len(guard.history):.2f}") # 失敗パターンの分析 failures = [ call.validation_response for call in guard.history if not call.validation_passed ]
コンポーネント間の連携
典型的な連携パターン
1. Pydantic/RAILでSchemaを定義
2. Schemaの各フィールドにValidatorを紐付け
3. Schema + ValidatorからGuardを作成
4. GuardでLLMを呼び出し、結果を取得
5. 必要に応じてHistoryを参照
次章では、Validatorの詳細と組み込みバリデーターの使い方を解説する。
参考文献
[1] Guardrails AI - Components - https://docs.guardrailsai.com/concepts/
[2] Guardrails AI - Validators - https://docs.guardrailsai.com/concepts/validators/
[1] Guardrails AI - Components - https://docs.guardrailsai.com/concepts/
[2] Guardrails AI - Validators - https://docs.guardrailsai.com/concepts/validators/