5.3 エージェント統合

Agent Integration

エージェントでのGuardrails活用

LangChainエージェントのツール出力や最終応答にGuardrailsを適用できる。これにより、エージェントの出力品質を担保する。

エージェントでの適用箇所

・ツールの出力検証

・最終応答のフォーマット強制

・エージェントの行動選択の検証

ツール出力の検証

from langchain.tools import tool
from guardrails import Guard
from pydantic import BaseModel

class OrderResult(BaseModel):
    order_id: str
    status: str
    total: int

guard = Guard.from_pydantic(OrderResult)

@tool
def create_order(product_id: str, quantity: int) -> dict:
    """商品を注文する"""
    # LLMによる処理
    raw_result = llm_process_order(product_id, quantity)
    
    # Guardrailsで検証
    validated = guard.parse(raw_result)
    return validated.validated_output

エージェント最終応答の検証

from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI

class AgentResponse(BaseModel):
    answer: str
    sources: list[str]
    confidence: float

response_guard = Guard.from_pydantic(AgentResponse)

# エージェント実行後に検証
agent_executor = AgentExecutor(agent=agent, tools=tools)
raw_response = agent_executor.invoke({"input": query})

# 応答を検証
validated = response_guard.parse(raw_response["output"])

自動発注エージェントの例

実務で使用する自動発注エージェントでの適用例。

class OrderAction(BaseModel):
    action: Annotated[str, ValidChoices(["order", "cancel", "modify"])]
    product_id: str
    quantity: Annotated[int, ValidRange(min=1, max=1000)]
    reason: str

class OrderConfirmation(BaseModel):
    success: bool
    order_id: Optional[str]
    message: str
    total_price: Annotated[int, ValidRange(min=0)]

# エージェントの行動を検証
action_guard = Guard.from_pydantic(OrderAction)

# 結果を検証
result_guard = Guard.from_pydantic(OrderConfirmation)
エージェント制御の重要性

自動発注のような実務処理では、エージェントの誤動作が直接的な損害につながる。Guardrailsによる出力検証は、このリスクを軽減する。

参考文献
[1] LangChain - Agents - https://python.langchain.com/docs/concepts/agents/