//gpt 分词计数 namespace string.gpt; tokens = function(str, mode = "o200k"){ if(!#str) return 0; var cjk, asciiRun, others = 0,0,0; for ch in ..string.eachChar(str){ var code = ..string.charCodeAt(ch); /* ASCII a-z A-Z 0-9 连续片段 */ if(code <= 0x7F){ if( (code>=0x30 && code<=0x39) || (code>=0x41 && code<=0x5A) || (code>=0x61 && code<=0x7A) ){ asciiRun++; continue; } /* 片段结算 */ if(asciiRun>0){ others += asciiRun; asciiRun = 0; } /* 空格忽略,标点算 1 */ if(code!=0x20) others += 1; continue; } /* CJK */ if(code>=0x4E00 && code<=0x9FFF){ if(asciiRun>0){ others += asciiRun; asciiRun = 0; } cjk++; continue; } /* 其它 Emoji/全角… */ if(asciiRun>0){ others += asciiRun; asciiRun = 0; } others += 1; } if(asciiRun>0) others += asciiRun; var estimate; if(mode=="o200k"){ estimate = ..math.ceil(others/4.3) + cjk; } var base, coeff; if(mode=="o200k"){ base = 1.07 + 0.55 / (1 + ..math.log(estimate/320)/16); var scale = 0.72 + 0.05 * (1 - ..math.exp(-estimate / 28000)); coeff = base * scale; } return ..math.round(estimate * coeff); } //https://platform.openai.com/tokenizer /*****intellisense() string.gpt = 用于快速估算 OpenAI GPT4o/GPT5 的 token 计数。\n其他大模型建议改用 mmseg.llmTokens 函数估算。 string.gpt.tokens(__/*字符串*/) = 快速估算 token 数。\n参数 @1 指定要计算的字符串,参数 @2 为保留参数请不要指定任何值。\n返回值可调用 math.format.size(tokens," tokens") 函数格式化为类似“21K tokens”的文本。 end intellisense*****/