フレームワークとプラットフォーム

Guardrails

Guardrailsを使用してTokenLabモデルの出力を検証する

概要

TokenLab の Base URL で OpenAI SDK を設定し、JSON を要求して、返されたテキストを Guard.parse で検証します。

タイプ: 検証および構造化出力フレームワーク

主要なパス: OpenAI互換のChat Completions

サポートの信頼性: サポートされているOpenAI互換パス

インストール

pip install guardrails-ai openai

環境設定

export TOKENLAB_API_KEY="sk-your-tokenlab-key"

例

import os

from guardrails import Guard
from openai import OpenAI
from pydantic import BaseModel, Field


class Pet(BaseModel):
    pet_type: str = Field(description="Species of pet")
    name: str = Field(description="A unique pet name")


guard = Guard.for_pydantic(output_class=Pet)

client = OpenAI(
    api_key=os.environ["TOKENLAB_API_KEY"],
    base_url="https://api.tokenlab.sh/v1",
)

response = client.chat.completions.create(
    model="claude-sonnet-5",
    response_format={"type": "json_object"},
    messages=[{
        "role": "user",
        "content": "Suggest a pet. Return only JSON with string fields pet_type and name.",
    }],
)

outcome = guard.parse(response.choices[0].message.content)
print(outcome.validated_output)

エンドポイントに関する注意点

Guardrailsは、LLM呼び出し周辺の検証に重点を置いています。チャット補完フローにはOpenAI互換パスを使用するか、アプリケーションでネイティブなTokenLabエンドポイントが必要な場合はカスタムの呼び出し可能オブジェクトを渡してください。

このページの内容