22
33namespace Borah \KnowledgeBase \Traits ;
44
5+ use Borah \KnowledgeBase \Client \KnowledgeBaseClient ;
56use Borah \KnowledgeBase \DTO \KnowledgeBaseQueryResponse ;
67use Borah \KnowledgeBase \DTO \KnowledgeEmbeddingText ;
78use Borah \KnowledgeBase \DTO \KnowledgeInsertItem ;
89use Borah \KnowledgeBase \Facades \KnowledgeBase ;
910use Illuminate \Database \Eloquent \Model ;
10- use Illuminate \Database \Eloquent \Relations \MorphOne ;
11+ use Illuminate \Database \Eloquent \Relations \MorphMany ;
1112use function Illuminate \Events \queueable ;
1213
1314trait BelongsToKnowledgeBase
@@ -27,33 +28,60 @@ public static function bootBelongsToKnowledgeBase()
2728 }));
2829 }
2930
30- public function knowledgeBaseId (): MorphOne
31+ public function knowledgeBaseChunks (): MorphMany
3132 {
32- return $ this ->morphOne (config ('knowledge_base.models.knowledge_base_id ' ), 'model ' );
33+ return $ this ->morphMany (config ('knowledge_base.models.knowledge_base_chunk ' ), 'model ' );
34+ }
35+
36+ public function knowledgeBasePayload (): array
37+ {
38+ return [];
3339 }
3440
3541 /**
3642 * @return KnowledgeInsertItem[]
3743 */
3844 public function knowledgeInsertItems (): array
3945 {
40- $ knowledgeBaseId = $ this ->knowledgeBaseId ?? $ this ->knowledgeBaseId ()->create ();
4146 $ texts = $ this ->getEmbeddingsTexts ();
42- if (! is_array ($ texts )) {
47+ if (!is_array ($ texts )) {
4348 $ texts = [$ texts ];
4449 }
4550
46- return collect ($ texts )
47- ->map (fn (KnowledgeEmbeddingText $ text ) => new KnowledgeInsertItem (
48- id: $ knowledgeBaseId ->id ,
51+ $ items = [];
52+ $ existingChunks = $ this ->knowledgeBaseChunks ()->get ()->sortBy ('order ' );
53+ foreach ($ texts as $ i => $ text ) {
54+ $ chunk = $ existingChunks [$ i ] ?? $ this ->knowledgeBaseChunks ()->create ([
55+ 'text ' => $ text ->text ,
56+ 'order ' => $ i ,
57+ ]);
58+
59+ if (!$ chunk ->wasRecentlyCreated && $ chunk ->text !== $ text ->text ) {
60+ $ chunk ->update (['text ' => $ text ->text ]);
61+ }
62+
63+ $ items [] = new KnowledgeInsertItem (
64+ id: $ chunk ->id ,
4965 entity: $ text ->entity ,
5066 text: $ text ->text ,
5167 payload: [
52- ...$ this ->toArray (),
68+ ...$ this ->knowledgeBasePayload (),
5369 'original_record_id ' => $ this ->getKey (),
5470 ],
55- ))
56- ->toArray ();
71+ );
72+ }
73+
74+ $ chunksToDelete = $ this ->knowledgeBaseChunks ()
75+ ->where ('order ' , '>= ' , count ($ texts ))
76+ ->select ('id ' , 'order ' )
77+ ->get ();
78+ $ client = new KnowledgeBaseClient ();
79+ foreach ($ chunksToDelete as $ chunk ) {
80+ $ client ->destroy ($ chunk ->id );
81+ $ chunk ->delete ();
82+ }
83+
84+ return $ items ;
5785 }
5886
5987 public static function searchInKnowledgeBase (string $ query , int $ k = 10 , ?array $ where = null ): KnowledgeBaseQueryResponse
0 commit comments