-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathllmo.js
More file actions
1534 lines (1312 loc) · 54.9 KB
/
llmo.js
File metadata and controls
1534 lines (1312 loc) · 54.9 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
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {
ok, badRequest, forbidden, createResponse, notFound, internalServerError,
} from '@adobe/spacecat-shared-http-utils';
import {
SPACECAT_USER_AGENT,
tracingFetch as fetch,
hasText,
isObject,
isValidUUID,
llmoConfig as llmo,
llmoStrategy,
schemas,
composeBaseURL,
isValidUrl,
} from '@adobe/spacecat-shared-utils';
import { Config } from '@adobe/spacecat-shared-data-access/src/models/site/config.js';
import crypto from 'crypto';
import { Entitlement as EntitlementModel } from '@adobe/spacecat-shared-data-access';
import TokowakaClient, { calculateForwardedHost } from '@adobe/spacecat-shared-tokowaka-client';
import AccessControlUtil from '../../support/access-control-util.js';
import { exchangePromiseToken } from '../../support/utils.js';
import { triggerBrandProfileAgent } from '../../support/brand-profile-trigger.js';
import {
applyFilters,
applyInclusions,
applyExclusions,
applyGroups,
applyMappings,
LLMO_SHEETDATA_SOURCE_URL,
EDGE_OPTIMIZE_CDN_STRATEGIES,
EDGE_OPTIMIZE_CDN_TYPES,
} from './llmo-utils.js';
import { LLMO_SHEET_MAPPINGS } from './llmo-mappings.js';
import {
validateSiteNotOnboarded,
generateDataFolder,
performLlmoOnboarding,
performLlmoOffboarding,
postLlmoAlert,
} from './llmo-onboarding.js';
import { queryLlmoFiles } from './llmo-query-handler.js';
import { updateModifiedByDetails } from './llmo-config-metadata.js';
import { handleLlmoRationale } from './llmo-rationale.js';
import { notifyStrategyChanges } from '../../support/opportunity-workspace-notifications.js';
const { readConfig, writeConfig } = llmo;
const { readStrategy, writeStrategy } = llmoStrategy;
const { llmoConfig: llmoConfigSchema } = schemas;
function LlmoController(ctx) {
const accessControlUtil = AccessControlUtil.fromContext(ctx);
// Helper function to get site and validate LLMO config
const getSiteAndValidateLlmo = async (context) => {
const { siteId } = context.params;
const { dataAccess } = context;
const { Site } = dataAccess;
const site = await Site.findById(siteId);
const config = site.getConfig();
const llmoConfig = config.getLlmoConfig();
if (!llmoConfig?.dataFolder) {
throw new Error('LLM Optimizer is not enabled for this site, add llmo config to the site');
}
const hasAccessToElmo = await accessControlUtil.hasAccess(
site,
'',
EntitlementModel.PRODUCT_CODES.LLMO,
);
if (!hasAccessToElmo) {
throw new Error('Only users belonging to the organization can view its sites');
}
return { site, config, llmoConfig };
};
// Helper function to save site config with error handling
const saveSiteConfig = async (site, config, log, operation) => {
site.setConfig(Config.toDynamoItem(config));
try {
await site.save();
} catch (error) {
log.error(`Error ${operation} for site's llmo config ${site.getId()}: ${error.message}`);
}
};
// Helper function to validate question key
const validateQuestionKey = (config, questionKey) => {
const humanQuestions = config.getLlmoHumanQuestions() || [];
const aiQuestions = config.getLlmoAIQuestions() || [];
if (!humanQuestions.some((question) => question.key === questionKey)
&& !aiQuestions.some((question) => question.key === questionKey)) {
throw new Error('Invalid question key, please provide a valid question key');
}
};
// Helper function to validate customer intent key
const validateCustomerIntentKey = (config, intentKey) => {
const customerIntent = config.getLlmoCustomerIntent() || [];
if (!customerIntent.some((intent) => intent.key === intentKey)) {
throw new Error('Invalid customer intent key, please provide a valid customer intent key');
}
};
// Handles requests to the LLMO sheet data endpoint
const getLlmoSheetData = async (context) => {
const { log } = context;
const {
siteId, dataSource, sheetType, week,
} = context.params;
const { env } = context;
try {
const { llmoConfig } = await getSiteAndValidateLlmo(context);
// Construct the sheet URL based on which parameters are provided
let sheetURL;
if (sheetType && week) {
sheetURL = `${llmoConfig.dataFolder}/${sheetType}/${week}/${dataSource}.json`;
} else if (sheetType) {
sheetURL = `${llmoConfig.dataFolder}/${sheetType}/${dataSource}.json`;
} else {
sheetURL = `${llmoConfig.dataFolder}/${dataSource}.json`;
}
// Add limit, offset and sheet query params to the url
const url = new URL(`${LLMO_SHEETDATA_SOURCE_URL}/${sheetURL}`);
const { limit, offset, sheet } = context.data;
if (limit) {
url.searchParams.set('limit', limit);
}
if (offset) {
url.searchParams.set('offset', offset);
}
// allow fetching a specific sheet from the sheet data source
if (sheet) {
url.searchParams.set('sheet', sheet);
}
// Fetch data from the external endpoint using the dataFolder from config
const response = await fetch(url.toString(), {
headers: {
Authorization: `token ${env.LLMO_HLX_API_KEY || 'hlx_api_key_missing'}`,
'User-Agent': SPACECAT_USER_AGENT,
'Accept-Encoding': 'br',
},
});
if (!response.ok) {
log.error(`Failed to fetch data from external endpoint: ${response.status} ${response.statusText}`);
throw new Error(`External API returned ${response.status}: ${response.statusText}`);
}
// Get the response data
const data = await response.json();
// Return the data, pass through any compression headers from upstream
return ok(data, {
...(response.headers ? Object.fromEntries(response.headers.entries()) : {}),
});
} catch (error) {
log.error(`Error proxying data for siteId: ${siteId}, error: ${error.message}`);
return badRequest(error.message);
}
};
// Handles POST requests to the LLMO sheet data endpoint
// with query capabilities (filtering, exclusions, grouping)
const queryLlmoSheetData = async (context) => {
const { log } = context;
const {
siteId, dataSource, sheetType, week,
} = context.params;
const { env } = context;
// Start timing for the entire method
const methodStartTime = Date.now();
const FIXED_LLMO_LIMIT = 1000000;
// Extract and validate request body structure
const {
sheets = [],
filters = {},
include = [],
exclude = [],
groupBy = [],
limit = FIXED_LLMO_LIMIT, // Default to 1M records to return all records
offset = 0, // Default to 0 to return the first 1M records
} = context.data || {};
// Validate request body structure
if (sheets && !Array.isArray(sheets)) {
return badRequest('sheets must be an array');
}
if (filters && typeof filters !== 'object') {
return badRequest('filters must be an object');
}
if (exclude && !Array.isArray(exclude)) {
return badRequest('exclude must be an array');
}
if (groupBy && !Array.isArray(groupBy)) {
return badRequest('groupBy must be an array');
}
if (include && !Array.isArray(include)) {
return badRequest('include must be an array');
}
try {
const { llmoConfig } = await getSiteAndValidateLlmo(context);
// Construct the sheet URL based on which parameters are provided
let sheetURL;
if (sheetType && week) {
sheetURL = `${llmoConfig.dataFolder}/${sheetType}/${week}/${dataSource}.json`;
} else if (sheetType) {
sheetURL = `${llmoConfig.dataFolder}/${sheetType}/${dataSource}.json`;
} else {
sheetURL = `${llmoConfig.dataFolder}/${dataSource}.json`;
}
// Add limit, offset and sheet query params to the url
const url = new URL(`${LLMO_SHEETDATA_SOURCE_URL}/${sheetURL}`);
if (limit) {
url.searchParams.set('limit', limit);
}
if (offset) {
url.searchParams.set('offset', offset);
}
// Log setup completion time
const setupTime = Date.now();
log.info(`LLMO query setup completed - elapsed: ${setupTime - methodStartTime}ms`);
// Fetch data from the external endpoint using the dataFolder from config
const fetchStartTime = Date.now();
const response = await fetch(url.toString(), {
headers: {
Authorization: `token ${env.LLMO_HLX_API_KEY || 'hlx_api_key_missing'}`,
'User-Agent': SPACECAT_USER_AGENT,
'Accept-Encoding': 'br',
},
});
if (!response.ok) {
log.error(`Failed to fetch data from external endpoint: ${response.status} ${response.statusText}`);
throw new Error(`External API returned ${response.status}: ${response.statusText}`);
}
// Get the response data
let data = await response.json();
const fetchEndTime = Date.now();
const fetchDuration = fetchEndTime - fetchStartTime;
log.info(`External API fetch completed - elapsed: ${fetchEndTime - methodStartTime}ms, duration: ${fetchDuration}ms`);
// Keep only the required sheets
if (sheets.length > 0 && (data[':type'] === 'multi-sheet')) {
Object.keys(data).filter((key) => !key.startsWith(':')).forEach((key) => {
if (sheets.indexOf(key) === -1) {
delete data[key];
}
});
}
// Apply mappings using external configuration
let mappingDuration = 0;
log.info(`Looking for mapping for dataSource: ${dataSource} mappings ${JSON.stringify(LLMO_SHEET_MAPPINGS)}`);
const mapping = LLMO_SHEET_MAPPINGS.find((m) => dataSource.toLowerCase().includes(m.pattern));
if (mapping) {
log.info(`Found mapping for dataSource: ${dataSource} mapping ${JSON.stringify(mapping)}`);
const mappingStartTime = Date.now();
data = applyMappings(data, mapping);
const mappingEndTime = Date.now();
mappingDuration = mappingEndTime - mappingStartTime;
log.info(`Mapping completed - elapsed: ${mappingEndTime - methodStartTime}ms, duration: ${mappingDuration}ms`);
}
// Apply inclusions if any are provided
let inclusionDuration = 0;
if (Object.keys(include).length > 0) {
const inclusionStartTime = Date.now();
data = applyInclusions(data, include);
const inclusionEndTime = Date.now();
inclusionDuration = inclusionEndTime - inclusionStartTime;
log.info(`Inclusion processing completed - elapsed: ${inclusionEndTime - methodStartTime}ms, duration: ${inclusionDuration}ms`);
}
// Apply filters if any are provided
let filterDuration = 0;
if (Object.keys(filters).length > 0) {
const filterStartTime = Date.now();
data = applyFilters(data, filters);
const filterEndTime = Date.now();
filterDuration = filterEndTime - filterStartTime;
log.info(`Filtering completed - elapsed: ${filterEndTime - methodStartTime}ms, duration: ${filterDuration}ms`);
}
// Apply exclusions if any are provided
let exclusionDuration = 0;
if (exclude.length > 0) {
const exclusionStartTime = Date.now();
data = applyExclusions(data, exclude);
const exclusionEndTime = Date.now();
exclusionDuration = exclusionEndTime - exclusionStartTime;
log.info(`Exclusion processing completed - elapsed: ${exclusionEndTime - methodStartTime}ms, duration: ${exclusionDuration}ms`);
}
// Apply grouping if any are provided
let groupingDuration = 0;
if (groupBy.length > 0) {
const groupingStartTime = Date.now();
data = applyGroups(data, groupBy);
const groupingEndTime = Date.now();
groupingDuration = groupingEndTime - groupingStartTime;
log.info(`Grouping completed - elapsed: ${groupingEndTime - methodStartTime}ms, duration: ${groupingDuration}ms`);
}
// Log final completion time with summary
const methodEndTime = Date.now();
const totalDuration = methodEndTime - methodStartTime;
log.info(`LLMO query completed - total duration: ${totalDuration}ms (fetch: ${fetchDuration}ms, inclusion: ${inclusionDuration}ms, filtering: ${filterDuration}ms, exclusion: ${exclusionDuration}ms, grouping: ${groupingDuration}ms, mapping: ${mappingDuration}ms)`);
// Return the data, pass through any compression headers from upstream
return ok(data, {
...(response.headers ? Object.fromEntries(response.headers.entries()) : {}),
});
} catch (error) {
const errorTime = Date.now();
log.error(`Error proxying data for siteId: ${siteId}, error: ${error.message} - elapsed: ${errorTime - methodStartTime}ms`);
return badRequest(error.message);
}
};
// Handles requests to the LLMO global sheet data endpoint
const getLlmoGlobalSheetData = async (context) => {
const { log } = context;
const { siteId, configName } = context.params;
const { env } = context;
try {
log.info(`validating LLMO global sheet data for siteId: ${siteId}, configName: ${configName}`);
// Validate LLMO access but don't use the site-specific dataFolder
await getSiteAndValidateLlmo(context);
// Use 'llmo-global' folder
const sheetURL = `llmo-global/${configName}.json`;
// Add limit, offset and sheet query params to the url
const url = new URL(`${LLMO_SHEETDATA_SOURCE_URL}/${sheetURL}`);
const { limit, offset, sheet } = context.data;
if (limit) {
url.searchParams.set('limit', limit);
}
if (offset) {
url.searchParams.set('offset', offset);
}
// allow fetching a specific sheet from the sheet data source
if (sheet) {
url.searchParams.set('sheet', sheet);
}
// Fetch data from the external endpoint using the global llmo-global folder
const response = await fetch(url.toString(), {
headers: {
Authorization: `token ${env.LLMO_HLX_API_KEY || 'hlx_api_key_missing'}`,
'User-Agent': SPACECAT_USER_AGENT,
'Accept-Encoding': 'br',
},
});
if (!response.ok) {
log.error(`Failed to fetch data from external endpoint: ${response.status} ${response.statusText}`);
throw new Error(`External API returned ${response.status}: ${response.statusText}`);
}
// Get the response data
const data = await response.json();
log.info(`Successfully proxied global data for siteId: ${siteId}, sheetURL: ${sheetURL}`);
// Return the data and let the framework handle the compression
return ok(data, {
...(response.headers ? Object.fromEntries(response.headers.entries()) : {}),
});
} catch (error) {
log.error(`Error proxying global data for siteId: ${siteId}, error: ${error.message}`);
return badRequest(error.message);
}
};
// Handles requests to the LLMO config endpoint
const getLlmoConfig = async (context) => {
const { log, s3 } = context;
const { siteId } = context.params;
const version = context.data?.version;
try {
// Validate site and LLMO access
await getSiteAndValidateLlmo(context);
if (!s3 || !s3.s3Client) {
return badRequest('LLMO config storage is not configured for this environment');
}
log.info(`Fetching LLMO config from S3 for siteId: ${siteId}${version != null ? ` with version: ${version}` : ''}`);
const { config, exists, version: configVersion } = await readConfig(siteId, s3.s3Client, {
s3Bucket: s3.s3Bucket,
version,
});
// If a specific version was requested but doesn't exist, return 404
if (version != null && !exists) {
return notFound(`LLMO config version '${version}' not found for site '${siteId}'`);
}
return ok({ config, version: configVersion || null }, {
'Content-Encoding': 'br',
});
} catch (error) {
log.error(`Error getting llmo config for siteId: ${siteId}, error: ${error.message}`);
return badRequest(error.message);
}
};
async function updateLlmoConfig(context) {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can update the LLMO config');
}
const {
log,
s3,
data,
pathInfo,
} = context;
const { siteId } = context.params;
const userId = context.attributes?.authInfo?.getProfile()?.sub || 'system';
try {
// Validate site and LLMO access
await getSiteAndValidateLlmo(context);
if (!isObject(data)) {
return badRequest('LLMO config update must be provided as an object');
}
if (!s3 || !s3.s3Client) {
return badRequest('LLMO config storage is not configured for this environment');
}
const prevConfig = await readConfig(siteId, s3.s3Client, { s3Bucket: s3.s3Bucket });
const { newConfig, stats } = updateModifiedByDetails(
data,
prevConfig?.exists ? prevConfig.config : null,
userId,
);
// Validate the config, return 400 if validation fails
const result = llmoConfigSchema.safeParse(newConfig);
if (!result.success) {
const { issues, message } = result.error;
return createResponse({
message: `Invalid LLMO config: ${message}`,
details: issues,
}, 400);
}
const parsedConfig = result.data;
const { version } = await writeConfig(
siteId,
parsedConfig,
s3.s3Client,
{ s3Bucket: s3.s3Bucket },
);
// Only send audit job message if X-Trigger-Audits header is present
if (pathInfo?.headers?.['x-trigger-audits']) {
await context.sqs.sendMessage(context.env.AUDIT_JOBS_QUEUE_URL, {
type: 'llmo-customer-analysis',
siteId,
auditContext: {
configVersion: version,
previousConfigVersion: prevConfig.exists
? prevConfig.version
: /* c8 ignore next */ null,
},
});
}
// Build config summary
const summaryParts = [
`${stats.prompts.total} prompts${stats.prompts.modified ? ` (${stats.prompts.modified} modified)` : ''}`,
`${stats.categories.total} categories${stats.categories.modified ? ` (${stats.categories.modified} modified)` : ''}`,
`${stats.topics.total} topics${stats.topics.modified ? ` (${stats.topics.modified} modified)` : ''}`,
`${stats.brandAliases.total} brand aliases${stats.brandAliases.modified ? ` (${stats.brandAliases.modified} modified)` : ''}`,
`${stats.competitors.total} competitors${stats.competitors.modified ? ` (${stats.competitors.modified} modified)` : ''}`,
`${stats.deletedPrompts.total} deleted prompts${stats.deletedPrompts.modified ? ` (${stats.deletedPrompts.modified} modified)` : ''}`,
`${stats.ignoredPrompts.total} ignored prompts${stats.ignoredPrompts.modified ? ` (${stats.ignoredPrompts.modified} modified)` : ''}`,
`${stats.categoryUrls.total} category URLs`,
];
const configSummary = summaryParts.join(', ');
log.info(`User ${userId} modifying customer configuration (${configSummary}) for siteId: ${siteId}, version: ${version}`);
return ok({ version });
} catch (error) {
const msg = `${error?.message || /* c8 ignore next */ error}`;
log.error(`User ${userId} error updating llmo config for siteId: ${siteId}, error: ${msg}`);
return badRequest(msg);
}
}
// Handles requests to the LLMO questions endpoint, returns both human and ai questions
const getLlmoQuestions = async (context) => {
const { llmoConfig } = await getSiteAndValidateLlmo(context);
return ok(llmoConfig.questions || {});
};
// Handles requests to the LLMO questions endpoint, adds a new question
// the body format is { Human: [question1, question2], AI: [question3, question4] }
const addLlmoQuestion = async (context) => {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can add questions');
}
const { log } = context;
const { site, config } = await getSiteAndValidateLlmo(context);
// add the question to the llmoConfig
const newQuestions = context.data;
if (!newQuestions) {
return badRequest('No questions provided in the request body');
}
let updated = false;
// Prepare human questions with unique keys
if (newQuestions.Human && newQuestions.Human.length > 0) {
const humanQuestionsWithKeys = newQuestions.Human.map((question) => ({
...question,
key: crypto.randomUUID(),
}));
config.addLlmoHumanQuestions(humanQuestionsWithKeys);
updated = true;
}
// Prepare AI questions with unique keys
if (newQuestions.AI && newQuestions.AI.length > 0) {
const aiQuestionsWithKeys = newQuestions.AI.map((question) => ({
...question,
key: crypto.randomUUID(),
}));
config.addLlmoAIQuestions(aiQuestionsWithKeys);
updated = true;
}
if (updated) {
await saveSiteConfig(site, config, log, 'adding new questions');
}
// return the updated llmoConfig questions
return ok(config.getLlmoConfig().questions);
};
// Handles requests to the LLMO questions endpoint, removes a question
const removeLlmoQuestion = async (context) => {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can remove questions');
}
const { log } = context;
const { questionKey } = context.params;
const { site, config } = await getSiteAndValidateLlmo(context);
validateQuestionKey(config, questionKey);
// remove the question using the config method
config.removeLlmoQuestion(questionKey);
await saveSiteConfig(site, config, log, 'removing question');
// return the updated llmoConfig questions
return ok(config.getLlmoConfig().questions);
};
// Handles requests to the LLMO questions endpoint, updates a question
const patchLlmoQuestion = async (context) => {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can update questions');
}
const { log } = context;
const { questionKey } = context.params;
const { data } = context;
const { site, config } = await getSiteAndValidateLlmo(context);
validateQuestionKey(config, questionKey);
// update the question using the config method
config.updateLlmoQuestion(questionKey, data);
await saveSiteConfig(site, config, log, 'updating question');
// return the updated llmoConfig questions
return ok(config.getLlmoConfig().questions);
};
// Handles requests to the LLMO customer intent endpoint, returns customer intent array
const getLlmoCustomerIntent = async (context) => {
try {
const { llmoConfig } = await getSiteAndValidateLlmo(context);
return ok(llmoConfig.customerIntent || []);
} catch (error) {
if (error.message === 'Only users belonging to the organization can view its sites') {
return forbidden(error.message);
}
return badRequest(error.message);
}
};
// Handles requests to the LLMO customer intent endpoint, adds new customer intent items
const addLlmoCustomerIntent = async (context) => {
const { log } = context;
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can add customer intent');
}
try {
const { site, config } = await getSiteAndValidateLlmo(context);
const newCustomerIntent = context.data;
if (!Array.isArray(newCustomerIntent)) {
return badRequest('Customer intent must be provided as an array');
}
// Get existing customer intent keys to check for duplicates
const existingCustomerIntent = config.getLlmoCustomerIntent() || [];
const existingKeys = new Set(existingCustomerIntent.map((item) => item.key));
const newKeys = new Set();
// Validate structure of each customer intent item and check for duplicates
for (const intent of newCustomerIntent) {
if (!hasText(intent.key) || !hasText(intent.value)) {
return badRequest('Each customer intent item must have both key and value properties');
}
if (existingKeys.has(intent.key)) {
return badRequest(`Customer intent key '${intent.key}' already exists`);
}
if (newKeys.has(intent.key)) {
return badRequest(`Duplicate customer intent key '${intent.key}' in request`);
}
newKeys.add(intent.key);
}
config.addLlmoCustomerIntent(newCustomerIntent);
await saveSiteConfig(site, config, log, 'adding customer intent');
// return the updated llmoConfig customer intent
return ok(config.getLlmoConfig().customerIntent || []);
} catch (error) {
if (error.message === 'Only users belonging to the organization can view its sites') {
return forbidden(error.message);
}
return badRequest(error.message);
}
};
// Handles requests to the LLMO customer intent endpoint, removes a customer intent item
const removeLlmoCustomerIntent = async (context) => {
const { log } = context;
const { intentKey } = context.params;
try {
const { site, config } = await getSiteAndValidateLlmo(context);
validateCustomerIntentKey(config, intentKey);
// remove the customer intent using the config method
config.removeLlmoCustomerIntent(intentKey);
await saveSiteConfig(site, config, log, 'removing customer intent');
// return the updated llmoConfig customer intent
return ok(config.getLlmoConfig().customerIntent || []);
} catch (error) {
if (error.message === 'Only users belonging to the organization can view its sites') {
return forbidden(error.message);
}
return badRequest(error.message);
}
};
// Handles requests to the LLMO customer intent endpoint, updates a customer intent item
const patchLlmoCustomerIntent = async (context) => {
const { log } = context;
const { intentKey } = context.params;
const { data } = context;
try {
const { site, config } = await getSiteAndValidateLlmo(context);
validateCustomerIntentKey(config, intentKey);
// Validate the update data
if (!isObject(data)) {
return badRequest('Update data must be provided as an object');
}
if (!hasText(data.value)) {
return badRequest('Customer intent value must be a non-empty string');
}
// update the customer intent using the config method
config.updateLlmoCustomerIntent(intentKey, data);
await saveSiteConfig(site, config, log, 'updating customer intent');
// return the updated llmoConfig customer intent
return ok(config.getLlmoConfig().customerIntent || []);
} catch (error) {
if (error.message === 'Only users belonging to the organization can view its sites') {
return forbidden(error.message);
}
return badRequest(error.message);
}
};
// Handles requests to the LLMO CDN logs filter endpoint, updates CDN logs filter configuration
const patchLlmoCdnLogsFilter = async (context) => {
const { log } = context;
const { data } = context;
const { siteId } = context.params;
try {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can update the CDN logs filter');
}
const { site, config } = await getSiteAndValidateLlmo(context);
if (!isObject(data)) {
return badRequest('Update data must be provided as an object');
}
const { cdnlogsFilter } = data;
config.updateLlmoCdnlogsFilter(cdnlogsFilter);
await saveSiteConfig(site, config, log, 'updating CDN logs filter');
return ok(config.getLlmoConfig().cdnlogsFilter || []);
} catch (error) {
log.error(`Error updating CDN logs filter for siteId: ${siteId}, error: ${error.message}`);
return badRequest(error.message);
}
};
// Handles requests to the LLMO CDN bucket config endpoint, updates CDN bucket configuration
const patchLlmoCdnBucketConfig = async (context) => {
const { log } = context;
const { data } = context;
const { siteId } = context.params;
try {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can update the CDN bucket config');
}
const { site, config } = await getSiteAndValidateLlmo(context);
if (!isObject(data)) {
return badRequest('Update data must be provided as an object');
}
const { cdnBucketConfig } = data;
config.updateLlmoCdnBucketConfig(cdnBucketConfig);
await saveSiteConfig(site, config, log, 'updating CDN logs bucket config');
return ok(config.getLlmoConfig().cdnBucketConfig || {});
} catch (error) {
log.error(`Error updating CDN bucket config for siteId: ${siteId}, error: ${error.message}`);
return badRequest(error.message);
}
};
/**
* Onboards a new customer to LLMO.
* This endpoint handles the complete onboarding process for net new customers
* including organization validation, site creation, and LLMO configuration.
* @param {object} context - The request context.
* @returns {Promise<Response>} The onboarding response.
*/
const onboardCustomer = async (context) => {
const { log, env, attributes } = context;
const { data } = context;
try {
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can onboard');
}
// Validate required fields
if (!data || typeof data !== 'object') {
return badRequest('Onboarding data is required');
}
const { domain, brandName } = data;
if (!domain || !brandName) {
return badRequest('domain and brandName are required');
}
const { authInfo } = attributes;
if (!authInfo) {
return badRequest('Authentication information is required');
}
const profile = authInfo.getProfile();
if (!profile || !profile.tenants?.[0]?.id) {
const message = 'User profile or organization ID not found in authentication token';
log.warn(`LLMO onboarding validation failed for domain ${domain}, brand ${brandName}. Validation Error: ${message}`);
return badRequest(message);
}
const imsOrgId = `${profile.tenants[0].id}@AdobeOrg`;
// Construct base URL and data folder name
const baseURL = composeBaseURL(domain);
const dataFolder = generateDataFolder(baseURL, env.ENV);
log.info(`Starting LLMO onboarding for IMS org ${imsOrgId}, domain ${domain}, brand ${brandName}`);
// Validate that the site has not been onboarded yet
const validation = await validateSiteNotOnboarded(baseURL, imsOrgId, dataFolder, context);
if (!validation.isValid) {
log.warn(`LLMO onboarding validation failed for IMS org ${imsOrgId}, domain ${domain}, brand ${brandName}. Validation Error: ${validation.error}`);
return badRequest(validation.error);
}
// Perform the complete onboarding process
const result = await performLlmoOnboarding(
{ domain, brandName, imsOrgId },
context,
);
let brandProfileExecutionName = null;
try {
const site = await context.dataAccess?.Site?.findById(result.siteId);
if (site) {
brandProfileExecutionName = await triggerBrandProfileAgent({
context,
site,
reason: 'llmo-http',
});
}
} catch (hookError) {
log.warn(`LLMO onboarding: failed to trigger brand-profile workflow for site ${result.siteId}`, hookError);
}
log.info(`LLMO onboarding completed successfully for domain ${domain}`);
return ok({
message: result.message,
domain,
brandName,
imsOrgId,
baseURL: result.baseURL,
dataFolder: result.dataFolder,
organizationId: result.organizationId,
siteId: result.siteId,
status: 'completed',
createdAt: new Date().toISOString(),
brandProfileExecutionName,
});
} catch (error) {
log.error(`Error during LLMO onboarding: ${error.message}`);
return badRequest(error.message);
}
};
/**
* Offboards a customer from LLMO.
* This endpoint handles the complete offboarding process including
* disabling audits and cleaning up LLMO configuration.
* @param {object} context - The request context.
* @returns {Promise<Response>} The offboarding response.
*/
const offboardCustomer = async (context) => {
const { log } = context;
const { siteId } = context.params;
try {
log.info(`Starting LLMO offboarding for site ${siteId}`);
// Validate site and LLMO access
const { site, config } = await getSiteAndValidateLlmo(context);
// Perform the complete offboarding process
const result = await performLlmoOffboarding(site, config, context);
log.info(`LLMO offboarding completed successfully for site ${siteId}`);
return ok({
message: result.message,
siteId: result.siteId,
baseURL: result.baseURL,
dataFolder: result.dataFolder,
status: 'completed',
completedAt: new Date().toISOString(),
});
} catch (error) {
log.error(`Error during LLMO offboarding for site ${siteId}: ${error.message}`);
return badRequest(error.message);
}
};
const queryFiles = async (context) => {
const { log } = context;
const { siteId } = context.params;
try {
const { llmoConfig } = await getSiteAndValidateLlmo(context);
const { data, headers } = await queryLlmoFiles(context, llmoConfig);
return ok(data, headers);
} catch (error) {
log.error(`Error during LLMO cached query for site ${siteId}: ${error.message}`);
return badRequest(error.message);
}
};
// Handles requests to the LLMO rationale endpoint
const getLlmoRationale = async (context) => {
const { log } = context;
const { siteId } = context.params;
try {
// Validate site and LLMO access
await getSiteAndValidateLlmo(context);
// Delegate to the rationale handler for the actual processing
return await handleLlmoRationale(context);
} catch (error) {
log.error(`Error getting LLMO rationale for site ${siteId}: ${error.message}`);
return badRequest(error.message);
}
};
/**
* POST /sites/{siteId}/llmo/edge-optimize-config
* Creates or updates Tokowaka edge optimization configuration
* - Updates site's tokowaka meta-config in S3
* - Updates site's tokowakaEnabled in site config
* @param {object} context - Request context
* @returns {Promise<Response>} Created/updated edge config
*/
const createOrUpdateEdgeConfig = async (context) => {
const { log, dataAccess, env } = context;
const { siteId } = context.params;
const { authInfo: { profile } } = context.attributes;
const { Site } = dataAccess;
const {
enhancements, tokowakaEnabled, forceFail, patches = {}, prerender,
} = context.data || {};
if (!accessControlUtil.isLLMOAdministrator()) {
return forbidden('Only LLMO administrators can update the edge optimize config');
}
log.info(`createOrUpdateEdgeConfig request received for site ${siteId}, data=${JSON.stringify(context.data)}`);
if (tokowakaEnabled !== undefined && typeof tokowakaEnabled !== 'boolean') {
return badRequest('tokowakaEnabled field must be a boolean');
}
if (enhancements !== undefined && typeof enhancements !== 'boolean') {
return badRequest('enhancements field must be a boolean');
}
if (forceFail !== undefined && typeof forceFail !== 'boolean') {
return badRequest('forceFail field must be a boolean');
}
if (patches !== undefined && typeof patches !== 'object') {
return badRequest('patches field must be an object');
}
if (prerender !== undefined && (typeof prerender !== 'object' || Array.isArray(prerender) || !Array.isArray(prerender.allowList))) {
return badRequest('prerender field must be an object with allowList property that is an array');
}