🛡️TypeSafe 中文文档
原文档 ↗

用法

使用 TypeSafe Python SDK 的指南与模式。

调用 System One API

python
import asyncio

from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul, Score


async def main() -> None:
    async with AsyncTypeSafeClient() as client:
        result = await client.system_one(
            "I was charged twice. Please help ASAP.",
            {
                "billing": Noul(instructions="Is this about billing?"),
                "tone": Choice(
                    instructions="What is the tone?",
                    criteria={"calm": None, "angry": None},
                ),
                "urgency": Score(
                    instructions="How urgent is this?",
                    criteria=["low", "medium", "high"],
                ),
            },
        )
        print(
            result.nouls["billing"].noul,
            result.choices["tone"].choice,
            result.scores["urgency"].score,
        )


asyncio.run(main())
python
from typesafe_sdk import Choice, Noul, Score, TypeSafeClient

client = TypeSafeClient() state = &quot;I was charged twice. Please help ASAP.&quot; questions = { &quot;billing&quot;: Noul(instructions=&quot;Is this about billing?&quot;), &quot;tone&quot;: Choice( instructions=&quot;What is the tone?&quot;, criteria={&quot;calm&quot;: None, &quot;angry&quot;: None} ), &quot;urgency&quot;: Score( instructions=&quot;How urgent is this?&quot;, criteria=[&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;] ), } result = client.system_one(state, questions) print( result.nouls[&quot;billing&quot;].noul, result.choices[&quot;tone&quot;].choice, result.scores[&quot;urgency&quot;].score, )</pre></div></div></div>

类型化的 system_one 响应

可以为 system_one 提供一个响应模型,使响应的使用更具类型安全性:

python
from typesafe_sdk import Noul, NoulAnswer, SystemOneResponse, TypeSafeClient


class BillingResponse(SystemOneResponse):
    billing: NoulAnswer


with TypeSafeClient() as client:
    result = client.system_one(
        "I was charged twice.",
        {"billing": Noul(instructions="Is this about billing?")},
        response_model=BillingResponse,
    )
    assert 0 <= result.billing.noul <= 1
    assert result.billing == result.nouls["billing"]
    print(result.request_id)

自定义响应类型

也可以定义一个全新的响应模型,而无需继承 SystemOneResponse:

python
from pydantic import BaseModel

from typesafe_sdk import Noul, NoulAnswer, TypeSafeClient


class BillingAnswers(BaseModel):
    billing: NoulAnswer


class BillingResponse(BaseModel):
    answers: BillingAnswers


result = TypeSafeClient().system_one(
    "I was charged twice.",
    {"billing": Noul(instructions="Is this about billing?")},
    response_model=BillingResponse,
)
assert 0 <= result.answers.billing.noul <= 1

选择模型

查看可用模型:

python
from typesafe_sdk import TypeSafeClient

print(TypeSafeClient().models.list())

在构造客户端时选择模型:

python
client = TypeSafeClient(model="jev")

详见 Models 资源参考。

配置 base URL

若要将 SDK 与其他 API 地址搭配使用,请在客户端上设置 base_url,或设置 TYPESAFE_BASE_URL 环境变量。

例如,通过 AI 网关连接,并使用其 API 密钥和模型 ID:

使用 OpenRouter API 密钥和 OpenRouter 模型 ID:

skip: next

python
import os

from typesafe_sdk import Noul, TypeSafeClient

with TypeSafeClient(
    api_key=os.environ["OPENROUTER_API_KEY"],
    base_url="https://openrouter.ai/api",
    model="~typesafe/jev-latest",
) as client:
    result = client.system_one(
        "I was charged twice.",
        {"billing": Noul(instructions="Is this about billing?")},
    )
    print(result.nouls["billing"].noul)

SDK 可以使用 Vercel 的 TypeSafe 兼容 API:

skip: next

python
import os

from typesafe_sdk import Noul, TypeSafeClient

with TypeSafeClient(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh/typesafe",
    model="typesafe-ai/jev",
) as client:
    result = client.system_one(
        "I was charged twice.",
        {"billing": Noul(instructions="Is this about billing?")},
    )
    print(result.nouls["billing"].noul)

这要求备用的 API 遵循 TypeSafe OpenAPI 规范。

重试

在客户端上或按单次调用传入自定义的 RetryPolicy 作为 retry。

python
from typesafe_sdk import RetryPolicy, TypeSafeClient

client = TypeSafeClient(retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0))
python
from typesafe_sdk import RetryPolicy

client.system_one( state, questions, retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0) )</pre></div></div></div>

错误处理

处理 SDK 引发的异常:

python
from typesafe_sdk import TypeSafeAPIError

try:
    client.system_one(state, questions)
except TypeSafeAPIError as error:
    print(error.status, error.request_id)

日志

SDK 会将日志记录到 typesafe_sdk logger。可按照 标准 logging 指南进行配置:

python
import logging

logging.getLogger("typesafe_sdk").setLevel(logging.DEBUG)

或在导入 SDK 之前,将 TYPESAFE_LOG_LEVEL 设置为 debug、info、warning、error 或 off 之一。

info 会为每个请求记录一行摘要;debug 还会记录请求与响应的头和体。敏感请求头——authorization、API key、cookie,以及名称中包含 token 或 secret 的任何请求头——都会从日志输出中脱敏。请求体与响应体不会脱敏。

环境变量

SDK 会读取并使用以下环境变量:

变量配置项默认值
TYPESAFE_API_KEYAPI key(必需)—
TYPESAFE_BASE_URLAPI 根 URLhttps://api.typesafe.ai
TYPESAFE_DEFAULT_MODEL默认模型jev-latest
TYPESAFE_LOG_LEVELtypesafe_sdk logger 级别,导入时应用一次未设置

SDK 默认值详见常量参考。

向前兼容

随着 TypeSafe API 的演进,SDK 仍能持续正常工作,因此你可以在 SDK 版本为其提供一等支持之前,先行采用新的 API 特性。

额外请求字段

通过 extra_body 发送当前 SDK 版本尚不支持的请求字段:

python
from typesafe_sdk import Noul, TypeSafeClient

with TypeSafeClient() as client:
    client.system_one(
        "I was charged twice.",
        {"billing": Noul(instructions="About billing?")},
        extra_body={"beam_width": 4},
    )

原始问题字典

python
from typesafe_sdk import TypeSafeClient

with TypeSafeClient() as client:
    client.system_one(
        "I was charged twice.",
        {"billing": {"type": "noul", "instructions": "About billing?", "weight": 2}},
    )
💡提示

提示

未知字段是一种向前兼容的应急手段。忽略由此产生的类型检查错误,并优先选择升级 SDK。

未知的答案类型

SDK 会记录一条警告并跳过无法识别的答案类型。可使用 raw_http_response 检查完整的 API 响应,包括这些答案:

python
from typesafe_sdk import Noul, TypeSafeClient

result = TypeSafeClient().system_one(
    "I was charged twice.",
    {"billing": Noul(instructions="Is this about billing?")},
)
raw_answers = result.raw_http_response.json()["answers"]

未知的响应字段

已识别响应上的未知额外字段会被忽略。

本站为 docs.typesafe.ai 的中文翻译,仅供学习参考;内容版权归原作者所有。