Files
crm.clientright.ru/newai.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

166 lines
5.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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
// 🔹 Настройки API OpenAI
const OPENAI_API_KEY = 'sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY';
const OPENAI_ASSISTANT_API = 'https://api.proxyapi.ru/openai/v1/assistants';
const OPENAI_FILES_API = 'https://api.proxyapi.ru/openai/v1/files';
// 🔹 Функция создания ассистента с File Search
function createAssistant($assistantName, $instructions) {
echo "🚀 Создаём ассистента `$assistantName`...\n";
$data = [
"name" => $assistantName,
"instructions" => $instructions,
"model" => "gpt-4-turbo",
"tools" => [
["type" => "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;
}
}
// 🔹 Получение файлов из папки
function getFilesFromDirectory($directory) {
$supportedExtensions = ['txt', 'pdf', 'doc', 'docx'];
$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;
}
// 🔹 Функция загрузки файла в 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;
}
// 🔹 Функция привязки файлов к ассистенту
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";
}
// 🔹 Основная функция
function setupAssistantWithFiles($directory) {
$assistantName = "Legal AI";
$instructions = "Ты юридический ассистент. Используй загруженные файлы как базу знаний.";
// 🔹 Создаём ассистента
$assistantId = createAssistant($assistantName, $instructions);
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);
?>