PHPackages                             token27/nexus-ai-pricing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. token27/nexus-ai-pricing

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

token27/nexus-ai-pricing
========================

Financial cost calculation for LLM API usage. Supports token-accurate pricing for OpenAI, Anthropic (with Prompt Caching discounts), Google Gemini, DeepSeek, Groq, Mistral, and more.

v1.1.0(2mo ago)0492MITPHP ^8.3

Since May 21Compare

[ Source](https://github.com/token27/nexus-ai-pricing)[ Packagist](https://packagist.org/packages/token27/nexus-ai-pricing)[ Docs](https://github.com/token27/nexus-ai-pricing)[ RSS](/packages/token27-nexus-ai-pricing/feed)WikiDiscussions Synced 3w ago

READMEChangelog (2)Dependencies (4)Versions (3)Used By (2)

nexus-ai-pricing
================

[](#nexus-ai-pricing)

[![CI](https://github.com/token27/nexus-ai-pricing/actions/workflows/ci.yml/badge.svg)](https://github.com/token27/nexus-ai-pricing/actions)[![PHPStan Level 8](https://camo.githubusercontent.com/412205ac46adf8d1c9329cfcacca7da2697c664b7f1ffd18076a4a17c1e9de6d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230382d316636666562)](https://phpstan.org/)[![Latest Version](https://camo.githubusercontent.com/c2213a007b54fbe80a26038731734f6183528786dd61d154bf17c43ae4d4ed8f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f6b656e32372f6e657875732d61692d70726963696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/token27/nexus-ai-pricing)[![PHP 8.3+](https://camo.githubusercontent.com/38027453aeb7eb818641c9de8f82b7624c3558d92634f1946edc715c3ddf8956/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e332532422d3737374242343f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://php.net)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE)[![Tests](https://camo.githubusercontent.com/c318016c0fd259debf6db852016128fcbe17a85094056bd0835c2b1ef730302d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54657374732d373225323070617373696e672d627269676874677265656e)](docs/testing.md)

An **extensively engineered, framework-agnostic** PHP 8.3+ financial calculation library precisely mapped for LLM API computations. Support inherently covers mathematically accurate pricing for OpenAI, Anthropic, Google Gemini, DeepSeek, Groq, Mistral, and Perplexity — resolving everything from Prompt Caching variants to multimodal image tiles locally.

Why nexus-ai-pricing?
---------------------

[](#why-nexus-ai-pricing)

Calculating AI costs is chaotic. OpenAI utilizes a *subset caching* methodology where read tokens are subtracted from prompt tokens. Anthropic relies on *additive cache writes* with massive entry surcharges. Gemini alters limits based on *context tier tiers* and Perplexity adds *per-request bounds*.

**nexus-ai-pricing** solves this permanently by:

- **Mathematical Accuracy:** Handling all floating-point conversions safely without exception flaws.
- **Provider-agnostic core:** Evaluate cache, images, and text outputs using homogeneous DTOs (`PricingResult`).
- **Zero-Latency Estimations:** Utilizing [`token27/nexus-ai-tokenizer`](../nexus-ai-tokenizer) heavily to count everything strictly offline before issuing network requests.
- **Graceful Degradation:** Safely tags unknown models without triggering fatal system crashes during recursive loops.

Features
--------

[](#features)

- **Universal Support**: Standard metrics evaluated and natively bundled for ChatGPT, Claude, Gemini, DeepSeek Flash, and more.
- **Advanced Caching Mathematics**: Separating explicitly standard text costs from cached outputs seamlessly.
- **Vision Dimension Math**: Evaluates visual inputs correctly processing parameter rules dynamically (Tiles vs Dimensions).
- **Chained Price Tables**: Override built-in arrays securely via `JsonFilePriceTable` structures explicitly resolving priority overrides.
- **Glob Pattern Matcher**: Registers dynamic limits using wildcard variables (e.g. `gemini-2.1-*`) safely.
- **Type Safety**: PHPStan Level 8, completely production-grade testing limits.

Installation
------------

[](#installation)

```
composer require token27/nexus-ai-pricing
```

**Requires:** PHP 8.3+ · [`token27/nexus-ai-tokenizer`](https://packagist.org/packages/token27/nexus-ai-tokenizer) `^1.0`

Quick Start
-----------

[](#quick-start)

### 1. Post-Request Billing calculation (Using API returned values)

[](#1-post-request-billing-calculation-using-api-returned-values)

```
use Token27\NexusAI\Pricing\Engine\PricingEngine;

$result = PricingEngine::for('claude-sonnet-4-6')->calculate(
    inputTokens: 250,
    outputTokens: 400,
    cacheWriteTokens: 800,  // Anthropic 5-minute surcharge
    cacheReadTokens: 5000   // 90% discounted block
);

echo $result->totalCostUsd();     // Output standard metrics seamlessly
echo $result->cacheSavingsUsd();  // Output exactly what was saved against baselines
```

### 2. Pre-Request Proactive Estimations

[](#2-pre-request-proactive-estimations)

```
// Processes offline immediately avoiding Network HTTP limits
$estimated = PricingEngine::for('gpt-4o-mini')
    ->estimate('Generate a dense historical assessment regarding the Roman Empire.');

echo $estimated->format();
```

### 3. Multimodal Image Evaluation

[](#3-multimodal-image-evaluation)

```
use Token27\NexusAI\Pricing\ValueObject\ImageAttachment;

// Handles internal tile mapping explicitly
$visionPrice = PricingEngine::for('gpt-4o')->estimateWithImages(
    text: 'Analyze the architectural defect visible here',
    images: [
        ImageAttachment::highDetail(1920, 1080)
    ]
);

echo $visionPrice->imageCostUsd();
```

### 4. Custom Image Estimators

[](#4-custom-image-estimators)

All three pricing axes are independently injectable. For proprietary or custom vision models, pass your own `ImageTokenEstimatorInterface` implementations:

```
use Token27\NexusAI\Pricing\Engine\PricingEngine;
use Token27\NexusAI\Pricing\PriceTable\ArrayPriceTable;
use Token27\NexusAI\Pricing\ValueObject\ModelPrice;
use Token27\Tokenizer\Contract\ImageTokenEstimatorInterface;
use Token27\Tokenizer\Contract\TokenCountInterface;
use Token27\Tokenizer\Registry\TokenizerRegistry;
use Token27\Tokenizer\ValueObject\TokenCount;
use Token27\Tokenizer\Vision\AnthropicImageEstimator;
use Token27\Tokenizer\Vision\GeminiImageEstimator;
use Token27\Tokenizer\Vision\OpenAIImageEstimator;

// Proprietary model: flat 500 tokens per image regardless of size/detail
$myEstimator = new class implements ImageTokenEstimatorInterface {
    public function estimateImageTokens(int $widthPx, int $heightPx, string $detail, string $model): TokenCountInterface
    {
        return new TokenCount(count: 500, model: $model, strategy: 'flat_500', approximate: false);
    }
    public function supports(string $model): bool
    {
        return str_starts_with($model, 'my-vision-');
    }
};

$engine = new PricingEngine(
    tokenizer:       TokenizerRegistry::createDefault(),
    priceTable:      new ArrayPriceTable([
        new ModelPrice('my-vision-model', inputPerMillion: 1.00, outputPerMillion: 4.00, imageInputPerMillion: 2.00),
    ]),
    imageEstimators: [
        $myEstimator,                  // my-vision-* → 500 tokens flat (checked first)
        new OpenAIImageEstimator(),    // gpt-4o, o1, o3, …  (built-in)
        new AnthropicImageEstimator(), // claude-*           (built-in)
        new GeminiImageEstimator(),    // gemini-*           (built-in)
    ],
);

$result = $engine->make('my-vision-model')->estimateWithImages(
    text:   'Analyse this diagram.',
    images: [ImageAttachment::highDetail(1920, 1080), ImageAttachment::lowDetail(800, 600)],
);

echo $result->imageTokens();   // 1000 (2 images × 500 flat)
echo $result->imageCostUsd();
```

Resolution: the first estimator whose `supports($model)` returns `true` wins. When `imageEstimators` is empty (the default), all three built-in estimators are used automatically.

Documentation
-------------

[](#documentation)

- [Getting Started](docs/getting-started.md) — Cost calculations and quick one-liners
- [Installation Setup](docs/installation.md) — Composer, requirements, and DI container setup
- [Architecture Schematic](docs/architecture.md) — Core concepts, pricing engine flows and data structures
- [Pricing Engine Rules](docs/pricing-engine.md) — Class APIs, estimate methods, and facades
- [Pricing Result Typings](docs/pricing-result.md) — Returned metrics, DTOs, and standard formatting
- [Caching Strategies](docs/caching-strategies.md) — Anthropic Additive Logic vs OpenAI Subset bounds
- [Multimodal Vision Pricing](docs/multimodal-vision.md) — Image complexities, tiles, constraints, custom image estimators
- [Custom Price Tables](docs/custom-tables.md) — Decorating interfaces using external JSON arrays
- [Pricing Registry](docs/pricing-registry.md) — Factory instantiation, memory safety
- [Advanced Integration](docs/advanced-integration.md) — Immutable recursive iteration
- [Examples Guide](docs/examples.md) — Directory map against all 8 baseline examples
- [Default Internal Catalog](docs/default-catalog.md) — Complete parameter specifications
- [System Internals](docs/internals.md) — Math limits and unknown models
- [Testing &amp; Validation](docs/testing.md) — PHPUnit, CS-Fixer and logic overrides
- [Contributing Guidelines](docs/contributing.md) — Safe repository upgrades

License
-------

[](#license)

MIT. See [LICENSE](LICENSE).

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance87

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

64d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/78189912?v=4)[Token27](/maintainers/token27)[@token27](https://github.com/token27)

---

Tags

tokensopenaiGeminillmanthropicdeepseekcostpricing

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/token27-nexus-ai-pricing/health.svg)

```
[![Health](https://phpackages.com/badges/token27-nexus-ai-pricing/health.svg)](https://phpackages.com/packages/token27-nexus-ai-pricing)
```

###  Alternatives

[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

326123.0k1](/packages/cognesy-instructor-php)[symfony/ai-platform

PHP library for interacting with AI platform provider.

521.4M300](/packages/symfony-ai-platform)[llm-agents/agents

LLM Agents PHP SDK - Autonomous Language Model Agents for PHP

16716.2k9](/packages/llm-agents-agents)[soukicz/llm

LLM client with support for cache, tools and async requests

4414.3k](/packages/soukicz-llm)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
