How to work with OpenAI maximum context length is 2049 tokens?

news2024/9/26 5:24:12

题意:"如何处理OpenAI的最大上下文长度为2049个tokens的问题?"

问题背景:

I'd like to send the text from various PDF's to OpenAI's API. Specifically the Summarize for a 2nd grader or the TL;DR summarization API's.

"我想将来自各种PDF的文本发送到OpenAI的API,特别是用于‘给二年级学生的总结’或‘TL;DR总结’的API。"

I can extract the text from PDF's using PyMuPDF and prepare the OpenAI prompt.

"我可以使用 PyMuPDF 从 PDF 中提取文本,并准备 OpenAI 的提示。"

Question: How best to prepare the prompt when the token count is longer than the allowed 2049?

"问题:当token数量超过允许的2049时,如何最好地准备提示?"

  • Do I just truncate the text then send multiple requests?

"我是否只需截断文本然后发送多个请求?"

  • Or is there a way to sample the text to "compress" it to lose key points?

"还是有办法对文本进行采样,以‘压缩’它而不丢失关键点?"

问题解决:

I faced the same problem. Here is the strategy I used to send text that is much, much longer than OpenAIs GPT3 token limit.

"我遇到了同样的问题。以下是我用来发送远远超过OpenAI GPT-3 token限制的文本的策略。"

Depending on the model (Davinci, Curie, etc.) used, requests can use up to 4097 tokens shared between prompt and completion.

"根据使用的模型(如Davinci、Curie等),请求可以使用最多4097个tokens,这些tokens在提示和完成之间共享。"

  • Prompt being the input you send to OpenAI, i.e. your "command", e.g. "Summarize the following text" plus the text itself

"提示是你发送给OpenAI的输入,即你的‘命令’,例如‘总结以下文本’以及文本本身。"

  • Completion being the response, i.e. the entire summary of your text

"完成部分是指响应,即你的文本的完整摘要。"

If your prompt is 4000 tokens, your completion can be 97 tokens at most. For more information on OpenAI tokens and how to count them, see here.

"如果你的提示是4000个tokens,那么完成部分最多只能有97个tokens。"

To ensure that we don’t exceed the maximum length limit for prompt plus completion, we need to ensure that prompt (i.e. your text) and completion (i.e. the summary) put together always fits into the 4097 token boundary.

为了确保我们不会超过提示和完成的最大长度限制,我们需要确保提示(即你的文本)和完成(即总结)加在一起始终符合4097个标记的边界。

For that reason we split the entire text into multiple text chunks, summarize each chunk independently and finally merge all summarized chunks using a simple " ".join() function.

为此,我们将整个文本拆分成多个文本块,独立总结每个块,然后使用简单的 `" ".join()` 函数将所有总结后的块合并起来。

Maximum Number of Words - Token-to-Word Conversion

最大词数 - 标记到词的转换

OpenAI has a fixed limit on the number of tokens. However, a token is not the same as a word. Hence, we first need to calculate the maximum number of words we can send to OpenAI. The documentation says:

OpenAI 对标记的数量有固定限制。然而,标记与词并不相同。因此,我们首先需要计算可以发送给 OpenAI 的最大词数。文档中写道:

Given the token-to-word ratio, we can send approximately 2900 words to OpenAI's GPT3 assuming a 5 sentence summary per text chunk.

考虑到标记与词的比例,我们可以向 OpenAI 的 GPT-3 发送大约 2900 个词,假设每个文本块有 5 句话的总结。

  • Max tokens per request: 4000 tokens (leaving 97 tokens as a safety buffer) = 3000 words

每次请求的最大标记数:4000 个标记(留出 97 个标记作为安全缓冲)= 3000 个词

  • Max prompt tokens: “Summarize the following text in five sentences” has 7 words = 10 tokens

最大提示标记数:“Summarize the following text in five sentences” 包含 7 个词 = 10 个标记

  • Max tokens of returned summary (5 sentences): 20 words per sentence. 5 * 20 = 100 words = 133 tokens

