以编程方式使用文档

语言模型有 token 限制。你不应该超过 token 限制。当你 分割你的文本 成块时,因此最好计算 token 的数量。有很多分词器。当你在文本中计算 token 时,你应该使用与语言模型中使用的相同分词器。

js-tiktoken

创建。我们可以使用 tiktoken 使用 TokenTextSplitter 估算使用的 token。它可能对 OpenAI 模型更准确。

  1. 文本如何分割:通过传入的字符。
  2. 块大小如何测量:通过 tiktoken tokenizer.
npm install @langchain/textsplitters
pnpm install @langchain/textsplitters
yarn add @langchain/textsplitters
bun add @langchain/textsplitters
// Example: read a long document
const stateOfTheUnion = readFileSync("state_of_the_union.txt", "utf8");

要使用 TokenTextSplitter 分割文本,然后使用 tiktoken合并块,在初始化 TokenTextSplitter 时传入 encodingName (e.g. cl100k_基础)作为参数。请注意,从这个方法得到的分割可能比通过 tiktoken tokenizer.

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