File size: 3,911 Bytes
5f32fbd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | <?php
namespace App\Helpers\Classes;
use App\Models\Chatbot\ChatbotData;
use App\Models\Chatbot\ChatbotDataVector;
use Exception;
use Illuminate\Support\Arr;
use OpenAI\Laravel\Facades\OpenAI;
class OpenAiHelper
{
public static function embeddingData($chatbotId, array $data = [], array $trainedData = []): void
{
Helper::setOpenAiKey();
if (! is_array($trainedData)) {
$trainedData = [];
}
$text = '';
foreach ($data as $chatbotDataId => $text) {
if (in_array($chatbotDataId, $trainedData)) {
continue;
}
$trainedData[] = $chatbotDataId;
$page = $text;
if (! mb_check_encoding($text, 'UTF-8')) {
$page = mb_convert_encoding($text, 'UTF-8', mb_detect_encoding($text));
}
$countWords = strlen($page) / 500 + 1;
$meta_index = 1;
for ($i = 0; $i < $countWords; $i++) {
if (500 * $i + 1000 > strlen($page)) {
try {
$subtxt = substr($page, 500 * $i, strlen($page) - 500 * $i);
$subtxt = mb_convert_encoding($subtxt, 'UTF-8', 'UTF-8');
$subtxt = iconv('UTF-8', 'UTF-8//IGNORE', $subtxt);
$response = self::textVector($subtxt);
if (strlen(substr($page, 500 * $i, strlen($page) - 500 * $i)) > 10) {
ChatbotDataVector::query()->create([
'chatbot_id' => $chatbotId,
'chatbot_data_id' => $chatbotDataId,
'content' => substr($page, 500 * $i, strlen($page) - 500 * $i),
'embedding' => $response,
]);
self::trained($chatbotDataId);
$meta_index++;
}
} catch (Exception $e) {
// dd($e->getMessage());
}
} else {
try {
$subtxt = substr($page, 500 * $i, 1000);
$subtxt = mb_convert_encoding($subtxt, 'UTF-8', 'UTF-8');
$subtxt = iconv('UTF-8', 'UTF-8//IGNORE', $subtxt);
$response = self::textVector($subtxt);
if (strlen(substr($page, 500 * $i, 1000)) > 10) {
ChatbotDataVector::query()->create([
'chatbot_id' => $chatbotId,
'chatbot_data_id' => $chatbotDataId,
'content' => substr($page, 500 * $i, 1000),
'embedding' => $response,
]);
self::trained($chatbotDataId);
$meta_index++;
}
} catch (Exception $e) {
// dd($e->getMessage());
}
}
}
}
}
public static function trained($chatbotDataId)
{
ChatbotData::query()->where('id', $chatbotDataId)->update([
'status' => 'trained',
]);
}
public static function textVector($text): ?array
{
$response = OpenAI::embeddings()->create([
'model' => 'text-embedding-ada-002',
'input' => $text,
]);
$embeddings = $response->embeddings;
if (is_array($embeddings)) {
$embedding = Arr::first($embeddings);
if ($embedding && $embedding?->embedding) {
return $embedding->embedding;
}
}
return null;
}
}
|