@braintrust/lingua

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

TypeScript bindings for Lingua - Universal message format for LLM APIs

原始使用文档
文档目录16 节
  1. Installation
  2. Usage
  3. Node.js
  4. Browser
  5. Next.js
  6. Package architecture
  7. Development
  8. Building
  9. Generating Types
  10. Running Tests
  11. Project Structure
  12. API Reference
  13. Conversion Functions
  14. Types
  15. Type Compatibility
  16. License

@braintrust/lingua

TypeScript bindings for Lingua - a universal message format for LLMs.

Installation

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

This automatically installs @braintrust/lingua-wasm as a dependency (you don't need to install it separately).

If you only need TypeScript types and do not need conversion or validation functions, install the types-only package instead:

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

Usage

The package provides separate entry points for Node.js and browser environments:

  • @braintrust/lingua or @braintrust/lingua/node - Node.js with native WASM (auto-initialized)
  • @braintrust/lingua/browser - Browser with web-targeted WASM (requires explicit initialization)

Node.js

In Node.js, the WASM module is automatically loaded - just import and use:

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]);

Browser

The browser build requires explicit initialization before use:

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);

Initialization options:

// 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);

Important: You must provide a WASM source to init(). The function will throw an error if called without an argument.

Next.js

For Next.js applications, you need to:

  1. Copy the WASM file to your public directory during build
  2. Exclude the WASM package from webpack processing
  3. Initialize on the client side

Step 1: Configure 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;

Step 2: Create a client-side wrapper

// 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";

Step 3: Use in your components

"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);
}

Package architecture

The TypeScript packages are split by runtime needs:

@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 - Pure TypeScript that imports from @braintrust/lingua-wasm
  • @braintrust/lingua-wasm - Raw wasm-pack output, separate package for clean bundling
  • @braintrust/lingua-types - Bundled TypeScript declarations for consumers that only need types

This separation ensures webpack/bundlers can properly handle the WASM files without complex configuration.

Development

This package is part of the Lingua monorepo. The TypeScript types are automatically generated from the Rust source code using ts-rs.

Building

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

Generating Types

To regenerate the TypeScript types from Rust:

pnpm generate

Running Tests

pnpm test

Project Structure

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 Reference

Conversion Functions

// 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

Types

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

Type Compatibility

The generated types are designed to be compatible with popular LLM SDKs:

  • OpenAI SDK (openai)
  • Anthropic SDK (@anthropic-ai/sdk)

License

MIT

版本与发布记录

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

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

关于 @braintrust/lingua 的常见问题

@braintrust/lingua 是什么?

TypeScript bindings for Lingua - Universal message format for LLM APIs

如何安装 @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 和提交记录判断。