feat: таймаут от модели и оценка стоимости запроса
- Tools\\Support\\Timeout: значение timeout из аргументов модели, но не выше максимума инструмента; параметр описан в схемах - run_command и http_request принимают timeout (по умолчанию / maxTimeout) - Cost: тарифы по модели задаются явно, estimate() и format(); неизвестная модель даёт null, а не выдуманное число - Agent копит usage по всем раундам: usage() и сброс в reset() - пример 12 показывает расход и стоимость - 112 тестов
This commit is contained in:
1 parent
78aca90074
commit
ab081a4dcd
10 files changed
+304
-12
No files matched your search
+34
-2
@@ -42,6 +42,9 @@ final class Agent
|
||||
/** @var list<array{name: string, arguments: array<string, mixed>, output: string, ms: int, blocked: bool}> */
|
||||
private array $trace = [];
|
||||
|
||||
/** @var array{prompt_tokens: int, completion_tokens: int} */
|
||||
private array $usage = ['prompt_tokens' => 0, 'completion_tokens' => 0];
|
||||
|
||||
private string $systemPrompt;
|
||||
|
||||
/**
|
||||
@@ -152,7 +155,7 @@ final class Agent
|
||||
];
|
||||
|
||||
// Без инструментов и без tool_choice: иначе API может отвергнуть запрос.
|
||||
$result = $this->client->chat($this->messages, []);
|
||||
$result = $this->send($this->messages, []);
|
||||
}
|
||||
|
||||
$text = $result->text !== '' ? $result->text : '(модель вернула пустой ответ)';
|
||||
@@ -181,6 +184,16 @@ final class Agent
|
||||
return $this->trace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Суммарный расход токенов за все запросы этого диалога.
|
||||
*
|
||||
* @return array{prompt_tokens: int, completion_tokens: int}
|
||||
*/
|
||||
public function usage(): array
|
||||
{
|
||||
return $this->usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Начать диалог заново.
|
||||
*/
|
||||
@@ -188,6 +201,7 @@ final class Agent
|
||||
{
|
||||
$this->messages = [];
|
||||
$this->trace = [];
|
||||
$this->usage = ['prompt_tokens' => 0, 'completion_tokens' => 0];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,14 +412,32 @@ final class Agent
|
||||
|
||||
private function chat(bool $withToolChoice = false): ChatResult
|
||||
{
|
||||
return $this->client->chat(
|
||||
return $this->send(
|
||||
$this->messages,
|
||||
$this->tools->definitions(),
|
||||
$this->chatOptions($withToolChoice),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Один запрос к модели с накоплением расхода токенов.
|
||||
*
|
||||
* @param list<array<string, mixed>> $messages
|
||||
* @param list<array<string, mixed>> $tools
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
private function send(array $messages, array $tools, array $options = []): ChatResult
|
||||
{
|
||||
$result = $this->client->chat($messages, $tools, $options);
|
||||
|
||||
$this->usage['prompt_tokens'] += (int) ($result->usage['prompt_tokens'] ?? 0);
|
||||
$this->usage['completion_tokens'] += (int) ($result->usage['completion_tokens'] ?? 0);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Быстрый старт: агент с инструментами по умолчанию.
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Оценка стоимости запросов по тарифу провайдера.
|
||||
*
|
||||
* Тарифы не зашиты: они меняются и зависят от модели, поэтому задаются
|
||||
* явно. Цены — в долларах за 1 миллион токенов.
|
||||
*
|
||||
* $cost = (new Cost())
|
||||
* ->withRate('deepseek-chat', input: 0.27, output: 1.10);
|
||||
*
|
||||
* echo $cost->format($cost->estimate('deepseek-chat', $agent->usage()));
|
||||
*
|
||||
* Если модель не описана — estimate() вернёт null (а format() — «—»):
|
||||
* лучше честное «неизвестно», чем выдуманное число.
|
||||
*/
|
||||
final class Cost
|
||||
{
|
||||
/** @param array<string, array{input: float, output: float}> $rates USD за 1M токенов */
|
||||
public function __construct(private readonly array $rates = [])
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавить тариф модели. Возвращает новый экземпляр.
|
||||
*/
|
||||
public function withRate(string $model, float $input, float $output): self
|
||||
{
|
||||
$rates = $this->rates;
|
||||
$rates[$model] = ['input' => $input, 'output' => $output];
|
||||
|
||||
return new self($rates);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{0?: int, prompt_tokens?: int, completion_tokens?: int} $usage
|
||||
*/
|
||||
public function estimate(string $model, array $usage): ?float
|
||||
{
|
||||
$rate = $this->rates[$model] ?? null;
|
||||
|
||||
if ($rate === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prompt = (int) ($usage['prompt_tokens'] ?? 0);
|
||||
$completion = (int) ($usage['completion_tokens'] ?? 0);
|
||||
|
||||
return ($prompt * $rate['input'] + $completion * $rate['output']) / 1_000_000;
|
||||
}
|
||||
|
||||
public function format(?float $usd, int $precision = 6): string
|
||||
{
|
||||
if ($usd === null) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
if ($usd === 0.0) {
|
||||
return '$0';
|
||||
}
|
||||
|
||||
return '$' . rtrim(rtrim(number_format($usd, $precision, '.', ''), '0'), '.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{input: float, output: float}>
|
||||
*/
|
||||
public function rates(): array
|
||||
{
|
||||
return $this->rates;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user