惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Latest news
Latest news
B
Blog RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
博客园 - Franky
博客园_首页
爱范儿
爱范儿
博客园 - 聂微东
月光博客
月光博客
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
IT之家
IT之家
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
Scott Helme
Scott Helme
The Hacker News
The Hacker News
Jina AI
Jina AI
V
Visual Studio Blog
小众软件
小众软件
WordPress大学
WordPress大学
N
News and Events Feed by Topic
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
美团技术团队
D
Darknet – Hacking Tools, Hacker News & Cyber Security
宝玉的分享
宝玉的分享
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Hacker News: Ask HN
Hacker News: Ask HN
雷峰网
雷峰网
Martin Fowler
Martin Fowler
C
Cybersecurity and Infrastructure Security Agency CISA
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
Recorded Future
Recorded Future
N
News and Events Feed by Topic

Lan小站-嗯,不错! - Python

滑块验证图片匹配 - Lan小站-嗯,不错! 从 pip 到 uv:一场 Python 包管理的「换引擎」革命 通过终端管理宝塔Python项目管理器里面的Python项目 - Lan小站-嗯,不错! requests优雅的重试 - Lan小站-嗯,不错! 某牛某客专栏文章爬虫 - Lan小站-嗯,不错! 解决Mac下ssl.SSLCertVerificationError:[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate(_ssl.c:1056) Debian11安装部署stable-diffusion-webui记录 - Lan小站-嗯,不错! django怎么在迁移数据库的时候,自动生成数据 - Lan小站-嗯,不错! python datetime 东八区时间 - Lan小站-嗯,不错!
调用ChatGPT超过4096Token后自动截取保留指定长度的Token - Lan小站-嗯,不错!
Lan · 2023-04-19 · via Lan小站-嗯,不错! - Python

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

pip install tiktoken

截取并返回


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