框架与平台

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)

端点说明

Chat Completions 可以直接使用上面的 OpenAI SDK 配置。其他 TokenLab API 需要把相应的调用方法封装成 Guardrails 可接受的 callable。

本页内容