/
chieforik
/
AgroPro
Обзор
Документация
Войти
/
chieforik
/
AgroPro
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
services/GigaChatService.php
173 строки
5 KB
Орловский Александр
Первый
25 сен 2025, 02:26
25 сен 2025, 02:26
1567008
Код
Авторство
О чём код?
<?php namespace app\services; use app\models\GigaChatMessage; use Exception; use GuzzleHttp\Client; use Ramsey\Uuid\Uuid; use Yii; use yii\base\Component; class GigaChatService extends Component { private $lastRequestTime = 0; public $clientId; public $clientSecret; public $scope = 'GIGACHAT_API_PERS'; private $accessToken; private $httpClient; /** * @throws Exception */ public function init(): void { parent::init(); $this->httpClient = new Client(); $this->authenticate(); } /** * Аутентификация и получение токена * @throws Exception */ private function authenticate(): void { $credentials = base64_encode("{$this->clientId}:{$this->clientSecret}"); try { $response = $this->httpClient->post('https://ngw.devices.sberbank.ru:9443/api/v2/oauth', [ 'headers' => [ 'Authorization' => 'Basic ' . $credentials, 'RqUID' => $this->generateUuid(), 'Content-Type' => 'application/x-www-form-urlencoded', ], 'form_params' => [ 'scope' => $this->scope, ], 'verify' => false, // Отключил проверку SSL для тестов ]); $data = json_decode($response->getBody()->getContents(), true); $this->accessToken = $data['access_token']; } catch (Exception $e) { Yii::error('GigaChat authentication error: ' . $e->getMessage()); throw new Exception('Failed to authenticate with GigaChat'); } } /** * Отправка сообщения в GigaChat * @throws Exception */ public function sendMessage($message, $model = 'GigaChat-2-Max') { if (!$this->accessToken) { $this->authenticate(); } try { $response = $this->httpClient->post('https://gigachat.devices.sberbank.ru/api/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->accessToken, 'Content-Type' => 'application/json', ], 'json' => [ 'model' => $model, 'messages' => [ [ 'role' => 'user', 'content' => $message, ] ], 'temperature' => 1, 'top_p' => 0.1, 'n' => 1, 'stream' => false, // 'max_tokens' => 512, 'repetition_penalty' => 1, ], 'verify' => false, ]); $data = json_decode($response->getBody()->getContents(), true); return $data['choices'][0]['message']['content'] ?? 'Нет ответа от GigaChat'; } catch (Exception $e) { Yii::error('GigaChat API error: ' . $e->getMessage()); return 'Error: ' . $e->getMessage(); } } /** * Генерация UUID для запроса */ private function generateUuid(): string { return Uuid::uuid4()->toString(); } /** * Отправка сообщения с сохранением в БД * @throws Exception */ public function sendAndSaveMessage($message, $model = 'GigaChat', $sessionId = null) { $currentTime = time(); if ($currentTime - $this->lastRequestTime < 1) { Yii::warning('Повторный запрос', 'gigachat'); return 'Пожалуйста, подождите перед отправкой следующего сообщения'; } $this->lastRequestTime = $currentTime; if (!$this->accessToken) { $this->authenticate(); } try { $response = $this->httpClient->post('https://gigachat.devices.sberbank.ru/api/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->accessToken, 'Content-Type' => 'application/json', ], 'json' => [ 'model' => $model, 'messages' => [ [ 'role' => 'user', 'content' => $message, ] ], 'temperature' => 1, 'top_p' => 0.1, 'n' => 1, 'stream' => false, 'repetition_penalty' => 1, ], 'verify' => false, ]); $data = json_decode($response->getBody()->getContents(), true); $aiResponse = $data['choices'][0]['message']['content'] ?? 'No response from GigaChat'; // Сохраняем в базу данных GigaChatMessage::saveMessage($message, $aiResponse, $sessionId); return $aiResponse; } catch (Exception $e) { Yii::error('GigaChat API error: ' . $e->getMessage()); // Сохраняем сообщение об ошибке GigaChatMessage::saveMessage($message, 'Error: ' . $e->getMessage(), $sessionId); return 'Error: ' . $e->getMessage(); } } }