Skip to main content
语言模型有 Token 限制。您不应超过此限制。当您将文本分割为块时,计算 Token 数量是一个好主意。有许多分词器。当您计算文本中的 Token 时,应使用与语言模型相同的分词器。

js-tiktoken

js-tiktokenOpenAI 创建的 BPE 分词器的 JavaScript 版本。
我们可以使用 tiktoken 来估算 TokenTextSplitter 使用的 Token。对于 OpenAI 模型,这可能更准确。
  1. 文本如何分割:按传入的字符。
  2. 块大小如何测量:按 tiktoken 分词器。
npm install @langchain/textsplitters
import { TokenTextSplitter } from "@langchain/textsplitters";
import { readFileSync } from "fs";

// Example: read a long document
const stateOfTheUnion = readFileSync("state_of_the_union.txt", "utf8");
要使用 TokenTextSplitter 进行分割,然后使用 tiktoken 合并块,请在初始化 TokenTextSplitter 时传入 encodingName(例如 cl100k_base)。请注意,此方法的分割结果可能大于 tiktoken 分词器测量的块大小。
import { TokenTextSplitter } from "@langchain/textsplitters";

// Example: use cl100k_base encoding
const splitter = new TokenTextSplitter({ encodingName: "cl100k_base", chunkSize: 10, chunkOverlap: 0 });

const texts = splitter.splitText(stateOfTheUnion);
console.log(texts[0]);
Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.

Last year COVID-19 kept us apart. This year we are finally together again.

Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans.

With a duty to one another to the American people to the Constitution.