Skip to main content

用法

机器翻译译自英文(docs.typesafe.ai)本页 39 段已全部译完

文档索引

在以下地址获取完整的文档索引:https://docs.typesafe.ai/llms.txt 使用此文件可以在进一步探索之前发现所有可用页面。

用法

有关使用 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())

带类型的 system_one 响应

你也可以向 system_one 提供响应模型,使响应的使用更加类型安全:

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 的全新响应模型:

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

选择模型

检查可用的模型:

from typesafe_sdk import TypeSafeClient

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

在创建客户端时选择模型:

client = TypeSafeClient(model="jev")

有关详细信息,请参阅 Models 资源参考。

重试

在客户端或每次调用时,将自定义 RetryPolicy 作为 retry 传递。

客户端每次调用

from typesafe_sdk import RetryPolicy, TypeSafeClient

client = TypeSafeClient(retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0))

错误处理

处理 SDK 引发的 异常:

from typesafe_sdk import TypeSafeAPIError

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

日志记录

SDK 会向日志记录器 typesafe_sdk 记录日志。请根据标准日志记录指南进行配置:

import logging

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

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

info 为每个请求记录一行摘要;debug 还会记录请求和响应的标头及正文。敏感标头(授权、API 密钥、Cookie,以及任何名称包含 token 或 secret 的标头)在日志输出中会被屏蔽。请求和响应正文不会被屏蔽。

环境变量

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

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

有关 SDK 默认值,请参阅常量参考。

向前兼容

随着 TypeSafe API 的演变,SDK 将继续正常工作,因此你可以在 SDK 版本发布为其提供一流支持之前采用新的 API 功能。

额外请求字段

使用 extra_body 发送此 SDK 版本之前未包含的请求字段:

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},
    )

原始问题字典

from typesafe_sdk import TypeSafeClient

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

Tip

提示

未知字段是向前兼容的逃生舱。请忽略其类型检查错误,并优先升级 SDK。

未知回答类型

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

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"]

未知响应字段

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