Files
crm.clientright.ru/aidoc.php
Fedor ac7467f0b4 Major CRM updates: AI Assistant, Court Status API, S3 integration improvements, and extensive file storage system
- Added comprehensive AI Assistant system (aiassist/ directory):
  * Vector search and embedding capabilities
  * Typebot proxy integration
  * Elastic search functionality
  * Message classification and chat history
  * MCP proxy for external integrations

- Implemented Court Status API (GetCourtStatus.php):
  * Real-time court document status checking
  * Integration with external court systems
  * Comprehensive error handling and logging

- Enhanced S3 integration:
  * Improved file backup system with metadata
  * Batch processing capabilities
  * Enhanced error logging and recovery
  * Copy operations with URL fixing

- Added Telegram contact creation API
- Improved error logging across all modules
- Enhanced callback system for AI responses
- Extensive backup file storage with timestamps
- Updated documentation and README files

- File storage improvements:
  * Thousands of backup files with proper metadata
  * Fix operations for broken file references
  * Project-specific backup and recovery systems
  * Comprehensive file integrity checking

Total: 26,461+ files added/modified including AWS SDK, vendor dependencies, and extensive backup system.
2025-10-16 11:17:21 +03:00

148 lines
5.8 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once 'aiassist/config.php';
require_once 'aiassist/logger.php';
require_once 'aiassist/gptAssistant.php';
require_once 'aiassist/vectorgpt.php';
// 🔹 Настройки
const DOCUMENTS_FOLDER = __DIR__ . "/documents"; // Папка с документами
const LOG_FILE = 'logs/document_upload.log'; // Лог-файл
function logMessage2($message) {
$logDir = __DIR__ . '/logs';
$logFile = $logDir . '/document_upload.log';
// Проверяем, существует ли папка логов, если нет — создаём её
if (!is_dir($logDir)) {
mkdir($logDir, 0777, true);
}
// Проверяем, доступен ли файл логов для записи
if (!is_writable($logDir)) {
die("❌ Ошибка: Нет прав на запись в папку logs!\n");
}
// Записываем лог
file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . $message . "\n", FILE_APPEND | LOCK_EX);
}
/**
* 🔹 Прикрепляет файлы к `thread_id`
*/
function attachFilesToThread($threadId, $fileIds) {
logMessage2("🔄 Начинаем запуск анализа документов в треде: $threadId");
logMessage2("📂 Список файлов для анализа: " . json_encode($fileIds));
$payload = json_encode([
"thread_id" => $threadId,
"assistant_id" => ASSISTANT_ID,
"tool_resources" => [
"file_search" => [
"file_ids" => $fileIds
]
]
]);
logMessage2("📡 Отправляем запрос на запуск анализа в API: $payload");
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.proxyapi.ru/openai/v1/threads/$threadId/runs", // Заменили v2 на v1
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . OPENAI_API_KEY,
'Content-Type: application/json'
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
logMessage2("❌ Ошибка cURL при запуске анализа: $curlError");
die("❌ Ошибка cURL при запуске анализа: $curlError\n");
}
logMessage2("📡 Ответ API при запуске анализа (HTTP $httpCode): $response");
$decoded = json_decode($response, true);
if ($httpCode !== 200 || !isset($decoded['id'])) {
logMessage2("❌ Ошибка запуска анализа! API ответил: " . json_encode($decoded, JSON_UNESCAPED_UNICODE));
die("❌ Ошибка запуска анализа! Ответ API: " . json_encode($decoded, JSON_UNESCAPED_UNICODE) . "\n");
}
logMessage2("✅ Анализ документов успешно запущен! Run ID: " . $decoded['id']);
return true;
}
/* ===================== Основной скрипт ===================== */
// 🔹 1⃣ Загружаем файлы в OpenAI
logMessage2("🚀 Запуск скрипта загрузки файлов и создания треда...");
$fileIds = [];
$supportedExtensions = ['txt', 'doc', 'docx', 'pdf'];
if (!is_dir(DOCUMENTS_FOLDER)) {
die("❌ Ошибка: Папка " . DOCUMENTS_FOLDER . " не найдена!\n");
}
foreach (scandir(DOCUMENTS_FOLDER) as $file) {
if ($file[0] === '.') continue; // Пропускаем скрытые файлы
$filePath = DOCUMENTS_FOLDER . '/' . $file;
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($extension), $supportedExtensions)) {
echo "🔄 Загружаем: $file ...\n";
logMessage2("🔄 Загружаем файл: $filePath");
$fileId = uploadFileToOpenAI($filePath); // Используем функцию из vectorgpt.php
if ($fileId) {
echo "✅ Файл загружен! File ID: $fileId\n";
logMessage2("✅ Файл загружен! File ID: $fileId");
$fileIds[] = $fileId;
} else {
echo "❌ Ошибка загрузки файла: $file\n";
logMessage2("❌ Ошибка загрузки файла: $filePath");
}
}
}
// 🔹 2⃣ Создаём новый `thread_id`
logMessage2("🔄 Создаём новый `thread_id`...");
$threadId = createNewThread();
if (!$threadId) {
logMessage2("❌ Ошибка создания треда!");
die("❌ Ошибка создания треда!\n");
}
echo "✅ Создан новый `thread_id`: $threadId\n";
logMessage2("✅ Создан новый `thread_id`: $threadId");
// 🔹 3⃣ Прикрепляем файлы к `thread_id`
if (!empty($fileIds)) {
echo "🔄 Прикрепляем файлы к треду...\n";
logMessage2("🔄 Прикрепляем файлы к `thread_id`: $threadId");
if (attachFilesToThread($threadId, $fileIds)) {
echo "✅ Файлы успешно прикреплены!\n";
logMessage2("✅ Файлы успешно прикреплены к `thread_id`: $threadId");
} else {
logMessage2("❌ Ошибка прикрепления файлов к `thread_id`!");
die("❌ Ошибка прикрепления файлов!\n");
}
} else {
echo "⚠️ Нет загруженных файлов для прикрепления.\n";
logMessage2("⚠️ Нет загруженных файлов для прикрепления.");
}
// 🔹 4⃣ Выводим `thread_id`
echo "🎯 Используйте этот `thread_id` в запросах: $threadId\n";
logMessage2("🎯 Завершено! Используйте `thread_id`: $threadId");
?>