跳到主要内容
语言模型有 token 限制。你不应该超过 token 限制。因此,当你将文本拆分成块时,计算 token 数量是个好主意。有许多分词器。当你计算文本中的 token 时,你应该使用与语言模型中使用的相同分词器。

js-tiktoken

js-tiktoken 是由 OpenAI 创建的 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.

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.