Jev Python SDK 完整教程
安装 TypeSafe Python SDK,发送 Jev 类型化请求,并安全读取 Choice、Score、Noul 与置信度结果。
1. 安装与鉴权
API Key 应仅保存在服务端。SDK 会读取 TYPESAFE_API_KEY 环境变量,无需把密钥写进应用代码。
python -m pip install "typesafe-sdk==0.7.2" "truststore>=0.10.5"
export TYPESAFE_API_KEY="your-api-key" 2. 发起类型化决策
state 提供需要判断的事实,questions 定义期望返回的封闭决策。下面的示例同时完成工单路由与紧急程度判断。
from typesafe_sdk import Choice, Noul, TypeSafeClient
with TypeSafeClient() as client:
response = client.system_one(
state={"message": "Stripe has failed for 3 days."},
questions={
"department": Choice(
instructions="Which team should handle this?",
criteria={
"billing": "Payments or subscriptions",
"technical": "Bugs or integrations",
"sales": "Pricing or account questions",
},
),
"is_urgent": Noul(
instructions="Does the message convey urgency?"
),
},
) 3. 安全读取答案
Choice 返回胜出标签、完整概率分布与置信度;Noul 返回命题为真的概率。应把结果当成决策数据,而不是生成文本。
department = response.answers["department"]
print(department.choice)
print(department.probabilities)
print(department.confidence)
urgent = response.answers["is_urgent"]
print(urgent.noul) # P(true) 4. 上线检查清单
记录模型版本,保持问题 ID 稳定,在触发副作用前校验答案,并将低置信度或高风险案例交给人工。
动手验证:完整示例与失败路径
并发 TLS 注意:旧版 truststore 的共享 SSLContext 可能导致解释器崩溃,安装命令要求 truststore>=0.10.5。这里保留受测试的 SDK 0.7.2,并单独约束传递依赖;这不等于本站复现了崩溃或验证了所有平台的真实 TLS 握手。truststore 0.10.5 ↗
下方是完整文件,不需要补写省略函数。示例仅打印建议或转人工状态,不修改工单、不执行支付或发布。
验证范围:锁定依赖的类型/语法检查和模拟传输;未进行真实 API 性能或准确率测试。真实运行需要自己的服务端密钥,可能产生费用。纯校准和输入处理示例不联网。
同步与异步的选择
前面的同步调用适合脚本。下面的异步版本需要 Python 3.11+,可嵌入已有事件循环;在 FastAPI 等异步应用内直接 await suggest_team(client),不要再次 asyncio.run。with/async with 负责释放连接。
timeout=2 限制单次请求,max_retries=1 最多两次尝试;asyncio.timeout(8) 限制重试与等待的总时间。失败后返回人工复核,不把网络异常当成“不紧急”。
本课的交付物是可嵌入异步应用的 suggest_team(client):成功时得到建议,失败时进入复核。接下来的类型课单独练习“如何解释答案”,可靠性课再处理数据库持久化与重复投递;不要把一次 SDK 调用当成完整工作流。
python_async.py
import asyncio
from math import isfinite
from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul, Score, RetryPolicy
async def suggest_team(client):
# Overall deadline bounds requests, retries and backoff together.
async with asyncio.timeout(8):
response = await client.system_one(
model="jev-1.13.0",
state={"message": "Checkout fails for every customer.", "scope": "all customers"},
questions={
"route": Choice(instructions="Which team owns this incident?", criteria={
"technical": "Bugs or integrations", "billing": "Invoices", "human": "Unclear ownership"}),
"severity": Score(instructions="How blocked are customers?", criteria=[
"Unaffected", "Workaround available", "Core workflow blocked"]),
"urgent": Noul(instructions="Does the message describe an ongoing service disruption?"),
},
)
route = response.choices["route"]
# The SDK validates the response shape. This branch is application policy.
valid = route.choice in {"technical", "billing", "human"} and isfinite(route.confidence) and 0 <= route.confidence <= 1
# Teaching threshold only; calibrate on independently labeled outcomes.
return {"action": "review" if not valid or route.choice == "human" or route.confidence < 0.75 else "suggest",
"team": route.choice, "severity": response.scores["severity"].score,
"urgent_probability": response.nouls["urgent"].noul}
async def main():
try:
async with AsyncTypeSafeClient(timeout=2, retry=RetryPolicy(max_retries=1)) as client:
print(await suggest_team(client))
except Exception:
print({"action": "review", "reason": "provider_or_configuration_failure"})
if __name__ == "__main__":
asyncio.run(main())
下载此文件运行
python -m pip install "typesafe-sdk==0.7.2" "truststore>=0.10.5"
export TYPESAFE_API_KEY="your-server-side-key"
python python_async.py如何判断是否运行正确
有 API 的示例应输出 action、team 等结构化字段;具体标签与分数会随输入和模型变化,不能要求与模拟值一致。删除密钥应走复核分支,不应泄露异常正文。校准脚本输出 development 与 held-out 两组指标;它不验证模型质量。