This commit is contained in:
deploy-bot committed 2026-12-05 19:00:02 +00:00
commit 4769402b1b
298 files changed
+20934

No files matched your search

+365
View File
@@ -0,0 +1,365 @@
<?php
namespace IriksIT\Manager\Support\Costs;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use IriksIT\Manager\Models\WorkCost;
use IriksIT\Manager\Support\IriksStorage\Client;
/**
* The pieces of work on the site with the tokens that went into each, read from the table of the site's `TOKENS.md`, and priced in euros.
*
* A row of the table: date, what was made, the release it is in (empty while it is not released), the model, the number of answers
* of the model, four kinds of tokens (written, read for the first time, stored in the cache, read again from the cache) and, as an
* optional last cell, the hours that were worked on it.
*
* A row is priced once and the answer is kept in the table `work_costs`, because the price of a day in the past does not change. Who
* prices it, in this order: a class of the site (`manager.costs.pricer`, invokable, gets the rows to price and returns the costs by
* reference), the IriksIT API (when `manager.media.iriksit` is set and `manager.costs.use_api` is on: it keeps the price lists of the
* models and the euro rates with their history), and last the fixed rates of `manager.costs.rates`. `priced_by` of a row says which.
*
* Three costs are kept apart: the tokens of the AI model (`eur`), the work itself (`work_eur`, the hours at the hourly rate) and hosting
* (a fixed amount per year).
*/
final class Ledger
{
private const FAILED = 'manager.costs.failed';
private const UNPRICEABLE = 'manager.costs.unpriceable:';
/** Rows to price in one request. */
private const BATCH = 50;
/**
* @return list<array{date: string, name: string, version: string|null, model: string, steps: int, output: int, input: int, cache_write: int, cache_read: int, tokens: int, usd: float|null, eur: float|null, priced_by: string|null, usd_to_eur: float|null, hours: float|null, work_eur: float|null}>
*/
public function items(?bool $ask = null): array
{
$items = $this->rows();
$costs = $this->kept($items, $ask ?? (bool) config('manager.costs.price_on_visit', true));
foreach ($items as $index => $item) {
$cost = $costs['row-'.$index] ?? null;
if ($cost !== null) {
$items[$index] = ['usd' => round($cost['usd'], 4), 'eur' => round($cost['eur'], 2), 'priced_by' => 'service', 'usd_to_eur' => round(1 / $cost['usd_per_eur'], 4)] + $item;
}
}
return $items;
}
/** The rows of the file, priced with the fixed rates. */
private function rows(): array
{
$path = config('manager.costs.ledger') ?: base_path('TOKENS.md');
if (! is_string($path) || ! is_file($path)) {
return [];
}
$items = [];
$inTable = false;
foreach (preg_split('/\R/', (string) file_get_contents($path)) ?: [] as $line) {
$line = trim($line);
if (! str_starts_with($line, '|')) {
$inTable = false;
continue;
}
$cells = array_map(trim(...), explode('|', trim($line, '|')));
// Nine cells, or ten with the hours that were worked as the last one.
if (in_array(count($cells), [9, 10], true) && strcasecmp($cells[0], 'Datum') === 0) {
$inTable = true;
continue;
}
// A row of this table starts with a date; the line of dashes under the header does not.
if (! $inTable || ! in_array(count($cells), [9, 10], true) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $cells[0]) !== 1) {
continue;
}
$item = [
'date' => $cells[0],
'name' => $cells[1],
'version' => $cells[2] !== '' ? $cells[2] : null,
'model' => $cells[3],
'steps' => self::number($cells[4]),
'output' => self::number($cells[5]),
'input' => self::number($cells[6]),
'cache_write' => self::number($cells[7]),
'cache_read' => self::number($cells[8]),
];
$item['tokens'] = $item['output'] + $item['input'] + $item['cache_write'] + $item['cache_read'];
// A row of work without the model (hours only) costs nothing in tokens.
$item['usd'] = $item['tokens'] === 0 ? 0.0 : $this->usd($item);
$item['eur'] = $item['usd'] !== null && $this->rate() > 0 ? round($item['usd'] * $this->rate(), 2) : null;
$item['priced_by'] = $item['eur'] !== null ? 'config' : null;
$item['usd_to_eur'] = $item['eur'] !== null ? $this->rate() : null;
$item['hours'] = self::hours($cells[9] ?? '');
$item['work_eur'] = $item['hours'] !== null ? round($item['hours'] * $this->hourlyRate(), 2) : null;
$items[] = $item;
}
return $items;
}
/**
* What the tokens of the rows cost, by the place of the row in the list ("row-0"), from the table of kept prices and, when `$ask` is
* on, for the rows that are not in it, from the pricer of the site or the API. A row is priced once and kept for good (the price of a
* day in the past does not change), so after the first run only the rows of the newest release are ever asked, in as few requests as
* possible (fifty rows at a time). A site that does not want a visit to the screen to ask anything switches `price_on_visit` off and
* lets `manager:costs-price` do it after a deploy.
*
* Two things are remembered so a price source is not asked over and over: when it could not answer, nothing is asked for an hour; and
* a row it answered without a price (a model it does not know) is not asked again until `manager:costs-price --retry`.
*
* @param list<array<string, mixed>> $items
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>
*/
private function kept(array $items, bool $ask): array
{
$prints = [];
foreach ($items as $index => $item) {
// A row without tokens costs nothing and needs no price.
if ($item['tokens'] > 0) {
$prints[$index] = self::fingerprint($item);
}
}
if ($prints === []) {
return [];
}
$costs = [];
$stored = WorkCost::query()->whereIn('fingerprint', array_values($prints))->get()->keyBy('fingerprint');
foreach ($prints as $index => $print) {
$kept = $stored->get($print);
if ($kept instanceof WorkCost) {
$costs['row-'.$index] = ['usd' => (float) $kept->usd, 'eur' => (float) $kept->eur, 'usd_per_eur' => (float) $kept->usd_per_eur];
}
}
$missing = array_filter($prints, fn (string $print) => ! $stored->has($print) && ! Cache::has(self::UNPRICEABLE.$print));
if (! $ask || $missing === [] || Cache::has(self::FAILED)) {
return $costs;
}
foreach (array_chunk($missing, self::BATCH, true) as $batch) {
$rows = [];
foreach ($batch as $index => $print) {
$rows[] = [
'reference' => 'row-'.$index,
'model' => $items[$index]['model'],
'date' => $items[$index]['date'],
// The sessions that wrote the table used the one-hour cache.
'tokens' => ['output' => $items[$index]['output'], 'input' => $items[$index]['input'], 'cache_write_1h' => $items[$index]['cache_write'], 'cache_read' => $items[$index]['cache_read']],
];
}
$answer = $this->ask($rows);
if ($answer === null) {
Cache::put(self::FAILED, true, now()->addHour());
break;
}
foreach ($batch as $index => $print) {
$cost = $answer['row-'.$index] ?? null;
if ($cost === null) {
// It answered, and has no price for this row: leave it be.
Cache::forever(self::UNPRICEABLE.$print, true);
continue;
}
WorkCost::query()->updateOrCreate(['fingerprint' => $print], [
'date' => $items[$index]['date'],
'name' => mb_substr($items[$index]['name'], 0, 255),
'version' => $items[$index]['version'],
'model' => $items[$index]['model'],
'usd' => $cost['usd'],
'eur' => $cost['eur'],
'usd_per_eur' => $cost['usd_per_eur'],
'priced_at' => now(),
]);
$costs['row-'.$index] = $cost;
}
}
return $costs;
}
/** Forgets that a price source could not, or would not, price rows, so the next run asks again. */
public function retry(): void
{
Cache::forget(self::FAILED);
foreach ($this->rows() as $item) {
if ($item['tokens'] > 0) {
Cache::forget(self::UNPRICEABLE.self::fingerprint($item));
}
}
}
/**
* @param list<array<string, mixed>> $ask
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>|null
*/
private function ask(array $ask): ?array
{
$pricer = config('manager.costs.pricer');
if (is_string($pricer) && $pricer !== '' && (class_exists($pricer) || app()->bound($pricer))) {
$answer = app($pricer)($ask);
return is_array($answer) ? $answer : null;
}
if (! config('manager.costs.use_api', true)) {
return null;
}
$client = new Client((array) config('manager.media.iriksit', []));
return $client->isConfigured() ? $client->tokenCosts($ask) : null;
}
/**
* What makes a row the row it is, for its price: the day, the model and the tokens.
*
* @param array<string, mixed> $item
*/
private static function fingerprint(array $item): string
{
return hash('sha256', implode('|', [$item['date'], $item['model'], $item['output'], $item['input'], $item['cache_write'], $item['cache_read']]));
}
/** Euros for an hour of work: a cost of its own, apart from what the AI model costs. */
public function hourlyRate(): float
{
$rate = config('manager.costs.hourly_rate');
return is_numeric($rate) ? (float) $rate : 0.0;
}
/**
* What hosting has cost until a day: the yearly amount once for every year that has begun since its first day, and nothing before.
*
* @return array{per_year: float, from: string|null, years: int, eur: float}
*/
public function hosting(?CarbonImmutable $on = null): array
{
$perYear = config('manager.costs.hosting.per_year');
$from = config('manager.costs.hosting.from');
$perYear = is_numeric($perYear) ? (float) $perYear : 0.0;
$on ??= CarbonImmutable::today();
if (! is_string($from) || $from === '') {
return ['per_year' => $perYear, 'from' => null, 'years' => 0, 'eur' => 0.0];
}
$start = CarbonImmutable::parse($from)->startOfDay();
$years = $on->lt($start) ? 0 : (int) floor($start->diffInYears($on)) + 1;
return ['per_year' => $perYear, 'from' => $start->toDateString(), 'years' => $years, 'eur' => round($years * $perYear, 2)];
}
/**
* The discount on the work and the AI costs: which share, and until which day (rows dated on or after that day get none).
* Null when there is no discount. Hosting is not part of it.
*
* @return array{percent: float, until: string}|null
*/
public function discount(): ?array
{
$percent = config('manager.costs.discount.percent');
$until = config('manager.costs.discount.until');
if (! is_numeric($percent) || (float) $percent <= 0 || ! is_string($until) || $until === '') {
return null;
}
return ['percent' => min(100.0, (float) $percent), 'until' => CarbonImmutable::parse($until)->toDateString()];
}
/**
* What of a row is not charged: the discount on its work and its AI costs.
*
* @param array<string, mixed> $item
*/
public function discountOn(array $item): float
{
$discount = $this->discount();
if ($discount === null || $item['date'] >= $discount['until']) {
return 0.0;
}
return round((($item['work_eur'] ?? 0.0) + ($item['eur'] ?? 0.0)) * $discount['percent'] / 100, 2);
}
/** Euros for one US dollar, for the rows that are priced with the fixed rates; 0 when the site gave none. */
public function rate(): float
{
$rate = config('manager.costs.usd_to_eur');
return is_numeric($rate) ? (float) $rate : 0.0;
}
/**
* What a row costs at the fixed price list, or null when the model has no prices there.
*
* @param array<string, mixed> $item
*/
private function usd(array $item): ?float
{
$rates = config('manager.costs.rates.'.$item['model']);
if (! is_array($rates)) {
return null;
}
$usd = 0.0;
foreach (['output', 'input', 'cache_write', 'cache_read'] as $kind) {
$price = $rates[$kind] ?? null;
if (! is_numeric($price)) {
return null;
}
$usd += $item[$kind] * (float) $price / 1_000_000;
}
return round($usd, 4);
}
/** "1,25" or "1.25" hours as it is written in the file; an empty cell is not known. */
private static function hours(string $cell): ?float
{
$cell = str_replace(',', '.', trim($cell));
return is_numeric($cell) && (float) $cell >= 0 ? round((float) $cell, 2) : null;
}
/** "1.234.567" as it is written in the file. */
private static function number(string $cell): int
{
return (int) preg_replace('/\D/', '', $cell);
}
}