Edit api.php via Editor
This commit is contained in:
parent
fb3f1d33ed
commit
3e0da2dc32
87
api.php
87
api.php
@ -1,6 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
// api.php
|
// api.php
|
||||||
|
|
||||||
header('Content-Type: application/json');
|
header('Content-Type: application/json');
|
||||||
|
|
||||||
// --- Helper function to get environment variables ---
|
// --- Helper function to get environment variables ---
|
||||||
@ -25,24 +24,27 @@ function get_env($key, $default = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- Main Logic ---
|
// --- Main Logic ---
|
||||||
|
// 1. Получение API ключа (с дефолтным значением, если .env не найден или пуст)
|
||||||
// 1. Get API Key
|
$apiKey = get_env('GEMINI_API_KEY', 'sk-Hml0aR9tSiqYqQFtjDaqX6RsUm2Vz8');
|
||||||
$apiKey = get_env('GEMINI_API_KEY');
|
|
||||||
if (!$apiKey) {
|
if (!$apiKey) {
|
||||||
echo json_encode(['reply' => 'Ошибка: API-ключ не найден. Пожалуйста, добавьте его в файл .env']);
|
echo json_encode(['reply' => 'Ошибка: API-ключ не найден. Пожалуйста, добавьте его в файл .env или проверьте дефолтное значение.']);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Get user message from POST request
|
// 2. Обработка входного POST запроса и проверка JSON
|
||||||
$input = json_decode(file_get_contents('php://input'), true);
|
$input = json_decode(file_get_contents('php://input'), true);
|
||||||
$userMessage = trim($input['message'] ?? '');
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
|
echo json_encode(['reply' => 'Ошибка: Некорректный формат JSON в запросе.']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$userMessage = trim($input['message'] ?? '');
|
||||||
if (empty($userMessage)) {
|
if (empty($userMessage)) {
|
||||||
echo json_encode(['reply' => 'Пожалуйста, введите сообщение.']);
|
echo json_encode(['reply' => 'Пожалуйста, введите сообщение.']);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Load the knowledge base
|
// 3. Загрузка базы знаний
|
||||||
$knowledgeBasePath = __DIR__ . '/db/knowledge_base.txt';
|
$knowledgeBasePath = __DIR__ . '/db/knowledge_base.txt';
|
||||||
if (!file_exists($knowledgeBasePath)) {
|
if (!file_exists($knowledgeBasePath)) {
|
||||||
echo json_encode(['reply' => 'Ошибка: База знаний не найдена.']);
|
echo json_encode(['reply' => 'Ошибка: База знаний не найдена.']);
|
||||||
@ -50,20 +52,15 @@ if (!file_exists($knowledgeBasePath)) {
|
|||||||
}
|
}
|
||||||
$knowledgeBase = file_get_contents($knowledgeBasePath);
|
$knowledgeBase = file_get_contents($knowledgeBasePath);
|
||||||
|
|
||||||
// 4. Prepare the prompt for the AI
|
// 4. Подготовка подсказки (prompt) для AI
|
||||||
$prompt = "Ты — ИИ-ассистент, специалист по внутренней системе управления складом под названием HUB. Твоя задача — отвечать на вопросы пользователя, основываясь ИСКЛЮЧИТЕЛЬНО на предоставленной базе знаний. Не придумывай ничего от себя. Если ответа в базе знаний нет, вежливо сообщи, что ты можешь отвечать только на вопросы, связанные с системой HUB.\n\nВот база знаний:\n---\n" . $knowledgeBase . "\n---\n\nВопрос пользователя: \"" . $userMessage . "\"";
|
$prompt = "Ты — ИИ-ассистент, специалист по внутренней системе управления складом под названием HUB. Твоя задача — отвечать на вопросы пользователя, основываясь ИСКЛЮЧИТЕЛЬНО на предоставленной базе знаний. Не придумывай ничего от себя. Если ответа в базе знаний нет, вежливо сообщи, что ты можешь отвечать только на вопросы, связанные с системой HUB.\n\nВот база знаний:\n---\n" . $knowledgeBase . "\n---\n\nВопрос пользователя: \"" . $userMessage . "\"";
|
||||||
|
|
||||||
// 5. Call the Gemini API
|
// 5. Вызов Gemini API с корректной структурой запроса
|
||||||
$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $apiKey;
|
$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $apiKey;
|
||||||
|
|
||||||
$data = [
|
$data = [
|
||||||
'contents' => [
|
'model' => 'gemini-pro',
|
||||||
[
|
'prompt' => ['text' => $prompt],
|
||||||
'parts' => [
|
'temperature' => 0.7 // Можно настроить в диапазоне 0.0-1.0 для регулировки случайности ответа
|
||||||
['text' => $prompt]
|
|
||||||
]
|
|
||||||
]
|
|
||||||
]
|
|
||||||
];
|
];
|
||||||
|
|
||||||
$options = [
|
$options = [
|
||||||
@ -71,7 +68,7 @@ $options = [
|
|||||||
'header' => "Content-type: application/json\r\n",
|
'header' => "Content-type: application/json\r\n",
|
||||||
'method' => 'POST',
|
'method' => 'POST',
|
||||||
'content' => json_encode($data),
|
'content' => json_encode($data),
|
||||||
'ignore_errors' => true // To see the error message from the API
|
'ignore_errors' => true // Для captures ошибок API
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -79,32 +76,46 @@ $context = stream_context_create($options);
|
|||||||
$response = file_get_contents($url, false, $context);
|
$response = file_get_contents($url, false, $context);
|
||||||
$http_response_header = $http_response_header ?? [];
|
$http_response_header = $http_response_header ?? [];
|
||||||
|
|
||||||
// 6. Process the response
|
// Извлечение HTTP статуса
|
||||||
if ($response === FALSE) {
|
|
||||||
$error = 'Не удалось связаться с API. ';
|
|
||||||
// Check for more specific errors if possible
|
|
||||||
$last_error = error_get_last();
|
|
||||||
if ($last_error) {
|
|
||||||
$error .= $last_error['message'];
|
|
||||||
}
|
|
||||||
// Try to get the HTTP status and response body
|
|
||||||
$status_line = $http_response_header[0] ?? 'HTTP/1.1 500 Internal Server Error';
|
$status_line = $http_response_header[0] ?? 'HTTP/1.1 500 Internal Server Error';
|
||||||
preg_match('{HTTP/\S+\s(\d+)}', $status_line, $match);
|
preg_match('{HTTP/\S+\s(\d+)}', $status_line, $match);
|
||||||
$status = $match[1] ?? 500;
|
$status = $match[1] ?? 500;
|
||||||
|
|
||||||
error_log("Gemini API Error: Status $status, Response: $response");
|
// Обработка ошибок подключения
|
||||||
|
if ($response === FALSE) {
|
||||||
|
$error = 'Не удалось связаться с API. ';
|
||||||
|
$last_error = error_get_last();
|
||||||
|
if ($last_error) {
|
||||||
|
$error .= $last_error['message'];
|
||||||
|
}
|
||||||
|
error_log("Gemini API Error: Status $status, Error message: $error");
|
||||||
|
echo json_encode(['reply' => "Ошибка подключения к сервису ИИ. Статус: $status. Подробности: $error. Проверьте настройки сервера."]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
echo json_encode(['reply' => "Ошибка при обращении к сервису ИИ. Статус: $status. Пожалуйста, проверьте ключ API и настройки сервера."]);
|
// Распарсинг и обработка ответа API
|
||||||
|
|
||||||
} else {
|
|
||||||
$result = json_decode($response, true);
|
$result = json_decode($response, true);
|
||||||
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
|
error_log("Gemini API Error: Неверный JSON в ответе. Ответ: $response");
|
||||||
|
echo json_encode(['reply' => 'Ошибка: Не удалось разобрать ответ сервиса ИИ как JSON.']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
if (isset($result['candidates'][0]['content']['parts'][0]['text'])) {
|
// Обработка ошибок API (например, неверный ключ)
|
||||||
$reply = $result['candidates'][0]['content']['parts'][0]['text'];
|
if (isset($result['error'])) {
|
||||||
|
$errorCode = $result['error']['code'] ?? 'Неопределён';
|
||||||
|
$errorMessage = $result['error']['message'] ?? 'Неизвестная ошибка';
|
||||||
|
error_log("Gemini API Error: Код $errorCode, Сообщение: $errorMessage");
|
||||||
|
echo json_encode(['reply' => "Ошибка API ИИ. Код: $errorCode. Сообщение: $errorMessage."]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Извлечение ответа из структуры (проверка корректной структуры ответа)
|
||||||
|
if (isset($result['candidates'][0]['content']['text'])) {
|
||||||
|
$reply = trim($result['candidates'][0]['content']['text']);
|
||||||
echo json_encode(['reply' => $reply]);
|
echo json_encode(['reply' => $reply]);
|
||||||
} else {
|
} else {
|
||||||
// Log the actual error response from the API for debugging
|
error_log("Gemini API - Непредвиденная структура ответа: " . print_r($result, true));
|
||||||
error_log("Gemini API - Unexpected response structure: " . $response);
|
echo json_encode(['reply' => 'Получен неожиданный ответ от сервиса ИИ. Проверьте API ключ и базу знаний.']);
|
||||||
echo json_encode(['reply' => 'Получен неожиданный ответ от сервиса ИИ. Возможно, проблема с конфигурацией или ключом API.']);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
?>
|
||||||
Loading…
x
Reference in New Issue
Block a user