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