前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >调用ChatGPT超过4096Token后自动截取保留指定长度的Token

调用ChatGPT超过4096Token后自动截取保留指定长度的Token

作者头像
SingYi
发布2023-08-23 08:26:53
2700
发布2023-08-23 08:26:53
举报
文章被收录于专栏:Lan小站Lan小站

需要用到官方计算token的包:tiktoken

pip install tiktoken

截取并返回

代码语言:javascript
复制
def num_tokens_from_string(string: str) -> int:
    # www.lanol.cn
    encoding = tiktoken.get_encoding('cl100k_base')
    num_tokens = len(encoding.encode(string))
    return num_tokens


def truncate_messages(messages, max_chars):
    # By Lan www.lanol.cn
    total_chars = sum(num_tokens_from_string(message['content']) for message in messages)
    while total_chars > max_chars:
        removed_message = messages.pop(0)
        total_chars -= num_tokens_from_string(removed_message['content'])
    return messages
www.lanol.cn
www.lanol.cn
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023年04月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档