- 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.
203 lines
6.8 KiB
PHP
203 lines
6.8 KiB
PHP
<?php
|
||
|
||
// 🔹 Настройки API OpenAI
|
||
const OPENAI_API_KEY = 'sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY'; // Укажите свой API-ключ
|
||
const OPENAI_ASSISTANT_API = 'https://api.proxyapi.ru/openai/v1/assistants';
|
||
const OPENAI_VECTOR_STORES_API = 'https://api.proxyapi.ru/openai/v1/vector_stores';
|
||
const OPENAI_FILES_API = 'https://api.proxyapi.ru/openai/v1/files';
|
||
|
||
|
||
// 🔹 1️⃣ Создаём `Vector Store`, если его ещё нет
|
||
function createVectorStore() {
|
||
echo "🚀 Создаём Vector Store для хранения документов...\n";
|
||
|
||
$curl = curl_init();
|
||
$payload = json_encode(["name" => "Clientright_Legal_Vector_Store"]);
|
||
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => OPENAI_VECTOR_STORES_API,
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_POST => true,
|
||
CURLOPT_POSTFIELDS => $payload,
|
||
CURLOPT_HTTPHEADER => [
|
||
'Content-Type: application/json',
|
||
'Authorization: Bearer ' . OPENAI_API_KEY,
|
||
'OpenAI-Beta: assistants=v2'
|
||
]
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
curl_close($curl);
|
||
|
||
$decoded = json_decode($response, true);
|
||
if (isset($decoded['id'])) {
|
||
echo "✅ Vector Store создан: " . $decoded['id'] . "\n";
|
||
return $decoded['id'];
|
||
} else {
|
||
echo "❌ Ошибка создания Vector Store: " . json_encode($decoded, JSON_UNESCAPED_UNICODE) . "\n";
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 🔹 2️⃣ Создаём ассистента, БЕЗ `vector_store_search`, но с `file_search`
|
||
function createAssistant($prompt) {
|
||
echo "🚀 Создаём ассистента...\n";
|
||
|
||
$data = [
|
||
"name" => "Clientright Legal Assistant2",
|
||
"instructions" => $prompt,
|
||
"model" => "gpt-4-turbo",
|
||
"tools" => [
|
||
["type" => "file_search"] // Только `file_search`
|
||
]
|
||
];
|
||
|
||
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
|
||
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => OPENAI_ASSISTANT_API,
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_POST => true,
|
||
CURLOPT_POSTFIELDS => $body,
|
||
CURLOPT_HTTPHEADER => [
|
||
'Content-Type: application/json',
|
||
'Authorization: Bearer ' . OPENAI_API_KEY,
|
||
'OpenAI-Beta: assistants=v2'
|
||
]
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
curl_close($curl);
|
||
|
||
$decodedResponse = json_decode($response, true);
|
||
if (isset($decodedResponse['id'])) {
|
||
echo "✅ Ассистент создан: " . $decodedResponse['id'] . "\n";
|
||
return $decodedResponse['id'];
|
||
} else {
|
||
echo "❌ Ошибка создания ассистента: " . json_encode($decodedResponse, JSON_UNESCAPED_UNICODE) . "\n";
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 🔹 3️⃣ Получаем все файлы из папки
|
||
function getFilesFromDirectory($directory) {
|
||
$supportedExtensions = ['txt', 'pdf', 'doc', 'docx', 'csv', 'xlsx', 'pptx', 'json', 'xml']; // Только поддерживаемые форматы
|
||
$files = [];
|
||
|
||
if (is_dir($directory)) {
|
||
foreach (scandir($directory) as $file) {
|
||
if ($file !== '.' && $file !== '..') {
|
||
$filePath = realpath($directory . DIRECTORY_SEPARATOR . $file);
|
||
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
|
||
|
||
if (is_file($filePath) && in_array($extension, $supportedExtensions)) {
|
||
$files[] = $filePath;
|
||
} else {
|
||
echo "⚠️ Пропущен неподдерживаемый файл: $filePath\n";
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return $files;
|
||
}
|
||
|
||
// 🔹 4️⃣ Загружаем файлы в OpenAI
|
||
function uploadFileToOpenAI($filePath) {
|
||
echo "📂 Загружаем файл: $filePath\n";
|
||
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => OPENAI_FILES_API,
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_POST => true,
|
||
CURLOPT_POSTFIELDS => [
|
||
'file' => new CURLFile($filePath),
|
||
'purpose' => 'assistants'
|
||
],
|
||
CURLOPT_HTTPHEADER => [
|
||
'Authorization: Bearer ' . OPENAI_API_KEY,
|
||
'OpenAI-Beta: assistants=v2'
|
||
]
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
curl_close($curl);
|
||
|
||
$decoded = json_decode($response, true);
|
||
return $decoded['id'] ?? null;
|
||
}
|
||
|
||
// 🔹 5️⃣ Привязываем файлы к ассистенту
|
||
function attachFilesToAssistant($assistantId, $fileIds) {
|
||
echo "📡 Привязываем файлы к ассистенту $assistantId...\n";
|
||
|
||
$payload = json_encode([
|
||
"tool_resources" => [
|
||
"file_search" => ["file_ids" => $fileIds]
|
||
]
|
||
]);
|
||
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => OPENAI_ASSISTANT_API . "/$assistantId",
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_CUSTOMREQUEST => "POST",
|
||
CURLOPT_POSTFIELDS => $payload,
|
||
CURLOPT_HTTPHEADER => [
|
||
'Content-Type: application/json',
|
||
'Authorization: Bearer ' . OPENAI_API_KEY
|
||
]
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
curl_close($curl);
|
||
|
||
echo "✅ Файлы привязаны к ассистенту.\n";
|
||
}
|
||
|
||
// 🔹 6️⃣ Основная функция: создаём ассистента, загружаем файлы и привязываем их к нему
|
||
function setupAssistantWithFiles($directory) {
|
||
$vectorStoreId = createVectorStore();
|
||
if (!$vectorStoreId) {
|
||
die("❌ Ошибка создания Vector Store\n");
|
||
}
|
||
|
||
$prompt = "🔹 **Юридический анализ документов**
|
||
- Проанализируй загруженные документы и судебные решения.
|
||
- Оцени вероятность успешного исхода дела.
|
||
- Выяви основные правовые нормы и риски.";
|
||
|
||
$assistantId = createAssistant($prompt);
|
||
if (!$assistantId) {
|
||
die("❌ Ошибка создания ассистента\n");
|
||
}
|
||
|
||
$filesToUpload = getFilesFromDirectory($directory);
|
||
if (empty($filesToUpload)) {
|
||
die("❌ В папке нет файлов для загрузки\n");
|
||
}
|
||
|
||
$uploadedFileIds = [];
|
||
foreach ($filesToUpload as $filePath) {
|
||
$fileId = uploadFileToOpenAI($filePath);
|
||
if ($fileId) {
|
||
$uploadedFileIds[] = $fileId;
|
||
}
|
||
}
|
||
|
||
if (!empty($uploadedFileIds)) {
|
||
attachFilesToAssistant($assistantId, $uploadedFileIds);
|
||
}
|
||
|
||
echo "🎉 Ассистент создан, файлы загружены и привязаны к OpenAI!\n";
|
||
}
|
||
|
||
// 📌 Указываем папку с документами
|
||
$directory = "documents";
|
||
|
||
// 🚀 Запускаем процесс
|
||
setupAssistantWithFiles($directory);
|
||
|
||
?>
|