diff --git a/README.md b/README.md index e7f7a5f..c6ee331 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ src/ ChatResult.php ответ модели: текст, tool_calls, usage Agent.php цикл: вопрос → инструменты → ответ LoggingClient.php декоратор: логи запросов и ответов + Cost.php оценка стоимости по токенам и тарифу Tool.php интерфейс инструмента ToolRegistry.php набор инструментов HttpTransport.php низкоуровневый HTTP: методы, тело, лимит размера @@ -70,7 +71,7 @@ tools/ DateCalcTool.php разница дат и прибавление интервала UuidTool.php UUID v4 HashTool.php sha256/sha1/md5 - Support/ общие помощники: Bytes, FileWalker, UrlGuard, AtomicWriter + Support/ помощники: Bytes, FileWalker, UrlGuard, AtomicWriter, Timeout examples/ 01-chat.php простой вопрос 02-tools.php агент с тремя инструментами @@ -261,3 +262,4 @@ $agent->ask('вопрос'); + diff --git a/docs/reference.md b/docs/reference.md index b658aa3..85e88d9 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -56,6 +56,11 @@ $result = $client->chat($messages, $tools = [], $options = []); // options: tool_choice, parallel_tool_calls, temperature, max_tokens $result->text; $result->toolCalls; $result->usage; +// Расход и стоимость +$agent->usage(); // [prompt_tokens, completion_tokens] за диалог +$cost = (new Cost())->withRate('model', input: 0.07, output: 0.28); +echo $cost->format($cost->estimate('model', $agent->usage())); + // Логирование поверх любого клиента $client = new LoggingClient($client, sink: fn (string $l) => error_log($l), verbose: true); @@ -98,3 +103,4 @@ $tools->add(new FinishTool()); ``` + diff --git a/docs/tools.md b/docs/tools.md index aaa22be..4e846eb 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -103,7 +103,8 @@ $tools->add(new HttpRequestTool( - `headers` — свои заголовки, кроме `Host`, `Content-Length`, `Transfer-Encoding`, `Connection` (их ставит cURL); - `auth` аргументом — для разовых запросов; аргумент важнее карты из конструктора; -- `max_chars` — ограничение ответа. +- `max_chars` — ограничение ответа; +- `timeout` — сколько секунд ждать (модель может попросить больше, но не выше максимума инструмента). Защита: @@ -137,6 +138,9 @@ read-only пользователя; в ядре такие права «по у ## Команды оболочки +Модель может передать `timeout` в секундах: значение применяется, но не выше +максимума инструмента (`maxTimeout`). Это же работает в `http_request`. + `run_command` — единственный инструмент, который может сделать на машине что угодно. В реестр сам себя он не добавляет: регистрируйте осознанно. @@ -230,3 +234,4 @@ $agent = new Agent(AiClient::fromEnv(), $tools); чем «курс валют ЦБ на сегодня; вызывай, когда спрашивают про курс доллара». + diff --git a/examples/12-logging.php b/examples/12-logging.php index ecc3bf1..0105264 100644 --- a/examples/12-logging.php +++ b/examples/12-logging.php @@ -18,6 +18,8 @@ require dirname(__DIR__) . '/bootstrap.php'; use AiSdk\Agent; use AiSdk\AiClient; +use AiSdk\Cost; +use AiSdk\Env; use AiSdk\LoggingClient; use AiSdk\ToolRegistry; use AiSdk\Tools\CalculatorTool; @@ -38,6 +40,17 @@ $agent = new Agent($client, $tools, 'Отвечай кратко, одной с echo PHP_EOL . 'ответ: ' . $agent->ask('Который час в Москве и сколько будет 2+2?') . PHP_EOL; +// Расход виден без декоратора: Agent копит usage по всем раундам. +$usage = $agent->usage(); +$model = Env::get('AI_MODEL', 'deepseek-chat') ?? 'deepseek-chat'; + +// Тарифы примерные — сверяйтесь с провайдером. +$cost = (new Cost())->withRate($model, input: 0.07, output: 0.28); + +echo 'токены: ' . $usage['prompt_tokens'] . ' / ' . $usage['completion_tokens'] . PHP_EOL; +echo 'стоимость: ' . $cost->format($cost->estimate($model, $usage)) . PHP_EOL; + // Тот же декоратор без verbose пишет одну строку на запрос — удобно для продакшена: // // $quiet = new LoggingClient(AiClient::fromEnv(), sink: fn ($l) => error_log($l)); + diff --git a/src/Agent.php b/src/Agent.php index 6b0a021..d9b00a0 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -42,6 +42,9 @@ final class Agent /** @var list, 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> $messages + * @param list> $tools + * @param array $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; + } + /** * Быстрый старт: агент с инструментами по умолчанию. */ } + diff --git a/src/Cost.php b/src/Cost.php new file mode 100644 index 0000000..3aedb28 --- /dev/null +++ b/src/Cost.php @@ -0,0 +1,76 @@ +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 $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 + */ + public function rates(): array + { + return $this->rates; + } +} diff --git a/tests/cases/support.php b/tests/cases/support.php new file mode 100644 index 0000000..6e4a678 --- /dev/null +++ b/tests/cases/support.php @@ -0,0 +1,82 @@ + 5], 10.0, 60.0); + + assertSame(5.0, $timeout->seconds); + assertSame(false, $timeout->clamped()); +}); + +test('timeout: без параметра берётся значение по умолчанию', function (): void { + assertSame(10.0, Timeout::from([], 10.0, 60.0)->seconds); +}); + +test('timeout: больше максимума урезается', function (): void { + $timeout = Timeout::from(['timeout' => 999], 10.0, 60.0); + + assertSame(60.0, $timeout->seconds); + assertSame(true, $timeout->clamped()); +}); + +test('timeout: меньше секунды поднимается до одной', function (): void { + assertSame(1.0, Timeout::from(['timeout' => 0.1], 10.0, 60.0)->seconds); +}); + +test('timeout: нечисловое значение игнорируется', function (): void { + assertSame(10.0, Timeout::from(['timeout' => 'abc'], 10.0, 60.0)->seconds); +}); + +test('tools: timeout есть в схемах run_command и http_request', function (): void { + assertTrue(isset((new ShellTool())->parameters()['properties']['timeout'])); + assertTrue(isset((new HttpRequestTool())->parameters()['properties']['timeout'])); +}); + +test('cost: считает по тарифу за миллион токенов', function (): void { + $cost = (new Cost())->withRate('demo', 1.0, 2.0); + $estimate = $cost->estimate('demo', ['prompt_tokens' => 1000, 'completion_tokens' => 500]); + + assertSame(0.002, round((float) $estimate, 9)); +}); + +test('cost: неизвестная модель — null и прочерк', function (): void { + $cost = new Cost(); + + assertSame(null, $cost->estimate('nope', ['prompt_tokens' => 10])); + assertSame('—', $cost->format(null)); +}); + +test('cost: форматирование суммы', function (): void { + $cost = new Cost(); + + assertSame('$0', $cost->format(0.0)); + assertSame('$0.000412', $cost->format(0.000412)); +}); + +test('agent: usage суммируется по запросам и сбрасывается', function (): void { + $client = new FakeClient([ + new ChatResult('a', [], ['role' => 'assistant', 'content' => 'a'], ['prompt_tokens' => 10, 'completion_tokens' => 5]), + new ChatResult('b', [], ['role' => 'assistant', 'content' => 'b'], ['prompt_tokens' => 20, 'completion_tokens' => 7]), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'тест', 3); + + $agent->ask('раз'); + $agent->ask('два'); + + assertSame(['prompt_tokens' => 30, 'completion_tokens' => 12], $agent->usage()); + + $agent->reset(); + assertSame(['prompt_tokens' => 0, 'completion_tokens' => 0], $agent->usage()); +}); diff --git a/tools/HttpRequestTool.php b/tools/HttpRequestTool.php index 0d6ae1f..b5fbfe4 100644 --- a/tools/HttpRequestTool.php +++ b/tools/HttpRequestTool.php @@ -6,6 +6,7 @@ namespace AiSdk\Tools; use AiSdk\HttpTransport; use AiSdk\HttpRequest; +use AiSdk\Tools\Support\Timeout; use AiSdk\Tools\Support\UrlGuard; use AiSdk\Tool; @@ -23,7 +24,6 @@ use AiSdk\Tool; final class HttpRequestTool implements Tool { private const MAX_REDIRECTS = 3; - private const TIMEOUT = 10.0; private const MAX_BYTES = 262144; private const MAX_BODY = 65536; @@ -40,6 +40,8 @@ final class HttpRequestTool implements Tool array $auth = [], bool $allowPrivate = false, private readonly int $defaultChars = 4000, + private readonly float $timeout = 10.0, + private readonly float $maxTimeout = 60.0, ) { $normalized = []; @@ -100,6 +102,10 @@ final class HttpRequestTool implements Tool 'type' => 'integer', 'description' => 'Сколько символов ответа вернуть, по умолчанию ' . $this->defaultChars . '.', ], + 'timeout' => [ + 'type' => 'number', + 'description' => Timeout::parameterDescription($this->timeout, $this->maxTimeout), + ], ], 'required' => ['url'], 'additionalProperties' => false, @@ -116,6 +122,7 @@ final class HttpRequestTool implements Tool $maxChars = (int) ($args['max_chars'] ?? $this->defaultChars); $maxChars = max(200, min($maxChars, 20000)); + $timeout = Timeout::from($args, $this->timeout, $this->maxTimeout); $body = $args['body'] ?? null; @@ -150,7 +157,7 @@ final class HttpRequestTool implements Tool $response = HttpTransport::request( $url, - self::TIMEOUT, + $timeout->seconds, false, self::MAX_BYTES, $request->method, @@ -228,3 +235,4 @@ final class HttpRequestTool implements Tool } + diff --git a/tools/ShellTool.php b/tools/ShellTool.php index 241dbf8..9e4413e 100644 --- a/tools/ShellTool.php +++ b/tools/ShellTool.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace AiSdk\Tools; use AiSdk\Tool; +use AiSdk\Tools\Support\Timeout; /** * Выполнение команд оболочки. @@ -30,7 +31,8 @@ final class ShellTool implements Tool /** * @param string|null $workdir каталог, где выполняется команда (по умолчанию текущий) * @param string $shell auto | bash | sh | cmd | powershell | pwsh - * @param float $timeout секунды до принудительного завершения + * @param float $timeout секунды до принудительного завершения (по умолчанию для модели) + * @param float $maxTimeout предел, который модель не может превысить * @param int $maxOutput предел вывода stdout/stderr в байтах * @param list $allow если не пусто — разрешены только эти первые слова * @param string|null $tmpDir где создавать файлы вывода (по умолчанию системный temp) @@ -39,6 +41,7 @@ final class ShellTool implements Tool ?string $workdir = null, string $shell = 'auto', private readonly float $timeout = 10.0, + private readonly float $maxTimeout = 120.0, private readonly int $maxOutput = 16000, private readonly array $allow = [], ?string $tmpDir = null, @@ -70,6 +73,10 @@ final class ShellTool implements Tool 'type' => 'string', 'description' => 'Команда, например "ls -la" или "php -v".', ], + 'timeout' => [ + 'type' => 'number', + 'description' => Timeout::parameterDescription($this->timeout, $this->maxTimeout), + ], ], 'required' => ['command'], 'additionalProperties' => false, @@ -89,6 +96,8 @@ final class ShellTool implements Tool . 'Разрешены: ' . implode(', ', $this->allow) . '.'; } + $timeout = Timeout::from($args, $this->timeout, $this->maxTimeout); + try { $commandLine = $this->commandLine($command); } catch (\InvalidArgumentException $e) { @@ -110,7 +119,7 @@ final class ShellTool implements Tool [$outFile, $errFile] = $files; try { - $run = $this->run($commandLine, $cwd, $outFile, $errFile); + $run = $this->run($commandLine, $cwd, $outFile, $errFile, $timeout->seconds); } catch (\RuntimeException $e) { return $e->getMessage(); } finally { @@ -120,7 +129,7 @@ final class ShellTool implements Tool @unlink($errFile); } - return $this->format($command, $stdout, $stderr, $run['timedOut'], $run['overflow'], $run['exitCode']); + return $this->format($command, $stdout, $stderr, $run['timedOut'], $run['overflow'], $run['exitCode'], $timeout->seconds); } /** @@ -158,7 +167,7 @@ final class ShellTool implements Tool * * @return array{timedOut: bool, overflow: bool, exitCode: int} */ - private function run(string $commandLine, string $cwd, string $outFile, string $errFile): array + private function run(string $commandLine, string $cwd, string $outFile, string $errFile, float $timeout): array { $process = @proc_open($commandLine, [ 0 => ['pipe', 'r'], @@ -187,7 +196,7 @@ final class ShellTool implements Tool break; } - if ((microtime(true) - $startedAt) > $this->timeout) { + if ((microtime(true) - $startedAt) > $timeout) { $timedOut = true; @proc_terminate($process, 9); $this->killTree((int) $status['pid']); @@ -297,11 +306,12 @@ final class ShellTool implements Tool bool $timedOut, bool $overflow, int $exitCode, + float $timeout, ): string { $lines = ['$ ' . $command]; $lines[] = match (true) { - $timedOut => 'exit: таймаут ' . $this->timeout . ' с (процесс завершён)', + $timedOut => 'exit: таймаут ' . Timeout::format($timeout) . ' с (процесс завершён)', $overflow => 'exit: вывод превысил лимит, процесс завершён', default => 'exit: ' . $exitCode, }; @@ -335,3 +345,5 @@ final class ShellTool implements Tool return mb_strcut($text, 0, $this->maxOutput) . "\n… (обрезано)"; } } + + diff --git a/tools/Support/Timeout.php b/tools/Support/Timeout.php new file mode 100644 index 0000000..c3b532b --- /dev/null +++ b/tools/Support/Timeout.php @@ -0,0 +1,56 @@ + $arguments аргументы вызова от модели + */ + public static function from(array $arguments, float $default, float $max): self + { + $max = max(1.0, $max); + $raw = $arguments['timeout'] ?? null; + $requested = is_numeric($raw) ? (float) $raw : null; + + return new self(max(1.0, min($max, $requested ?? $default)), $requested, $max); + } + + /** + * Модель попросила значение, которое пришлось урезать. + */ + public function clamped(): bool + { + return $this->requested !== null && abs($this->requested - $this->seconds) > 0.001; + } + + public static function parameterDescription(float $default, float $max): string + { + return sprintf( + 'Сколько секунд ждать (по умолчанию %s, максимум %s; больше — будет урезано).', + self::format($default), + self::format($max), + ); + } + + public static function format(float $seconds): string + { + return rtrim(rtrim(number_format($seconds, 1, '.', ''), '0'), '.'); + } +}