跳转到内容

JavaScript 指南

调用 Jev 有两条路:官方 SDK(需要 Node.js 20 及以上),或原生 fetch(Node.js 18 及以上、边缘运行时均可)。两者请求的都是同一个 API 端点

安装
npm install @typesafe-ai/sdk
example.ts
import { choice, noul, TypeSafeClient } from '@typesafe-ai/sdk';
const client = new TypeSafeClient(); // 默认读取 TYPESAFE_API_KEY;模型默认 jev-latest
const { answers } = await client.systemOne({
state: 'Hi, my Stripe integration keeps failing. Please refund my subscription.',
questions: {
department: choice('Which team should handle this', {
billing: 'Payment or subscription issues',
technical: 'Bugs or integration problems',
}),
asks_refund: noul('The customer explicitly requests a refund'),
},
});
console.log(answers.department.choice, answers.department.confidence);
console.log(answers.asks_refund.noul);
// answers.department.choice 的类型由 criteria 的键推断为 "billing" | "technical",
// 写错分支名会在编译期报错——这就是"类型安全"落到代码里的样子。

问题用 choice() / score() / noul() 创建;要固定模型版本时在请求里加 model。SDK 还内置答案类型推断、RetryPolicy 重试(默认重试 408、429 与 5xx,含 529)和结构化错误类(RateLimitErrorAuthenticationError 等)。仓库:typesafe-ai/typesafe-sdk-js(MIT,206★,2026-09-22 核验)。

不想引 SDK 时,直接 fetch 端点即可。完整可运行示例 triage.mjs 可以直接下载(零依赖,Node.js 18 及以上):

下载并模拟运行(不联网、不需要 Key)
curl -O https://typesafe-jev.com/examples/javascript/triage.mjs
TYPESAFE_USE_FIXTURE=1 node triage.mjs
真实调用(需要 Key)
TYPESAFE_API_KEY=你的Key node triage.mjs

示例做的事:一条请求同时问部门 Choice、沮丧度 Score、退款 Noul,然后按 confidence 阈值决定自动派单还是转人工。核心结构:

triage.mjs(节选)
const response = await fetch('https://api.typesafe.ai/v1/systemone', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.TYPESAFE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
// 401/422 不要重试;429/529 应指数退避
console.error(`HTTP ${response.status}: ${await response.text()}`);
process.exit(1);
}

不要TYPESAFE_API_KEY 打进浏览器包。需要网页交互时,由你自己的后端(Serverless Function、Worker)持 Key 代理调用,前端只跟你自己的 API 说话。参考场景:工具审批

API 参考 · Python 指南 · 工单分流实战