-
Notifications
You must be signed in to change notification settings - Fork 0
/
OchaAiChat.php
1548 lines (1381 loc) · 51.2 KB
/
OchaAiChat.php
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Drupal\ocha_ai_chat\Services;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Database\Connection;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\State\StateInterface;
use Drupal\ocha_ai\Helpers\VectorHelper;
use Drupal\ocha_ai\Plugin\AnswerValidatorPluginInterface;
use Drupal\ocha_ai\Plugin\AnswerValidatorPluginManagerInterface;
use Drupal\ocha_ai\Plugin\CompletionPluginInterface;
use Drupal\ocha_ai\Plugin\CompletionPluginManagerInterface;
use Drupal\ocha_ai\Plugin\EmbeddingPluginInterface;
use Drupal\ocha_ai\Plugin\EmbeddingPluginManagerInterface;
use Drupal\ocha_ai\Plugin\RankerPluginInterface;
use Drupal\ocha_ai\Plugin\RankerPluginManagerInterface;
use Drupal\ocha_ai\Plugin\SourcePluginInterface;
use Drupal\ocha_ai\Plugin\SourcePluginManagerInterface;
use Drupal\ocha_ai\Plugin\TextExtractorPluginInterface;
use Drupal\ocha_ai\Plugin\TextExtractorPluginManagerInterface;
use Drupal\ocha_ai\Plugin\TextSplitterPluginInterface;
use Drupal\ocha_ai\Plugin\TextSplitterPluginManagerInterface;
use Drupal\ocha_ai\Plugin\VectorStorePluginInterface;
use Drupal\ocha_ai\Plugin\VectorStorePluginManagerInterface;
use GuzzleHttp\ClientInterface;
use Psr\Log\LoggerInterface;
/**
* OCHA AI Chat service.
*/
class OchaAiChat {
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected ConfigFactoryInterface $configFactory;
/**
* The logger service.
*
* @var \Psr\Log\LoggerInterface
*/
protected LoggerInterface $logger;
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected StateInterface $state;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected AccountProxyInterface $currentUser;
/**
* The database.
*
* @var \Drupal\Core\Database\Connection
*/
protected Connection $database;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected TimeInterface $time;
/**
* The HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected ClientInterface $httpClient;
/**
* Answer validator plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\AnswerValidatorPluginManagerInterface
*/
protected AnswerValidatorPluginManagerInterface $answerValidatorPluginManager;
/**
* Completion plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\CompletionPluginManagerInterface
*/
protected CompletionPluginManagerInterface $completionPluginManager;
/**
* Embedding plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\EmbeddingPluginManagerInterface
*/
protected EmbeddingPluginManagerInterface $embeddingPluginManager;
/**
* Ranker plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\RankerPluginManagerInterface
*/
protected RankerPluginManagerInterface $rankerPluginManager;
/**
* Source plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\SourcePluginManagerInterface
*/
protected SourcePluginManagerInterface $sourcePluginManager;
/**
* Text extractor plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\TextExtractorPluginManagerInterface
*/
protected TextExtractorPluginManagerInterface $textExtractorPluginManager;
/**
* Text splitter plugin manager.
*
* @var \Drupal\ocha_ai\Plugin\TextSplitterPluginManagerInterface
*/
protected TextSplitterPluginManagerInterface $textSplitterPluginManager;
/**
* Vector store manager.
*
* @var \Drupal\ocha_ai\Plugin\VectorStorePluginManagerInterface
*/
protected VectorStorePluginManagerInterface $vectorStorePluginManager;
/**
* Static cache for the settings.
*
* @var array
*/
protected array $settings;
/**
* Constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory service.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
* The logger factory service.
* @param \Drupal\Core\State\StateInterface $state
* The state service.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* The current user.
* @param \Drupal\Core\Database\Connection $database
* The database.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \GuzzleHttp\ClientInterface $http_client
* The HTTP client service.
* @param \Drupal\ocha_ai_chat\Plugin\AnswerValidatorPluginManagerInterface $answer_validator_plugin_manager
* The answer validator plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\CompletionPluginManagerInterface $completion_plugin_manager
* The completion plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\EmbeddingPluginManagerInterface $embedding_plugin_manager
* The embedding plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\RankerPluginManagerInterface $ranker_plugin_manager
* The ranker plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\SourcePluginManagerInterface $source_plugin_manager
* The source plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\TextExtractorPluginManagerInterface $text_extractor_plugin_manager
* The text extractor plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\TextSplitterPluginManagerInterface $text_splitter_plugin_manager
* The text splitter plugin manager.
* @param \Drupal\ocha_ai_chat\Plugin\VectorStorePluginManagerInterface $vector_store_plugin_manager
* The vector store plugin manager.
*/
public function __construct(
ConfigFactoryInterface $config_factory,
LoggerChannelFactoryInterface $logger_factory,
StateInterface $state,
AccountProxyInterface $current_user,
Connection $database,
TimeInterface $time,
ClientInterface $http_client,
AnswerValidatorPluginManagerInterface $answer_validator_plugin_manager,
CompletionPluginManagerInterface $completion_plugin_manager,
EmbeddingPluginManagerInterface $embedding_plugin_manager,
RankerPluginManagerInterface $ranker_plugin_manager,
SourcePluginManagerInterface $source_plugin_manager,
TextExtractorPluginManagerInterface $text_extractor_plugin_manager,
TextSplitterPluginManagerInterface $text_splitter_plugin_manager,
VectorStorePluginManagerInterface $vector_store_plugin_manager,
) {
$this->configFactory = $config_factory;
$this->logger = $logger_factory->get('ocha_ai_chat');
$this->state = $state;
$this->currentUser = $current_user;
$this->database = $database;
$this->time = $time;
$this->httpClient = $http_client;
$this->answerValidatorPluginManager = $answer_validator_plugin_manager;
$this->completionPluginManager = $completion_plugin_manager;
$this->embeddingPluginManager = $embedding_plugin_manager;
$this->rankerPluginManager = $ranker_plugin_manager;
$this->sourcePluginManager = $source_plugin_manager;
$this->textExtractorPluginManager = $text_extractor_plugin_manager;
$this->textSplitterPluginManager = $text_splitter_plugin_manager;
$this->vectorStorePluginManager = $vector_store_plugin_manager;
}
/**
* Answer the question against the ReliefWeb documents from the river URL.
*
* @param string $question
* Question.
* @param array $source
* Data to retrieve the source documents.
* @param int $limit
* Number of documents to retrieve.
* @param \Drupal\ocha_ai_chat\Plugin\CompletionPluginInterface $completion_plugin
* Optional completion plugin override.
*
* @return array
* Associative array with the qestion, the answer, the source URL,
* the limit, the plugins, the stats and the relevant passages.
*/
public function answer(string $question, array $source, int $limit = 10, ?CompletionPluginInterface $completion_plugin = NULL): array {
$mode = $this->getSetting(['form', 'retrieval_mode'], NULL, FALSE);
if ($mode === 'keywords') {
return $this->answerKeywords($question, $source, $limit, $completion_plugin);
}
return $this->answerEmbeddings($question, $source, $limit, $completion_plugin);
}
/**
* Answer the question against the ReliefWeb documents from the river URL.
*
* Embeddings mode.
*
* 1. Retrieve the documents from the ReliefWeb API URL.
* 2. Embed the documents if not already.
* 3. Generate the embedding for the question
* 4. Find the documents relevant to the question.
* 5. Generate the prompt context.
* 6. Answer the question.
*
* @param string $question
* Question.
* @param array $source
* Data to retrieve the source documents.
* @param int $limit
* Number of documents to retrieve.
* @param \Drupal\ocha_ai_chat\Plugin\CompletionPluginInterface $completion_plugin
* Optional completion plugin override.
*
* @return array
* Associative array with the qestion, the answer, the source URL,
* the limit, the plugins, the stats and the relevant passages.
*/
public function answerEmbeddings(string $question, array $source, int $limit = 10, ?CompletionPluginInterface $completion_plugin = NULL): array {
$completion_plugin = $completion_plugin ?? $this->getCompletionPlugin();
$embedding_plugin = $this->getEmbeddingPlugin();
$source_plugin = $this->getSourcePlugin();
$vector_store_plugin = $this->getVectorStorePlugin();
// Stats to record the time of each operation.
// @todo either store the stats elsewhere (log etc.) or remove.
$data = [
'completion_plugin_id' => $completion_plugin->getPluginId(),
'embedding_plugin_id' => $embedding_plugin->getPluginId(),
'source_plugin_id' => $source_plugin->getPluginId(),
'source_data' => $source,
'source_limit' => $limit,
'source_document_ids' => [],
'question' => $question,
'answer' => '',
'original_answer' => '',
'passages' => [],
'status' => 'error',
'error' => '',
'timestamp' => $this->time->getRequestTime(),
'duration' => 0,
'uid' => $this->currentUser->id(),
'stats' => [
'Get source documents' => 0,
'Embed documents' => 0,
'Get question embedding' => 0,
'Get relevant passages' => 0,
'Get answer' => 0,
],
];
$time = microtime(TRUE);
// Retrieve the source documents matching the document source URL.
['index' => $index, 'documents' => $documents] = $this->getSourceDocuments($source, $limit);
$data['source_document_ids'] = array_keys($documents);
$data['stats']['Get source documents'] = 0 - $time + ($time = microtime(TRUE));
// If there are no documents to query, then no need to ask the AI.
if (empty($documents)) {
$data['answer'] = $this->getAnswer('no_document', 'Sorry, no source documents were found.');
$data['error'] = 'no_document';
return $this->logAnswerData($data);
}
// @todo Maybe that should be done outside of the answer pipeline or in a
// way that can help give feedback on the progress.
$result = $this->embedDocuments($index, $documents);
$data['stats']['Embed documents'] = 0 - $time + ($time = microtime(TRUE));
// Abort if we were unable to process the source documents.
// @todo maybe still proceed if some of the document could be processed?
if (!$result) {
$data['answer'] = $this->getAnswer('document_embedding_error', 'Sorry, there was an error trying to retrieve the documents to the answer to your question.');
$data['error'] = 'document_embedding_error';
return $this->logAnswerData($data);
}
// Generate the embedding for the question.
$embedding = $embedding_plugin->generateEmbedding($question, TRUE);
$data['stats']['Get question embedding'] = 0 - $time + ($time = microtime(TRUE));
// Abort if we were unable to generate the embedding for the question as
// we cannot retrieve the relevant passages in that case.
if (empty($embedding)) {
$data['answer'] = $this->getAnswer('question_embedding_error', 'Sorry, there was an error trying to process the qestion.');
$data['error'] = 'question_embedding_error';
return $this->logAnswerData($data);
}
// Find document passages relevant to the question.
$passages = $vector_store_plugin->getRelevantPassages($index, array_keys($documents), $question, $embedding);
$data['stats']['Get relevant passages'] = 0 - $time + ($time = microtime(TRUE));
// Language of the documents.
// @todo retrieve the language of the documents. Currently we only support
// English but the ranker, for example, supports more languages.
$language = 'en';
// Rerank the passages.
$passages = $this->rerankPassages($question, $passages, $language);
$data['stats']['Rerank passages'] = 0 - $time + ($time = microtime(TRUE));
// If there are no passages matching the question, we inject metadata from
// the documents. It helps for questions such as "What are those documents
// about?".
if (empty($passages)) {
$data['error'] = 'no_passage';
$passages = $this->getFallbackPassages($index, $documents);
}
else {
// Generate inline references for the passages.
foreach ($passages ?? [] as $key => $passage) {
$source_document = $documents[$passage['source']['id']];
$passages[$key]['reference'] = $source_plugin->generateInlineReference($source_document);
}
}
$data['passages'] = $passages;
// Generate the context to answer the question based on the relevant
// passages.
$context = $completion_plugin->generateContext($question, $passages);
// @todo parse the answer and try to detect "failure" to propose
// alternatives or instructions to clarify the question.
$answer = trim($completion_plugin->answer($question, $context) ?? '');
$data['stats']['Get answer'] = 0 - $time + ($time = microtime(TRUE));
$data['original_answer'] = $answer;
// The answer is empty for example if there was an error during the request.
if ($answer === '') {
$data['answer'] = $this->getAnswer('no_answer', 'Sorry, I was unable to answer your question. Please try again in a short moment.');
$data['error'] = 'no_answer';
return $this->logAnswerData($data);
}
// Validate the answer.
elseif (!$this->validateAnswer($answer, $question, $passages, $language)) {
$data['answer'] = $this->getAnswer('invalid_answer', 'Sorry, I was unable to answer your question.');
$data['error'] = 'invalid_answer';
return $this->logAnswerData($data);
}
else {
$data['answer'] = $answer;
}
// Arrived at this point we have a valid answer so we consider the request
// successful.
$data['status'] = 'success';
return $this->logAnswerData($data);
}
/**
* Answer the question against the ReliefWeb documents from the river URL.
*
* Keywords mode.
*
* 1. Retrieve the documents from the ReliefWeb API URL.
* 2. Get the term vectors for the document from the Elasticsearch backend.
* 3. Get the most relevant terms in regards to the question.
* 4. Query Elasticseach with those terms and use its highlight functionality
* to get the most relevant passages.
* 5. Generate the prompt context.
* 6. Answer the question.
*
* @param string $question
* Question.
* @param array $source
* Data to retrieve the source documents.
* @param int $limit
* Number of documents to retrieve.
* @param \Drupal\ocha_ai_chat\Plugin\CompletionPluginInterface $completion_plugin
* Optional completion plugin override.
*
* @return array
* Associative array with the qestion, the answer, the source URL,
* the limit, the plugins, the stats and the relevant passages.
*/
public function answerKeywords(string $question, array $source, int $limit = 10, ?CompletionPluginInterface $completion_plugin = NULL): array {
$completion_plugin = $completion_plugin ?? $this->getCompletionPlugin();
$source_plugin = $this->getSourcePlugin();
$logger = $this->logger;
// Stats to record the time of each operation.
// @todo either store the stats elsewhere (log etc.) or remove.
$data = [
'completion_plugin_id' => $completion_plugin->getPluginId(),
'embedding_plugin_id' => NULL,
'source_plugin_id' => $source_plugin->getPluginId(),
'source_data' => $source,
'source_limit' => $limit,
'source_document_ids' => [],
'question' => $question,
'answer' => '',
'original_answer' => '',
'passages' => [],
'status' => 'error',
'error' => '',
'timestamp' => $this->time->getRequestTime(),
'duration' => 0,
'uid' => $this->currentUser->id(),
'stats' => [
'Get source documents' => 0,
'Embed documents' => 0,
'Get question embedding' => 0,
'Get relevant passages' => 0,
'Get answer' => 0,
],
];
$time = microtime(TRUE);
$ranker_plugin = $this->getRankerPlugin();
if (empty($ranker_plugin)) {
$data['answer'] = $this->getAnswer('no_ranker', 'Sorry, there is an error. Please contact the administrator.');
$data['error'] = 'no_ranker';
return $this->logAnswerData($data);
}
$elasticsearch = $this->getConfig('reliefweb_api.settings')?->get('elasticsearch');
if (empty($elasticsearch)) {
$data['answer'] = $this->getAnswer('no_elasticsearch', 'Sorry, there is an error. Please contact the administrator.');
$data['error'] = 'no_elasticsearch';
return $this->logAnswerData($data);
}
$base_index_name = $this->getConfig('reliefweb_api.settings')?->get('base_index_name');
if (empty($base_index_name)) {
$data['answer'] = $this->getAnswer('no_base_index_name', 'Sorry, there is an error. Please contact the administrator.');
$data['error'] = 'no_base_index_name';
return $this->logAnswerData($data);
}
// Retrieve the source documents matching the document source URL.
['index' => $index, 'documents' => $documents] = $this->getSourceDocuments($source, $limit);
$data['source_document_ids'] = array_keys($documents);
$data['stats']['Get source documents'] = 0 - $time + ($time = microtime(TRUE));
// If there are no documents to query, then no need to ask the AI.
if (empty($documents)) {
$data['answer'] = $this->getAnswer('no_document', 'Sorry, no source documents were found.');
$data['error'] = 'no_document';
return $this->logAnswerData($data);
}
// @todo inject dependency.
$http_client = $this->httpClient;
$document_ids = array_map(function ($document) {
return $document['raw']['id'];
}, array_values($documents));
$document_language = 'en';
$document_fields = ['title', 'body'];
// Retrieve the term vectors for the documents.
//
// @todo currently, the idea is to get the document terms using the ES
// term vectors API. Another option could be to add an endpoint to the OCHA
// AI helper to return a list of keywords associated with the question.
$document_terms = call_user_func(function (array $ids, array $fields) use ($http_client, $logger, $elasticsearch, $base_index_name): array {
try {
// @todo this is restricted to the reports for now.
$endpoint = $elasticsearch . '/' . $base_index_name . '_reports/_mtermvectors';
$response = $http_client->post($endpoint, [
'json' => [
'ids' => $ids,
'parameters' => [
'fields' => $fields,
'offsets' => FALSE,
'payloads' => FALSE,
'positions' => FALSE,
'field_statistics' => FALSE,
'term_statistics' => FALSE,
],
],
]);
$data = $response->getBody()->getContents();
$data = json_decode($data, TRUE, flags: \JSON_THROW_ON_ERROR);
$terms = [];
foreach ($data['docs'] ?? [] as $doc) {
foreach ($doc['term_vectors'] ?? [] as $field_data) {
foreach (array_keys($field_data['terms'] ?? []) as $term) {
$term = trim(mb_strtolower($term));
// We try to filter out some "bad" terms. It's important to note
// that we use shingles and other term transformations when
// indexing ReliefWeb content into Elasticsearch. This can result
// in a messy bag of term vectors.
//
// @todo additional filtering to reduce the number of terms.
if ($term !== '' && mb_strlen($term) > 1 && !is_numeric($term) && mb_strpos($term, ' ') === FALSE) {
$terms[$term] = TRUE;
}
}
}
}
return array_keys($terms);
}
catch (\Exception $exception) {
$logger->error(strtr('Unable to retrieve term vectors for documents: @ids with error: @error', [
'@ids' => implode(', ', $ids),
'@error' => $exception->getMessage(),
]));
}
return [];
}, $document_ids, $document_fields);
// Skip if there are no relevant terms.
if (empty($document_terms)) {
return [];
}
// Get the relevant keywords.
$relevant_keywords = call_user_func(function (string $question, array $terms, string $language, int $limit) use ($ranker_plugin, $logger): array {
try {
$texts = $ranker_plugin->rankTexts($question, $terms, $language, $limit);
return array_slice(array_keys($texts), 0, $limit);
}
catch (\Exception $exception) {
$logger->error(strtr('Error while retrieving pertinent keywords: @error', [
'@error' => $exception->getMessage(),
]));
}
return [];
}, $question, $document_terms, $document_language, 50);
// Skip if there are no relevant keywords.
if (empty($relevant_keywords)) {
return [];
}
// Get the relevant passages.
$relevant_passages = call_user_func(function (array $ids, string $question, array $keywords, array $fields) use ($http_client, $logger, $elasticsearch, $base_index_name): array {
$limit = 30;
$length = 500;
$endpoint = $elasticsearch . '/' . $base_index_name . '_reports/_search';
// Generate match queries for the question and for the keywords.
$queries = array_map(function (string $term) use ($fields): array {
return [
'multi_match' => [
'query' => $term,
'fields' => $fields,
],
];
}, array_merge([$question], $keywords));
try {
$response = $http_client->post($endpoint, [
'json' => [
'query' => [
'bool' => [
'filter' => [
'ids' => [
'values' => $ids,
],
],
'should' => $queries,
],
],
// Highlights will give us passages which contain keywords. We
// rank them by score to get the ones with the most matches first.
'highlight' => [
'order' => 'score',
'number_of_fragments' => $limit,
'fragment_size' => $length,
'pre_tags' => [''],
'post_tags' => [''],
'fields' => [
'*' => (object) [],
],
],
],
]);
$data = $response->getBody()->getContents();
$data = json_decode($data, TRUE, flags: \JSON_THROW_ON_ERROR);
$passages = [];
foreach ($data['hits']['hits'] ?? [] as $hit) {
foreach ($hit['highlight'] as $highlights) {
foreach ($highlights as $highlight) {
$passages[$highlight] = ['text' => $highlight];
}
}
}
return array_slice($passages, 0, $limit);
}
catch (\Exception $exception) {
$logger->error(strtr('Error while retrieving relevant passages: @error', [
'@error' => $exception->getMessage(),
]));
}
return [];
}, $document_ids, $question, $relevant_keywords, $document_fields);
$data['stats']['Get relevant passages'] = 0 - $time + ($time = microtime(TRUE));
$passages = $relevant_passages;
// Generate inline references for the passages.
$source_document = reset($documents);
$reference = $source_plugin->generateInlineReference($source_document);
foreach ($passages ?? [] as $key => $passage) {
$passages[$key]['source'] = $source_document;
$passages[$key]['reference'] = $reference;
}
// If there are no passages matching the question, we inject metadata from
// the documents. It helps for questions such as "What are those documents
// about?".
$passages = array_merge($passages, $this->getFallbackPassages($index, $documents));
// Rerank the passages.
// @todo retrieve the language of the document. Currently we only support
// English but the ranker supports more languages.
$passages = $this->rerankPassages($question, $passages, 'en', 3);
$data['stats']['Rerank passages'] = 0 - $time + ($time = microtime(TRUE));
$data['passages'] = $passages;
// Generate the context to answer the question based on the relevant
// passages.
$context = $completion_plugin->generateContext($question, $passages);
// @todo parse the answer and try to detect "failure" to propose
// alternatives or instructions to clarify the question.
$answer = trim($completion_plugin->answer($question, $context) ?? '');
$data['stats']['Get answer'] = 0 - $time + ($time = microtime(TRUE));
$data['original_answer'] = $answer;
// The answer is empty for example if there was an error during the request.
if ($answer === '') {
$data['answer'] = $this->getAnswer('no_answer', 'Sorry, I was unable to answer your question. Please try again in a short moment.');
$data['error'] = 'no_answer';
return $this->logAnswerData($data);
}
// Validate the answer.
elseif (!$this->validateAnswer($answer, $question, $passages, $document_language)) {
$data['answer'] = $this->getAnswer('invalid_answer', 'Sorry, I was unable to answer your question.');
$data['error'] = 'invalid_answer';
return $this->logAnswerData($data);
}
else {
$data['answer'] = $answer;
}
// Arrived at this point we have a valid answer so we consider the request
// successful.
$data['status'] = 'success';
return $this->logAnswerData($data);
}
/**
* Get a predetermined answer.
*
* @param string $key
* The answer key in the config.
* @param string $default
* The default answer if none was found in the settings.
*
* @return string
* The answer.
*/
public function getAnswer(string $key, string $default): string {
return $this->getSetting(['form', 'answers', $key], $default, FALSE);
}
/**
* Get the fallback passages for the documents.
*
* @param stirng $index
* The vector store index.
* @param array $documents
* Documents.
*
* @return array
* Passages generated from the document descriptions.
*/
public function getFallbackPassages(string $index, array $documents): array {
// Retrieve the descriptions of the documents.
$data = $this->getVectorStorePlugin()->getDocuments($index, array_keys($documents), [
'id',
'description',
]);
foreach ($documents as $id => $document) {
if (isset($data[$id]['description'])) {
$documents[$id]['description'] = $data[$id]['description'];
}
}
return $this->getSourcePlugin()->describeDocuments($documents);
}
/**
* Validate the answer against the context to ensure validity.
*
* @param string $answer
* The answer.
* @param string $question
* The question.
* @param array $passages
* The text passages used as context for the answer.
* @param string $language
* Language of the passages.
*
* @return bool
* TRUE if the answer seems valid.
*/
public function validateAnswer(string $answer, string $question, array $passages, string $language): bool {
$answer_validator_plugin = $this->getAnswerValidatorPlugin();
if (empty($answer_validator_plugin)) {
return TRUE;
}
return $answer_validator_plugin->validate($answer, $question, $passages, $language, [
'completion' => $this->getCompletionPlugin(),
'embedding' => $this->getEmbeddingPlugin(),
'ranker' => $this->getRankerPlugin(),
'vector_store' => $this->getVectorStorePlugin(),
]);
}
/**
* Log the answer data.
*
* @param array $data
* Answer data.
*
* @return array
* Answer data
*
* @see ::answer()
*/
protected function logAnswerData(array $data): array {
// Remove the embedding of the passages as they are not really useful
// to have in the result or logs.
// Also remove unnecessary source information.
foreach ($data['passages'] as $index => $passage) {
unset($data['passages'][$index]['embedding']);
unset($data['passages'][$index]['source']['contents']);
unset($data['passages'][$index]['source']['description']);
unset($data['passages'][$index]['source']['raw']);
}
// Set the duration.
$data['duration'] = $this->time->getCurrentTime() - $data['timestamp'];
// Encode non scalar data like passages and stats.
$fields = array_map(function ($item) {
return is_scalar($item) ? $item : json_encode($item);
}, $data);
// Insert the record and retrieve the log ID. It can be used for example
// to set the "satisfaction score" afterwards.
$data['id'] = $this->database
->insert('ocha_ai_chat_logs')
->fields($fields)
->execute();
// Log the entry as well.
$this->logger->info(json_encode($data));
return $data;
}
/**
* Add feedback to an answer.
*
* @param int $id
* The ID of the answer log.
* @param int $satisfaction
* A satisfaction score from 0 to 5.
* @param string $feedback
* Feedback comment.
*
* @return bool
* TRUE if a record was updated.
*/
public function addAnswerFeedback(int $id, int $satisfaction, string $feedback): bool {
$updated = $this->database
->update('ocha_ai_chat_logs')
->fields([
'satisfaction' => $satisfaction,
'feedback' => $feedback,
])
->condition('id', $id, '=')
->execute();
return !empty($updated);
}
/**
* Add thumbs up/down to an answer's log entry.
*
* @param int $id
* The ID of the answer log.
* @param string $value
* Up or down.
*
* @return bool
* TRUE if a record was updated.
*/
public function addAnswerThumbs(int $id, string $value): bool {
$updated = $this->database
->update('ocha_ai_chat_logs')
->fields([
'thumbs' => $value,
])
->condition('id', $id, '=')
->execute();
return !empty($updated);
}
/**
* Get thumbs up/down from an answer's log entry.
*
* @param int $id
* The ID of the answer log.
*
* @return string
* Blank, up or down.
*/
public function getAnswerThumbs(int $id): string {
$value = $this->database
->select('ocha_ai_chat_logs')
->fields('ocha_ai_chat_logs', [
'thumbs',
])
->condition('id', $id, '=')
->execute()
->fetchField();
return $value ?? '';
}
/**
* Record that a copy-to-clipboard button was used.
*
* @param int $id
* The ID of the answer log.
* @param string $value
* Copied or not.
*
* @return bool
* TRUE if a record was updated.
*/
public function addAnswerCopy(int $id, string $value): bool {
$updated = $this->database
->update('ocha_ai_chat_logs')
->fields([
'copied' => $value,
])
->condition('id', $id, '=')
->execute();
return !empty($updated);
}
/**
* Rerank passages against the question.
*
* @param string $question
* The user question.
* @param array $passages
* Relevant passages retrieved from the document.
* @param string $language
* Language of the document.
* @param ?int $limit
* Optional limit override.
*
* @return array
* Reranked passages.
*/
protected function rerankPassages(string $question, array $passages, string $language, ?int $limit = NULL): array {
$limit ??= $this->getSetting(['plugins', 'ranker', 'limit'], count($passages), FALSE);
$ranker_plugin = $this->getRankerPlugin();
if (empty($ranker_plugin)) {
return array_slice($passages, 0, $limit);
}
$unranked_passages = [];
foreach ($passages as $passage) {
if (!isset($unranked_passages[$passage['text']])) {
$unranked_passages[$passage['text']] = $passage;
}
}
$texts = array_keys($unranked_passages);
$ranked_texts = $ranker_plugin->rankTexts($question, $texts, $language, $limit);
$ranked_passages = array_intersect_key($unranked_passages, $ranked_texts);
return $ranked_passages;
}
/**
* Get a list of source documents for the given document source URL.
*
* @param array $source
* Data to retrieve the source documents.
* @param int $limit
* Number of documents to retrieve.
*
* @return array
* Associative array with the index corresponding to the type of
* documents and the list of source documents for the source URL.
*
* @todo we should store which plugins were used to generate the embeddings
* so that they can be regenerated if the plugins change.
*/
protected function getSourceDocuments(array $source, int $limit): array {
$plugin = $this->getSourcePlugin();
$documents = $plugin->getDocuments($source, $limit);
// @todo allow multiple indices.
$resource = key($documents);
$documents = $documents[$resource] ?? [];
if (empty($documents)) {
$this->logger->notice(strtr('No documents found for the source: @source', [
'@source' => strtr(print_r($source, TRUE), "\n", ' '),
]));
}
// For the similarity search, we cannot compare vectors generated by an
// embedding model with a vector from another embedding model even if they
// have the same dimensions so we ensure that doesn't happen by prefixing
// the index used to store the vectors with the embedding plugin id and the
// model ID and dimensions.
//
// @todo review if we really need the source ID as well. If the index
// structure is the same between documents regardless of the source then
// we could remove it.
//
// @todo ensure it's below 255 characters (ex: generate a hash?)
//
// @todo this is not good because the text splitter, text extractor plugins
// impact the generation of the embeddings. So we need to generate an index
// name with all the plugin IDs or the info about the plugins in the index
// so that we can regenerate the embeddings when the plugins change.
$index = implode('__', [