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:
rsgrinko committed 2026-11-13 00:18:21 +03:00
1 parent 78aca90074
commit ab081a4dcd
10 files changed
+304 -12

No files matched your search

+10 -2
View File
@@ -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
}
+18 -6
View File
@@ -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<string> $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… (обрезано)";
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Таймаут действия, который может попросить сама модель (параметр timeout).
*
* Значение модели применяется как есть, но в пределах жёсткого максимума
* инструмента: модель не может «повесить» процесс навсегда. Если она попросила
* больше максимума — применяется максимум, и это видно в {@see self::clamped()}.
*/
final class Timeout
{
private function __construct(
public readonly float $seconds,
public readonly ?float $requested,
public readonly float $max,
) {
}
/**
* @param array<string, mixed> $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'), '.');
}
}