返回总结的最大标记数(5 句话):每句话 20 个词。5 * 20 = 100 个词 = 133 个标记

  • Max tokens of text chunk: 4000 - 10 - 133 = 3857 tokens = 2900 words

文本块的最大标记数:4000 - 10 - 133 = 3857 个标记 = 2900 个词

Text Chunking        文本切块

We can choose from a plethora of strategies to split up the entire text into smaller chunks.

我们可以从多种策略中选择,将整个文本拆分成较小的块。

The simplest approach is creating a single list of all words by splitting the entire text on whitespaces, and then creating buckets of words with words evenly distributed across all buckets. The downside is that we are likely to split a sentence half-way through and lose the meaning of the sentence because GPT ends up summarizing the first half of the sentence independently from the second half — ignoring any relations between the two chunks.

最简单的方法是通过空白符将整个文本拆分成单词列表,然后创建多个单词桶,使单词在各个桶中均匀分布。缺点是,我们可能会在句子中间拆分,从而丧失句子的含义,因为 GPT 会独立地总结句子的前半部分和后半部分——忽略了这两个块之间的关系。

Other options include tokenizers such as SentencePiece and spaCy’s sentence splitter. Choosing the later generates the most stable results.

其他选项包括使用 SentencePiece 和 spaCy 的句子分割器等分词器。选择后者可以生成最稳定的结果。

Implementation of Text Chunking with spaCy

使用 spaCy 实现文本切块

The following example splits the text “My first birthday was great. My 2. was even better.” into a list of two sentences.

以下示例将文本“My first birthday was great. My 2. was even better.”拆分成两个句子的列表。

python -m spacy download en_core_web_sm
import spacy
from spacy.lang.en import English

nlp = spacy.load("en_core_web_sm")

text = "My first birthday was great. My 2. was even better."
    
for sentence in nlp(text).sents:
  print(sentence.text)

Output        输出

My first birthday was great.
My 2. was even better.

spaCy correctly detected the second sentence instead of splitting it after the “2.”.

spaCy 正确地识别了第二个句子,而没有在“2.”之后将其分割。

Now, let’s write a text_to_chunks helper function to generate chunks of sentences where each chunk holds at most 2700 words. 2900 words was the initially calculated word limit, but we want to ensure to have enough buffer for words that are longer than 1.33 tokens.

现在,让我们编写一个 `text_to_chunks` 辅助函数来生成句子块,其中每个块最多包含 2700 个单词。最初计算的单词限制是 2900 个,但我们希望为超过 1.33 个标记的长单词预留足够的缓冲空间。

def text_to_chunks(text):
  chunks = [[]]
  chunk_total_words = 0

  sentences = nlp(text)

  for sentence in sentences.sents:
    chunk_total_words += len(sentence.text.split(" "))

    if chunk_total_words > 2700:
      chunks.append([])
      chunk_total_words = len(sentence.text.split(" "))

    chunks[len(chunks)-1].append(sentence.text)
  
  return chunks

An alternative approach to determine the number of tokens of a text was recently introduced by OpenAI. The approach uses tiktoken and is tailored towards OpenAI's models.

最近,OpenAI 引入了一种替代方法来确定文本的标记数量。该方法使用 `tiktoken`,并针对 OpenAI 的模型进行了优化。

import tiktoken

encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
number_of_tokens = len(encoding.encode("tiktoken is great!"))
print(number_of_tokens)

Next, we wrap the text summarization logic into a summarize_text function.

接下来,我们将文本摘要逻辑封装到一个 `summarize_text` 函数中。

def summarize_text(text):
  prompt = f"Summarize the following text in 5 sentences:\n{text}"

  response = openai.Completion.create(
      engine="text-davinci-003", 
      prompt=prompt,
      temperature=0.3, 
      max_tokens=150, # = 112 words
      top_p=1, 
      frequency_penalty=0,
      presence_penalty=1
  )

  return response["choices"][0]["text"]

Our final piece of code looks like this:

我们的最终代码如下所示:

chunks = text_to_chunks(one_large_text)

