- 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.
170 lines
5.7 KiB
PHP
170 lines
5.7 KiB
PHP
<?php
|
||
// 🔹 Настройки API OpenAI
|
||
const OPENAI_API_KEY = 'sk-NsasXO7IPLdzUSNaAy64R3EBveyIZNfIV3PaOEq5_WT3BlbkFJWTivsJpMK1J2YPfVDSMCrU6hQMxwEy64RktHVWEvEA';
|
||
const OPENAI_ASSISTANT_API = 'https://api.openai.com/v1/assistants';
|
||
const OPENAI_FILES_API = 'https://api.openai.com/v1/files';
|
||
|
||
// 🔹 Модель ассистента
|
||
const ASSISTANT_MODEL = 'gpt-4.1-mini';
|
||
|
||
// 🔹 Функция создания ассистента с File Search
|
||
function createAssistant(string $assistantName, string $instructions): ?string {
|
||
echo "🚀 Создаём ассистента «{$assistantName}»...\n";
|
||
|
||
$data = [
|
||
"name" => $assistantName,
|
||
"instructions" => $instructions,
|
||
"model" => ASSISTANT_MODEL,
|
||
"tools" => [
|
||
["type" => "file_search"]
|
||
]
|
||
];
|
||
|
||
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
|
||
|
||
$curl = curl_init(OPENAI_ASSISTANT_API);
|
||
curl_setopt_array($curl, [
|
||
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);
|
||
|
||
$decoded = json_decode($response, true);
|
||
if (!empty($decoded['id'])) {
|
||
echo "✅ Ассистент создан, ID: " . $decoded['id'] . "\n";
|
||
return $decoded['id'];
|
||
}
|
||
|
||
echo "❌ Ошибка создания ассистента: " . ($decoded['error']['message'] ?? json_encode($decoded)) . "\n";
|
||
return null;
|
||
}
|
||
|
||
// 🔹 Получение списка файлов из директории
|
||
function getFilesFromDirectory(string $directory): array {
|
||
$supported = ['txt','pdf','doc','docx'];
|
||
$files = [];
|
||
|
||
if (!is_dir($directory)) {
|
||
echo "❌ Директория не найдена: {$directory}\n";
|
||
return $files;
|
||
}
|
||
|
||
foreach (scandir($directory) as $file) {
|
||
if (in_array($file, ['.','..'], true)) continue;
|
||
$path = realpath("{$directory}/{$file}");
|
||
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
||
if (is_file($path) && in_array($ext, $supported, true)) {
|
||
$files[] = $path;
|
||
} else {
|
||
echo "⚠️ Пропущен неподдерживаемый файл: {$path}\n";
|
||
}
|
||
}
|
||
|
||
return $files;
|
||
}
|
||
|
||
// 🔹 Загрузка файла в OpenAI
|
||
function uploadFileToOpenAI(string $filePath): ?string {
|
||
echo "📂 Загружаем файл: {$filePath}\n";
|
||
|
||
$curl = curl_init(OPENAI_FILES_API);
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_POST => true,
|
||
CURLOPT_HTTPHEADER => [
|
||
'Authorization: Bearer ' . OPENAI_API_KEY,
|
||
'OpenAI-Beta: assistants=v2'
|
||
],
|
||
CURLOPT_POSTFIELDS => [
|
||
'file' => new CURLFile($filePath),
|
||
'purpose' => 'assistants'
|
||
],
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
curl_close($curl);
|
||
|
||
$decoded = json_decode($response, true);
|
||
if (!empty($decoded['id'])) {
|
||
return $decoded['id'];
|
||
}
|
||
|
||
echo "❌ Ошибка загрузки файла: " . ($decoded['error']['message'] ?? json_encode($decoded)) . "\n";
|
||
return null;
|
||
}
|
||
|
||
// 🔹 Привязка загруженных файлов к ассистенту
|
||
function attachFilesToAssistant(string $assistantId, array $fileIds): void {
|
||
echo "📡 Привязываем файлы к ассистенту {$assistantId}...\n";
|
||
|
||
$payload = json_encode([
|
||
"tool_resources" => [
|
||
"file_search" => ["file_ids" => $fileIds]
|
||
]
|
||
], JSON_UNESCAPED_UNICODE);
|
||
|
||
$curl = curl_init(OPENAI_ASSISTANT_API . "/{$assistantId}");
|
||
curl_setopt_array($curl, [
|
||
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";
|
||
}
|
||
|
||
// 🔹 Основная функция: создаём ассистента и загружаем файлы
|
||
function setupAssistantWithFiles(string $directory): void {
|
||
$assistantName = "Clientright";
|
||
$instructions = "Ты юридический аналитик. Проанализируй материалы согласно инструкции.";
|
||
|
||
// Создаём ассистента
|
||
$assistantId = createAssistant($assistantName, $instructions);
|
||
if (!$assistantId) {
|
||
exit("❌ Не удалось создать ассистента.\n");
|
||
}
|
||
|
||
// Получаем файлы из директории
|
||
$files = getFilesFromDirectory($directory);
|
||
if (empty($files)) {
|
||
exit("❌ В директории '{$directory}' нет поддерживаемых файлов.\n");
|
||
}
|
||
|
||
// Загружаем каждый файл
|
||
$uploadedIds = [];
|
||
foreach ($files as $filePath) {
|
||
$fileId = uploadFileToOpenAI($filePath);
|
||
if ($fileId) {
|
||
$uploadedIds[] = $fileId;
|
||
}
|
||
}
|
||
|
||
// Привязываем файлы к ассистенту
|
||
if (!empty($uploadedIds)) {
|
||
attachFilesToAssistant($assistantId, $uploadedIds);
|
||
}
|
||
|
||
echo "🎉 Ассистент готов к работе!\n";
|
||
}
|
||
|
||
// 📌 Укажите папку с вашими документами
|
||
$directory = __DIR__ . '/documents';
|
||
|
||
// 🚀 Запускаем процесс
|
||
setupAssistantWithFiles($directory);
|