Files
crm.clientright.ru/ainew.php

203 lines
6.8 KiB
PHP
Executable File
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
// 🔹 Настройки 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);
?>