-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathconfig.py
More file actions
2081 lines (1705 loc) · 71.9 KB
/
config.py
File metadata and controls
2081 lines (1705 loc) · 71.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
"""Model with service configuration."""
# pylint: disable=too-many-lines
import re
from enum import Enum
from functools import cached_property
from pathlib import Path
from re import Pattern
from typing import Any, Literal, Optional, Self
import jsonpath_ng
import yaml
from jsonpath_ng.exceptions import JSONPathError
from pydantic import (
AnyHttpUrl,
BaseModel,
ConfigDict,
Field,
FilePath,
NonNegativeInt,
PositiveInt,
PrivateAttr,
SecretStr,
field_validator,
model_validator,
)
from pydantic.dataclasses import dataclass
import constants
from log import get_logger
from utils import checks
from utils.mcp_auth_headers import resolve_authorization_headers
logger = get_logger(__name__)
class ConfigurationBase(BaseModel):
"""Base class for all configuration models that rejects unknown fields."""
model_config = ConfigDict(extra="forbid")
class TLSConfiguration(ConfigurationBase):
"""TLS configuration.
Transport Layer Security (TLS) is a cryptographic protocol designed to
provide communications security over a computer network, such as the
Internet. The protocol is widely used in applications such as email,
instant messaging, and voice over IP, but its use in securing HTTPS remains
the most publicly visible.
Useful resources:
- [FastAPI HTTPS Deployment](https://fastapi.tiangolo.com/deployment/https/)
- [Transport Layer Security Overview](https://en.wikipedia.org/wiki/Transport_Layer_Security)
- [What is TLS](https://www.ssltrust.eu/learning/ssl/transport-layer-security-tls)
"""
tls_certificate_path: Optional[FilePath] = Field(
None,
title="TLS certificate path",
description="SSL/TLS certificate file path for HTTPS support.",
)
tls_key_path: Optional[FilePath] = Field(
None,
title="TLS key path",
description="SSL/TLS private key file path for HTTPS support.",
)
tls_key_password: Optional[FilePath] = Field(
None,
title="SSL/TLS key password path",
description="Path to file containing the password to decrypt the SSL/TLS private key.",
)
@model_validator(mode="after")
def check_tls_configuration(self) -> Self:
"""
Perform post-validation checks for the TLS configuration.
Currently a no-op that returns the model unchanged.
Returns:
Self: The validated model instance.
"""
return self
class CORSConfiguration(ConfigurationBase):
"""CORS configuration.
CORS or 'Cross-Origin Resource Sharing' refers to the situations when a
frontend running in a browser has JavaScript code that communicates with a
backend, and the backend is in a different 'origin' than the frontend.
Useful resources:
- [CORS in FastAPI](https://fastapi.tiangolo.com/tutorial/cors/)
- [Wikipedia article](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
- [What is CORS?](https://dev.to/akshay_chauhan/what-is-cors-explained-8f1)
"""
# not AnyHttpUrl: we need to support "*" that is not valid URL
allow_origins: list[str] = Field(
["*"],
title="Allow origins",
description="A list of origins allowed for cross-origin requests. An origin "
"is the combination of protocol (http, https), domain "
"(myapp.com, localhost, localhost.tiangolo.com), and port (80, 443, 8080). "
"Use ['*'] to allow all origins.",
)
allow_credentials: bool = Field(
False,
title="Allow credentials",
description="Indicate that cookies should be supported for cross-origin requests",
)
allow_methods: list[str] = Field(
["*"],
title="Allow methods",
description="A list of HTTP methods that should be allowed for "
"cross-origin requests. You can use ['*'] to allow "
"all standard methods.",
)
allow_headers: list[str] = Field(
["*"],
title="Allow headers",
description="A list of HTTP request headers that should be supported "
"for cross-origin requests. You can use ['*'] to allow all headers. The "
"Accept, Accept-Language, Content-Language and Content-Type headers are "
"always allowed for simple CORS requests.",
)
@model_validator(mode="after")
def check_cors_configuration(self) -> Self:
"""
Validate CORS settings and enforce that credentials are not allowed.
Raises:
ValueError: If `allow_credentials` is true while
`allow_origins` contains the "*" wildcard.
Returns:
Self: The validated configuration instance.
"""
# credentials are not allowed with wildcard origins per CORS/Fetch spec.
# see https://fastapi.tiangolo.com/tutorial/cors/
if self.allow_credentials and "*" in self.allow_origins:
raise ValueError(
"Invalid CORS configuration: allow_credentials can not be set to true when "
"allow origins contains the '*' wildcard."
"Use explicit origins or disable credentials."
)
return self
class SQLiteDatabaseConfiguration(ConfigurationBase):
"""SQLite database configuration."""
db_path: str = Field(
...,
title="DB path",
description="Path to file where SQLite database is stored",
)
class InMemoryCacheConfig(ConfigurationBase):
"""In-memory cache configuration."""
max_entries: PositiveInt = Field(
...,
title="Max entries",
description="Maximum number of entries stored in the in-memory cache",
)
class PostgreSQLDatabaseConfiguration(ConfigurationBase):
"""PostgreSQL database configuration.
PostgreSQL database is used by Lightspeed Core Stack service for storing
information about conversation IDs. It can also be leveraged to store
conversation history and information about quota usage.
Useful resources:
- [Psycopg: connection classes](https://www.psycopg.org/psycopg3/docs/api/connections.html)
- [PostgreSQL connection strings](https://www.connectionstrings.com/postgresql/)
- [How to Use PostgreSQL in Python](https://www.freecodecamp.org/news/postgresql-in-python/)
"""
host: str = Field(
"localhost",
title="Hostname",
description="Database server host or socket directory",
)
port: PositiveInt = Field(
5432,
title="Port",
description="Database server port",
)
db: str = Field(
...,
title="Database name",
description="Database name to connect to",
)
user: str = Field(
...,
title="User name",
description="Database user name used to authenticate",
)
password: SecretStr = Field(
...,
title="Password",
description="Password used to authenticate",
)
namespace: Optional[str] = Field(
"public",
title="Name space",
description="Database namespace",
)
ssl_mode: str = Field(
constants.POSTGRES_DEFAULT_SSL_MODE,
title="SSL mode",
description="SSL mode",
)
gss_encmode: str = Field(
constants.POSTGRES_DEFAULT_GSS_ENCMODE,
title="GSS encmode",
description="This option determines whether or with what priority a secure GSS "
"TCP/IP connection will be negotiated with the server.",
)
ca_cert_path: Optional[FilePath] = Field(
None,
title="CA certificate path",
description="Path to CA certificate",
)
@model_validator(mode="after")
def check_postgres_configuration(self) -> Self:
"""
Validate PostgreSQL configuration constraints.
Ensures the configured port is within the valid TCP port range.
Returns:
self: The validated configuration instance.
Raises:
ValueError: If `port` is greater than 65535.
"""
if self.port > 65535:
raise ValueError("Port value should be less than 65536")
return self
class DatabaseConfiguration(ConfigurationBase):
"""Database configuration."""
sqlite: Optional[SQLiteDatabaseConfiguration] = Field(
None,
title="SQLite configuration",
description="SQLite database configuration",
)
postgres: Optional[PostgreSQLDatabaseConfiguration] = Field(
None,
title="PostgreSQL configuration",
description="PostgreSQL database configuration",
)
@model_validator(mode="after")
def check_database_configuration(self) -> Self:
"""
Ensure exactly one database backend is configured, defaulting to a temporary SQLite one.
If neither `sqlite` nor `postgres` is set, assigns a default SQLite
configuration using the file path "/tmp/lightspeed-stack.db". If both
backends are configured, raises a `ValueError`.
Returns:
self: The configuration instance with exactly one
database backend set.
"""
total_configured_dbs = sum([self.sqlite is not None, self.postgres is not None])
if total_configured_dbs == 0:
# Default to SQLite in a (hopefully) tmpfs if no database configuration is provided.
# This is good for backwards compatibility for deployments that do not mind having
# no persistent database.
sqlite_file_name = "/tmp/lightspeed-stack.db"
self.sqlite = SQLiteDatabaseConfiguration(db_path=sqlite_file_name)
elif total_configured_dbs > 1:
raise ValueError("Only one database configuration can be provided")
return self
@property
def db_type(self) -> Literal["sqlite", "postgres"]:
"""
Determine which database backend is configured.
Returns:
The string "sqlite" if a SQLite configuration is
present, "postgres" if a PostgreSQL configuration is
present.
Raises:
ValueError: If neither SQLite nor PostgreSQL configuration is set.
"""
if self.sqlite is not None:
return "sqlite"
if self.postgres is not None:
return "postgres"
raise ValueError("No database configuration found")
@property
def config(self) -> SQLiteDatabaseConfiguration | PostgreSQLDatabaseConfiguration:
"""
Get the active database backend configuration.
Returns:
SQLiteDatabaseConfiguration or PostgreSQLDatabaseConfiguration: The
configured SQLite configuration if `sqlite` is set, otherwise the
configured PostgreSQL configuration if `postgres` is set.
Raises:
ValueError: If neither `sqlite` nor `postgres` is
configured.
"""
if self.sqlite is not None:
return self.sqlite
if self.postgres is not None:
return self.postgres
raise ValueError("No database configuration found")
class ServiceConfiguration(ConfigurationBase):
"""Service configuration.
Lightspeed Core Stack is a REST API service that accepts requests on a
specified hostname and port. It is also possible to enable authentication
and specify the number of Uvicorn workers. When more workers are specified,
the service can handle requests concurrently.
"""
host: str = Field(
"localhost",
title="Host",
description="Service hostname",
)
port: PositiveInt = Field(
8080,
title="Port",
description="Service port",
)
base_url: Optional[str] = Field(
None,
title="Base URL",
description="Externally reachable base URL for the service; needed for A2A support.",
)
auth_enabled: bool = Field(
False,
title="Authentication enabled",
description="Enables the authentication subsystem",
)
workers: PositiveInt = Field(
1,
title="Number of workers",
description="Number of Uvicorn worker processes to start",
)
color_log: bool = Field(
True,
title="Color log",
description="Enables colorized logging",
)
access_log: bool = Field(
True,
title="Access log",
description="Enables logging of all access information",
)
tls_config: TLSConfiguration = Field(
default_factory=lambda: TLSConfiguration(
tls_certificate_path=None, tls_key_path=None, tls_key_password=None
),
title="TLS configuration",
description="Transport Layer Security configuration for HTTPS support",
)
root_path: str = Field(
"",
title="Root path",
description="ASGI root path for serving behind a reverse proxy on a subpath",
)
@field_validator("root_path")
@classmethod
def validate_root_path(cls, value: str) -> str:
"""Validate root_path format.
Ensures the root path is either empty or starts with a leading
slash and does not end with a trailing slash.
Parameters:
----------
value: The root path value to validate.
Returns:
-------
The validated root path value.
Raises:
------
ValueError: If root_path is missing a leading slash or has
a trailing slash.
"""
if value and not value.startswith("/"):
raise ValueError("root_path must start with '/'")
if value.endswith("/"):
raise ValueError("root_path must not end with '/'")
return value
cors: CORSConfiguration = Field(
default_factory=lambda: CORSConfiguration(
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
),
title="CORS configuration",
description="Cross-Origin Resource Sharing configuration for cross-domain requests",
)
@model_validator(mode="after")
def check_service_configuration(self) -> Self:
"""
Validate service configuration and enforce allowed port range.
Raises:
ValueError: If `port` is greater than 65535.
Returns:
self: The validated model instance.
"""
if self.port > 65535:
raise ValueError("Port value should be less than 65536")
return self
class ModelContextProtocolServer(ConfigurationBase):
"""Model context protocol server configuration.
MCP (Model Context Protocol) servers provide tools and capabilities to the
AI agents. These are configured by this structure. Only MCP servers
defined in the lightspeed-stack.yaml configuration are available to the
agents. Tools configured in the llama-stack run.yaml are not accessible to
lightspeed-core agents.
Useful resources:
- [Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro)
- [MCP FAQs](https://modelcontextprotocol.io/faqs)
- [Wikipedia article](https://en.wikipedia.org/wiki/Model_Context_Protocol)
"""
name: str = Field(
...,
title="MCP name",
description="MCP server name that must be unique",
)
provider_id: str = Field(
"model-context-protocol",
title="Provider ID",
description="MCP provider identification",
)
url: str = Field(
...,
title="MCP server URL",
description="URL of the MCP server",
)
authorization_headers: dict[str, str] = Field(
default_factory=dict,
title="Authorization headers",
description=(
"Headers to send to the MCP server. "
"The map contains the header name and the path to a file containing "
"the header value (secret). "
"There are 3 special cases: "
"1. Usage of the kubernetes token in the header. "
"To specify this use a string 'kubernetes' instead of the file path. "
"2. Usage of the client-provided token in the header. "
"To specify this use a string 'client' instead of the file path. "
"3. Usage of the oauth token in the header. "
"To specify this use a string 'oauth' instead of the file path. "
),
)
_resolved_authorization_headers: dict[str, str] = PrivateAttr(default_factory=dict)
@property
def resolved_authorization_headers(self) -> dict[str, str]:
"""Resolved authorization headers (computed from authorization_headers)."""
return self._resolved_authorization_headers
headers: list[str] = Field(
default_factory=list,
title="Propagated headers",
description=(
"List of HTTP header names to automatically forward from the incoming "
"request to this MCP server. Headers listed here are extracted from "
"the original client request and included when calling the MCP server. "
"This is useful when infrastructure components (e.g. API gateways) "
"inject headers that MCP servers need, such as x-rh-identity in HCC. "
"Header matching is case-insensitive. "
"These headers are additive with authorization_headers and MCP-HEADERS."
),
)
@field_validator("headers")
@classmethod
def validate_headers(cls, value: list[str]) -> list[str]:
"""Validate propagated headers: no empty strings, no case-insensitive duplicates."""
seen: set[str] = set()
for header in value:
if not header.strip():
msg = "Header names must not be empty"
raise ValueError(msg)
lower = header.lower()
if lower in seen:
msg = f"Duplicate header name (case-insensitive): '{header}'"
raise ValueError(msg)
seen.add(lower)
return value
timeout: Optional[PositiveInt] = Field(
default=None,
title="Request timeout",
description=(
"Timeout in seconds for requests to the MCP server. "
"If not specified, the default timeout from Llama Stack will be used. "
"Note: This field is reserved for future use when Llama Stack adds timeout support."
),
)
@model_validator(mode="after")
def resolve_auth_headers(self) -> Self:
"""
Resolve authorization headers by reading secret files.
Automatically populates resolved_authorization_headers by reading
secret files specified in authorization_headers. Special values
'kubernetes' and 'client' are preserved for later substitution.
Returns:
Self: The model instance with resolved_authorization_headers populated.
"""
if self.authorization_headers:
self._resolved_authorization_headers = resolve_authorization_headers(
self.authorization_headers
)
return self
class LlamaStackConfiguration(ConfigurationBase):
"""Llama stack configuration.
Llama Stack is a comprehensive system that provides a uniform set of tools
for building, scaling, and deploying generative AI applications, enabling
developers to create, integrate, and orchestrate multiple AI services and
capabilities into an adaptable setup.
Useful resources:
- [Llama Stack](https://www.llama.com/products/llama-stack/)
- [Python Llama Stack client](https://github.com/llamastack/llama-stack-client-python)
- [Build AI Applications with Llama Stack](https://llamastack.github.io/)
"""
url: Optional[AnyHttpUrl] = Field(
None,
title="Llama Stack URL",
description="URL to Llama Stack service; used when library mode is disabled. "
"Must be a valid HTTP or HTTPS URL.",
)
api_key: Optional[SecretStr] = Field(
None,
title="API key",
description="API key to access Llama Stack service",
)
use_as_library_client: Optional[bool] = Field(
None,
title="Use as library",
description="When set to true Llama Stack will be used in library mode, not in "
"server mode (default)",
)
library_client_config_path: Optional[str] = Field(
None,
title="Llama Stack configuration path",
description="Path to configuration file used when Llama Stack is run in library mode",
)
timeout: PositiveInt = Field(
180,
title="Request timeout",
description="Timeout in seconds for requests to Llama Stack service. "
"Default is 180 seconds (3 minutes) to accommodate long-running RAG queries.",
)
@model_validator(mode="after")
def check_llama_stack_model(self) -> Self:
"""
Validate the Llama Stack configuration and enforce mode-specific requirements.
If no URL is provided, requires explicit library-client mode selection.
When library-client mode is enabled, requires a non-empty
`library_client_config_path` that points to a regular, readable YAML
file (checked via checks.file_check). Also normalizes a None
`use_as_library_client` to False.
Returns:
Self: The validated LlamaStackConfiguration instance.
Raises:
ValueError: If the configuration is invalid, e.g. no
URL and library-client mode is unspecified or
disabled, or library-client mode is enabled but
`library_client_config_path` is not provided.
"""
if self.url is None:
# when URL is not set, it is supposed that Llama Stack should be run in library mode
# it means that use_as_library_client attribute must be set to True
if self.use_as_library_client is None:
raise ValueError(
"Llama stack URL is not specified and library client mode is not specified"
)
if self.use_as_library_client is False:
raise ValueError(
"Llama stack URL is not specified and library client mode is not enabled"
)
# None -> False conversion
if self.use_as_library_client is None:
self.use_as_library_client = False
if self.use_as_library_client:
# when use_as_library_client is set to true, Llama Stack will be run in library mode
# it means that:
# - Llama Stack URL should not be set, and
# - library_client_config_path attribute must be set and must point to
# a regular readable YAML file
if self.library_client_config_path is None:
# pylint: disable=line-too-long
raise ValueError(
"Llama stack library client mode is enabled but a configuration file path is not specified"
)
# the configuration file must exists and be regular readable file
checks.file_check(
Path(self.library_client_config_path), "Llama Stack configuration file"
)
return self
class SplunkConfiguration(ConfigurationBase):
"""Splunk HEC (HTTP Event Collector) configuration.
Splunk HEC allows sending events directly to Splunk over HTTP/HTTPS.
This configuration is used to send telemetry events for inference
requests to the corporate Splunk deployment.
Useful resources:
- [Splunk HEC Docs](https://docs.splunk.com/Documentation/SplunkCloud)
- [About HEC](https://docs.splunk.com/Documentation/Splunk/latest/Data)
"""
enabled: bool = Field(
False,
title="Enabled",
description="Enable or disable Splunk HEC integration.",
)
url: Optional[str] = Field(
None,
title="HEC URL",
description="Splunk HEC endpoint URL.",
)
token_path: Optional[FilePath] = Field(
None,
title="Token path",
description="Path to file containing the Splunk HEC authentication token.",
)
index: Optional[str] = Field(
None,
title="Index",
description="Target Splunk index for events.",
)
source: str = Field(
"lightspeed-stack",
title="Source",
description="Event source identifier.",
)
timeout: PositiveInt = Field(
5,
title="Timeout",
description="HTTP timeout in seconds for HEC requests.",
)
verify_ssl: bool = Field(
True,
title="Verify SSL",
description="Whether to verify SSL certificates for HEC endpoint.",
)
@model_validator(mode="after")
def check_splunk_configuration(self) -> Self:
"""Validate that required fields are set when Splunk is enabled.
Returns:
Self: The validated configuration instance.
Raises:
ValueError: If enabled is True but required fields are missing.
"""
if self.enabled:
missing_fields = []
if not self.url:
missing_fields.append("url")
if not self.token_path:
missing_fields.append("token_path")
if not self.index:
missing_fields.append("index")
if missing_fields:
raise ValueError(
f"Splunk is enabled but required fields are missing: "
f"{', '.join(missing_fields)}"
)
return self
class UserDataCollection(ConfigurationBase):
"""User data collection configuration."""
feedback_enabled: bool = Field(
False,
title="Feedback enabled",
description="When set to true the user feedback is stored and later sent for analysis.",
)
feedback_storage: Optional[str] = Field(
None,
title="Feedback storage directory",
description="Path to directory where feedback will be saved for further processing.",
)
transcripts_enabled: bool = Field(
False,
title="Transcripts enabled",
description="When set to true the conversation history is stored and later sent for "
"analysis.",
)
transcripts_storage: Optional[str] = Field(
None,
title="Transcripts storage directory",
description="Path to directory where conversation history will be saved for further "
"processing.",
)
@model_validator(mode="after")
def check_storage_location_is_set_when_needed(self) -> Self:
"""
Ensure storage locations are configured and writable when feedback is enabled.
If feedback collection is enabled, `feedback_storage` must be provided
and refer to a directory that exists or can be created and is writable.
If transcript collection is enabled, `transcripts_storage` must be
provided and refer to a directory that exists or can be created and is
writable.
Returns:
self: The validated UserDataCollection instance.
"""
if self.feedback_enabled:
if self.feedback_storage is None:
raise ValueError(
"feedback_storage is required when feedback is enabled"
)
checks.directory_check(
Path(self.feedback_storage),
desc="Check directory to store feedback",
must_exists=False,
must_be_writable=True,
)
if self.transcripts_enabled:
if self.transcripts_storage is None:
raise ValueError(
"transcripts_storage is required when transcripts is enabled"
)
checks.directory_check(
Path(self.transcripts_storage),
desc="Check directory to store transcripts",
must_exists=False,
must_be_writable=True,
)
return self
class JsonPathOperator(str, Enum):
"""Supported operators for JSONPath evaluation.
Note: this is not a real model, just an enumeration of all supported JSONPath operators.
"""
EQUALS = "equals"
CONTAINS = "contains"
IN = "in"
MATCH = "match"
class JwtRoleRule(ConfigurationBase):
"""Rule for extracting roles from JWT claims."""
jsonpath: str = Field(
...,
title="JSON path",
description="JSONPath expression to evaluate against the JWT payload",
)
operator: JsonPathOperator = Field(
...,
title="Operator",
description="JSON path comparison operator",
)
negate: bool = Field(
False,
title="Negate rule",
description="If set to true, the meaning of the rule is negated",
)
value: Any = Field(
...,
title="Value",
description="Value to compare against",
)
roles: list[str] = Field(
...,
title="List of roles",
description="Roles to be assigned if the rule matches",
)
@model_validator(mode="after")
def check_jsonpath(self) -> Self:
"""
Validate that the `jsonpath` expression parses as a JSONPath.
Returns:
self: The same model instance when the JSONPath
expression is valid.
Raises:
ValueError: If the `jsonpath` cannot be parsed; the
message includes the offending expression and parser
error.
"""
try:
# try to parse the JSONPath
jsonpath_ng.parse(self.jsonpath)
return self
except JSONPathError as e:
raise ValueError(
f"Invalid JSONPath expression: {self.jsonpath}: {e}"
) from e
@model_validator(mode="after")
def check_roles(self) -> Self:
"""
Validate the rule's roles list and enforce required constraints.
Performs three checks: ensures at least one role is present, enforces
that all roles are unique, and prohibits the wildcard role `"*"`.
Returns:
self: The same `JwtRoleRule` instance when validation
succeeds.
"""
if not self.roles:
raise ValueError("At least one role must be specified in the rule")
if len(self.roles) != len(set(self.roles)):
raise ValueError("Roles must be unique in the rule")
if any(role == "*" for role in self.roles):
raise ValueError(
"The wildcard '*' role is not allowed in role rules, "
"everyone automatically gets this role"
)
return self
@model_validator(mode="after")
def check_regex_pattern(self) -> Self:
"""
Validate that when the operator is MATCH, the rule is a valid regular expression string.
Raises:
ValueError: If the operator is MATCH and `value` is
not a string or is not a valid regular expression.
Returns:
Self: The same JwtRoleRule instance.
"""
if self.operator == JsonPathOperator.MATCH:
if not isinstance(self.value, str):
raise ValueError(
f"MATCH operator requires a string pattern, {type(self.value).__name__}"
)
try:
re.compile(self.value)
except re.error as e:
raise ValueError(
f"Invalid regex pattern for MATCH operator: {self.value}: {e}"
) from e
return self
@cached_property
def compiled_regex(self) -> Optional[Pattern[str]]:
"""
Provide a compiled regex when the rule uses the MATCH operator and the value is a string.
Returns:
Optional[Pattern[str]]: Compiled `re.Pattern` of `value` if
`operator` is `JsonPathOperator.MATCH` and `value` is a `str`,
`None` otherwise.
"""
if self.operator == JsonPathOperator.MATCH and isinstance(self.value, str):
return re.compile(self.value)
return None
class Action(str, Enum):
"""Available actions in the system.
Note: this is not a real model, just an enumeration of all action names.
"""
# Special action to allow unrestricted access to all actions
ADMIN = "admin"
# List the conversations of other users
LIST_OTHERS_CONVERSATIONS = "list_other_conversations"
# Read the contents of conversations of other users
READ_OTHERS_CONVERSATIONS = "read_other_conversations"
# Continue the conversations of other users
QUERY_OTHERS_CONVERSATIONS = "query_other_conversations"
# Delete the conversations of other users
DELETE_OTHERS_CONVERSATIONS = "delete_other_conversations"
# Access the query endpoint
QUERY = "query"
# Access the streaming query endpoint
STREAMING_QUERY = "streaming_query"
# Access the conversation endpoint
GET_CONVERSATION = "get_conversation"
# List own conversations