forked from cce-uzk/AIChatPageComponent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
1565 lines (1342 loc) · 57.8 KB
/
Copy pathapi.php
File metadata and controls
1565 lines (1342 loc) · 57.8 KB
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
// Start output buffering to prevent any stray output from corrupting JSON response
ob_start();
use ILIAS\Plugin\pcaic\Model\ChatConfig;
use ILIAS\Plugin\pcaic\Model\ChatSession;
use ILIAS\Plugin\pcaic\Model\ChatMessage;
use ILIAS\Plugin\pcaic\Model\Attachment;
use ILIAS\Plugin\pcaic\Validation\FileUploadValidator;
/**
* AI Chat Page Component REST API
*
* RESTful API endpoint for AI chat interactions in ILIAS pages.
* Provides clean, session-based architecture with automatic configuration management.
*
* ## Architecture
*
* **Clean API Design:**
* - Frontend sends only `chat_id` + `message` + optional `attachment_ids`
* - Backend loads all configuration from ChatConfig model
* - User sessions managed automatically via ChatSession
* - Messages linked to sessions for proper conversation flow
* - File attachments handled via ILIAS ResourceStorage
*
* ## Supported Actions
*
* **POST /api.php**
* - `send_message`: Send message to AI with optional file attachments
* - `get_messages`: Retrieve conversation history for current user session
* - `upload_file`: Upload file attachment for multimodal AI analysis
*
* **GET /api.php**
* - `get_messages`: Retrieve message history (alternative to POST)
* - `get_chat_config`: Get chat configuration details
*
* ## Request Format
*
* ```json
* {
* "action": "send_message",
* "chat_id": "unique_chat_identifier",
* "message": "User message text",
* "attachment_ids": [123, 456] // Optional file attachments
* }
* ```
*
* ## Response Format
*
* ```json
* {
* "success": true,
* "message": "AI response text",
* "messages": [...], // Full conversation history
* "attachments": [...] // File attachment metadata
* }
* ```
*
* ## Security
* - ILIAS authentication required
* - User session validation
* - Input sanitization and validation
* - File upload security checks
* - Component-specific logging
*
* ## Error Handling
* - HTTP status codes (401, 400, 500)
* - Structured error responses
* - Comprehensive logging for debugging
*
* @author Nadimo Staszak <nadimo.staszak@uni-koeln.de>
*
* @see ChatConfig For configuration management
* @see ChatSession For user session handling
* @see ChatMessage For conversation persistence
*/
// Initialize ILIAS environment for standalone API endpoint
$ilias_root = rtrim(dirname(__DIR__, 7), '/');
chdir($ilias_root);
require_once($ilias_root . '/Services/Init/classes/class.ilInitialisation.php');
ilContext::init(ilContext::CONTEXT_WEB);
ilInitialisation::initILIAS();
// Load plugin dependencies and AI service integrations
require_once(__DIR__ . '/src/bootstrap.php');
require_once(__DIR__ . '/classes/ai/class.AIChatPageComponentLLM.php');
require_once(__DIR__ . '/classes/ai/class.AIChatPageComponentRAMSES.php');
require_once(__DIR__ . '/classes/ai/class.AIChatPageComponentOpenAI.php');
global $DIC;
$logger = $DIC->logger()->comp('pcaic');
// Configure HTTP response for JSON API
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
try {
// Enforce ILIAS authentication - reject anonymous access
if (!$DIC->user() || $DIC->user()->getId() == ANONYMOUS_USER_ID) {
sendApiResponse(['error' => 'Authentication required'], 401);
}
$method = $_SERVER['REQUEST_METHOD'];
$request = $DIC->http()->request();
if ($method === 'GET') {
$queryParams = $request->getQueryParams();
$data = is_array($queryParams) ? $queryParams : $queryParams->toArray();
} elseif ($method === 'POST') {
// Check if this is a file upload (multipart/form-data)
$content_type = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($content_type, 'multipart/form-data') !== false) {
// File upload - use $_POST data, convert ILIAS wrapper to array
$postData = $request->getParsedBody();
$data = is_array($postData) ? $postData : $postData->toArray();
} else {
// Regular JSON request
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if ($data === null) {
// Fallback to form data
$postData = $request->getParsedBody();
$data = is_array($postData) ? $postData : $postData->toArray();
}
}
} else {
sendApiResponse(['error' => 'Method not allowed'], 405);
}
$action = $data['action'] ?? '';
switch ($action) {
case 'send_message':
$result = handleSendMessage($data);
break;
case 'send_message_stream':
handleSendMessageStream($data);
return; // Stream response, no JSON output
case 'upload_file':
$result = handleFileUpload($data);
break;
case 'get_upload_config':
$result = getUploadConfig($data);
break;
case 'get_global_config':
$result = getGlobalConfig($data);
break;
case 'load_chat':
$result = handleLoadChat($data);
break;
case 'clear_chat':
$result = handleClearChat($data);
break;
case 'test':
$result = ['test' => 'API is working', 'timestamp' => time()];
break;
default:
$result = ['error' => 'Invalid action'];
}
sendApiResponse($result);
} catch (\Exception $e) {
$logger->error("API request failed", ['error' => $e->getMessage(), 'action' => $data['action'] ?? 'unknown']);
sendApiResponse(['error' => 'Internal server error'], 500);
}
/**
* Handle load chat - Load user's session for a chat
*/
function handleLoadChat(array $data): array
{
global $DIC;
$logger = $DIC->logger()->root();
$chat_id = $data['chat_id'] ?? '';
if (empty($chat_id)) {
return ['error' => 'Missing chat_id parameter'];
}
$user_id = $DIC->user()->getId();
try {
// Load chat configuration
$chatConfig = new ChatConfig($chat_id);
if (!$chatConfig->exists()) {
return ['error' => 'Chat configuration not found'];
}
// Find user's session for this chat
$session = ChatSession::findForUserAndChat($user_id, $chat_id);
if (!$session) {
// Create new session if none exists
$session = ChatSession::createForUserAndChat($user_id, $chat_id);
$session->save();
}
// Load messages
$messages = $session->getMessages();
return [
'success' => true,
'config' => $chatConfig->toArray(),
'session' => $session->toArray(),
'messages' => array_map(fn($msg) => $msg->toArray(), $messages)
];
} catch (\Exception $e) {
$logger->warning("Failed to load chat configuration", ['chat_id' => $chat_id, 'error' => $e->getMessage()]);
return ['error' => 'Failed to load chat'];
}
}
/**
* Handle clear chat - Clear user's session for a chat
*/
function handleClearChat(array $data): array
{
global $DIC;
$logger = $DIC->logger()->root();
$chat_id = $data['chat_id'] ?? '';
if (empty($chat_id)) {
return ['error' => 'Missing chat_id parameter'];
}
$user_id = $DIC->user()->getId();
try {
// Find user's session for this chat
$session = ChatSession::findForUserAndChat($user_id, $chat_id);
if ($session) {
// Delete session and all its messages
$session->delete();
}
return [
'success' => true,
'message' => 'Chat cleared successfully'
];
} catch (\Exception $e) {
$logger->warning("Failed to clear chat", ['chat_id' => $chat_id, 'error' => $e->getMessage()]);
return ['error' => 'Failed to clear chat'];
}
}
/**
* Handle send message with separated context structure
*/
function handleSendMessage(array $data): array
{
global $DIC;
$logger = $DIC->logger()->root();
// Extract required data from frontend
$chat_id = $data['chat_id'] ?? '';
$user_message = $data['message'] ?? '';
$attachment_ids = $data['attachment_ids'] ?? [];
if (empty($chat_id) || empty($user_message)) {
return ['error' => 'Missing required parameters: chat_id and message'];
}
// Validate message length against configuration
$char_limit = (int)(\platform\AIChatPageComponentConfig::get('characters_limit') ?: 2000);
if (strlen($user_message) > $char_limit) {
return ['error' => sprintf('Message too long. Maximum %d characters allowed.', $char_limit)];
}
// Ensure attachment_ids is an array
if (!is_array($attachment_ids)) {
$attachment_ids = [];
}
$user_id = $DIC->user()->getId();
try {
// Load chat configuration (PageComponent settings)
$chatConfig = new ChatConfig($chat_id);
if (!$chatConfig->exists()) {
return ['error' => 'Chat configuration not found'];
}
// Get or create user session for this chat
$session = ChatSession::getOrCreateForUserAndChat($user_id, $chat_id);
// Add user message to session
$userMessage = $session->addMessage('user', $user_message);
// Bind attachments to the message if any
if (!empty($attachment_ids)) {
foreach ($attachment_ids as $attachment_id) {
if (!empty($attachment_id)) {
try {
$db = $DIC->database();
$db->update('pcaic_attachments',
['message_id' => ['integer', $userMessage->getMessageId()]],
['id' => ['integer', $attachment_id]]
);
} catch (\Exception $e) {
$logger->warning("Failed to bind attachment to message", ['attachment_id' => $attachment_id, 'message_id' => $userMessage->getMessageId(), 'error' => $e->getMessage()]);
}
}
}
}
// Get recent messages for AI context (respecting max_memory)
$recentMessages = ChatMessage::getRecentForSession(
$session->getSessionId(),
$chatConfig->getMaxMemory()
);
// Build CLEAN system prompt (ONLY AI behavior, no content)
$clean_system_prompt = $chatConfig->getSystemPrompt();
// Build context resources (ALL context as structured resources)
$contextResources = [];
// Add page context as resource if enabled
if ($chatConfig->isIncludePageContext()) {
$page_context = getPageContextForChat($chatConfig);
if (!empty($page_context)) {
$contextResources[] = [
'kind' => 'page_context',
'id' => 'current-page',
'title' => 'Aktuelle Lernseite',
'content' => $page_context
];
}
}
// Add background files as resources
$background_files = $chatConfig->getBackgroundFiles();
if (!empty($background_files)) {
$irss = $DIC->resourceStorage();
foreach ($background_files as $file_id) {
try {
$identification = $irss->manage()->find($file_id);
if ($identification === null) continue;
$revision = $irss->manage()->getCurrentRevision($identification);
if ($revision === null) continue;
$suffix = strtolower($revision->getInformation()->getSuffix());
$mime_type = $revision->getInformation()->getMimeType();
// Process ALL file types as structured resources
if (in_array($suffix, ['txt', 'md', 'csv'])) {
// Text files
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
$contextResources[] = [
'kind' => 'text_file',
'id' => 'bg-text-' . $file_id,
'title' => $revision->getTitle(),
'mime_type' => $mime_type,
'content' => $content
];
}
} elseif (in_array($suffix, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
// Single images
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
$contextResources[] = [
'kind' => 'image_file',
'id' => 'bg-img-' . $file_id,
'title' => $revision->getTitle(),
'mime_type' => $mime_type,
'url' => $content
];
}
} elseif ($suffix === 'pdf') {
// PDF pages (converted to images)
$content = extractFileContentFromIRSS($identification);
if (!empty($content) && is_array($content)) {
foreach ($content as $pageIndex => $pageDataUrl) {
$contextResources[] = [
'kind' => 'pdf_page',
'id' => 'bg-pdf-' . $file_id . '-page-' . ($pageIndex + 1),
'title' => $revision->getTitle() . ' (Seite ' . ($pageIndex + 1) . ')',
'mime_type' => 'image/png', // converted to PNG
'page_number' => $pageIndex + 1,
'source_file' => $revision->getTitle(),
'url' => $pageDataUrl
];
}
}
}
} catch (\Exception $e) {
$logger->warning("Background file processing failed", ['file_info' => $file_info, 'error' => $e->getMessage()]);
continue;
}
}
}
// Initialize AI service
$llm = createLLMInstance($chatConfig->getAiService());
$llm->setPrompt($clean_system_prompt);
$llm->setMaxMemoryMessages($chatConfig->getMaxMemory());
// Convert messages to AI format (including attachments)
$aiMessages = [];
foreach ($recentMessages as $msg) {
$content = $msg->getMessage();
$attachments = $msg->getAttachments();
// If message has attachments, create multimodal content
if (!empty($attachments)) {
$multimodalContent = [];
// Add text content if not empty
if (!empty(trim($content))) {
$multimodalContent[] = [
'type' => 'text',
'text' => $content
];
}
// Add image and PDF attachments
foreach ($attachments as $attachment) {
try {
if ($attachment->isImage()) {
$imageData = $attachment->getOptimizedContentAsBase64();
if ($imageData) {
$multimodalContent[] = [
'type' => 'image_url',
'image_url' => [
'url' => $imageData
]
];
}
} elseif ($attachment->isPdf()) {
// Handle PDF attachments - convert to image pages
$pdfDataUrls = $attachment->getDataUrl(); // Returns array of page URLs
if ($pdfDataUrls && is_array($pdfDataUrls)) {
foreach ($pdfDataUrls as $pageDataUrl) {
if ($pageDataUrl) {
$multimodalContent[] = [
'type' => 'image_url',
'image_url' => [
'url' => $pageDataUrl
]
];
}
}
} else {
$logger->warning("PDF attachment conversion failed", ['attachment_id' => $attachment->getAttachmentId()]);
}
}
} catch (\Exception $e) {
$logger->warning("Attachment processing error", ['attachment_id' => $attachment->getAttachmentId(), 'error' => $e->getMessage()]);
}
}
$aiMessages[] = [
'role' => $msg->getRole(),
'content' => $multimodalContent
];
} else {
// Text-only message
$aiMessages[] = [
'role' => $msg->getRole(),
'content' => $content
];
}
}
// Send to AI
$aiResponse = $llm->sendMessagesArray($aiMessages, $contextResources);
// Add AI response to session
$aiMessage = $session->addMessage('assistant', $aiResponse);
// 11. Return chat state
return [
'success' => true,
'message' => $aiResponse,
'session' => $session->toArray(),
'messages' => array_map(fn($msg) => $msg->toArray(), $session->getMessages()),
'experimental' => true,
'context_resources_count' => count($contextResources)
];
} catch (\Exception $e) {
$logger->error("Message sending failed", [
'chat_id' => $chat_id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
// Return detailed error for debugging
return [
'error' => 'Failed to send message: ' . $e->getMessage(),
'debug' => [
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine()
]
];
}
}
/**
* Handle send message with Server-Sent Events streaming
*/
function handleSendMessageStream(array $data): void
{
global $DIC;
$logger = $DIC->logger()->root();
// Set Server-Sent Events headers
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
// Extract required data from frontend
$chat_id = $data['chat_id'] ?? '';
$user_message = $data['message'] ?? '';
// Handle attachment_ids - could be JSON string from GET parameters or array from POST
$attachment_ids = $data['attachment_ids'] ?? [];
if (is_string($attachment_ids) && !empty($attachment_ids)) {
$attachment_ids = json_decode($attachment_ids, true) ?: [];
}
if (!is_array($attachment_ids)) {
$attachment_ids = [];
}
if (empty($chat_id) || empty($user_message)) {
echo "data: " . json_encode(['error' => 'Missing required parameters']) . "\n\n";
exit;
}
// Validate message length
$char_limit = (int)(\platform\AIChatPageComponentConfig::get('characters_limit') ?: 2000);
if (strlen($user_message) > $char_limit) {
echo "data: " . json_encode(['error' => 'Message too long']) . "\n\n";
exit;
}
$user_id = $DIC->user()->getId();
try {
// Load chat configuration
$chatConfig = new ChatConfig($chat_id);
if (!$chatConfig->exists()) {
echo "data: " . json_encode(['error' => 'Chat configuration not found']) . "\n\n";
exit;
}
// Get or create session
$session = ChatSession::getOrCreateForUserAndChat($user_id, $chat_id);
// Add user message to session
$userMessage = $session->addMessage('user', $user_message);
// Process attachments if provided
if (!empty($attachment_ids)) {
foreach ($attachment_ids as $attachment_id) {
if (is_numeric($attachment_id)) {
$userMessage->addAttachment($attachment_id);
}
}
}
// Get recent messages for context
$recent_limit = min($chatConfig->getMaxMemory(), 20);
$recentMessages = $session->getRecentMessages($recent_limit);
// Build context resources (background files, page context, etc.)
$contextResources = [];
// Add page context if enabled
if ($chatConfig->isIncludePageContext()) {
$pageContext = getPageContextForChat($chatConfig);
if (!empty($pageContext)) {
$contextResources[] = [
'kind' => 'page_context',
'title' => 'Page Context',
'content' => $pageContext,
'mime_type' => 'text/plain'
];
}
}
// Add background files as resources
$background_files = $chatConfig->getBackgroundFiles();
if (!empty($background_files)) {
$irss = $DIC->resourceStorage();
foreach ($background_files as $file_id) {
try {
$identification = $irss->manage()->find($file_id);
if ($identification === null) continue;
$revision = $irss->manage()->getCurrentRevision($identification);
if ($revision === null) continue;
$suffix = strtolower($revision->getInformation()->getSuffix());
$mime_type = $revision->getInformation()->getMimeType();
// Process ALL file types as structured resources
if (in_array($suffix, ['txt', 'md', 'csv'])) {
// Text files
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
$contextResources[] = [
'kind' => 'text_file',
'id' => 'bg-text-' . $file_id,
'title' => $revision->getTitle(),
'mime_type' => $mime_type,
'content' => $content
];
}
} elseif (in_array($suffix, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
// Single images
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
$contextResources[] = [
'kind' => 'image_file',
'id' => 'bg-img-' . $file_id,
'title' => $revision->getTitle(),
'mime_type' => $mime_type,
'url' => $content
];
}
} elseif ($suffix === 'pdf') {
// PDF pages (converted to images)
$content = extractFileContentFromIRSS($identification);
if (!empty($content) && is_array($content)) {
foreach ($content as $pageIndex => $pageDataUrl) {
if (!empty($pageDataUrl)) {
$contextResources[] = [
'kind' => 'pdf_page',
'id' => 'bg-pdf-' . $file_id . '-p' . ($pageIndex + 1),
'title' => $revision->getTitle() . ' (Page ' . ($pageIndex + 1) . ')',
'mime_type' => 'image/png',
'page_number' => $pageIndex + 1,
'source_file' => $revision->getTitle(),
'url' => $pageDataUrl
];
}
}
}
}
} catch (\Exception $e) {
$logger->warning("Background file processing failed", ['file_id' => $file_id, 'error' => $e->getMessage()]);
continue;
}
}
}
// Initialize AI service with streaming enabled
$llm = createLLMInstance($chatConfig->getAiService());
$llm->setStreaming(true); // Enable streaming
$llm->setPrompt($chatConfig->getSystemPrompt());
$llm->setMaxMemoryMessages($chatConfig->getMaxMemory());
// Send start event
echo "data: " . json_encode(['type' => 'start']) . "\n\n";
flush();
// Convert messages to AI format
$aiMessages = [];
foreach ($recentMessages as $msg) {
$content = $msg->getMessage();
$attachments = $msg->getAttachments();
if (!empty($attachments)) {
$multimodalContent = [];
if (!empty(trim($content))) {
$multimodalContent[] = ['type' => 'text', 'text' => $content];
}
foreach ($attachments as $attachment) {
try {
if ($attachment->isImage()) {
$imageData = $attachment->getOptimizedContentAsBase64();
if ($imageData) {
$multimodalContent[] = [
'type' => 'image_url',
'image_url' => ['url' => $imageData]
];
}
} elseif ($attachment->isPdf()) {
$pdfDataUrls = $attachment->getDataUrl();
if ($pdfDataUrls && is_array($pdfDataUrls)) {
foreach ($pdfDataUrls as $pageDataUrl) {
if ($pageDataUrl) {
$multimodalContent[] = [
'type' => 'image_url',
'image_url' => ['url' => $pageDataUrl]
];
}
}
}
}
} catch (\Exception $e) {
$logger->warning("Attachment processing failed", ['error' => $e->getMessage()]);
}
}
$aiMessages[] = [
'role' => $msg->getRole(),
'content' => $multimodalContent
];
} else {
$aiMessages[] = [
'role' => $msg->getRole(),
'content' => $content
];
}
}
// Send to AI with streaming (this will output chunks directly)
$aiResponse = $llm->sendMessagesArray($aiMessages, $contextResources);
// Send completion event
echo "data: " . json_encode(['type' => 'complete', 'message' => $aiResponse]) . "\n\n";
flush();
// Add AI response to session
$session->addMessage('assistant', $aiResponse);
} catch (\Exception $e) {
$logger->error("Streaming message error: " . $e->getMessage());
echo "data: " . json_encode(['error' => 'Failed to send message']) . "\n\n";
}
exit;
}
/**
* Get page context for chat configuration
*/
function getPageContextForChat(ChatConfig $chatConfig): string
{
global $DIC;
$logger = $DIC->logger()->root();
$page_id = (int) $chatConfig->getPageId(); // bei wpg: DIESE musst du nehmen
$parent_id = (int) $chatConfig->getParentId(); // Objekt-ID (z.B. Kurs, Wiki-Objekt)
$parent_type = (string) $chatConfig->getParentType();
// COPage-Typ bestimmen
$copage_type_map = [
'crs' => 'cont',
'grp' => 'cont',
'cont'=> 'cont',
'cat' => 'cont',
'lm' => 'lm',
'wpg' => 'wpg', // Wiki-Page (einzelne Seite)
'wiki'=> 'wpg', // falls du hier "wiki" speicherst, auch auf wpg mappen
'copa'=> 'copa',
'glo' => 'glo',
'blp' => 'blp',
'frm' => 'frm',
'tst' => 'tst',
'qpl' => 'qpl'
];
$copage_type = $copage_type_map[$parent_type] ?? null;
if (!$copage_type) {
$logger->info("No page context available for parent type", ['parent_type' => $parent_type]);
return '';
}
$page_manager = $DIC->copage()->internal()->domain()->page();
$page = null;
try {
if ($copage_type === 'wpg') {
if ($page_id > 0) {
$page = $page_manager->get('wpg', $page_id);
} else {
$logger->info("Missing wiki page_id for wpg context");
return '';
}
} else {
$target_page_id = $page_id ?: $parent_id;
if ($target_page_id <= 0) {
$logger->info("No page/parent id available", ['copage_type' => $copage_type]);
return '';
}
$page = $page_manager->get($copage_type, $target_page_id);
}
} catch (\Throwable $e) {
$logger->error("page()->get() failed: " . $e->getMessage());
$page = null;
}
if (!$page) {
$logger->info("Service returned null for page context", ['copage_type' => $copage_type, 'id' => ($copage_type === 'wpg' ? $page_id : ($page_id ?: $parent_id))]);
return '';
}
$content = $page->getRenderedContent() ?? '';
$title = ilObject::_lookupTitle($parent_id);
$description = ilObject::_lookupDescription($parent_id);
$result = '';
if ($title !== '') { $result .= "Page Title: $title\n\n"; }
if ($description !== '') { $result .= "Page Description: $description\n\n"; }
if ($content !== '') { $result .= "Page Content: $content\n\n"; }
// Apply page context character limit to prevent token overflow
$max_context_chars_config = \platform\AIChatPageComponentConfig::get('max_page_context_chars');
$max_context_chars = $max_context_chars_config ? (int)$max_context_chars_config : 50000;
// Log config source
if ($max_context_chars_config !== null) {
} else {
}
if (strlen($result) > $max_context_chars) {
$original_length = strlen($result);
$result = substr($result, 0, $max_context_chars) . "\n\n[Content truncated due to length limit]";
$logger->info("Page context truncated", [
'original_length' => $original_length,
'truncated_length' => strlen($result) - 42, // minus truncation message
'limit' => $max_context_chars,
'truncated_chars' => $original_length - $max_context_chars
]);
}
$logger->debug("Return content, len=" . strlen($result) . ", type=" . $copage_type);
return $result;
}
/**
* Get background files context for chat configuration (TEXT FILES ONLY for system prompt)
*/
function getBackgroundFilesContextForChat(ChatConfig $chatConfig): string
{
global $DIC;
$logger = $DIC->logger()->root();
try {
$background_files = $chatConfig->getBackgroundFiles();
if (empty($background_files)) {
return '';
}
$context_parts = [];
$irss = $DIC->resourceStorage();
foreach ($background_files as $file_id) {
try {
$identification = $irss->manage()->find($file_id);
if ($identification === null) {
continue;
}
$revision = $irss->manage()->getCurrentRevision($identification);
if ($revision === null) {
continue;
}
// Only process text files for system prompt
$suffix = strtolower($revision->getInformation()->getSuffix());
if (!in_array($suffix, ['txt', 'md', 'csv'])) {
continue; // Skip non-text files
}
// Add file metadata
$file_context = "File: " . $revision->getTitle();
$file_context .= " (Type: " . $revision->getInformation()->getMimeType() . ")";
$file_context .= "\n";
// Extract content based on file type
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
$file_context .= "Content: " . $content;
}
$context_parts[] = $file_context;
} catch (\Exception $e) {
$logger->warning("Background file context error", ['file_id' => $file_info['file_id'], 'error' => $e->getMessage()]);
continue;
}
}
return implode("\n\n---\n\n", $context_parts);
} catch (\Exception $e) {
$logger->error("Failed to build background files context", ['error' => $e->getMessage()]);
return '';
}
}
/**
* Get background image messages for chat configuration (IMAGES and PDFs as multimodal messages)
*/
function getBackgroundImageMessagesForChat(ChatConfig $chatConfig): array
{
global $DIC;
$logger = $DIC->logger()->root();
try {
$background_files = $chatConfig->getBackgroundFiles();
if (empty($background_files)) {
return [];
}
$image_files = [];
$irss = $DIC->resourceStorage();
foreach ($background_files as $file_id) {
try {
$identification = $irss->manage()->find($file_id);
if ($identification === null) {
continue;
}
$revision = $irss->manage()->getCurrentRevision($identification);
if ($revision === null) {
continue;
}
// Process images and PDFs
$suffix = strtolower($revision->getInformation()->getSuffix());
$mime_type = $revision->getInformation()->getMimeType();
if (in_array($suffix, ['jpg', 'jpeg', 'png', 'gif', 'webp']) || $suffix === 'pdf') {
$content = extractFileContentFromIRSS($identification);
if (!empty($content)) {
if ($suffix === 'pdf') {
// PDF content is already converted to image URLs by extractFileContentFromIRSS
if (is_array($content)) {
// Multiple PDF pages
foreach ($content as $page_data_url) {
$image_files[] = [
'type' => 'image_url',
'image_url' => [
'url' => $page_data_url
]
];
}
} else {
// Single page or data URL
$image_files[] = [
'type' => 'image_url',
'image_url' => [
'url' => $content
]
];
}
} else {
// Regular image
$image_files[] = [
'type' => 'image_url',
'image_url' => [
'url' => $content
]
];
}
}
}
} catch (\Exception $e) {
$logger->warning("Background image processing failed", ['file_id' => $file_info['file_id'], 'error' => $e->getMessage()]);
continue;
}
}
// Return as multimodal user message
if (!empty($image_files)) {
$content = [
[
'type' => 'text',
'text' => 'Background Images: The following images have been uploaded as background context. Please analyze them and be ready to answer questions about their content:'
]
];
$content = array_merge($content, $image_files);
return [[
'role' => 'user',
'content' => $content
]];
}
return [];
} catch (\Exception $e) {
$logger->error("Failed to build background image messages", ['error' => $e->getMessage()]);
return [];
}
}
/**
* Convert PDF to images directly using Ghostscript
* Returns array of image data URLs for each page
*/
function convertPdfToImagesDirectly($identification, $revision, $irss): ?array