TracksAiCost
namespace Aaix\LaravelAiCosts\Concerns;
trait TracksAiCostDrop-in replacement for Laravel\Ai\Promptable that tracks an AiCostResult on each prompt() call. Internally it imports Promptable and renames the original prompt() to a private promptWithoutTracking().
prompt()
public function prompt(
string $prompt,
array $attachments = [],
\Laravel\Ai\Enums\Lab|array|string|null $provider = null,
?string $model = null,
?int $timeout = null,
): \Laravel\Ai\Responses\AgentResponseSame signature as Promptable::prompt(). Forwards to the underlying implementation, then appends AiCostCalculator::fromResponse($response) to the internal cost buffer.
lastCost()
public function lastCost(): ?AiCostResultReturns the most recent AiCostResult, or null if no prompt has been issued.
costs()
/** @return AiCostResult[] */
public function costs(): arrayReturns every AiCostResult recorded since instantiation (or the last resetCosts()).
totalCostUsd()
public function totalCostUsd(): floatSum of totalCostUsd across the buffer.
resetCosts()
public function resetCosts(): voidClears the internal buffer.
State scope
Costs are stored on the agent instance (protected array $aiCosts), so they live as long as the agent does. If you re-instantiate the agent per request (the common Laravel pattern), each request starts with an empty buffer.
