yethee/tiktoken
PHP port of OpenAI tiktoken for fast tokenization. Get encoders by model or encoding, encode text to token IDs, with built-in vocabulary caching (configurable cache dir). Optional experimental FFI mode using tiktoken-rs for better performance on larger inputs.
tiktoken, making it ideal for Laravel applications leveraging GPT-3.5/4/5/5.x models, embeddings, or token-aware features (e.g., cost optimization, prompt validation, RAG chunking).EncoderProvider), and composer ecosystem. Can integrate with Laravel’s middleware, queues, or logging for token tracking.composer require + minimal boilerplate (e.g., EncoderProvider setup).sys_get_temp_dir()) reduces I/O overhead. Configurable via TIKTOKEN_CACHE_DIR or EncoderProvider::setVocabCache().text-embedding-3-*), and o1/o3 models. No GPT-2 or special tokens (e.g., <|endofprompt|>).tiktoken-rs for high throughput (requires LD_LIBRARY_PATH setup). Not recommended for production due to stability risks and build complexity.encodeInChunks() is unimplemented (TODO in v1.0.0).| Risk Area | Severity | Mitigation |
|---|---|---|
| Unsupported Models | Medium | Avoid GPT-2 or models requiring special tokens. Use OpenAI SDK as fallback. |
| Lib Mode Instability | High | Skip unless benchmarked for your workload. Prefer native encoder for stability. |
| Cache Race Conditions | Low | Fixed in v1.1.1. Monitor cache performance in production. |
| Performance Bottlenecks | Medium | Benchmark with composer bench. Use LibEncoder only for large batches. |
| BC Breaks | Low | API is stable since v1.0.0. Cache dir is now required (no null support). |
| Dependency Bloat | None | Zero external dependencies (pure PHP). |
Log or Sentry.EncoderProvider as a singleton for global access.ValidatePromptTokens).Log::info('Tokens used:', $tokenCount).guzzlehttp/ringphp or openai-php/client.| Step | Action | Complexity | Dependencies |
|---|---|---|---|
| 1. Install | composer require yethee/tiktoken |
Low | Composer |
| 2. Configure Cache | Set TIKTOKEN_CACHE_DIR or call EncoderProvider::setVocabCache() |
Low | Filesystem |
| 3. Basic Usage | Inject EncoderProvider into services and use getForModel('gpt-4') |
Low | Laravel DI |
| 4. Middleware | Add ValidatePromptTokens to API routes |
Medium | Laravel Middleware |
| 5. Logging | Log token counts with Log::info() or Sentry |
Low | Laravel Logging |
| 6. Queue Jobs | Offload tokenization for batch processing (e.g., document chunking) | Medium | Laravel Queues |
| 7. Lib Mode (Opt.) | Build Rust lib and configure TIKTOKEN_LIB_PATH |
High | Rust, FFI, CI/CD |
EncoderProvider.EncoderProvider.LibEncoder for high-throughput use cases (requires Rust expertise).How can I help you explore Laravel packages today?