purewater2011/tiktoken-php7
Composer 安装命令:
composer require purewater2011/tiktoken-php7
包简介
PHP 7.4+ compatible version of tiktoken - OpenAI's tiktoken tokenizer ported to PHP
README 文档
README
A PHP 7.4+ compatible port of OpenAI's tiktoken tokenizer.
This package is a backward-compatible fork that brings tiktoken functionality to PHP 7.4+, making it accessible to projects that haven't yet migrated to PHP 8.1+.
Features
- ✅ PHP 7.4+ compatibility (downgraded from PHP 8.1+)
- ✅ Support for all OpenAI models (GPT-3.5, GPT-4, GPT-4o, etc.)
- ✅ Multiple encoding formats (r50k_base, p50k_base, cl100k_base, o200k_base)
- ✅ Efficient caching system
- ✅ Optional FFI-based native library support for better performance
- ✅ Full compatibility with original tiktoken API
Installation
composer require purewater2011/tiktoken-php7
Requirements
- PHP 7.4 or higher
ext-ffi(optional, for LibEncoder performance boost)
Quick Start
<?php use Purewater2011\TiktokenPhp7\EncoderProvider; $provider = new EncoderProvider(); // Get encoder for a specific model $encoder = $provider->getForModel('gpt-3.5-turbo'); $tokens = $encoder->encode('Hello, world!'); print_r($tokens); // Output: [9906, 11, 1917, 0] // Decode tokens back to text $text = $encoder->decode($tokens); echo $text; // Output: "Hello, world!" // Get encoder by encoding name $encoder = $provider->get('cl100k_base'); $tokens = $encoder->encode('Hello, world!'); print_r($tokens); // Output: [9906, 11, 1917, 0]
Supported Models
This package supports all current OpenAI models:
| Model Family | Encoding |
|---|---|
| GPT-4o, GPT-4o mini | o200k_base |
| GPT-4, GPT-3.5-turbo | cl100k_base |
| GPT-3 (Davinci, Curie, etc.) | p50k_base |
| GPT-3 (Ada, Babbage) | r50k_base |
Advanced Usage
Encoding in Chunks
For processing large texts, you can encode in chunks:
$encoder = $provider->getForModel('gpt-4'); $chunks = $encoder->encodeInChunks($largeText, 1000); // Max 1000 tokens per chunk foreach ($chunks as $chunk) { echo "Chunk has " . count($chunk) . " tokens\n"; }
Custom Cache Directory
By default, vocabulary files are cached in the system temp directory. You can customize this:
// Via environment variable putenv('TIKTOKEN_CACHE_DIR=/path/to/cache'); // Or via method call $provider = new EncoderProvider(); $provider->setVocabCache('/path/to/cache');
Using Custom Vocabulary Loader
use Purewater2011\TiktokenPhp7\Vocab\Loader\DefaultVocabLoader; $provider = new EncoderProvider(); $provider->setVocabLoader(new DefaultVocabLoader('/custom/cache/path'));
Performance Optimization with LibEncoder (Experimental)
For better performance with large texts, you can use the FFI-based LibEncoder:
use Purewater2011\TiktokenPhp7\Encoder\LibEncoder; use Purewater2011\TiktokenPhp7\EncoderProvider; // Initialize the library path LibEncoder::init('/path/to/libtiktoken_php.so'); // Use LibEncoder for better performance $provider = new EncoderProvider(true); $encoder = $provider->getForModel('gpt-4');
Building the Native Library
If you want to use LibEncoder, you need to build the Rust library:
Requirements
- Rust >= 1.85
Build Steps
git clone https://github.com/purewater2011/tiktoken-php7.git
cd tiktoken-php7
cargo build --release
Copy the appropriate binary:
libtiktoken_php.so(Linux)libtiktoken_php.dylib(macOS)tiktoken_php.dll(Windows)
Token Counting Examples
$provider = new EncoderProvider(); $encoder = $provider->getForModel('gpt-3.5-turbo'); // Count tokens in a message $message = "How many tokens is this?"; $tokenCount = count($encoder->encode($message)); echo "Token count: $tokenCount\n"; // Useful for staying within API limits $maxTokens = 4096; $prompt = "Your long prompt here..."; $promptTokens = count($encoder->encode($prompt)); if ($promptTokens > $maxTokens) { echo "Prompt too long! Tokens: $promptTokens, Max: $maxTokens\n"; }
Differences from Original
This package maintains full API compatibility with the original yethee/tiktoken but with these key changes:
- PHP 7.4+ compatibility instead of PHP 8.1+
- Updated namespace:
Purewater2011\TiktokenPhp7instead ofYethee\Tiktoken - Compatible dependency versions for PHP 7.4
- All modern PHP 8.1+ syntax converted to PHP 7.4 compatible code
Migration Guide
If you're migrating from yethee/tiktoken:
-
Update your composer requirement:
composer remove yethee/tiktoken composer require purewater2011/tiktoken-php7
-
Update namespace imports:
// Old use Yethee\Tiktoken\EncoderProvider; // New use Purewater2011\TiktokenPhp7\EncoderProvider;
-
All other usage remains identical!
Limitations
- GPT-2 encoding is not supported
- Special tokens (like
<|endofprompt|>) are not supported - LibEncoder::encodeInChunks() method is not yet implemented
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
Credits
- Original tiktoken implementation by OpenAI
- PHP port by yethee
- PHP 7.4 compatibility by purewater2011
purewater2011/tiktoken-php7 适用场景与选型建议
purewater2011/tiktoken-php7 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「tokenizer」 「encode」 「decode」 「ai」 「php74」 「bpe」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 purewater2011/tiktoken-php7 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 purewater2011/tiktoken-php7 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 purewater2011/tiktoken-php7 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Library emulating the PHP internal reflection using just the tokenized source code.
AMWSCAN (Antimalware Scanner) is a php antimalware/antivirus scanner console script written in php for scan your project. This can work on php projects and a lot of others platform.
Encode integer IDs using a preset or customized symbol set
A program for performing lexical analysis, written in PHP
A simple library for make Lexer and Parsers to build a language
Runn Me! Serialization Library
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 29
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-10