用法
使用 TypeSafe Python SDK 的指南与模式。
调用 System One API
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())from typesafe_sdk import Choice, Noul, Score, TypeSafeClient</pre></div></div></div>client = TypeSafeClient() state = "I was charged twice. Please help ASAP." questions = { "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"] ), } result = client.system_one(state, questions) print( result.nouls["billing"].noul, result.choices["tone"].choice, result.scores["urgency"].score, )
类型化的
system_one响应可以为
system_one提供一个响应模型,使响应的使用更具类型安全性:pythonfrom 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:pythonfrom 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选择模型
查看可用模型:
pythonfrom typesafe_sdk import TypeSafeClient print(TypeSafeClient().models.list())在构造客户端时选择模型:
pythonclient = TypeSafeClient(model="jev")详见 Models 资源参考。
配置 base URL
若要将 SDK 与其他 API 地址搭配使用,请在客户端上设置
base_url,或设置TYPESAFE_BASE_URL环境变量。例如,通过 AI 网关连接,并使用其 API 密钥和模型 ID:
使用 OpenRouter API 密钥和 OpenRouter 模型 ID:
skip: next
pythonimport 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
pythonimport 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。pythonfrom typesafe_sdk import RetryPolicy, TypeSafeClient client = TypeSafeClient(retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0))pythonfrom typesafe_sdk import RetryPolicy</pre></div></div></div>client.system_one( state, questions, retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0) )
错误处理
处理 SDK 引发的异常:
pythonfrom typesafe_sdk import TypeSafeAPIError try: client.system_one(state, questions) except TypeSafeAPIError as error: print(error.status, error.request_id)日志
SDK 会将日志记录到
typesafe_sdklogger。可按照 标准 logging 指南进行配置:pythonimport 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 根 URL https://api.typesafe.aiTYPESAFE_DEFAULT_MODEL默认模型 jev-latestTYPESAFE_LOG_LEVELtypesafe_sdklogger 级别,导入时应用一次未设置 SDK 默认值详见常量参考。
向前兼容
随着 TypeSafe API 的演进,SDK 仍能持续正常工作,因此你可以在 SDK 版本为其提供一等支持之前,先行采用新的 API 特性。
额外请求字段
通过
extra_body发送当前 SDK 版本尚不支持的请求字段:pythonfrom 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}, )原始问题字典
pythonfrom 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 响应,包括这些答案:pythonfrom 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"]未知的响应字段
已识别响应上的未知额外字段会被忽略。