-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdomain_objects.py
More file actions
1577 lines (1203 loc) · 58 KB
/
domain_objects.py
File metadata and controls
1577 lines (1203 loc) · 58 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 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed 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 CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines domain objects for model endpoint interactions."""
from __future__ import annotations
import json
import logging
import re
import urllib.parse
import uuid
from collections.abc import Generator
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import auto, Enum, StrEnum
from typing import Annotated, Any, Literal, Self, TypeAlias, Union
from uuid import uuid4
from zoneinfo import ZoneInfo
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt
from pydantic.functional_validators import AfterValidator, field_validator, model_validator
from utilities.constants import DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, MIN_PAGE_SIZE
from utilities.healthcheck_validator import validate_healthcheck_command
from utilities.time import now, utc_now
from utilities.validation import (
validate_all_fields_defined,
validate_any_fields_defined,
validate_instance_type,
ValidationError,
)
logger = logging.getLogger(__name__)
class InferenceContainer(StrEnum):
"""Defines supported inference container types."""
TGI = auto()
TEI = auto()
VLLM = auto()
class ModelStatus(StrEnum):
"""Defines possible model deployment states."""
CREATING = "Creating"
IN_SERVICE = "InService"
STARTING = "Starting"
STOPPING = "Stopping"
STOPPED = "Stopped"
UPDATING = "Updating"
DELETING = "Deleting"
FAILED = "Failed"
class ModelType(StrEnum):
"""Defines supported model categories."""
TEXTGEN = auto()
IMAGEGEN = auto()
VIDEOGEN = auto()
EMBEDDING = auto()
class ModelHostingType(StrEnum):
"""Defines where a model is hosted."""
THIRD_PARTY = auto()
LISA_HOSTED = auto()
INTERNAL_HOSTED = auto()
class GuardrailMode(StrEnum):
"""Defines supported guardrail execution modes."""
PRE_CALL = auto()
DURING_CALL = auto()
POST_CALL = auto()
class GuardrailConfig(BaseModel):
"""Defines configuration for a single guardrail."""
guardrailName: str = Field(min_length=1)
guardrailIdentifier: str = Field(min_length=1)
guardrailVersion: str = Field(default="DRAFT")
mode: GuardrailMode = Field(default=GuardrailMode.PRE_CALL)
description: str | None = None
allowedGroups: list[str] = Field(default_factory=list)
markedForDeletion: bool | None = Field(default=False)
# Type alias for guardrails configuration - maps guardrail IDs to their configs
GuardrailsConfig: TypeAlias = dict[str, GuardrailConfig]
class GuardrailRequest(BaseModel):
"""Defines request structure for guardrails API operations."""
model_id: str = Field(min_length=1)
guardrails_config: GuardrailsConfig
class GuardrailResponse(BaseModel):
"""Defines response structure for guardrails API operations."""
model_id: str
guardrails_config: GuardrailsConfig
success: bool
message: str
class GuardrailsTableEntry(BaseModel):
"""Represents a guardrail entry in DynamoDB table."""
guardrailId: str # Partition key
modelId: str # Sort key
guardrailName: str
guardrailIdentifier: str
guardrailVersion: str
mode: str
description: str | None
allowedGroups: list[str]
createdDate: int = Field(default_factory=lambda: now())
lastModifiedDate: int = Field(default_factory=lambda: now())
class MetricConfig(BaseModel):
"""Defines metrics configuration for auto-scaling policies."""
albMetricName: str = Field(default="RequestCountPerTarget", min_length=1)
targetValue: NonNegativeInt = Field(default=30)
duration: PositiveInt
estimatedInstanceWarmup: PositiveInt
class LoadBalancerHealthCheckConfig(BaseModel):
"""Specifies health check parameters for load balancer configuration."""
path: str = Field(min_length=1)
interval: PositiveInt
timeout: PositiveInt
healthyThresholdCount: PositiveInt
unhealthyThresholdCount: PositiveInt
class LoadBalancerConfig(BaseModel):
"""Defines load balancer settings."""
healthCheckConfig: LoadBalancerHealthCheckConfig
class ScheduleType(str, Enum):
"""Defines supported schedule types for resource scheduling"""
def __str__(self) -> str:
"""Returns string representation of the enum value"""
return str(self.value)
DAILY = "DAILY"
RECURRING = "RECURRING"
class DaySchedule(BaseModel):
"""Defines start and stop times for a single day"""
startTime: str = Field(pattern=r"^([01]?[0-9]|2[0-3]):[0-5][0-9]$")
stopTime: str = Field(pattern=r"^([01]?[0-9]|2[0-3]):[0-5][0-9]$")
@field_validator("startTime", "stopTime")
@classmethod
def validate_time_format(cls, v: str) -> str:
"""Validates time format is HH:MM"""
try:
datetime.strptime(v, "%H:%M")
except ValueError:
raise ValueError("Time must be in HH:MM format")
return v
@model_validator(mode="after")
def validate_stop_after_start(self) -> Self:
"""Validates that stop time is after start time and at least 2 hours later"""
start_time = datetime.strptime(self.startTime, "%H:%M").time()
stop_time = datetime.strptime(self.stopTime, "%H:%M").time()
# Reject if start and stop times are exactly equal
if start_time == stop_time:
raise ValueError("Stop time must be at least 2 hours after start time")
# Convert to datetime objects for easier calculation
start_dt = datetime.combine(datetime.today(), start_time)
stop_dt = datetime.combine(datetime.today(), stop_time)
# Handle case where stop time is next day (e.g., start at 23:00, stop at 01:00)
if stop_time < start_time:
stop_dt += timedelta(days=1)
# Calculate the time difference
time_diff = stop_dt - start_dt
# Ensure stop time is at least 2 hours after start time
min_duration = timedelta(hours=2)
if time_diff < min_duration:
raise ValueError("Stop time must be at least 2 hours after start time")
return self
class WeeklySchedule(BaseModel):
"""Defines schedule for each day of the week with one start/stop time per day"""
monday: DaySchedule | None = None
tuesday: DaySchedule | None = None
wednesday: DaySchedule | None = None
thursday: DaySchedule | None = None
friday: DaySchedule | None = None
saturday: DaySchedule | None = None
sunday: DaySchedule | None = None
@model_validator(mode="after")
def validate_daily_schedules(self) -> Self:
"""Validates that at least one day has a schedule configured"""
days = [self.monday, self.tuesday, self.wednesday, self.thursday, self.friday, self.saturday, self.sunday]
if not any(days):
raise ValueError("At least one day must have a schedule configured")
return self
class NextScheduledAction(BaseModel):
"""Defines the next scheduled action for a model"""
action: str = Field(pattern=r"^(START|STOP)$")
scheduledTime: str
class ScheduleFailure(BaseModel):
"""Defines schedule failure information"""
timestamp: str
error: str
retryCount: int
class BaseSchedulingConfig(BaseModel):
"""Base configuration shared by all scheduling types"""
timezone: str = Field(default="UTC")
# Schedule metadata and tracking
scheduleEnabled: bool = False
lastScheduleUpdate: str | None = None
scheduledActionArns: list[str] | None = None
# Status tracking
scheduleConfigured: bool = False
lastScheduleFailed: bool = False
# Next scheduled action info (computed field)
nextScheduledAction: NextScheduledAction | None = None
# Failure tracking
lastScheduleFailure: ScheduleFailure | None = None
@field_validator("timezone")
@classmethod
def validate_timezone(cls, v: str) -> str:
"""Validates timezone is a valid IANA timezone identifier"""
try:
ZoneInfo(v)
except Exception:
raise ValueError(f"Invalid timezone: {v}, timezone must be a valid IANA timezone identifier")
return v
class DailySchedulingConfig(BaseSchedulingConfig):
"""Configuration for daily schedules with different times per day"""
scheduleType: Literal["DAILY"] = "DAILY"
dailySchedule: WeeklySchedule
@model_validator(mode="after")
def validate_daily_schedule_exclusivity(self) -> Self:
"""Validates that only dailySchedule is present for DAILY type"""
# Check if any recurring schedule data was included
if hasattr(self, "recurringSchedule"):
raise ValueError("recurringSchedule not allowed for DAILY schedule type")
return self
class RecurringSchedulingConfig(BaseSchedulingConfig):
"""Configuration for recurring schedules with same time every day"""
scheduleType: Literal["RECURRING"] = "RECURRING"
recurringSchedule: DaySchedule
@model_validator(mode="after")
def validate_recurring_schedule_exclusivity(self) -> Self:
"""Validates that only recurringSchedule is present for RECURRING type"""
# Check if any daily schedule data was included
if hasattr(self, "dailySchedule"):
raise ValueError("dailySchedule not allowed for RECURRING schedule type")
return self
# Discriminated union type for scheduling configurations
SchedulingConfig = Annotated[
Union[DailySchedulingConfig, RecurringSchedulingConfig], Field(discriminator="scheduleType")
]
class AutoScalingConfig(BaseModel):
"""Specifies auto-scaling parameters for model deployment."""
blockDeviceVolumeSize: NonNegativeInt | None = 50
minCapacity: PositiveInt
maxCapacity: PositiveInt
desiredCapacity: PositiveInt | None = None
cooldown: PositiveInt
defaultInstanceWarmup: Annotated[int, Field(gt=0, le=3600)]
metricConfig: MetricConfig
scheduling: SchedulingConfig | None = None
@model_validator(mode="after")
def validate_auto_scaling_config(self) -> Self:
"""Validates auto-scaling configuration parameters."""
if self.minCapacity > self.maxCapacity:
raise ValueError("minCapacity must be less than or equal to the maxCapacity.")
if self.blockDeviceVolumeSize is not None and self.blockDeviceVolumeSize < 30:
raise ValueError("blockDeviceVolumeSize must be greater than or equal to 30.")
if self.desiredCapacity and self.desiredCapacity > self.maxCapacity:
raise ValueError("Desired capacity must be less than or equal to max capacity.")
if self.desiredCapacity and self.desiredCapacity < self.minCapacity:
raise ValueError("Desired capacity must be greater than or equal to minimum capacity.")
return self
class AutoScalingInstanceConfig(BaseModel):
"""Defines instance count parameters for auto-scaling updates."""
minCapacity: PositiveInt | None = None
maxCapacity: PositiveInt | None = None
desiredCapacity: PositiveInt | None = None
cooldown: PositiveInt | None = None
defaultInstanceWarmup: Annotated[int, Field(gt=0, le=3600)] | None = None
@model_validator(mode="after")
def validate_auto_scaling_instance_config(self) -> Self:
"""Validates auto-scaling instance configuration parameters."""
config_fields = [
self.minCapacity,
self.maxCapacity,
self.desiredCapacity,
self.cooldown,
self.defaultInstanceWarmup,
]
if not validate_any_fields_defined(config_fields):
raise ValueError("At least one option of autoScalingInstanceConfig must be defined.")
if self.desiredCapacity and self.maxCapacity and self.desiredCapacity > self.maxCapacity:
raise ValueError("Desired capacity must be less than or equal to max capacity.")
if self.desiredCapacity and self.minCapacity and self.desiredCapacity < self.minCapacity:
raise ValueError("Desired capacity must be greater than or equal to minimum capacity.")
return self
class ContainerHealthCheckConfig(BaseModel):
"""Specifies container health check parameters."""
command: str | list[str]
interval: PositiveInt
startPeriod: PositiveInt
timeout: PositiveInt
retries: PositiveInt
@field_validator("command")
@classmethod
def validate_command(cls, command: str | list[str]) -> str | list[str]:
"""Validates healthcheck command format for ECS compatibility."""
validate_healthcheck_command(command)
return command
class ContainerConfigImage(BaseModel):
"""Defines container image configuration."""
baseImage: str = Field(min_length=1)
type: str = Field(min_length=1)
class ContainerConfig(BaseModel):
"""Specifies container deployment settings."""
image: ContainerConfigImage
sharedMemorySize: PositiveInt
healthCheckConfig: ContainerHealthCheckConfig
environment: dict[str, str] | None = {}
memoryReservation: int | None = Field(
default=None, ge=0, description="Memory reservation in MiB for the container."
)
@field_validator("environment")
@classmethod
def validate_environment(cls, environment: dict[str, str]) -> dict[str, str]:
"""Validates environment variable key names."""
if environment:
if not all(key for key in environment.keys()):
raise ValueError("Empty strings are not allowed for environment variable key names.")
return environment
class ContainerConfigUpdatable(BaseModel):
"""Specifies container configuration fields that can be updated."""
environment: dict[str, str] | None = None
sharedMemorySize: PositiveInt | None = None
healthCheckCommand: str | list[str] | None = None
healthCheckInterval: PositiveInt | None = None
healthCheckTimeout: PositiveInt | None = None
healthCheckStartPeriod: PositiveInt | None = None
healthCheckRetries: PositiveInt | None = None
@field_validator("environment")
@classmethod
def validate_environment(cls, environment: dict[str, str]) -> dict[str, str]:
"""Validates environment variable key names."""
if environment:
if not all(key for key in environment.keys()):
raise ValueError("Empty strings are not allowed for environment variable key names.")
return environment
class ModelFeature(BaseModel):
"""Defines model feature attributes."""
__exceptions: list[Any] = []
name: str
overview: str
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
class LISAModel(BaseModel):
"""Defines core model attributes and configuration."""
autoScalingConfig: AutoScalingConfig | None = None
containerConfig: ContainerConfig | None = None
inferenceContainer: InferenceContainer | None = None
instanceType: Annotated[str, AfterValidator(validate_instance_type)] | None = None
loadBalancerConfig: LoadBalancerConfig | None = None
modelId: str
modelName: str
modelDescription: str | None = None
modelType: ModelType
modelUrl: str | None = None
status: ModelStatus
streaming: bool
features: list[ModelFeature] | None = None
allowedGroups: list[str] | None = None
guardrailsConfig: GuardrailsConfig | None = None
contextWindow: int | None = None
hostingType: ModelHostingType | None = ModelHostingType.THIRD_PARTY
class ApiResponseBase(BaseModel):
"""Defines base structure for API responses."""
model: LISAModel
class CreateModelRequest(BaseModel):
"""Specifies parameters for model creation requests."""
autoScalingConfig: AutoScalingConfig | None = None
containerConfig: ContainerConfig | None = None
inferenceContainer: InferenceContainer | None = None
instanceType: Annotated[str, AfterValidator(validate_instance_type)] | None = None
loadBalancerConfig: LoadBalancerConfig | None = None
modelId: str = Field(min_length=1)
modelName: str = Field(min_length=1)
modelDescription: str | None = None
modelType: ModelType
modelUrl: str | None = None
streaming: bool | None = False
features: list[ModelFeature] | None = None
allowedGroups: list[str] | None = None
apiKey: str | None = None
guardrailsConfig: GuardrailsConfig | None = None
hostingType: ModelHostingType | None = ModelHostingType.THIRD_PARTY
@model_validator(mode="after")
def validate_create_model_request(self) -> Self:
"""Validates model creation request parameters."""
if self.modelType == ModelType.EMBEDDING and self.streaming:
raise ValueError("Embedding model cannot be set with streaming enabled.")
required_hosting_fields = [
self.autoScalingConfig,
self.containerConfig,
self.inferenceContainer,
self.instanceType,
self.loadBalancerConfig,
]
if validate_any_fields_defined(required_hosting_fields):
if not validate_all_fields_defined(required_hosting_fields):
raise ValueError(
"All of the following fields must be defined if creating a LISA-hosted model: "
"autoScalingConfig, containerConfig, inferenceContainer, instanceType, and loadBalancerConfig"
)
if self.hostingType == ModelHostingType.INTERNAL_HOSTED and not self.modelUrl:
raise ValueError("modelUrl is required for INTERNAL_HOSTED models.")
if self.hostingType == ModelHostingType.INTERNAL_HOSTED and self.modelUrl:
parsed_url = urllib.parse.urlparse(self.modelUrl)
if not parsed_url.hostname or not parsed_url.hostname.lower().endswith(".elb.amazonaws.com"):
raise ValueError("modelUrl for INTERNAL_HOSTED models must target an AWS load balancer hostname.")
return self
class CreateModelResponse(ApiResponseBase):
"""Defines response structure for model creation."""
pass
class ListModelsResponse(BaseModel):
"""Defines response structure for model listing."""
models: list[LISAModel]
class GetModelResponse(ApiResponseBase):
"""Defines response structure for model retrieval."""
pass
class UpdateModelRequest(BaseModel):
"""Specifies parameters for model update requests."""
autoScalingInstanceConfig: AutoScalingInstanceConfig | None = None
enabled: bool | None = None
modelType: ModelType | None = None
modelDescription: str | None = None
streaming: bool | None = None
allowedGroups: list[str] | None = None
features: list[ModelFeature] | None = None
containerConfig: ContainerConfigUpdatable | None = None
guardrailsConfig: GuardrailsConfig | None = None
@model_validator(mode="after")
def validate_update_model_request(self) -> Self:
"""Validates model update request parameters."""
fields = [
self.autoScalingInstanceConfig,
self.enabled,
self.modelType,
self.modelDescription,
self.streaming,
self.allowedGroups,
self.features,
self.containerConfig,
self.guardrailsConfig,
]
if not validate_any_fields_defined(fields):
raise ValueError(
"At least one field out of autoScalingInstanceConfig, containerConfig, enabled, modelType, "
"modelDescription, streaming, allowedGroups, features, or guardrailsConfig must be "
"defined in request payload."
)
if self.modelType == ModelType.EMBEDDING and self.streaming:
raise ValueError("Embedding model cannot be set with streaming enabled.")
return self
@field_validator("autoScalingInstanceConfig")
@classmethod
def validate_autoscaling_instance_config(cls, config: AutoScalingInstanceConfig) -> AutoScalingInstanceConfig:
"""Validates auto-scaling instance configuration."""
if not config:
raise ValueError("The autoScalingInstanceConfig must not be null if defined in request payload.")
return config
@field_validator("containerConfig")
@classmethod
def validate_container_config(cls, config: ContainerConfigUpdatable) -> ContainerConfigUpdatable:
"""Validates container configuration update."""
if not config:
raise ValueError("The containerConfig must not be null if defined in request payload.")
return config
class UpdateModelResponse(ApiResponseBase):
"""Defines response structure for model updates."""
pass
class UpdateContextWindowRequest(BaseModel):
"""Request body for manually setting a model's context window."""
contextWindow: int = Field(gt=0, description="The maximum context window size (number of tokens) for the model.")
class UpdateContextWindowResponse(ApiResponseBase):
"""Response for a single-model context window update."""
pass
class DeleteModelResponse(ApiResponseBase):
"""Defines response structure for model deletion."""
pass
class UpdateScheduleResponse(BaseModel):
"""Response object for schedule create/update operations."""
message: str
modelId: str
scheduleEnabled: bool
class GetScheduleResponse(BaseModel):
"""Response object for getting schedule configuration."""
modelId: str
scheduling: dict[str, Any]
nextScheduledAction: dict[str, str] | None = None
class DeleteScheduleResponse(BaseModel):
"""Response object for schedule deletion."""
message: str
modelId: str
scheduleEnabled: bool
class GetScheduleStatusResponse(BaseModel):
"""Response object for getting schedule status."""
modelId: str
scheduleEnabled: bool
scheduleConfigured: bool
lastScheduleFailed: bool
scheduleStatus: str
scheduleType: str | None = None
timezone: str
nextScheduledAction: dict[str, str] | None = None
lastScheduleUpdate: str | None = None
lastScheduleFailure: dict[str, Any] | None = None
class IngestionType(StrEnum):
"""Specifies whether ingestion was automatic or manual."""
AUTO = auto() # Automatic ingestion via pipeline (event-driven)
MANUAL = auto() # Manual ingestion via API (user-initiated)
EXISTING = auto() # Pre-existing document discovered in KB (user-managed)
class JobActionType(StrEnum):
"""Defines deletion job types."""
DOCUMENT_INGESTION = auto()
DOCUMENT_BATCH_INGESTION = auto()
DOCUMENT_DELETION = auto()
DOCUMENT_BATCH_DELETION = auto()
COLLECTION_DELETION = auto()
RagDocumentDict = dict[str, Any]
class ChunkingStrategyType(StrEnum):
"""Defines supported document chunking strategies."""
FIXED = auto()
NONE = auto()
class IngestionStatus(StrEnum):
"""Defines possible states for document ingestion process."""
INGESTION_PENDING = "INGESTION_PENDING"
INGESTION_IN_PROGRESS = "INGESTION_IN_PROGRESS"
INGESTION_COMPLETED = "INGESTION_COMPLETED"
INGESTION_FAILED = "INGESTION_FAILED"
DELETE_PENDING = "DELETE_PENDING"
DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"
DELETE_COMPLETED = "DELETE_COMPLETED"
DELETE_FAILED = "DELETE_FAILED"
def is_terminal(self) -> bool:
"""Check if status is terminal."""
return self in [
IngestionStatus.INGESTION_COMPLETED,
IngestionStatus.INGESTION_FAILED,
IngestionStatus.DELETE_COMPLETED,
IngestionStatus.DELETE_FAILED,
]
def is_success(self) -> bool:
"""Check if status is success."""
return self in [
IngestionStatus.INGESTION_COMPLETED,
IngestionStatus.DELETE_COMPLETED,
]
class FixedChunkingStrategy(BaseModel):
"""Defines parameters for fixed-size document chunking."""
type: ChunkingStrategyType = ChunkingStrategyType.FIXED
size: int = Field(ge=100, le=10000)
overlap: int = Field(ge=0)
@model_validator(mode="after")
def validate_overlap(self) -> Self:
"""Validates overlap is not more than half of chunk size."""
if self.overlap > self.size / 2:
raise ValueError(
f"chunk overlap ({self.overlap}) must be less than or equal to " f"half of chunk size ({self.size / 2})"
)
return self
class NoneChunkingStrategy(BaseModel):
"""Defines parameters for no-chunking strategy - documents ingested as-is."""
type: ChunkingStrategyType = ChunkingStrategyType.NONE
ChunkingStrategy = Union[FixedChunkingStrategy, NoneChunkingStrategy]
class RagSubDocument(BaseModel):
"""Represents a sub-document entity for DynamoDB storage."""
document_id: str
subdocs: list[str] = Field(default_factory=lambda: [])
index: int | None = Field(default=None)
sk: str | None = None
def __init__(self, **data: Any) -> None:
super().__init__(**data)
self.sk = f"subdoc#{self.document_id}#{self.index}"
class RagDocument(BaseModel):
"""Represents a RAG document entity for DynamoDB storage."""
pk: str | None = None
document_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
repository_id: str = Field(min_length=3, max_length=20)
collection_id: str
document_name: str
source: str
username: str
subdocs: list[str] = Field(default_factory=lambda: [], exclude=True)
chunk_strategy: ChunkingStrategy
ingestion_type: IngestionType = Field(default_factory=lambda: IngestionType.MANUAL)
upload_date: int = Field(default_factory=lambda: now())
chunks: int | None = 0
model_config = ConfigDict(use_enum_values=True, validate_default=True)
def __init__(self, **data: Any) -> None:
super().__init__(**data)
self.pk = self.createPartitionKey(self.repository_id, self.collection_id)
# Only calculate chunks if not explicitly provided in data (for new documents)
if "chunks" not in data:
self.chunks = len(self.subdocs)
@staticmethod
def createPartitionKey(repository_id: str, collection_id: str) -> str:
"""Generates a partition key from repository and collection IDs."""
return f"{repository_id}#{collection_id}"
def chunk_doc(self, chunk_size: int = 1000) -> Generator[RagSubDocument]:
"""Segments document into smaller sub-documents."""
total_subdocs = len(self.subdocs)
for start_index in range(0, total_subdocs, chunk_size):
end_index = min(start_index + chunk_size, total_subdocs)
yield RagSubDocument(
document_id=self.document_id, subdocs=self.subdocs[start_index:end_index], index=start_index
)
@staticmethod
def join_docs(documents: list[RagDocumentDict]) -> list[RagDocumentDict]:
"""Combines multiple sub-documents into a single document."""
grouped_docs: dict[str, list[RagDocumentDict]] = {}
for doc in documents:
doc_id = doc.get("document_id", "")
if doc_id not in grouped_docs:
grouped_docs[doc_id] = []
grouped_docs[doc_id].append(doc)
joined_docs: list[RagDocumentDict] = []
for docs in grouped_docs.values():
joined_doc = docs[0]
joined_doc["subdocs"] = [sub_doc for doc in docs for sub_doc in (doc.get("subdocs", []) or [])]
joined_docs.append(joined_doc)
return joined_docs
class IngestionJob(BaseModel):
"""Represents an ingestion job entity for DynamoDB storage."""
id: str = Field(default_factory=lambda: str(uuid4()))
s3_path: str
collection_id: str | None = Field(
default=None, description="Collection ID for full deletion, None for default collection deletion"
)
document_id: str | None = Field(default=None)
repository_id: str
chunk_strategy: ChunkingStrategy | None = Field(default=None)
embedding_model: str | None = Field(
default=None, description="Embedding model name, used as index identifier for default collections"
)
username: str | None = Field(default=None)
ingestion_type: IngestionType = Field(
default=IngestionType.MANUAL, description="How the document was ingested (MANUAL, AUTO, or EXISTING)"
)
status: IngestionStatus = IngestionStatus.INGESTION_PENDING
created_date: str = Field(default_factory=lambda: utc_now().isoformat())
error_message: str | None = Field(default=None)
document_name: str | None = Field(default=None)
auto: bool | None = Field(default=None)
metadata: dict | None = Field(default=None)
job_type: JobActionType | None = Field(default=None, description="Type of deletion job")
collection_deletion: bool = Field(default=False, description="Indicates this is a collection deletion job")
s3_paths: list[str] | None = Field(default=None, description="List of S3 paths for batch ingestion operations")
document_ids: list[str] | None = Field(
default=None, description="List of document IDs from completed batch operations"
)
def __init__(self, **data: Any) -> None:
super().__init__(**data)
self.document_name = self.s3_path.split("/")[-1] if self.s3_path else ""
self.auto = self.username == "system"
@model_validator(mode="after")
def validate_collection_deletion_identifiers(self) -> Self:
"""Validate that for collection deletion jobs, exactly one of collection_id or embedding_model is provided."""
if self.collection_deletion:
has_collection_id = self.collection_id is not None
has_embedding_model = self.embedding_model is not None
# XOR: exactly one must be true
if has_collection_id == has_embedding_model:
if not has_collection_id and not has_embedding_model:
raise ValueError(
"For collection deletion jobs, either collection_id or embedding_model must be provided"
)
else:
raise ValueError(
"For collection deletion jobs, only one of collection_id or "
"embedding_model should be provided, not both"
)
return self
class PaginatedResponse(BaseModel):
"""Base class for paginated API responses."""
lastEvaluatedKey: dict[str, str] | None = None
hasNextPage: bool = False
hasPreviousPage: bool = False
class DeleteResponse(BaseModel):
"""Generic response model for delete operations."""
deleted: bool = False
class SuccessResponse(BaseModel):
"""Generic response model for successful operations."""
message: str
class ListJobsResponse(PaginatedResponse):
"""Response structure for listing ingestion jobs with pagination."""
jobs: list[IngestionJob]
@dataclass
class PaginationResult:
"""Result of pagination analysis."""
has_next_page: bool
has_previous_page: bool
@classmethod
def from_keys(cls, original_key: dict[str, str] | None, returned_key: dict[str, str] | None) -> PaginationResult:
"""Create pagination result from keys."""
return cls(has_next_page=returned_key is not None, has_previous_page=original_key is not None)
@dataclass
class PaginationParams:
"""Shared pagination parameter handling."""
page_size: int = DEFAULT_PAGE_SIZE
last_evaluated_key: dict[str, str] | None = None
@staticmethod
def parse_page_size(
query_params: dict[str, str], default: int = DEFAULT_PAGE_SIZE, max_size: int = MAX_PAGE_SIZE
) -> int:
"""Parse and validate page size with configurable limits."""
page_size = int(query_params.get("pageSize", str(default)))
return max(MIN_PAGE_SIZE, min(page_size, max_size))
@staticmethod
def parse_last_evaluated_key(query_params: dict[str, str], key_fields: list[str]) -> dict[str, str] | None:
"""Parse last evaluated key from query parameters.
Args:
query_params: Query string parameters dictionary
key_fields: List of field names to extract from query params (e.g., ['collectionId', 'status', 'createdAt'])
Returns:
Dictionary with last evaluated key fields, or None if no key present
Notes:
Query params should be formatted as lastEvaluatedKey{FieldName}, e.g.:
- lastEvaluatedKeyCollectionId
- lastEvaluatedKeyStatus
- lastEvaluatedKeyCreatedAt
"""
# Check if any lastEvaluatedKey fields are present
has_key = any(f"lastEvaluatedKey{field.capitalize()}" in query_params for field in key_fields)
if not has_key:
return None
last_evaluated_key = {}
for field in key_fields:
# Convert field name to camelCase for query param (e.g., collectionId -> CollectionId)
param_name = f"lastEvaluatedKey{field[0].upper()}{field[1:]}"
if param_name in query_params:
last_evaluated_key[field] = urllib.parse.unquote(query_params[param_name])
return last_evaluated_key if last_evaluated_key else None
@staticmethod
def parse_last_evaluated_key_v2(query_params: dict[str, str]) -> dict[str, Any] | None:
"""Parse v2 pagination token from query parameters.
The v2 token format supports scalable pagination with per-repository cursors.
It is passed as a JSON string in the lastEvaluatedKey query parameter.
Args:
query_params: Query string parameters dictionary
Returns:
Dictionary with v2 pagination token structure, or None if not present
Token Structure:
{
"version": "v2",
"repositoryCursors": {
"repo-id": {
"lastEvaluatedKey": {...},
"exhausted": bool
}
},
"globalOffset": int,
"filters": {
"filter": str,
"sortBy": str,
"sortOrder": str
}
}