chunk_summaries = []

for chunk in chunks:
  chunk_summary = summarize_text(" ".join(chunk))
  chunk_summaries.append(chunk_summary)

summary = " ".join(chunk_summaries)

References

    • How to count tokens with tiktoken, OpenAI Cookbook

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2088894.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

重谈地址空间

虚拟地址是如何转化的物理地址的? 我们以32位计算机为例子 32 为计算机的虚拟地址就是32位。 32 位的虚拟地址 分为三个部分 为 10 10 12; 这是由页表内部的结构决定的。 页表分为两级 虚拟地址的前十位为一级页表对应的位置, 次10位表示…

鸿蒙(API 12 Beta3版)【识别本地图片】

基本概念 图片识码能力支持对图库中的码图进行扫描识别,并获取信息。 场景介绍 图片识码能力支持对图库中的条形码、二维码、MULTIFUNCTIONAL CODE进行识别,并获得码类型、码值、码位置信息。该能力可用于一图单码和一图多码的识别,比如条…

【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二)

【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二) Demo效果展示: 方案思路: 1.修改调用相机的方式,使用cameraKit进行相机的调用,拍照…

怎么扫描试卷去除笔迹?建议试试这样做

怎么扫描试卷去除笔迹?在现代教育和办公环境中,电子版试卷的管理和使用变得越来越普遍。然而,手写答案和批注常常使得电子版试卷难以恢复到原始的空白状态。为了满足这一需求,市场上涌现出许多能够扫描试卷并去除笔迹的技术和工具…

巧用 HTML 列表:<ul>、<ol>、<dl>的实用指南

目录 无序列表 容器级标签 有序列表 定义列表 一个dt配很多dd 每一个dl里面只有一个dt和dd 一个dl配多个dt 多级列表 无序列表 <ul>标签用于定义无序列表。无序列表的特点是各个列表项之间没有特定的顺序&#xff0c;通常以小圆点作为先导符号。所有主流浏览器…

模拟+思维(时间规划烧饼)

前言&#xff1a;这个题目就是我们小时候学的的活动规划烧饼&#xff0c;我们要先算出我们最大耗时是多少&#xff0c;然后再对我们的活动进行规划 题目地址 我们这个题目还要求算出k&#xff08;执行次数&#xff09;我的做法是写两遍代码&#xff0c;其实也可以存起来&#x…

“重启就能解决一切问题”,iPhone重启方法大揭秘

随着iPhone不断更新换代&#xff0c;其设计与操作方式也在不断进化。从最初的实体Home键到如今的全面屏设计&#xff0c;iPhone的操作逻辑也随之发生了改变。 对于那些习惯了传统安卓手机操作的用户来说&#xff0c;iPhone的重启方式可能会显得有些不同寻常。下面我们就来一起…

学习之SQL语句之DCL(数据控制语言)

DCL英文全称是Data Control Language(数据控制语言)&#xff0c;用来管理数据库用户、控制数据库的访问 权限

滚柱导轨:数控机床高效运行的驱动力

机床制造者最关心的莫过于机床的精度&#xff0c;刚性和使用寿命&#xff0c;对导轨系统的关注甚少。但导轨为机床功能的实现奠定了可靠的基础&#xff0c;各种类型的机床工作部件&#xff0c;都是利用控制轴在指定的导轨上运动。机床设计者根据机床的类型和用途选用各种不同形…

前波士顿咨询Platinion董事总经理陈果加入望繁信科技

“很荣幸邀请果总加盟望繁信科技&#xff01;作为中国互联网可以查到的写作流程挖掘介绍文章第一人&#xff0c;他的先驱性工作为流程挖掘在中国的知识普及和应用创新做出了重要贡献&#xff01;更难能可贵的&#xff0c;是我们和果总在价值观层面高度契合&#xff01;我们非常…

Git学习尚硅谷(001 git介绍)

