4.3 Pydantic連携
Pydantic Integration
PydanticモデルでGuard作成
Pydanticは、Pythonの型ヒントを活用したデータ検証ライブラリ。Guardrails AIはPydanticモデルから直接Guardを作成できる。
from pydantic import BaseModel, Field from typing import Annotated, Optional from guardrails import Guard from guardrails.validators import ValidLength, ValidRange class UserProfile(BaseModel): name: Annotated[str, ValidLength(min=1, max=50)] = Field( description="ユーザー名" ) age: Annotated[int, ValidRange(min=0, max=150)] = Field( description="年齢" ) email: str = Field(description="メールアドレス") bio: Optional[str] = Field(default=None, description="自己紹介") guard = Guard.from_pydantic(UserProfile)
Pydanticの型とGuardrails
| Pydantic型 | Guardrails対応 |
|---|---|
str | 文字列バリデーション |
int, float | 数値範囲検証 |
bool | 真偽値検証 |
list[T] | 配列要素の検証 |
Optional[T] | Nullable対応 |
Literal[...] | 選択肢制限 |
ネストしたモデル
class Address(BaseModel): city: str postal_code: str class User(BaseModel): name: str address: Address # ネストしたモデル tags: list[str] # 配列 guard = Guard.from_pydantic(User)
Field descriptionの重要性
description活用
Fieldのdescriptionは、LLMへのプロンプトに自動的に含まれる。明確な説明を書くことで、LLMの出力精度が向上する。
参考文献
[1] Pydantic Documentation - https://docs.pydantic.dev/
[1] Pydantic Documentation - https://docs.pydantic.dev/