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:
rsgrinko committed 2026-11-12 18:06:01 +03:00
commit 14fe8d8a5e
22 files changed
+2122

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# Адрес OpenAI-совместимого API (без /chat/completions).
# DeepSeek https://api.deepseek.com
# OpenAI https://api.openai.com/v1
# OpenRouter https://openrouter.ai/api/v1
# Ollama (локально) http://localhost:11434/v1
# llama.cpp http://localhost:8080/v1
AI_BASE_URL=https://api.deepseek.com
# Модель: deepseek-chat / deepseek-flash / deepseek-reasoner / gpt-4o-mini / ...
AI_MODEL=deepseek-chat
# Ключ API. Для Ollama и llama.cpp не нужен — оставьте пустым.
AI_API_KEY=
# Таймаут одного запроса к модели, секунды.
AI_TIMEOUT=30
AI_TEMPERATURE=0.7
AI_MAX_TOKENS=1000
# Только для DeepSeek: отключить «размышления» — быстрее и дешевле.
# Для OpenAI, OpenRouter, Ollama оставьте false: лишнее поле может дать HTTP 400.
AI_DISABLE_THINKING=false
# Проверка TLS-сертификата. true — безопасно, так и должно быть в проде.
# false — только для локальной отладки (например, на Windows у PHP нет CA-бандла).
AI_VERIFY_SSL=true
# Свой CA-бандл (cacert.pem). Пусто — системные сертификаты PHP/OpenSSL.
# Актуально для Windows: скачайте https://curl.se/ca/cacert.pem и укажите путь.
AI_CAINFO=
+7
View File
@@ -0,0 +1,7 @@
# Нормализация переводов строк: в репозитории всегда LF.
* text=auto eol=lf
# Бинарные файлы
*.png binary
*.jpg binary
*.ico binary
+5
View File
@@ -0,0 +1,5 @@
.env
*.log
.idea/
.vscode/
.DS_Store
+286
View File
@@ -0,0 +1,286 @@
# AI SDK — минимальная основа для чата с инструментами
Крошечная PHP-библиотека без зависимостей: диалог с любой OpenAI-совместимой
моделью и **function calling** (вызов инструментов).
```php
$agent = new Agent(AiClient::fromEnv(), $tools);
echo $agent->ask('Который час в Москве и сколько будет 17% от 4300?');
```
Модель сама решит, что ей нужен `get_time` и `calculator`, вызовет их,
получит результаты и ответит. Вам не нужно писать парсеры намерений.
---
## Что внутри
- **`AiClient`** — один HTTP-вызов `/chat/completions` для DeepSeek, OpenAI,
OpenRouter, Ollama, llama.cpp, LM Studio.
- **`Agent`** — цикл вызова инструментов, история диалога, трассировка.
- **`Tool` + `ToolRegistry`** — инструмент = 4 метода; реестр сам отдаёт
схемы модели и вызывает нужный инструмент.
- **`ChatClient`** — интерфейс, чтобы подменить модель заглушкой в тестах.
- **3 готовых инструмента**: `get_time`, `calculator`, `get_weather`.
Без Composer, без фреймворка, без БД. Только PHP и расширение `curl`.
## Требования
- PHP **8.1+** (проверено на 8.3)
- расширение `curl`
- ключ API (или локальная модель)
## Быстрый старт
```bash
# 1. Вписать ключ в .env
# AI_API_KEY=sk-...
# 2. Проверить, что всё работает без сети
php tests/run.php
# 3. Первый запрос к модели
php examples/01-chat.php
```
Дальше — `php examples/02-tools.php`: там модель уже вызывает инструменты.
## Структура
```
bootstrap.php автозагрузка + чтение .env
src/
AiClient.php клиент OpenAI-совместимого API
ChatClient.php интерфейс (для тестов)
ChatResult.php ответ модели: текст, tool_calls, usage
Agent.php цикл: вопрос → инструменты → ответ
Tool.php интерфейс инструмента
ToolRegistry.php набор инструментов
Http.php маленький GET для инструментов
Env.php .env без зависимостей
AiException.php ошибки
tools/
TimeTool.php время в часовом поясе
CalculatorTool.php арифметика без eval()
WeatherTool.php погода через open-meteo.com (без ключа)
examples/
01-chat.php простой вопрос
02-tools.php агент с тремя инструментами
03-custom-tool.php свой инструмент с нуля
04-cli.php интерактивный чат в терминале
tests/run.php тесты без сети
```
## Как это работает
```
вопрос
↓
Agent::ask()
↓ messages + схемы инструментов
AiClient::chat() → модель
↓
есть tool_calls? ── нет ──→ финальный текст
│ да
↓
ToolRegistry::execute(name, args)
↓ результат строкой
messages += {role: tool, tool_call_id, content}
↓
снова chat() ... (до maxRounds)
```
Ключевая деталь: сообщение ассистента с `tool_calls` **обязательно**
добавляется в историю перед результатами инструментов — иначе API отвергнет
запрос. Это уже сделано внутри `Agent`.
Ошибки инструментов не ломают диалог: `ToolRegistry` превращает исключение в
текст, модель видит `Ошибка инструмента "x": ...` и может исправиться.
## Свой инструмент
Четыре метода. Всё.
```php
use AiSdk\Tool;
final class DiceTool implements Tool
{
public function name(): string
{
return 'roll_dice';
}
public function description(): string
{
// Модель читает это и решает, когда звать инструмент.
return 'Бросить кубик с указанным числом граней.';
}
public function parameters(): array
{
// JSON Schema, формат OpenAI function calling.
return [
'type' => 'object',
'properties' => [
'sides' => ['type' => 'integer', 'description' => 'Число граней, по умолчанию 6.'],
],
'required' => [],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$sides = max(2, (int) ($args['sides'] ?? 6));
return 'Выпало: ' . random_int(1, $sides);
}
}
```
Регистрация:
```php
$tools = (new ToolRegistry())->add(new DiceTool(), new TimeTool());
$agent = new Agent(AiClient::fromEnv(), $tools);
```
Советы по описанию: пишите, **когда** инструмент нужен, а не только что он
делает. Модель выбирает по описанию, поэтому «верни курс валют» работает хуже,
чем «курс валют ЦБ на сегодня; вызывай, когда спрашивают про курс доллара».
## Провайдеры
Меняется только `.env`:
| Провайдер | `AI_BASE_URL` | `AI_MODEL` |
|---|---|---|
| DeepSeek | `https://api.deepseek.com` | `deepseek-chat` / `deepseek-flash` |
| OpenAI | `https://api.openai.com/v1` | `gpt-4o-mini` |
| OpenRouter | `https://openrouter.ai/api/v1` | `anthropic/claude-3.5-sonnet` |
| Ollama | `http://localhost:11434/v1` | `qwen2.5:7b` |
| llama.cpp | `http://localhost:8080/v1` | `qwen3-8b` |
У Ollama и llama.cpp `AI_API_KEY` можно оставить пустым.
Не все локальные модели умеют function calling. Если инструменты не
вызываются — проверьте, что модель их поддерживает (qwen2.5/qwen3, llama 3.1+,
mistral-nemo и т.п.).
## Если не подключается
| Ошибка | Причина | Решение |
|---|---|---|
| `SSL certificate problem: unable to get local issuer certificate` | у PHP нет CA-бандла (обычно Windows) | `AI_CAINFO=C:\path\cacert.pem`; быстрый обход — `AI_VERIFY_SSL=false` |
| `Ошибка сети: Connection refused` | сервер не запущен или другой порт | проверить `AI_BASE_URL` (`curl http://host:8080/v1/models`) |
| `HTTP 401` | пустой или неверный ключ | `AI_API_KEY` |
| `HTTP 404` / `model not found` | модель не загружена | `AI_MODEL` = имя из `/v1/models` |
| `HTTP 400 unknown field 'thinking'` | провайдер не DeepSeek | `AI_DISABLE_THINKING=false` |
| Инструменты не вызываются | модель или сборка не умеют tools | qwen3 / llama 3.1+; llama.cpp должен быть с `--jinja` |
Проверить сервер до всякого кода:
```bash
curl http://10.10.10.77:8080/v1/models
```
## Тесты
```bash
php tests/run.php
```
18 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента
(успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель
подменяется `FakeClient` из `tests/run.php`.
## Чего здесь сознательно нет
Это основа, а не фреймворк. Добавляется по месту, когда понадобится:
| Нужно | Куда добавить |
|---|---|
| Повторы при 429/5xx | цикл в `AiClient::chat()` вокруг `post()` |
| Стриминг ответа | `stream: true` + чтение чанков (сложнее, отдельный метод) |
| Логирование запросов в БД | обёртка над `ChatClient` (декоратор), 20 строк |
| Память между запусками | сохранить `$agent->messages()` в JSON/БД |
| Стоимость и токены | уже есть в `ChatResult::$usage` |
| Ограничение частоты | обёртка над `ChatClient` по образцу логгера |
| Роли и права на инструменты | не отдавать часть `ToolRegistry` в `Agent` |
Декоратор — самый полезный приём. Пример логирования без правки SDK:
```php
final class LoggingClient implements ChatClient
{
public function __construct(private ChatClient $inner) {}
public function chat(array $messages, array $tools = []): ChatResult
{
$started = microtime(true);
$result = $this->inner->chat($messages, $tools);
error_log(sprintf('LLM: %d мс, токенов %d', (microtime(true) - $started) * 1000, $result->usage['total_tokens'] ?? 0));
return $result;
}
}
$agent = new Agent(new LoggingClient(AiClient::fromEnv()), $tools);
```
## Безопасность
- **Инструмент выполняет ваш код.** Не давайте модели то, что не дали бы
пользователю: `exec`, запись файлов, SQL, доступ к внутренней сети.
- **Валидируйте аргументы внутри `handle()`** — модель может прислать что
угодно, включая `null` и лишние поля.
- **Обрезайте результаты** — в реестре есть лимит (`maxResultChars`), он
защищает контекст от гигантских ответов.
- **Не отдавайте в `ToolRegistry` больше прав, чем нужно** конкретному сценарию.
- `calculator` считает сам, без `eval()` — не заменяйте на `eval`.
## Шпаргалка по API
```php
// Клиент
$client = AiClient::fromEnv();
$result = $client->chat($messages, $tools = []);
$result->text; $result->toolCalls; $result->usage;
// Агент
$agent = new Agent($client, $tools, $systemPrompt = '...', $maxRounds = 5);
$agent->ask('вопрос'); // string
$agent->trace(); // [{name, arguments, output, ms}]
$agent->messages(); // вся история
$agent->setSystemPrompt('новый промпт'); // на ходу, история сохраняется
$agent->systemPrompt(); // текущий промпт
$agent->reset();
// Реестр
$registry = (new ToolRegistry($maxResultChars = 4000))->add($tool1, $tool2);
$registry->definitions(); // схемы для модели
$registry->execute($name, $args); // string, не бросает исключений
// Инструмент
final class MyTool implements Tool {
public function name(): string;
public function description(): string;
public function parameters(): array;
public function handle(array $args): string;
}
```
## Проверка без модели
Если хочется проверить весь цикл, не тратя токены:
```php
$agent = new Agent($fakeClient, $tools); // ChatClient из tests/run.php
$agent->ask('вопрос');
```
---
Лицензия: делайте что хотите.
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* Точка входа SDK: автозагрузка классов + чтение .env.
*
* Во всех примерах и тестах достаточно одной строки:
* require __DIR__ . '/bootstrap.php';
*/
// Автозагрузка: AiSdk\Tools\* -> tools/, остальное AiSdk\* -> src/.
spl_autoload_register(static function (string $class): void {
$map = [
'AiSdk\\Tools\\' => __DIR__ . '/tools/',
'AiSdk\\' => __DIR__ . '/src/',
];
foreach ($map as $prefix => $dir) {
if (!str_starts_with($class, $prefix)) {
continue;
}
$file = $dir . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
if (is_file($file)) {
require $file;
return;
}
}
});
// .env рядом с bootstrap.php; если файла нет — работаем на значениях по умолчанию.
\AiSdk\Env::load(__DIR__ . '/.env');
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* Пример 1. Простой вопрос к модели — без инструментов.
*
* Запуск:
* php examples/01-chat.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\AiClient;
$client = AiClient::fromEnv();
$result = $client->chat([
['role' => 'system', 'content' => 'Отвечай одним коротким предложением.'],
['role' => 'user', 'content' => 'Что такое MeshCore?'],
]);
echo $result->text . PHP_EOL;
if ($result->usage !== []) {
echo PHP_EOL . 'токены: '
. ($result->usage['prompt_tokens'] ?? 0) . ' → '
. ($result->usage['completion_tokens'] ?? 0) . PHP_EOL;
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/**
* Пример 2. Агент с инструментами.
*
* Модель сама решает, какой инструмент вызвать: время, калькулятор или погоду.
* Мы только регистрируем инструменты и задаём вопрос.
*
* Запуск:
* php examples/02-tools.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\Agent;
use AiSdk\AiClient;
use AiSdk\ToolRegistry;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\TimeTool;
use AiSdk\Tools\WeatherTool;
$tools = new ToolRegistry();
$tools->add(
new TimeTool(),
new CalculatorTool(),
new WeatherTool(),
);
$agent = new Agent(AiClient::fromEnv(), $tools);
$answer = $agent->ask('Который час в Москве? И сколько будет 17% от 4300?');
echo $answer . PHP_EOL;
// Что реально вызывалось — для отладки и логов.
$trace = $agent->trace();
if ($trace !== []) {
echo PHP_EOL . 'Вызовы инструментов:' . PHP_EOL;
foreach ($trace as $step) {
$arguments = json_encode($step['arguments'], JSON_UNESCAPED_UNICODE);
echo ' ' . $step['name'] . '(' . $arguments . ')'
. ' → ' . $step['output']
. ' [' . $step['ms'] . ' мс]' . PHP_EOL;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
/**
* Пример 3. Свой инструмент за 4 метода.
*
* Класс ниже — шаблон: скопируйте, переименуйте и поменяйте name/description/
* parameters/handle. Регистрация — одна строка через $tools->add(...).
*
* Запуск:
* php examples/03-custom-tool.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\Agent;
use AiSdk\AiClient;
use AiSdk\Tool;
use AiSdk\ToolRegistry;
/**
* Инструмент «сведения о сервере».
* Параметр section — необязательный, поэтому модель может его не передавать.
*/
final class ServerInfoTool implements Tool
{
public function name(): string
{
return 'server_info';
}
public function description(): string
{
return 'Сведения о машине, где работает скрипт: версия PHP, ОС, свободное место, лимит памяти.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'section' => [
'type' => 'string',
'enum' => ['php', 'os', 'disk', 'all'],
'description' => 'Что именно вернуть. По умолчанию all.',
],
],
'required' => [],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$section = (string) ($args['section'] ?? 'all');
$lines = [];
if ($section === 'php' || $section === 'all') {
$lines[] = 'PHP ' . PHP_VERSION;
}
if ($section === 'os' || $section === 'all') {
$lines[] = 'ОС: ' . PHP_OS_FAMILY . ' (' . php_uname('m') . ')';
}
if ($section === 'disk' || $section === 'all') {
$free = @disk_free_space(__DIR__);
$lines[] = 'Свободно на диске: ' . ($free === false ? 'нет данных' : $this->human((float) $free));
}
if ($section === 'all') {
$lines[] = 'Лимит памяти: ' . ini_get('memory_limit');
}
return $lines === [] ? 'Неизвестный раздел: ' . $section : implode(PHP_EOL, $lines);
}
private function human(float $bytes): string
{
$units = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ'];
$index = 0;
while ($bytes >= 1024 && $index < count($units) - 1) {
$bytes /= 1024;
$index++;
}
return round($bytes, 1) . ' ' . $units[$index];
}
}
$tools = new ToolRegistry();
$tools->add(new ServerInfoTool());
$agent = new Agent(AiClient::fromEnv(), $tools);
echo $agent->ask('На каком сервере я запускаюсь? Версия PHP и сколько свободного места на диске?') . PHP_EOL;
foreach ($agent->trace() as $step) {
echo PHP_EOL . 'инструмент: ' . $step['name'] . ' ' . json_encode($step['arguments'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
echo $step['output'] . PHP_EOL;
}
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* Пример 4. Интерактивный чат в терминале.
*
* История диалога живёт в памяти процесса: агент помнит предыдущие реплики.
* Команды: /reset — начать заново, /quit — выход.
*
* Запуск:
* php examples/04-cli.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\Agent;
use AiSdk\AiClient;
use AiSdk\ToolRegistry;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\TimeTool;
use AiSdk\Tools\WeatherTool;
$tools = (new ToolRegistry())->add(
new TimeTool(),
new CalculatorTool(),
new WeatherTool(),
);
$agent = new Agent(AiClient::fromEnv(), $tools);
echo "Чат с моделью. /reset — очистить историю, /quit — выход.\n";
while (true) {
echo "\n> ";
$line = fgets(STDIN);
if ($line === false) {
break;
}
$line = trim($line);
if ($line === '') {
continue;
}
if (in_array($line, ['/quit', '/exit', 'exit', 'quit'], true)) {
break;
}
if ($line === '/reset') {
$agent->reset();
echo "история очищена\n";
continue;
}
try {
echo $agent->ask($line) . PHP_EOL;
foreach ($agent->trace() as $step) {
echo ' ↳ ' . $step['name'] . ' → ' . mb_substr($step['output'], 0, 120) . PHP_EOL;
}
} catch (Throwable $e) {
echo 'Ошибка: ' . $e->getMessage() . PHP_EOL;
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace AiSdk;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\TimeTool;
/**
* Диалог с моделью и цикл вызова инструментов.
*
* Ровно один публичный метод для работы:
* $agent->ask('вопрос');
*
* Внутри: отправили вопрос -> модель попросила инструменты -> выполнили ->
* отправили результаты -> получили ответ. И так до maxRounds.
*/
final class Agent
{
private const DEFAULT_SYSTEM_PROMPT = <<<'TXT'
Ты — полезный ассистент. Отвечай кратко и по делу.
Если для ответа нужен факт (время, расчёт, погода и т.п.), сначала вызови подходящий инструмент.
Не выдумывай данные, которые можно получить инструментом.
TXT;
/** @var list<array<string, mixed>> */
private array $messages = [];
/** @var list<array{name: string, arguments: array<string, mixed>, output: string, ms: int}> */
private array $trace = [];
private string $systemPrompt;
public function __construct(
private readonly ChatClient $client,
private readonly ToolRegistry $tools = new ToolRegistry(),
string $systemPrompt = self::DEFAULT_SYSTEM_PROMPT,
private readonly int $maxRounds = 5,
) {
$this->systemPrompt = $systemPrompt;
}
/**
* Сменить системный промпт на ходу.
*
* Если диалог уже начат, обновляется первое system-сообщение — история
* и инструменты при этом сохраняются. Если нет — промпт применится при
* следующем ask().
*/
public function setSystemPrompt(string $systemPrompt): void
{
$this->systemPrompt = $systemPrompt;
if (($this->messages[0]['role'] ?? '') === 'system') {
$this->messages[0]['content'] = $systemPrompt;
}
}
public function systemPrompt(): string
{
return $this->systemPrompt;
}
/**
* Задать вопрос. История диалога сохраняется между вызовами.
*/
public function ask(string $question): string
{
if ($this->messages === []) {
$this->messages[] = ['role' => 'system', 'content' => $this->systemPrompt];
}
$this->messages[] = ['role' => 'user', 'content' => $question];
$result = $this->chat();
$round = 0;
while ($result->hasToolCalls() && $round < $this->maxRounds) {
$round++;
// Сообщение ассистента с tool_calls обязательно: иначе API
// не примет следующие за ним tool-сообщения.
$this->messages[] = $result->assistantMessage;
foreach ($result->toolCalls as $call) {
$started = microtime(true);
$output = $this->tools->execute($call['name'], $call['arguments']);
$this->trace[] = [
'name' => $call['name'],
'arguments' => $call['arguments'],
'output' => $output,
'ms' => (int) round((microtime(true) - $started) * 1000),
];
$this->messages[] = [
'role' => 'tool',
'tool_call_id' => $call['id'],
'content' => $output,
];
}
$result = $this->chat();
}
// Модель зациклилась на инструментах — просим ответить без них.
if ($result->hasToolCalls()) {
$this->messages[] = [
'role' => 'user',
'content' => 'Лимит вызовов инструментов исчерпан. Ответь на вопрос без инструментов.',
];
$result = $this->client->chat($this->messages, []);
}
$text = $result->text !== '' ? $result->text : '(модель вернула пустой ответ)';
$this->messages[] = ['role' => 'assistant', 'content' => $text];
return $text;
}
/**
* Вся история диалога — удобно сохранить в БД или отдать в свой лог.
*
* @return list<array<string, mixed>>
*/
public function messages(): array
{
return $this->messages;
}
/**
* Что реально вызывалось: имя, аргументы, результат, время.
*
* @return list<array{name: string, arguments: array<string, mixed>, output: string, ms: int}>
*/
public function trace(): array
{
return $this->trace;
}
/**
* Начать диалог заново.
*/
public function reset(): void
{
$this->messages = [];
$this->trace = [];
}
private function chat(): ChatResult
{
return $this->client->chat($this->messages, $this->tools->definitions());
}
/**
* Быстрый старт: агент с инструментами по умолчанию.
*/
public static function withDefaults(ChatClient $client): self
{
return new self(
$client,
(new ToolRegistry())->add(new TimeTool(), new CalculatorTool()),
);
}
}
+244
View File
@@ -0,0 +1,244 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Клиент любого OpenAI-совместимого /chat/completions.
*
* Годится для DeepSeek, OpenAI, OpenRouter, Ollama, llama.cpp, LM Studio.
* Меняется только AI_BASE_URL и AI_MODEL в .env.
*/
final class AiClient implements ChatClient
{
/**
* @param array<string, mixed> $extraBody дополнительные поля тела запроса,
* если провайдер их требует
* @param bool $verifySsl проверять TLS-сертификат (по умолчанию да).
* false — только для локальной отладки.
* @param string $caInfo путь к своему CA-бандлу (cacert.pem). Пусто —
* системные сертификаты PHP/OpenSSL.
*/
public function __construct(
private readonly string $apiKey,
private readonly string $model = 'deepseek-chat',
private readonly string $baseUrl = 'https://api.deepseek.com',
private readonly float $timeout = 30.0,
private readonly float $temperature = 0.7,
private readonly int $maxTokens = 1000,
private readonly array $extraBody = [],
private readonly bool $verifySsl = true,
private readonly string $caInfo = '',
) {
}
/**
* Собрать клиент из .env. Все параметры необязательны, кроме ключа
* для закрытых провайдеров.
*/
public static function fromEnv(): self
{
$extraBody = [];
// DeepSeek умеет отключать «размышления» — так ответ быстрее и дешевле.
if (Env::bool('AI_DISABLE_THINKING', false)) {
$extraBody['thinking'] = ['type' => 'disabled'];
}
return new self(
apiKey: Env::get('AI_API_KEY', '') ?? '',
model: Env::get('AI_MODEL', 'deepseek-chat') ?? 'deepseek-chat',
baseUrl: Env::get('AI_BASE_URL', 'https://api.deepseek.com') ?? 'https://api.deepseek.com',
timeout: Env::float('AI_TIMEOUT', 30.0),
temperature: Env::float('AI_TEMPERATURE', 0.7),
maxTokens: Env::int('AI_MAX_TOKENS', 1000),
extraBody: $extraBody,
verifySsl: Env::bool('AI_VERIFY_SSL', true),
caInfo: Env::get('AI_CAINFO', '') ?? '',
);
}
public function chat(array $messages, array $tools = []): ChatResult
{
$body = [
'model' => $this->model,
'messages' => $messages,
'stream' => false,
'temperature' => $this->temperature,
'max_tokens' => $this->maxTokens,
];
if ($tools !== []) {
$body['tools'] = $tools;
$body['tool_choice'] = 'auto';
}
$body = array_merge($body, $this->extraBody);
[$raw, $status, $error] = $this->post($body);
if ($raw === null) {
throw new AiException('Ошибка сети: ' . $error . $this->tlsHint($error));
}
$data = json_decode($raw, true);
if (!is_array($data)) {
throw new AiException(
'Модель вернула не-JSON (HTTP ' . $status . '): ' . mb_substr($raw, 0, 300)
);
}
if ($status >= 400) {
$message = $data['error']['message'] ?? $raw;
throw new AiException('HTTP ' . $status . ': ' . mb_substr((string) $message, 0, 300));
}
$message = $data['choices'][0]['message'] ?? null;
if (!is_array($message)) {
throw new AiException('В ответе нет choices[0].message');
}
$text = is_string($message['content'] ?? null) ? $message['content'] : '';
$assistant = ['role' => 'assistant', 'content' => $text];
if (isset($message['tool_calls'])) {
$assistant['tool_calls'] = $message['tool_calls'];
}
return new ChatResult(
text: $text,
toolCalls: self::parseToolCalls($message),
assistantMessage: $assistant,
usage: is_array($data['usage'] ?? null) ? $data['usage'] : [],
raw: $data,
);
}
/**
* Разобрать tool_calls в удобный вид. Аргументы приходят строкой JSON.
*
* @param array<string, mixed> $message
* @return list<array{id: string, name: string, arguments: array<string, mixed>}>
*/
private static function parseToolCalls(array $message): array
{
$calls = [];
foreach ($message['tool_calls'] ?? [] as $call) {
if (!is_array($call)) {
continue;
}
$name = (string) ($call['function']['name'] ?? '');
if ($name === '') {
continue;
}
$rawArguments = $call['function']['arguments'] ?? '{}';
$arguments = is_string($rawArguments)
? json_decode($rawArguments, true)
: $rawArguments;
if (!is_array($arguments)) {
$arguments = [];
}
$id = (string) ($call['id'] ?? '');
$calls[] = [
'id' => $id !== '' ? $id : 'call_' . bin2hex(random_bytes(6)),
'name' => $name,
'arguments' => $arguments,
];
}
return $calls;
}
/**
* Подсказка при типовой ошибке TLS на Windows.
*/
private function tlsHint(string $error): string
{
if (!$this->verifySsl) {
return '';
}
if (!str_contains($error, 'certificate') && !str_contains($error, 'SSL')) {
return '';
}
return ' Подсказка: укажите путь к корневым сертификатам в AI_CAINFO '
. 'или временно поставьте AI_VERIFY_SSL=false (только локально).';
}
/**
* @param array<string, mixed> $body
* @return array{0: string|null, 1: int, 2: string|null} тело, HTTP-код, ошибка
*/
private function post(array $body): array
{
$url = rtrim($this->baseUrl, '/') . '/chat/completions';
$headers = [
'Content-Type: application/json',
'Accept: application/json',
'Expect:',
];
if ($this->apiKey !== '') {
$headers[] = 'Authorization: Bearer ' . $this->apiKey;
}
$payload = json_encode(
$body,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE
);
if ($payload === false) {
return [null, 0, 'не удалось сериализовать запрос в JSON'];
}
$ch = curl_init($url);
if ($ch === false) {
return [null, 0, 'не удалось создать cURL-дескриптор'];
}
$options = [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT_MS => (int) round($this->timeout * 1000),
CURLOPT_CONNECTTIMEOUT_MS => 5000,
// AI_VERIFY_SSL=false отключает проверку цепочки и имени хоста.
CURLOPT_SSL_VERIFYPEER => $this->verifySsl,
CURLOPT_SSL_VERIFYHOST => $this->verifySsl ? 2 : 0,
CURLOPT_FOLLOWLOCATION => false,
];
// Свой CA-бандл: актуально для Windows, где у PHP нет системных корней.
if ($this->caInfo !== '') {
$options[CURLOPT_CAINFO] = $this->caInfo;
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($raw === false) {
return [null, $status, $error !== '' ? $error : 'неизвестная ошибка cURL'];
}
return [(string) $raw, $status, null];
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Любая ошибка обращения к модели: сеть, HTTP 4xx/5xx, неожиданный ответ.
*/
final class AiException extends \RuntimeException
{
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Минимальный контракт чата. Отдельный интерфейс нужен, чтобы в тестах
* подставить фейковую модель и не ходить в сеть.
*/
interface ChatClient
{
/**
* @param list<array<string, mixed>> $messages история диалога
* @param list<array<string, mixed>> $tools определения в формате OpenAI
*/
public function chat(array $messages, array $tools = []): ChatResult;
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Результат одного ответа модели.
*
* assistantMessage — ровно то, что нужно положить обратно в историю, чтобы
* API принял следующие за ним tool-сообщения.
*/
final class ChatResult
{
/**
* @param list<array{id: string, name: string, arguments: array<string, mixed>}> $toolCalls
* @param array<string, mixed> $assistantMessage
* @param array<string, int> $usage
* @param array<string, mixed> $raw
*/
public function __construct(
public readonly string $text,
public readonly array $toolCalls,
public readonly array $assistantMessage,
public readonly array $usage = [],
public readonly array $raw = [],
) {
}
public function hasToolCalls(): bool
{
return $this->toolCalls !== [];
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Чтение настроек из .env без единой зависимости.
*
* Формат: KEY=VALUE, пустые строки и # - комментарии, значение можно брать
* в кавычки. Уже установленные переменные окружения не перезаписываются.
*/
final class Env
{
public static function load(string $file): void
{
if (!is_file($file)) {
return;
}
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
return;
}
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
continue;
}
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
if (strlen($value) >= 2) {
$quote = $value[0];
if (($quote === '"' || $quote === "'") && str_ends_with($value, $quote)) {
$value = substr($value, 1, -1);
}
}
if ($key !== '' && getenv($key) === false) {
putenv($key . '=' . $value);
}
}
}
public static function get(string $key, ?string $default = null): ?string
{
$value = getenv($key);
return $value === false ? $default : $value;
}
public static function int(string $key, int $default): int
{
$value = self::get($key);
return $value === null || $value === '' ? $default : (int) $value;
}
public static function float(string $key, float $default): float
{
$value = self::get($key);
return $value === null || $value === '' ? $default : (float) $value;
}
public static function bool(string $key, bool $default): bool
{
$value = self::get($key);
if ($value === null || $value === '') {
return $default;
}
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Минимальный HTTP-клиент для инструментов: один GET, таймаут, проверка TLS.
*
* POST не нужен — для инструментов хватает чтения. Если понадобится,
* добавьте рядом метод post() по образцу.
*/
final class Http
{
/**
* @return array{0: int, 1: string} HTTP-код и тело ответа
*/
public static function get(string $url, float $timeout = 10.0): array
{
$ch = curl_init($url);
if ($ch === false) {
throw new AiException('не удалось создать cURL-дескриптор');
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT_MS => (int) round($timeout * 1000),
CURLOPT_CONNECTTIMEOUT_MS => 5000,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'ai-sdk/1.0 (+https://example.local)',
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$body = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($body === false) {
throw new AiException('HTTP-ошибка: ' . ($error !== '' ? $error : 'неизвестно'));
}
return [$status, (string) $body];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Инструмент, который модель может вызвать.
*
* Четыре метода: имя, описание, схема аргументов и сама работа.
* Ничего больше не требуется — реестр сам отдаст схему модели и вызовет handle().
*/
interface Tool
{
/**
* Имя латиницей, snake_case. Именно его модель указывает в tool_calls.
*/
public function name(): string;
/**
* Что делает инструмент и когда его использовать.
* Модель читает это описание и решает, звать ли инструмент.
*/
public function description(): string;
/**
* JSON Schema аргументов в формате OpenAI function calling.
*
* @return array<string, mixed>
*/
public function parameters(): array;
/**
* Выполнить инструмент и вернуть текст для модели.
*
* Бросать исключения не обязательно: ToolRegistry превратит их в текст
* ошибки, и модель сможет исправиться.
*
* @param array<string, mixed> $args
*/
public function handle(array $args): string;
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Набор инструментов: хранит их, отдаёт схемы модели и вызывает по имени.
*/
final class ToolRegistry
{
/** @var array<string, Tool> */
private array $tools = [];
/**
* @param int $maxResultChars обрезка результата, чтобы не раздувать контекст
*/
public function __construct(private readonly int $maxResultChars = 4000)
{
}
public function add(Tool ...$tools): self
{
foreach ($tools as $tool) {
$this->tools[$tool->name()] = $tool;
}
return $this;
}
public function has(string $name): bool
{
return isset($this->tools[$name]);
}
/**
* @return list<Tool>
*/
public function all(): array
{
return array_values($this->tools);
}
/**
* Схемы для поля "tools" запроса к модели.
*
* @return list<array<string, mixed>>
*/
public function definitions(): array
{
$definitions = [];
foreach ($this->tools as $tool) {
$definitions[] = [
'type' => 'function',
'function' => [
'name' => $tool->name(),
'description' => $tool->description(),
'parameters' => $tool->parameters(),
],
];
}
return $definitions;
}
/**
* Выполнить инструмент по имени.
*
* Никогда не бросает исключение: любая проблема становится текстом,
* который модель получит как результат вызова и сможет обойти.
*
* @param array<string, mixed> $arguments
*/
public function execute(string $name, array $arguments): string
{
if (!isset($this->tools[$name])) {
return 'Ошибка: неизвестный инструмент "' . $name . '".';
}
try {
$result = $this->tools[$name]->handle($arguments);
} catch (\Throwable $e) {
return 'Ошибка инструмента "' . $name . '": ' . $e->getMessage();
}
if (mb_strlen($result) > $this->maxResultChars) {
return mb_substr($result, 0, $this->maxResultChars) . '…';
}
return $result;
}
}
+369
View File
@@ -0,0 +1,369 @@
<?php
declare(strict_types=1);
/**
* Тесты SDK: без сети, без модели и без API-ключа.
*
* Модель подменяется FakeClient — он отдаёт заранее заготовленные ответы.
* Именно так удобно тестировать агентов в своих проектах.
*
* Запуск:
* php tests/run.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\Agent;
use AiSdk\ChatClient;
use AiSdk\ChatResult;
use AiSdk\Tool;
use AiSdk\ToolRegistry;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\TimeTool;
mb_internal_encoding('UTF-8');
$passed = 0;
$failed = 0;
function test(string $name, callable $fn): void
{
global $passed, $failed;
try {
$fn();
$passed++;
echo 'ok ' . $name . PHP_EOL;
} catch (Throwable $e) {
$failed++;
echo 'FAIL ' . $name . PHP_EOL . ' ' . $e->getMessage() . PHP_EOL;
}
}
function assertSame(mixed $expected, mixed $actual, string $message = ''): void
{
if ($expected !== $actual) {
throw new RuntimeException(
($message !== '' ? $message . ': ' : '')
. 'ожидалось ' . var_export($expected, true)
. ', получено ' . var_export($actual, true)
);
}
}
function assertTrue(bool $value, string $message = ''): void
{
if (!$value) {
throw new RuntimeException($message !== '' ? $message : 'ожидалось true');
}
}
function assertContains(string $needle, string $haystack, string $message = ''): void
{
if (!str_contains($haystack, $needle)) {
throw new RuntimeException(
($message !== '' ? $message . ': ' : '')
. 'нет "' . $needle . '" в "' . $haystack . '"'
);
}
}
/**
* Модель-заглушка: отдаёт ответы по очереди и запоминает все запросы.
*/
final class FakeClient implements ChatClient
{
/** @var list<array{messages: array<int, mixed>, tools: array<int, mixed>}> */
public array $requests = [];
/**
* @param list<ChatResult> $results
*/
public function __construct(private array $results)
{
}
public function chat(array $messages, array $tools = []): ChatResult
{
$this->requests[] = ['messages' => $messages, 'tools' => $tools];
$result = array_shift($this->results);
if ($result === null) {
throw new RuntimeException('FakeClient: закончились заготовленные ответы');
}
return $result;
}
}
/**
* Ответ «вызови инструмент».
*
* @param array<string, mixed> $arguments
*/
function toolCall(string $name, array $arguments, string $id = 'call_1'): ChatResult
{
$message = [
'role' => 'assistant',
'content' => '',
'tool_calls' => [[
'id' => $id,
'type' => 'function',
'function' => [
'name' => $name,
'arguments' => json_encode($arguments, JSON_UNESCAPED_UNICODE),
],
]],
];
return new ChatResult('', [['id' => $id, 'name' => $name, 'arguments' => $arguments]], $message);
}
function textResult(string $text): ChatResult
{
return new ChatResult($text, [], ['role' => 'assistant', 'content' => $text]);
}
// ---------------------------------------------------------------------------
// Инструменты
// ---------------------------------------------------------------------------
test('calculator: приоритет операций', function (): void {
assertSame('2+2*2 = 6', (new CalculatorTool())->handle(['expression' => '2+2*2']));
});
test('calculator: скобки и степень', function (): void {
assertSame('(1+2)^2 = 9', (new CalculatorTool())->handle(['expression' => '(1+2)^2']));
});
test('calculator: деление даёт дробь', function (): void {
assertSame('10/4 = 2.5', (new CalculatorTool())->handle(['expression' => '10/4']));
});
test('calculator: деление на ноль — понятная ошибка', function (): void {
assertContains('деление на ноль', (new CalculatorTool())->handle(['expression' => '1/0']));
});
test('calculator: буквы не пропускаются', function (): void {
assertContains('Разрешены только', (new CalculatorTool())->handle(['expression' => '2+a']));
});
test('time: возвращает дату в нужном поясе', function (): void {
$result = (new TimeTool())->handle(['timezone' => 'Europe/Moscow']);
assertTrue(
preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S+ \((\p{L}{2})\)$/u', $result) === 1,
'неожиданный формат: ' . $result
);
});
test('time: неизвестный пояс — понятная ошибка', function (): void {
assertContains('Неизвестный часовой пояс', (new TimeTool())->handle(['timezone' => 'Mars/Olympus']));
});
// ---------------------------------------------------------------------------
// Реестр инструментов
// ---------------------------------------------------------------------------
test('реестр: схемы в формате OpenAI tools', function (): void {
$definitions = (new ToolRegistry())->add(new TimeTool(), new CalculatorTool())->definitions();
assertSame(2, count($definitions));
assertSame('function', $definitions[0]['type']);
assertSame('get_time', $definitions[0]['function']['name']);
assertSame('object', $definitions[0]['function']['parameters']['type']);
});
test('реестр: неизвестный инструмент не бросает исключение', function (): void {
$result = (new ToolRegistry())->execute('nope', []);
assertContains('неизвестный инструмент', $result);
});
test('реестр: исключение инструмента превращается в текст', function (): void {
$broken = new class implements Tool {
public function name(): string
{
return 'broken';
}
public function description(): string
{
return 'всегда падает';
}
public function parameters(): array
{
return ['type' => 'object', 'properties' => []];
}
public function handle(array $args): string
{
throw new RuntimeException('сломалось');
}
};
$result = (new ToolRegistry())->add($broken)->execute('broken', []);
assertContains('Ошибка инструмента "broken"', $result);
assertContains('сломалось', $result);
});
test('реестр: длинный результат обрезается', function (): void {
$verbose = new class implements Tool {
public function name(): string
{
return 'verbose';
}
public function description(): string
{
return 'много текста';
}
public function parameters(): array
{
return ['type' => 'object', 'properties' => []];
}
public function handle(array $args): string
{
return str_repeat('x', 100);
}
};
$result = (new ToolRegistry(10))->add($verbose)->execute('verbose', []);
assertSame(11, mb_strlen($result), 'ожидалось 10 символов и многоточие');
});
// ---------------------------------------------------------------------------
// Агент
// ---------------------------------------------------------------------------
test('агент: вызывает инструмент и отдаёт финальный ответ', function (): void {
$client = new FakeClient([
toolCall('calculator', ['expression' => '2+2'], 'call_42'),
textResult('Получилось 4.'),
]);
$agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 3);
$answer = $agent->ask('Сколько будет 2+2?');
assertSame('Получилось 4.', $answer);
assertSame(2, count($client->requests), 'должно быть два запроса к модели');
// Второй запрос обязан содержать результат инструмента.
$messages = $client->requests[1]['messages'];
$last = $messages[count($messages) - 1];
assertSame('tool', $last['role']);
assertSame('call_42', $last['tool_call_id']);
assertSame('2+2 = 4', $last['content']);
// И сами схемы инструментов ушли модели.
assertTrue($client->requests[0]['tools'] !== [], 'схемы инструментов не отправлены');
// Трассировка для отладки.
assertSame(1, count($agent->trace()));
assertSame('calculator', $agent->trace()[0]['name']);
});
test('агент: ошибка инструмента уходит модели, а не в exception', function (): void {
$client = new FakeClient([
toolCall('nope', []),
textResult('Не смог посчитать.'),
]);
$agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3);
$answer = $agent->ask('вопрос');
assertSame('Не смог посчитать.', $answer);
$messages = $client->requests[1]['messages'];
$last = $messages[count($messages) - 1];
assertContains('неизвестный инструмент', $last['content']);
});
test('агент: после лимита раундов просит ответ без инструментов', function (): void {
$client = new FakeClient([
toolCall('calculator', ['expression' => '1+1'], 'c1'),
toolCall('calculator', ['expression' => '1+1'], 'c2'),
toolCall('calculator', ['expression' => '1+1'], 'c3'),
textResult('Два.'),
]);
$agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 2);
assertSame('Два.', $agent->ask('сколько?'));
// 1 стартовый + 2 раунда + 1 финальный.
assertSame(4, count($client->requests));
$lastRequest = $client->requests[3];
assertSame([], $lastRequest['tools'], 'финальный запрос должен идти без инструментов');
});
test('агент: помнит историю между вопросами', function (): void {
$client = new FakeClient([
textResult('Первый ответ.'),
textResult('Второй ответ.'),
]);
$agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3);
$agent->ask('первый вопрос');
$agent->ask('второй вопрос');
$messages = $client->requests[1]['messages'];
$roles = array_column($messages, 'role');
assertSame(['system', 'user', 'assistant', 'user'], $roles);
assertSame('Первый ответ.', $messages[2]['content']);
});
test('агент: системный промпт можно сменить на ходу', function (): void {
$client = new FakeClient([textResult('первый'), textResult('второй')]);
$agent = new Agent($client, new ToolRegistry(), 'промпт №1', 3);
$agent->ask('вопрос');
$agent->setSystemPrompt('промпт №2');
$agent->ask('ещё вопрос');
assertSame('промпт №2', $agent->systemPrompt());
// System-сообщение остаётся первым и в истории, и в запросе к модели.
$messages = $client->requests[1]['messages'];
assertSame('system', $messages[0]['role']);
assertSame('промпт №2', $messages[0]['content']);
// История диалога при этом не потерялась.
assertSame(4, count($messages), 'system + 2 user + assistant');
});
test('агент: без явного промпта берётся встроенный', function (): void {
$agent = new Agent(new FakeClient([textResult('ок')]), new ToolRegistry());
assertTrue($agent->systemPrompt() !== '', 'промпт по умолчанию пустой');
});
test('агент: reset очищает историю и трассировку', function (): void {
$client = new FakeClient([textResult('ответ')]);
$agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3);
$agent->ask('вопрос');
$agent->reset();
assertSame([], $agent->messages());
assertSame([], $agent->trace());
});
// ---------------------------------------------------------------------------
echo PHP_EOL . 'пройдено: ' . $passed . ', провалено: ' . $failed . PHP_EOL;
exit($failed === 0 ? 0 : 1);
+190
View File
@@ -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'), '.');
}
}
+56
View File
@@ -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 . ')';
}
}
+152
View File
@@ -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),
];
}
}