@braintrust/lingua

中文文档
0.1.0发布于 2026/05/01MITTypeScriptES Module近 30 天下载 5074

LLM API 的通用信件格式

中文使用文档
文档目录16 节
  1. 安装
  2. 使用量
  3. 节点.js
  4. 浏览器
  5. 下一个.js
  6. 软件包架构
  7. 发展
  8. 大楼
  9. 生成类型
  10. 运行测试
  11. 项目结构
  12. API 参考
  13. 转换函数
  14. 类型
  15. 类型兼容性
  16. 许可证

@ raintrust/ 语言

TypeScript 绑定 Lingua - LLMs 的通用消息格式.

安装

pnpm add @braintrust/lingua
# or
npm install @braintrust/lingua
# or
yarn add @braintrust/lingua

此自动安装 @braintrust/lingua-wasm 作为依赖(你不需要单独安装).

如果您只需要类型脚本而不需要转换或验证功能,则安装只类型包:

pnpm add -D @braintrust/lingua-types
import type { Message, UniversalRequest } from "@braintrust/lingua-types";

使用量

该软件包为Node.js和浏览器环境提供了单独的切入点:

  • @braintrust/lingua 或者说 @braintrust/lingua/node - 带本地WASM的节点(自动初始化)
  • @braintrust/lingua/browser - 有网络目标WASM的浏览器(需要明确初始化)

节点.js

在Node.js中, WASM 模块自动加载 - 只是导入和使用:

import {
  type Message,
  linguaToChatCompletionsMessages,
  chatCompletionsMessagesToLingua,
} from "@braintrust/lingua";

// Create messages in Lingua format
const messages: Message[] = [
  { role: "user", content: "Hello, how are you?" },
];

// Convert to OpenAI format
const openaiMessages = linguaToChatCompletionsMessages(messages);

// Convert OpenAI response back to Lingua
const linguaMessages = chatCompletionsMessagesToLingua([response.choices[0].message]);

浏览器

浏览器构建需要在使用前明确初始化:

import init, {
  linguaToChatCompletionsMessages,
  type Message,
} from "@braintrust/lingua/browser";

// Initialize with WASM URL (must be called before using any functions)
await init("/wasm/lingua.wasm");

// Now you can use Lingua functions
const messages: Message[] = [{ role: "user", content: "Hello!" }];
const openaiMessages = linguaToChatCompletionsMessages(messages);

初始化选项 :

// Option 1: URL string (fetches the WASM file)
await init("/wasm/lingua.wasm");

// Option 2: ArrayBuffer/Uint8Array (useful for testing or custom loading)
const wasmBuffer = await fetch("/wasm/lingua.wasm").then((r) => r.arrayBuffer());
await init(wasmBuffer);

重要时间轴: 必须 提供一个 WASM 源 init()。如果调用时没有参数,函数会出错.

下一个.js

对于 Next.js 应用程序,您需要:

  1. 将 WASM 文件复制到您的公共目录 构建时
  2. 将 WASM 软件包排除在网页包处理之外
  3. 在客户端初始化

步骤1:配置 next.config.mjs

import CopyWebpackPlugin from "copy-webpack-plugin";

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config, { isServer }) => {
    // Copy WASM file to public directory
    config.plugins.push(
      new CopyWebpackPlugin({
        patterns: [
          {
            from: "node_modules/@braintrust/lingua-wasm/web/lingua_bg.wasm",
            to: "../public/wasm/lingua.wasm",
          },
        ],
      })
    );

    // Exclude lingua-wasm from webpack's WASM processing
    config.module.rules.push({
      test: /\.wasm$/,
      exclude: [/[\\/]lingua-wasm[\\/]/],
      type: "webassembly/async",
    });

    return config;
  },
  // Mark the WASM package as external for server-side
  serverExternalPackages: ["@braintrust/lingua-wasm"],
};

export default nextConfig;

步骤2: 创建客户端包装

// lib/lingua.tsx
"use client";

import * as linguaModule from "@braintrust/lingua/browser";
import { useEffect } from "react";

const WASM_URL = "/wasm/lingua.wasm";

let ready: Promise<void> | null = null;

export async function initLingua(): Promise<void> {
  if (!ready) {
    ready = linguaModule.init(WASM_URL).catch((error) => {
      console.error("[Lingua] Initialization failed:", error);
      ready = null;
      throw error;
    });
  }
  return ready;
}

// Optional: React provider to initialize on app load
export function LinguaProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    initLingua();
  }, []);

  return <>{children}</>;
}

