feat: минимальная PHP-библиотека для чата с вызовом инструментов
- AiClient: любой OpenAI-совместимый /chat/completions (DeepSeek, OpenAI, Ollama, llama.cpp) - Agent: цикл function calling, история диалога, трассировка вызовов - Tool + ToolRegistry: инструмент = 4 метода, ошибки уходят модели текстом - ChatClient: интерфейс, чтобы подменять модель в тестах - инструменты: get_time, calculator (без eval), get_weather (open-meteo) - 4 примера и 18 тестов без сети - настройки в .env: AI_BASE_URL/AI_MODEL/AI_API_KEY/AI_VERIFY_SSL/AI_CAINFO
This commit is contained in:
commit
14fe8d8a5e
22 files changed
+2122
No files matched your search
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk\Tools;
|
||||
|
||||
use AiSdk\Tool;
|
||||
|
||||
/**
|
||||
* Арифметика без eval(): рекурсивный спуск по выражению.
|
||||
*
|
||||
* Приоритеты: + - < * / % < ^, унарный минус, скобки.
|
||||
* Так модель не ошибётся в счёте, а вы не отдадите ей eval().
|
||||
*/
|
||||
final class CalculatorTool implements Tool
|
||||
{
|
||||
private string $source = '';
|
||||
private int $position = 0;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'calculator';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Точный расчёт арифметического выражения: + - * / % ^ и скобки. '
|
||||
. '% — остаток от деления, а не процент: 17% от 4300 считай как 0.17*4300. '
|
||||
. 'Используй вместо счёта в уме.';
|
||||
}
|
||||
|
||||
public function parameters(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'expression' => [
|
||||
'type' => 'string',
|
||||
'description' => 'Выражение, например (120+30)*0.15.',
|
||||
],
|
||||
],
|
||||
'required' => ['expression'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(array $args): string
|
||||
{
|
||||
$expression = str_replace(' ', '', (string) ($args['expression'] ?? ''));
|
||||
|
||||
if ($expression === '') {
|
||||
return 'Пустое выражение.';
|
||||
}
|
||||
|
||||
if (strlen($expression) > 200) {
|
||||
return 'Слишком длинное выражение (максимум 200 символов).';
|
||||
}
|
||||
|
||||
if (preg_match('/^[0-9+\-*\/%^().]+$/', $expression) !== 1) {
|
||||
return 'Разрешены только цифры, скобки и операции + - * / % ^.';
|
||||
}
|
||||
|
||||
$this->source = $expression;
|
||||
$this->position = 0;
|
||||
|
||||
try {
|
||||
$value = $this->parseExpression();
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return 'Ошибка в выражении: ' . $e->getMessage() . '.';
|
||||
}
|
||||
|
||||
if ($this->position < strlen($this->source)) {
|
||||
return 'Ошибка в выражении: лишние символы с позиции ' . $this->position . '.';
|
||||
}
|
||||
|
||||
if (!is_finite($value)) {
|
||||
return 'Результат не является числом (деление на ноль?).';
|
||||
}
|
||||
|
||||
return $expression . ' = ' . $this->format($value);
|
||||
}
|
||||
|
||||
private function parseExpression(): float
|
||||
{
|
||||
$value = $this->parseTerm();
|
||||
|
||||
while (($operator = $this->peek()) === '+' || $operator === '-') {
|
||||
$this->position++;
|
||||
$right = $this->parseTerm();
|
||||
$value = $operator === '+' ? $value + $right : $value - $right;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function parseTerm(): float
|
||||
{
|
||||
$value = $this->parsePower();
|
||||
|
||||
while (in_array($this->peek(), ['*', '/', '%'], true)) {
|
||||
$operator = $this->source[$this->position];
|
||||
$this->position++;
|
||||
$right = $this->parsePower();
|
||||
|
||||
if (($operator === '/' || $operator === '%') && $right == 0.0) {
|
||||
throw new \InvalidArgumentException('деление на ноль');
|
||||
}
|
||||
|
||||
$value = match ($operator) {
|
||||
'*' => $value * $right,
|
||||
'/' => $value / $right,
|
||||
default => fmod($value, $right),
|
||||
};
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function parsePower(): float
|
||||
{
|
||||
$value = $this->parseUnary();
|
||||
|
||||
if ($this->peek() === '^') {
|
||||
$this->position++;
|
||||
|
||||
// Правоассоциативно: 2^3^2 = 512.
|
||||
return $value ** $this->parsePower();
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function parseUnary(): float
|
||||
{
|
||||
$char = $this->peek();
|
||||
|
||||
if ($char === '-') {
|
||||
$this->position++;
|
||||
|
||||
return -$this->parseUnary();
|
||||
}
|
||||
|
||||
if ($char === '+') {
|
||||
$this->position++;
|
||||
|
||||
return $this->parseUnary();
|
||||
}
|
||||
|
||||
return $this->parsePrimary();
|
||||
}
|
||||
|
||||
private function parsePrimary(): float
|
||||
{
|
||||
if ($this->peek() === '(') {
|
||||
$this->position++;
|
||||
$value = $this->parseExpression();
|
||||
|
||||
if ($this->peek() !== ')') {
|
||||
throw new \InvalidArgumentException('не закрыта скобка');
|
||||
}
|
||||
|
||||
$this->position++;
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
// \G привязывает совпадение к текущей позиции.
|
||||
if (preg_match('/\G\d*\.?\d+/', $this->source, $match, 0, $this->position) !== 1) {
|
||||
throw new \InvalidArgumentException('ожидалось число с позиции ' . $this->position);
|
||||
}
|
||||
|
||||
$this->position += strlen($match[0]);
|
||||
|
||||
return (float) $match[0];
|
||||
}
|
||||
|
||||
private function peek(): string
|
||||
{
|
||||
return $this->source[$this->position] ?? '';
|
||||
}
|
||||
|
||||
private function format(float $value): string
|
||||
{
|
||||
if (abs($value - round($value)) < 1e-9) {
|
||||
return (string) (int) round($value);
|
||||
}
|
||||
|
||||
return rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk\Tools;
|
||||
|
||||
use AiSdk\Tool;
|
||||
|
||||
/**
|
||||
* Пример самого простого инструмента: без аргументов и без сети.
|
||||
*/
|
||||
final class TimeTool implements Tool
|
||||
{
|
||||
private const WEEKDAYS = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'get_time';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Текущие дата и время. Часовой пояс можно указать, если он важен.';
|
||||
}
|
||||
|
||||
public function parameters(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'timezone' => [
|
||||
'type' => 'string',
|
||||
'description' => 'Часовой пояс IANA, например Europe/Moscow. По умолчанию Europe/Moscow.',
|
||||
],
|
||||
],
|
||||
'required' => [],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(array $args): string
|
||||
{
|
||||
$timezone = trim((string) ($args['timezone'] ?? ''));
|
||||
$timezone = $timezone !== '' ? $timezone : 'Europe/Moscow';
|
||||
|
||||
try {
|
||||
$now = new \DateTimeImmutable('now', new \DateTimeZone($timezone));
|
||||
} catch (\Throwable) {
|
||||
return 'Неизвестный часовой пояс: ' . $timezone . '. Пример: Europe/Moscow.';
|
||||
}
|
||||
|
||||
$weekday = self::WEEKDAYS[(int) $now->format('N') - 1];
|
||||
|
||||
return $now->format('Y-m-d H:i:s T') . ' (' . $weekday . ')';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk\Tools;
|
||||
|
||||
use AiSdk\Http;
|
||||
use AiSdk\Tool;
|
||||
|
||||
/**
|
||||
* Пример инструмента с обращением к внешнему API.
|
||||
*
|
||||
* open-meteo.com не требует ключа: сначала геокодинг по названию города,
|
||||
* потом текущая погода по координатам.
|
||||
*/
|
||||
final class WeatherTool implements Tool
|
||||
{
|
||||
private const WEATHER_CODES = [
|
||||
0 => 'ясно',
|
||||
1 => 'в основном ясно',
|
||||
2 => 'переменная облачность',
|
||||
3 => 'облачно',
|
||||
45 => 'туман',
|
||||
48 => 'изморозь',
|
||||
51 => 'слабая морось',
|
||||
53 => 'морось',
|
||||
55 => 'сильная морось',
|
||||
61 => 'слабый дождь',
|
||||
63 => 'дождь',
|
||||
65 => 'сильный дождь',
|
||||
66 => 'ледяной дождь',
|
||||
67 => 'сильный ледяной дождь',
|
||||
71 => 'слабый снег',
|
||||
73 => 'снег',
|
||||
75 => 'сильный снег',
|
||||
77 => 'снежная крупа',
|
||||
80 => 'ливень',
|
||||
81 => 'сильный ливень',
|
||||
82 => 'очень сильный ливень',
|
||||
85 => 'снегопад',
|
||||
86 => 'сильный снегопад',
|
||||
95 => 'гроза',
|
||||
96 => 'гроза с градом',
|
||||
99 => 'сильная гроза с градом',
|
||||
];
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'get_weather';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Текущая погода в городе: температура, ощущаемая температура, влажность, ветер, осадки.';
|
||||
}
|
||||
|
||||
public function parameters(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'city' => [
|
||||
'type' => 'string',
|
||||
'description' => 'Название города, например Тула или Moscow.',
|
||||
],
|
||||
],
|
||||
'required' => ['city'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(array $args): string
|
||||
{
|
||||
$city = trim((string) ($args['city'] ?? ''));
|
||||
|
||||
if ($city === '') {
|
||||
return 'Не указан город.';
|
||||
}
|
||||
|
||||
$place = $this->geocode($city);
|
||||
|
||||
if ($place === null) {
|
||||
return 'Город не найден: ' . $city . '.';
|
||||
}
|
||||
|
||||
$query = http_build_query([
|
||||
'latitude' => $place['latitude'],
|
||||
'longitude' => $place['longitude'],
|
||||
'current' => 'temperature_2m,relative_humidity_2m,apparent_temperature,wind_speed_10m,weather_code',
|
||||
'timezone' => 'auto',
|
||||
]);
|
||||
|
||||
[$status, $body] = Http::get('https://api.open-meteo.com/v1/forecast?' . $query);
|
||||
$data = json_decode($body, true);
|
||||
$current = $data['current'] ?? null;
|
||||
|
||||
if ($status >= 400 || !is_array($current)) {
|
||||
return 'Не удалось получить погоду (HTTP ' . $status . ').';
|
||||
}
|
||||
|
||||
$code = (int) ($current['weather_code'] ?? 0);
|
||||
$description = self::WEATHER_CODES[$code] ?? ('код ' . $code);
|
||||
|
||||
return sprintf(
|
||||
'%s: %s, %.1f °C (ощущается %.1f °C), влажность %d%%, ветер %.1f км/ч.',
|
||||
$place['label'],
|
||||
$description,
|
||||
(float) ($current['temperature_2m'] ?? 0.0),
|
||||
(float) ($current['apparent_temperature'] ?? 0.0),
|
||||
(int) ($current['relative_humidity_2m'] ?? 0),
|
||||
(float) ($current['wind_speed_10m'] ?? 0.0),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{label: string, latitude: float, longitude: float}|null
|
||||
*/
|
||||
private function geocode(string $city): ?array
|
||||
{
|
||||
$query = http_build_query([
|
||||
'name' => $city,
|
||||
'count' => 1,
|
||||
'language' => 'ru',
|
||||
'format' => 'json',
|
||||
]);
|
||||
|
||||
[$status, $body] = Http::get('https://geocoding-api.open-meteo.com/v1/search?' . $query);
|
||||
|
||||
if ($status >= 400) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = json_decode($body, true);
|
||||
$first = $data['results'][0] ?? null;
|
||||
|
||||
if (!is_array($first)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$label = (string) ($first['name'] ?? $city);
|
||||
|
||||
if (($first['country'] ?? '') !== '') {
|
||||
$label .= ', ' . $first['country'];
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => $label,
|
||||
'latitude' => (float) ($first['latitude'] ?? 0.0),
|
||||
'longitude' => (float) ($first['longitude'] ?? 0.0),
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user