Files
crm.clientright.ru/newai.php

166 lines
5.3 KiB
PHP
Executable File
Raw 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);
?>