// Re-export everything from the browser module
export * from "@braintrust/lingua/browser";

第3步:在组件中使用

"use client";

import { initLingua, linguaToChatCompletionsMessages } from "@/lib/lingua";

async function convertMessages() {
  await initLingua(); // Ensures WASM is loaded

  const messages = [{ role: "user" as const, content: "Hello!" }];
  return linguaToChatCompletionsMessages(messages);
}

软件包架构

TypeScript 包由运行时间需求分割 :

@braintrust/lingua          # TypeScript wrapper (this package)
  └── @braintrust/lingua-wasm  # Raw WASM bindings (auto-installed dependency)
        ├── nodejs/            # Node.js WASM build
        └── web/               # Browser WASM build
@braintrust/lingua-types    # Type-only package with no WASM dependency
  • @braintrust/lingua - 从下列来源进口的纯类型脚本: @braintrust/lingua-wasm
  • @braintrust/lingua-wasm - 原始内容 wasm-pack 输出, 用于清洁捆绑的单独软件包
  • @braintrust/lingua-types - 仅供消费者使用的包式类型脚本申报

这种分离确保了webpack/bundlers可以正确处理WASM文件而无需复杂的配置.

发展

这个包裹是Lingua monorepo的一部分. TypeScript类型是使用ts-rs从 Rust 源代码自动生成的.

大楼

# Build TypeScript types, WASM, and wrapper packages from the repo root
make typescript

生成类型

从 Rust 重新生成类型脚本 :

pnpm generate

运行测试

pnpm test

项目结构

bindings/
├── lingua-wasm/           # @braintrust/lingua-wasm package
│   ├── nodejs/            # wasm-pack --target nodejs output
│   ├── web/               # wasm-pack --target web output
│   └── package.json
├── typescript-types/      # @braintrust/lingua-types package
│   ├── src/
│   └── dist/
└── typescript/            # @braintrust/lingua package (this directory)
    ├── src/
    │   ├── generated/         # Auto-generated types from Rust
    │   ├── index.ts           # Node.js entry point
    │   ├── index.browser.ts   # Browser entry point
    │   └── wasm-runtime.ts    # WASM initialization logic
    ├── dist/
    │   ├── index.mjs          # Compiled Node.js module
    │   ├── index.browser.mjs  # Compiled browser module
    │   └── *.d.mts            # Type definitions
    ├── tests/
    └── package.json

API 参考

转换函数

// OpenAI Chat Completions ↔ Lingua
linguaToChatCompletionsMessages(messages: Message[]): ChatCompletionMessageParam[]
chatCompletionsMessagesToLingua(messages: ChatCompletionMessage[]): Message[]

// Anthropic ↔ Lingua
linguaToAnthropicMessages(messages: Message[]): MessageParam[]
anthropicMessagesToLingua(messages: AnthropicMessage[]): Message[]

// Validation
validateChatCompletionsRequest(request: unknown): ValidationResult
validateChatCompletionsResponse(response: unknown): ValidationResult
validateAnthropicRequest(request: unknown): ValidationResult
validateAnthropicResponse(response: unknown): ValidationResult

类型

interface Message {
  role: "user" | "assistant" | "system" | "tool";
  content: string | ContentPart[];
  id?: string | null;
}

类型兼容性

生成的类型被设计为与流行的LLM SDK相兼容:

  • OpenAI SDK (英语:openai(中文(简体) )
  • 人类SDK(@anthropic-ai/sdk(中文(简体) )

许可证

麻省理工学院

版本与发布记录

@braintrust/lingua 共发布 1 个版本,首次发布于 2026/05/01;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.1.0latest2026/05/016 个月前

关于 @braintrust/lingua 的常见问题

@braintrust/lingua 是什么?

LLM API 的通用信件格式

如何安装 @braintrust/lingua?

在项目目录运行 npm install @braintrust/lingua,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@anthropic-ai/sdk(^0.63.0)、openai(^5.22.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@braintrust/lingua 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@braintrust/lingua 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@braintrust/lingua 可以商用吗?

@braintrust/lingua 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@braintrust/lingua 的下载量有多少?

根据 npm 官方下载统计,@braintrust/lingua 在 2026/10/09 – 2026/11/07 这 30 天内被下载 5,074 次,日均约 169 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@braintrust/lingua 还在维护吗?

最新版本 0.1.0 发布于 2026/05/01(6 个月前);至今共发布 1 个版本,其中过去 12 个月发布了 1 个;首次发布于 2026/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。