框架與平台
Guardrails
使用 Guardrails 驗證 TokenLab 模型輸出
概覽
使用 TokenLab Base URL 設定 OpenAI SDK,請求 JSON,然後使用 Guard.parse 驗證回傳的文字。
安裝
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 端點,請傳入自訂的可呼叫物件 (callable)。