社区 Runtime

Laya Node.js / TypeScript + ONNX

通过 ONNX Runtime 在 Node.js / TypeScript 中运行 Laya,并保持 typed-decision 请求/响应形态。

Node.js 后端TypeScriptONNX Runtime无需 Python Runtime
快速开始
npm install @receptron/laya
Source
receptron/laya

第一次使用会下载 ONNX 权重,需要为模型与 batch 预留内存。如果想直接在浏览器里跑,onnx-community 发布了三个 checkpoint 的 fp32 / fp16 ONNX 转换版,可配合 Transformers.js 和 WebGPU 使用(onnx-community/laya-ONNX、laya-multilingual-ONNX、laya-typed-decisions-ONNX)。

Usage
import { Laya } from "@receptron/laya";

const laya = await Laya.load();
const result = await laya.systemOne(state, questions);

@receptron/laya 通过 ONNX Runtime 在 Node.js 和 TypeScript 中运行 Laya,运行时既不需要 PyTorch,也不需要 Python。请求和返回结构与 Python 参考实现、TypeSafe Jev 的 system_one API 一致,项目称输出与 Python 实现精确到小数点后四位相同。

环境要求

  • Node.js 20 或更高版本。
  • ONNX 权重(约 1.7 GB,fp32)首次使用时从 Hugging Face 下载,缓存在 ~/.cache/receptron-laya(可用 LAYA_CACHE 修改)。
  • 模型加载后约需 2 GB 内存,每批问题再额外占用几百 MB。

使用方式

import { Laya } from "@receptron/laya";

const laya = await Laya.load();

const result = await laya.systemOne(
  { subject: "Refund not received", body: "I cancelled two weeks ago and still have no refund..." },
  {
    department: {
      type: "choice",
      instructions: "Which team should handle this ticket?",
      criteria: { billing: "payments, refunds, invoices", support: "product help and bugs" },
    },
    churn_risk: { type: "noul", instructions: "Is the customer likely to cancel or dispute?" },
  },
);

result.answers.department.choice;  // "billing"
result.answers.churn_risk.noul;    // P(true)
await laya.close();

返回值的类型跟随问题类型,例如 result.answers.department 直接就是 ChoiceAnswer,不需要类型断言。

速度

同一次 systemOne 调用里的所有问题会合并成一次推理。README 报告模型预热后,在 Apple Silicon CPU 上一次三个问题的调用约 140 ms。

配置项

Laya.load() 支持:本地 modelDir、Hugging Face 的 repo 和 subfolder(例如多语言版本)、固定 revision 以保证结果可复现、cacheDir、私有仓库用的 token、下载进度回调,以及 ONNX Runtime 的 executionProviders 和 sessionOptions(如 intraOpNumThreads)。

也可以用仓库里的 export/export_onnx.py 从 Hugging Face checkpoint 自己导出模型包,脚本会打印与 PyTorch 的最大 logit 差异(约 1e-5)。

限制

  • 每个问题的选项必须放得进 head_max_len(192 token),否则 systemOne 会报错。单个 choice 题建议少于约 20 个选项。
  • state 会被截断到 max_len(英文 checkpoint 为 512 token)。
  • JSON 格式的 state 会按 Python 的 json.dumps(ensure_ascii=False) 方式序列化,非整数的数字在 JavaScript 和 Python 之间可能格式不同。

上游仓库里也有官方的 TypeScript 包 laya-ts(在 Laya 仓库中),说明称其结果与 Python 包一致。

来源:receptron/laya · MIT(模型权重为 Apache 2.0)。

最后对照项目 README 核实:2026 年 9 月 24 日。