adachsoft / ai-image-cost
Calculates AI image generation costs from provider usage data.
Requires
- php: ^8.3
- adachsoft/ai-image-contract: ^0.4
- adachsoft/model-pricing-contracts: ^0.4.1 || ^0.5
- adachsoft/model-usage-ledger: ^0.2
Requires (Dev)
- adachsoft/php-code-style: ^0.9.0
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
adachsoft/ai-image-cost estimates the cost of one AI image generation request from ImageUsageDto usage data. It delegates price-sheet lookup and cost calculation to the CostEstimatorInterface contract from adachsoft/model-pricing-contracts and can use a provider-reported currency cost when no complete estimate is available.
Main capabilities
- Maps token- and image-based usage, resolution, and quality into pricing estimation requests.
- Returns complete or partial price-sheet estimates, or a valid provider-reported currency cost as a fallback.
- Decorates an image generator to record usage, cost, duration, and correlation metadata in a usage ledger.
Requirements
- PHP 8.3 or later.
- Composer.
- Compatible
adachsoft/ai-image-contract,adachsoft/model-pricing-contracts, andadachsoft/model-usage-ledgerpackages. The pricing library is optional and can be provided by the application when usingModelPricingFactory.
Installation
Install the package with Composer:
composer require adachsoft/ai-image-cost
The application must also provide compatible image contracts, pricing contracts, and—when recording usage—a model usage ledger implementation. A pricing estimator implementation can be supplied by adachsoft/model-pricing-lib.
Example
The estimator below is created by ModelPricingFactory from adachsoft/model-pricing-lib:
use AdachSoft\AiImageContract\Models\ImageUsageDto;
use AdachSoft\AiImageCost\ImageCostCalculator;
use AdachSoft\ModelPricingLib\ModelPricingFactory;
$catalog = ModelPricingFactory::createJsonCatalog(__DIR__ . '/var/model-prices');
$estimator = ModelPricingFactory::createEstimator($catalog);
$calculator = new ImageCostCalculator($estimator);
$usage = new ImageUsageDto(
provider: 'google',
model: 'gemini-image-model',
imageCount: 1,
resolution: '1024x1024',
quality: 'high',
inputTokens: 120,
outputTokens: 1024,
outputImageTokens: 1024,
);
$cost = $calculator->calculate($usage);
if ($cost !== null) {
printf('%s %s (%s)\n', $cost->amount, $cost->currency, $cost->source);
}
ImageCostCalculator accepts any implementation of CostEstimatorInterface; the pricing library is supplied by the application rather than required by this package.
Recording usage in the ledger
Wrap an existing image generator with UsageRecordingImageGenerator and provide an application-managed ModelUsageLedgerInterface implementation. The decorator records usage, the calculated cost when available, generation duration, and the current correlation scope while returning the provider response unchanged.
use AdachSoft\AiImageCost\Generator\UsageRecordingImageGenerator;
use AdachSoft\AiImageCost\ImageCostCalculator;
use AdachSoft\ModelUsageLedger\Dto\UsageCorrelationDto;
use AdachSoft\ModelUsageLedger\Scope\UsageScope;
$usageScope = new UsageScope();
$recordingGenerator = new UsageRecordingImageGenerator(
inner: $imageGenerator,
ledger: $ledger,
usageScope: $usageScope,
costCalculator: new ImageCostCalculator($estimator),
);
$response = $usageScope->run(
new UsageCorrelationDto(workflowRunId: 'workflow-123', stepId: 'image-generation'),
fn () => $recordingGenerator->generate($generationRequest),
);
$ledger, $imageGenerator, and $estimator are supplied by the application. If the response has no structured usage, no ledger entry is created. Cost-calculation and ledger-recording failures can be observed with the optional onError callback and do not prevent the generated response from being returned; errors from the image generator itself are propagated.
Usage mapping
- When either total input or output tokens are present, the calculator creates token-based usage items. Input image tokens are separated from regular input tokens. Output image tokens are separated from regular output tokens; when no output image breakdown is provided, all output tokens are treated as image tokens.
- Only positive usage quantities are sent to the estimator. The total input-token count is also supplied as the context token count.
- When token totals are absent,
imageCountis billed with theimagecomponent kind. - Non-null
resolutionandqualityvalues are added to the pricing context as matching conditions. - The default provider mapping is
googletogemini. Other provider IDs are passed through unchanged. Supply a custom map as the calculator's second constructor argument to override or extend this behavior. - A complete estimate is returned as an
estimatecost. If an estimate is incomplete and the provider reported a valid three-letter uppercase currency cost, that reported cost is preferred and the warningprovider_reported_cost_usedis added. When no price sheet exists, a valid provider-reported currency cost is used as a completeprovider_reportedresult. Non-currency units such as credits are not used as currency costs.
The result is an immutable ImageCostDto containing the decimal-string amount, currency, completeness, source, unpriced usage kinds, and warnings. Estimator exceptions are allowed to propagate to the caller.