ExecutionMetrics.php

Code Hygiene Score: 92

Keine Issues gefunden.

Dependencies 2

Klassen 1

Funktionen 14

Verwendet von 3

Versionen 2

Code

<?php

declare(strict_types=1);

namespace Domain\ValueObject;

// @responsibility: Immutables Value Object für Ausführungs-Metriken (Tokens + Kosten + Dauer)

use Domain\Constants;

final class ExecutionMetrics
{
    private function __construct(
        private TokenCount $tokens,
        private ?float $costUsd,
        private ?int $durationMs
    ) {
    }

    public static function create(TokenCount $tokens, ?float $costUsd = null, ?int $durationMs = null): self
    {
        return new self($tokens, $costUsd, $durationMs);
    }

    public static function zero(): self
    {
        return new self(TokenCount::zero(), null, null);
    }

    public static function fromEstimation(string $request, string $response): self
    {
        $inputTokens = max(1, (int) (strlen($request) / 4));
        $outputTokens = max(1, (int) (strlen($response) / 4));

        return new self(TokenCount::create($inputTokens, $outputTokens), null, null);
    }

    public function tokens(): TokenCount
    {
        return $this->tokens;
    }

    public function costUsd(): ?float
    {
        return $this->costUsd;
    }

    public function durationMs(): ?int
    {
        return $this->durationMs;
    }

    public function withCost(float $costUsd): self
    {
        return new self($this->tokens, $costUsd, $this->durationMs);
    }

    public function withDuration(int $durationMs): self
    {
        return new self($this->tokens, $this->costUsd, $durationMs);
    }

    public function withTokens(TokenCount $tokens): self
    {
        return new self($tokens, $this->costUsd, $this->durationMs);
    }

    public function hasCost(): bool
    {
        return $this->costUsd !== null;
    }

    public function hasDuration(): bool
    {
        return $this->durationMs !== null;
    }

    public function format(): string
    {
        $parts = [$this->tokens->format()];

        if ($this->costUsd !== null) {
            $parts[] = sprintf('$%.4f', $this->costUsd);
        }

        if ($this->durationMs !== null) {
            if ($this->durationMs < Constants::MS_PER_SECOND) {
                $parts[] = "{$this->durationMs}ms";
            } else {
                $parts[] = sprintf('%.2fs', $this->durationMs / Constants::MS_PER_SECOND);
            }
        }

        return implode(' | ', $parts);
    }

    public function toArray(): array
    {
        return [
            'tokens_input' => $this->tokens->input(),
            'tokens_output' => $this->tokens->output(),
            'tokens_total' => $this->tokens->total(),
            'cost_usd' => $this->costUsd,
            'duration_ms' => $this->durationMs,
        ];
    }
}
← Übersicht Graph