TokenLab

框架與平台

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 呼叫周邊的驗證。請針對 chat-completions 流程使用相容 OpenAI 的路徑,或者如果您的應用程式需要原生的 TokenLab 端點,請傳遞自訂的可呼叫物件。

本頁內容