尚硅谷Git入门到精通全套教程&#xff08;涵盖GitHub\Gitee码云\GitLab&#xff09; 总时长 4:52:00 共45P 此文章包含第1p-第p7的内容 文章目录 git介绍课程介绍git概述 何为版本控制集中式版本控制工具分布式版本控制工具git简史工作机制代码托管中心 git的安装 git介绍 课…

游泳时用什么耳机听歌好?四大实力非凡的高销游泳耳机严选

随着人们健康意识的提升和生活方式的变化&#xff0c;游泳已成为广受欢迎的健身方式之一。在水中畅游的同时&#xff0c;聆听喜爱的音乐可以让整个过程更加愉悦。然而&#xff0c;并非所有的耳机都适合在水下使用&#xff0c;因此选择一款适合游泳的耳机变得尤为重要。 近年来&…

深度探索Unity与C#:编织游戏世界的奇幻篇章

在数字编织的梦幻之境中&#xff0c;Unity游戏引擎与C#编程语言如同双生子&#xff0c;共同编织着游戏世界的奇幻篇章。《Unity游戏开发实战&#xff1a;从零到C#高手》这本书&#xff0c;不仅仅是技术的堆砌&#xff0c;它更像是一位智慧导师&#xff0c;引领着我们深入探索这…

auto的使用场景

auto的两面性 合理使用auto 不仅可以减少代码量, 也会大大提高代码的可读性. 但是事情总有它的两面性 如果滥用auto, 则会让代码失去可读性 推荐写法 这里推荐两种情况下使用auto 一眼就能看出声明变量的初始化类型的时候 比如迭代器的循环, 用例如下 #include <iostre…

ctfhub-web-ssrf-POST请求

这次是发一个HTTP POST请求.对了.ssrf是用php的curl实现的.并且会跟踪302跳转.加油吧骚年 定义&#xff1a;Gopher是Internet上一个非常有名的信息查找系统&#xff0c;它将Internet上的文件组织成某种索引&#xff0c;很方便地将用户从Internet的一处带到另一处。在WWW出现之…

走心机阀芯加工

阀芯加工走心机&#xff0c;是制造业中一个非常关键且高效的技术组合&#xff0c;深知这种技术在精密加工领域的重要性&#xff0c;下面我将从几个方面为您详细介绍阀芯加工走心机的特点和应用。 一、阀芯加工走心机的定义与特点 阀芯加工走心机&#xff0c;是一种结合了数控车…

模板进阶(C++)

一.非类型模板参数 1.使用方法和概念 模板参数分为类型形参与非类型形参。 类型形参:出现在模板参数列表中&#xff0c;跟在class或者typename之类的参数类型名称。 非类型形参:就是用一个常量作为类(函数)模板的一个参数&#xff0c;在类(函数)模板中可将该参数当成常量来使…

CSS线性渐变拼接,一个完整的渐变容器(div),要拆分成多个渐变容器(div),并且保持渐变效果一致

1 需求 一个有渐变背景的div&#xff0c;需要替换成多个渐变背景div拼接&#xff0c;渐变效果需要保持一致&#xff08;不通过一个大的div渐变&#xff0c;其他子的div绝对定位其上并且背景透明来解决&#xff09; 2 分析 主要工作&#xff1a; 计算完整div背景线性渐变时的…

福建聚鼎:装饰画店铺怎么做盈利快

在艺术的殿堂里&#xff0c;装饰画店铺是一扇通往美与创意的门。要想让这扇门快速盈利&#xff0c;我们需要从多个维度出发&#xff0c;打造一个独特且吸引人的艺术空间。 我们要注重产品的独特性。每一幅装饰画都应该是独一无二的艺术品&#xff0c;它们不仅仅是墙面的装饰&am…

Linux——IO模型_多路转接(epoll)

目录 0.往期文章 1.epoll的三个接口 1.epoll_create 2.epoll_ctl 结构体 epoll_event 3.epoll_wait 2. epoll的工作原理&#xff0c;和接口对应 1.理解数据到达主机 2.epoll的工作原理 3.基于epoll的TCP服务器&#xff08;代码) 辅助库 基于TCP的Socket封装 服务器代…