Skip to content

Knowledge Base Module

Service

unique_toolkit.services.knowledge_base

KnowledgeBaseService

Provides methods for searching, downloading and uploading content in the knowledge base.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
class KnowledgeBaseService:
    """
    Provides methods for searching, downloading and uploading content in the knowledge base.
    """

    def __init__(
        self,
        company_id: str,
        user_id: str,
        metadata_filter: dict[str, Any] | None = None,
    ):
        """
        Initialize the KnowledgeBaseService with a company_id, user_id and chat_id.
        """

        self._metadata_filter = None
        [company_id, user_id] = validate_required_values([company_id, user_id])
        self._company_id = company_id
        self._user_id = user_id
        self._metadata_filter = metadata_filter

    @classmethod
    @deprecated(
        "Use UniqueContext.from_chat_event(event) (if you have a ChatEvent) or "
        "UniqueContext.from_event(event) (for any BaseEvent) with UniqueServiceFactory instead."
    )
    def from_event(cls, event: BaseEvent[Any]):
        """
        Initialize the ContentService with an event.
        """
        metadata_filter = None

        if isinstance(event, (ChatEvent | Event)):
            metadata_filter = event.payload.metadata_filter

        return cls(
            company_id=event.company_id,
            user_id=event.user_id,
            metadata_filter=metadata_filter,
        )

    @classmethod
    def from_context(cls, context: UniqueContext) -> Self:
        """Create a KnowledgeBaseService from a :class:`UniqueContext`.

        This is the preferred constructor when using the service factory pattern.

        Args:
            context: The request context carrying auth and chat information.
        """
        metadata_filter = (
            context.chat.metadata_filter if context.chat is not None else None
        )
        return cls(
            company_id=context.auth.get_confidential_company_id(),
            user_id=context.auth.get_confidential_user_id(),
            metadata_filter=metadata_filter,
        )

    @classmethod
    def from_settings(
        cls,
        settings: UniqueSettings | str | None = None,
        metadata_filter: dict[str, Any] | None = None,
        **kwargs: Any,
    ):
        """
        Initialize the ContentService with a settings object and metadata filter.
        """

        if settings is None:
            settings = UniqueSettings.from_env_auto_with_sdk_init()
        elif isinstance(settings, str):
            settings = UniqueSettings.from_env_auto_with_sdk_init(filename=settings)

        if metadata_filter is None and settings.context.chat is not None:
            metadata_filter = settings.context.chat.metadata_filter

        return cls(
            company_id=settings.authcontext.get_confidential_company_id(),
            user_id=settings.authcontext.get_confidential_user_id(),
            metadata_filter=metadata_filter,
        )

    # Content Search
    # ------------------------------------------------------------------------------------------------

    @overload
    def search_content_chunks(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        metadata_filter: dict[str, Any],
        score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
    ) -> list[ContentChunk]: ...

    @overload
    def search_content_chunks(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        metadata_filter: dict[str, Any],
        content_ids: list[str],
        score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
    ) -> list[ContentChunk]: ...

    def search_content_chunks(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
        scope_ids: list[str] | None = None,
        metadata_filter: dict[str, Any] | None = None,
        content_ids: list[str] | None = None,
        score_threshold: float | None = None,
    ) -> list[ContentChunk]:
        """
        Performs a synchronous search for content chunks in the knowledge base.

        Args:
            search_string (str): The search string.
            search_type (ContentSearchType): The type of search to perform.
            limit (int): The maximum number of results to return.
            search_language (str, optional): The language for the full-text search. Defaults to "english".
            reranker_config (ContentRerankerConfig | None, optional): The reranker configuration. Defaults to None.
            scope_ids (list[str] | None, optional): Deprecated. Folded into ``metadata_filter``
                as a ``folderId in [scope_ids]`` clause; do not use for new code.
            metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
            content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
            score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.

        Returns:
            list[ContentChunk]: The search results.

        Raises:
            Exception: If there's an error during the search operation.
        """

        if metadata_filter is None:
            metadata_filter = self._metadata_filter

        if scope_ids:
            warnings.warn(
                "Passing scope_ids to KnowledgeBaseService.search_content_chunks is "
                "deprecated; use metadata_filter with folderId operator 'in' instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            clause = build_folder_id_in_clause(scope_ids)
            metadata_filter = merge_scope_clause_into_metadata_filter(
                clause, metadata_filter
            )
            scope_ids = None

        try:
            searches = search_content_chunks(
                user_id=self._user_id,
                company_id=self._company_id,
                chat_id="",
                search_string=search_string,
                search_type=search_type,
                limit=limit,
                search_language=search_language,
                reranker_config=reranker_config,
                chat_only=False,
                metadata_filter=metadata_filter,
                content_ids=content_ids,
                score_threshold=score_threshold,
            )
            return searches
        except Exception as e:
            _LOGGER.error(f"Error while searching content chunks: {e}")
            raise e

    @overload
    async def search_content_chunks_async(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        metadata_filter: dict[str, Any],
        score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
    ) -> list[ContentChunk]: ...

    @overload
    async def search_content_chunks_async(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        metadata_filter: dict[str, Any],
        content_ids: list[str],
        score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
    ) -> list[ContentChunk]: ...

    async def search_content_chunks_async(
        self,
        *,
        search_string: str,
        search_type: ContentSearchType,
        limit: int,
        search_language: str = DEFAULT_SEARCH_LANGUAGE,
        reranker_config: ContentRerankerConfig | None = None,
        scope_ids: list[str] | None = None,
        metadata_filter: dict[str, Any] | None = None,
        content_ids: list[str] | None = None,
        score_threshold: float | None = None,
    ):
        """
        Performs an asynchronous search for content chunks in the knowledge base.

        Args:
            search_string (str): The search string.
            search_type (ContentSearchType): The type of search to perform.
            limit (int): The maximum number of results to return.
            search_language (str, optional): The language for the full-text search. Defaults to "english".
            reranker_config (ContentRerankerConfig | None, optional): The reranker configuration. Defaults to None.
            scope_ids (list[str] | None, optional): Deprecated. Folded into ``metadata_filter``
                as a ``folderId in [scope_ids]`` clause; do not use for new code.
            metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
            content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
            score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.

        Returns:
            list[ContentChunk]: The search results.

        Raises:
            Exception: If there's an error during the search operation.
        """
        if metadata_filter is None:
            metadata_filter = self._metadata_filter

        if scope_ids:
            warnings.warn(
                "Passing scope_ids to KnowledgeBaseService.search_content_chunks_async is "
                "deprecated; use metadata_filter with folderId operator 'in' instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            clause = build_folder_id_in_clause(scope_ids)
            metadata_filter = merge_scope_clause_into_metadata_filter(
                clause, metadata_filter
            )
            scope_ids = None

        try:
            searches = await search_content_chunks_async(
                user_id=self._user_id,
                company_id=self._company_id,
                chat_id="",
                search_string=search_string,
                search_type=search_type,
                limit=limit,
                search_language=search_language,
                reranker_config=reranker_config,
                chat_only=False,
                metadata_filter=metadata_filter,
                content_ids=content_ids,
                score_threshold=score_threshold,
            )
            return searches
        except Exception as e:
            _LOGGER.error(f"Error while searching content chunks: {e}")
            raise e

    def search_contents(
        self,
        *,
        where: dict[str, Any],
        include_failed_content: bool = False,
    ) -> list[Content]:
        """
        Performs a search in the knowledge base by filter (and not a smilarity search)
        This function loads complete content of the files from the knowledge base in contrast to search_content_chunks.

        Args:
            where (dict): The search criteria.

        Returns:
            list[Content]: The search results.
        """

        return search_contents(
            user_id=self._user_id,
            company_id=self._company_id,
            chat_id="",
            where=where,
            include_failed_content=include_failed_content,
        )

    async def search_contents_async(
        self,
        *,
        where: dict[str, Any],
        include_failed_content: bool = False,
    ) -> list[Content]:
        """
        Performs an asynchronous search for content files in the knowledge base by filter.

        Args:
            where (dict): The search criteria.

        Returns:
            list[Content]: The search results.
        """

        return await search_contents_async(
            user_id=self._user_id,
            company_id=self._company_id,
            chat_id="",
            where=where,
            include_failed_content=include_failed_content,
        )

    # Content Management
    # ------------------------------------------------------------------------------------------------

    def upload_content_from_bytes(
        self,
        content: bytes,
        *,
        content_name: str,
        mime_type: str,
        scope_id: str,
        skip_ingestion: bool = False,
        ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> Content:
        """
        Uploads content to the knowledge base.

        Args:
            content (bytes): The content to upload.
            content_name (str): The name of the content.
            mime_type (str): The MIME type of the content.
            scope_id (str | None): The scope ID. Defaults to None.
            skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
            ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
            metadata (dict | None): The metadata to associate with the content. Defaults to None.

        Returns:
            Content: The uploaded content.
        """

        return upload_content_from_bytes(
            user_id=self._user_id,
            company_id=self._company_id,
            content=content,
            content_name=content_name,
            mime_type=mime_type,
            scope_id=scope_id,
            chat_id="",
            skip_ingestion=skip_ingestion,
            ingestion_config=ingestion_config,
            metadata=metadata,
        )

    async def upload_content_from_bytes_async(
        self,
        content: bytes,
        *,
        content_name: str,
        mime_type: str,
        scope_id: str,
        skip_ingestion: bool = False,
        ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> Content:
        """
        Uploads content to the knowledge base.

        Args:
            content (bytes): The content to upload.
            content_name (str): The name of the content.
            mime_type (str): The MIME type of the content.
            scope_id (str | None): The scope ID. Defaults to None.
            skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
            skip_excel_ingestion (bool): Whether to skip excel ingestion. Defaults to False.
            ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
            metadata (dict | None): The metadata to associate with the content. Defaults to None.

        Returns:
            Content: The uploaded content.
        """

        return await upload_content_from_bytes_async(
            user_id=self._user_id,
            company_id=self._company_id,
            content=content,
            content_name=content_name,
            mime_type=mime_type,
            scope_id=scope_id,
            chat_id="",
            skip_ingestion=skip_ingestion,
            ingestion_config=ingestion_config,
            metadata=metadata,
        )

    def upload_content(
        self,
        path_to_content: str,
        content_name: str,
        mime_type: str,
        scope_id: str,
        skip_ingestion: bool = False,
        skip_excel_ingestion: bool = False,
        ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> Content:
        """
        Uploads content to the knowledge base.

        Args:
            path_to_content (str): The path to the content to upload.
            content_name (str): The name of the content.
            mime_type (str): The MIME type of the content.
            scope_id (str | None): The scope ID. Defaults to None.
            skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
            skip_excel_ingestion (bool): Whether to skip excel ingestion. Defaults to False.
            ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
            metadata (dict[str, Any] | None): The metadata to associate with the content. Defaults to None.

        Returns:
            Content: The uploaded content.
        """

        return upload_content(
            user_id=self._user_id,
            company_id=self._company_id,
            path_to_content=path_to_content,
            content_name=content_name,
            mime_type=mime_type,
            scope_id=scope_id,
            chat_id="",
            skip_ingestion=skip_ingestion,
            skip_excel_ingestion=skip_excel_ingestion,
            ingestion_config=ingestion_config,
            metadata=metadata,
        )

    def download_content_to_file(
        self,
        *,
        content_id: str,
        output_dir_path: Path | None = None,
        output_filename: str | None = None,
    ) -> Path:
        """
        Downloads content from a chat and saves it to a file.

        Args:
            content_id (str): The ID of the content to download.
            output_filename (str | None): The name of the file to save the content as. If not provided, the original filename will be used. Defaults to None.
            output_dir_path (str | Path | None): The path to the temporary directory where the content will be saved. Defaults to "/tmp".

        Returns:
            Path: The path to the downloaded file.

        Raises:
            Exception: If the download fails or the filename cannot be determined.
        """

        return download_content_to_file_by_id(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            chat_id="",
            filename=output_filename,
            tmp_dir_path=output_dir_path,
        )

    def download_content_to_bytes(
        self,
        *,
        content_id: str,
    ) -> bytes:
        """
        Downloads content to memory

        Args:
            content_id (str): The id of the uploaded content.

        Returns:
            bytes: The downloaded content.

        Raises:
            Exception: If the download fails.
        """

        return download_content_to_bytes(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            chat_id=None,
        )

    async def download_content_to_bytes_async(
        self,
        *,
        content_id: str,
    ) -> bytes:
        """
        Asynchronously downloads content to memory.

        Args:
            content_id (str): The id of the uploaded content.

        Returns:
            bytes: The downloaded content.

        Raises:
            Exception: If the download fails.
        """

        return await download_content_to_bytes_async(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            chat_id=None,
        )

    def batch_file_upload(
        self,
        *,
        local_files: list[Path],
        remote_folders: list[PurePath],
        overwrite: bool = False,
        metadata_generator: Callable[[Path, PurePath], dict[str, Any]] | None = None,
    ) -> None:
        """
        Upload files to the knowledge base into corresponding folders

        Args:
            local_files (list[Path]): The local files to upload
            remote_folders (list[PurePath]): The remote folders to upload the files to
            overwrite (bool): Whether to overwrite existing files
            metadata_generator (Callable[[Path, PurePath], dict[str, Any]] | None): The metadata generator function

        Returns:
            None
        """

        if len(local_files) != len(remote_folders):
            raise ValueError(
                "The number of local files and remote folders must be the same"
            )

        creation_result = self.create_folders(paths=remote_folders)

        folders_path_to_scope_id = {
            folder_path: result.id
            for folder_path, result in zip(remote_folders, creation_result)
        }

        _old_scope_id = None
        _existing_file_names: list[str] = []

        for remote_folder_path, local_file_path in zip(remote_folders, local_files):
            scope_id = folders_path_to_scope_id[remote_folder_path]
            mime_type = mimetypes.guess_type(local_file_path.name)[0]

            if mime_type is None:
                _LOGGER.warning(
                    f"No mime type found for file {local_file_path.name}, skipping"
                )
                continue

            if not overwrite:
                if _old_scope_id is None or _old_scope_id != scope_id:
                    _LOGGER.debug(f"Switching to new folder {scope_id}")
                    _old_scope_id = scope_id
                    _existing_file_names = self.get_file_names_in_folder(
                        scope_id=scope_id
                    )

                if local_file_path.name in _existing_file_names:
                    _LOGGER.warning(
                        f"File {local_file_path.name} already exists in folder {scope_id}, skipping"
                    )
                    continue

            metadata = None
            if metadata_generator is not None:
                metadata = metadata_generator(local_file_path, remote_folder_path)

            self.upload_content(
                path_to_content=str(local_file_path),
                content_name=local_file_path.name,
                mime_type=mime_type,
                scope_id=scope_id,
                metadata=metadata,
            )

    # Content Information
    # ------------------------------------------------------------------------------------------------
    def get_paginated_content_infos(
        self,
        *,
        metadata_filter: dict[str, Any] | None = None,
        skip: int | None = None,
        take: int | None = None,
        file_path: str | None = None,
    ) -> PaginatedContentInfos:
        return get_content_info(
            user_id=self._user_id,
            company_id=self._company_id,
            metadata_filter=metadata_filter,
            skip=skip,
            take=take,
            file_path=file_path,
        )

    async def get_paginated_content_infos_async(
        self,
        *,
        metadata_filter: dict[str, Any] | None = None,
        skip: int | None = None,
        take: int | None = None,
        file_path: str | None = None,
    ) -> PaginatedContentInfos:
        return await get_content_info_async(
            user_id=self._user_id,
            company_id=self._company_id,
            metadata_filter=metadata_filter,
            skip=skip,
            take=take,
            file_path=file_path,
        )

    async def get_content_infos_async(
        self,
        *,
        metadata_filter: dict[str, Any] | None = None,
        step_size: int = 100,
        max_concurrent_requests: int = 10,
    ) -> list[ContentInfo]:
        """
        Fetches all content infos from the knowledge base using parallel pagination.
        The API limits responses to 100 items per request, so this method fetches
        the total count first, then retrieves all pages concurrently (bounded by
        ``max_concurrent_requests`` to avoid rate limiting or connection exhaustion).

        Args:
            metadata_filter (dict[str, Any] | None): The metadata filter to use. Defaults to None.
            step_size (int): Number of items per page. Defaults to 100.
            max_concurrent_requests (int): Maximum number of concurrent API calls.
                Defaults to 10.

        Returns:
            list[ContentInfo]: All content infos visible to the user.
        """

        info_for_count_of_total_content = await self.get_paginated_content_infos_async(
            metadata_filter=metadata_filter,
            take=1,
        )

        total_count = info_for_count_of_total_content.total_count

        semaphore = asyncio.Semaphore(max_concurrent_requests)

        async def _fetch_page(skip: int) -> PaginatedContentInfos:
            async with semaphore:
                return await self.get_paginated_content_infos_async(
                    metadata_filter=metadata_filter,
                    skip=skip,
                    take=step_size,
                )

        results: list[PaginatedContentInfos | BaseException] = await asyncio.gather(
            *[_fetch_page(i) for i in range(0, total_count, step_size)],
            return_exceptions=True,
        )

        for result in results:
            if isinstance(result, BaseException):
                _LOGGER.error("Error fetching paginated content infos", exc_info=result)

        return [
            content_info
            for result in results
            if not isinstance(result, BaseException)
            for content_info in result.content_infos
        ]

    def get_file_names_in_folder(self, *, scope_id: str) -> list[str]:
        """
        Get the list of file names in a knowledge base folder

        Args:
            scope_id (str): The scope id of the folder

        Returns:
            list[str]: The list of file names in the folder
        """
        smart_rule = Statement(
            operator=Operator.EQUALS, value=scope_id, path=["folderId"]
        )
        infos = self.get_paginated_content_infos(
            metadata_filter=smart_rule.model_dump(mode="json")
        )
        return [i.key for i in infos.content_infos]

    # Folder Management
    # ------------------------------------------------------------------------------------------------

    def get_folder_info(
        self,
        *,
        scope_id: str,
    ) -> FolderInfo:
        return get_folder_info(
            user_id=self._user_id,
            company_id=self._company_id,
            scope_id=scope_id,
        )

    async def get_folder_info_async(
        self,
        *,
        scope_id: str,
    ) -> FolderInfo:
        return await get_folder_info_async(
            user_id=self._user_id,
            company_id=self._company_id,
            scope_id=scope_id,
        )

    # File Tree Resolution
    # ------------------------------------------------------------------------------------------------

    @staticmethod
    def extract_scope_ids(content_infos: list[ContentInfo]) -> set[str]:
        """Extracts all unique scope IDs from the ``folderIdPath`` metadata field.

        Args:
            content_infos: The content infos to extract scope IDs from.

        Returns:
            set[str]: All unique scope IDs found across content infos.
        """
        scope_ids: set[str] = set()
        for content_info in content_infos:
            if (
                content_info.metadata
                and (folder_id_path := content_info.metadata.get("folderIdPath"))
                is not None
                and isinstance(folder_id_path, str)
            ):
                scope_ids.update(
                    sid
                    for sid in folder_id_path.replace("uniquepathid://", "").split("/")
                    if sid
                )
        return scope_ids

    async def _translate_scope_id_async(self, scope_id: str) -> str | None:
        """Resolve a single scope ID to its folder name.

        Returns the folder name, or ``None`` if the lookup fails.
        """
        try:
            folder_info = await self.get_folder_info_async(scope_id=scope_id)
            return folder_info.name
        except Exception as e:
            _LOGGER.warning(
                f"Could not resolve folder for scope_id {scope_id}", exc_info=e
            )
            return None

    async def _translate_scope_ids_async(
        self,
        scope_ids: set[str],
        *,
        max_concurrent_requests: int = 25,
    ) -> dict[str, str]:
        """Translate a set of scope IDs to folder names concurrently.

        Scope IDs that cannot be resolved are silently omitted from the result.

        Args:
            scope_ids: The scope IDs to translate.
            max_concurrent_requests: Maximum number of concurrent API calls.
                Defaults to 25.

        Returns:
            dict[str, str]: Mapping from scope ID to folder name.
        """
        scope_id_list = list(scope_ids)
        semaphore = asyncio.Semaphore(max_concurrent_requests)

        async def _resolve(sid: str) -> str | None:
            async with semaphore:
                return await self._translate_scope_id_async(sid)

        results = await asyncio.gather(*[_resolve(sid) for sid in scope_id_list])
        return {
            sid: name for sid, name in zip(scope_id_list, results) if name is not None
        }

    async def resolve_visible_file_paths_async(
        self,
        *,
        metadata_filter: dict[str, Any] | None = None,
    ) -> list[tuple[ContentInfo, list[str]]]:
        """Resolves file paths visible to the current user asynchronously.

        Returns each content item paired with its resolved file path segments.

        Args:
            metadata_filter: Optional metadata filter to narrow the content scope.

        Returns:
            list[tuple[ContentInfo, list[str]]]: Each tuple is
                ``(content_info, [folder1, folder2, ..., filename])``.
        """
        content_infos = await self.get_content_infos_async(
            metadata_filter=metadata_filter,
        )
        scope_ids = self.extract_scope_ids(content_infos)
        scope_id_to_folder_name = await self._translate_scope_ids_async(scope_ids)

        resolved: list[tuple[ContentInfo, list[str]]] = []
        for content_info in content_infos:
            if (
                content_info.metadata
                and (folder_id_path := content_info.metadata.get("folderIdPath"))
                is not None
                and isinstance(folder_id_path, str)
            ):
                file_path = [
                    scope_id_to_folder_name.get(sid, sid)
                    for sid in folder_id_path.replace("uniquepathid://", "").split("/")
                    if sid
                ]
            else:
                file_path = ["_no_folder_path"]

            file_path.append(content_info.key)
            resolved.append((content_info, file_path))

        return resolved

    def _pop_forbidden_metadata_keys(self, metadata: dict[str, Any]) -> dict[str, Any]:
        forbidden_keys = [
            "key",
            "url",
            "title",
            "folderId",
            "mimeType",
            "companyId",
            "contentId",
            "folderIdPath",
            "externalFileOwner",
        ]
        for key in forbidden_keys:
            metadata.pop(key, None)
        return metadata

    def create_folders(self, *, paths: list[PurePath]) -> list[BaseFolderInfo]:
        """
        Create folders in the knowledge base if the path does not exists.

        Args:
            paths (list[PurePath]): The paths to create the folders at

        Returns:
            list[BaseFolderInfo]: The information about the created folders or existing folders
        """
        result = unique_sdk.Folder.create_paths(
            user_id=self._user_id,
            company_id=self._company_id,
            paths=[path.as_posix() for path in paths],
        )
        return [
            BaseFolderInfo.model_validate(folder, by_alias=True, by_name=True)
            for folder in result["createdFolders"]
        ]

        # Metadata

    # Metadata Management
    # ------------------------------------------------------------------------------------------------

    def replace_content_metadata(
        self,
        *,
        content_id: str,
        metadata: dict[str, Any],
    ) -> ContentInfo:
        return update_content(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            metadata=metadata,
        )

    def update_content_metadata(
        self,
        *,
        content_info: ContentInfo,
        additional_metadata: dict[str, Any],
    ) -> ContentInfo:
        camelized_additional_metadata = humps.camelize(additional_metadata)
        camelized_additional_metadata = self._pop_forbidden_metadata_keys(
            camelized_additional_metadata
        )

        if content_info.metadata is not None:
            content_info.metadata.update(camelized_additional_metadata)
        else:
            content_info.metadata = camelized_additional_metadata

        return update_content(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_info.id,
            metadata=content_info.metadata,
        )

    def remove_content_metadata(
        self,
        *,
        content_info: ContentInfo,
        keys_to_remove: list[str],
    ) -> ContentInfo:
        """
        Removes the specified keys irreversibly from the content metadata.

        Note: Keys are camelized before being removed as metadata keys are stored in camelCase.
        """

        if content_info.metadata is None:
            _LOGGER.warning(f"Content metadata is None for content {content_info.id}")
            return content_info

        for key in keys_to_remove:
            content_info.metadata[humps.camelize(key)] = None

        return update_content(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_info.id,
            metadata=content_info.metadata or {},
        )

    @overload
    def update_contents_metadata(
        self,
        *,
        additional_metadata: dict[str, Any],
        content_infos: list[ContentInfo],
    ) -> list[ContentInfo]: ...

    @overload
    def update_contents_metadata(
        self, *, additional_metadata: dict[str, Any], metadata_filter: dict[str, Any]
    ) -> list[ContentInfo]: ...

    def update_contents_metadata(
        self,
        *,
        additional_metadata: dict[str, Any],
        metadata_filter: dict[str, Any] | None = None,
        content_infos: list[ContentInfo] | None = None,
    ) -> list[ContentInfo]:
        """Update the metadata of the contents matching the metadata filter.

        Note: Keys are camelized before being updated as metadata keys are stored in camelCase.
        """

        additional_metadata_camelized = humps.camelize(additional_metadata)
        additional_metadata_camelized = self._pop_forbidden_metadata_keys(
            additional_metadata_camelized
        )

        if content_infos is None:
            content_infos = self.get_paginated_content_infos(
                metadata_filter=metadata_filter,
            ).content_infos

        for info in content_infos:
            self.update_content_metadata(
                content_info=info, additional_metadata=additional_metadata_camelized
            )

        return content_infos

    @overload
    def remove_contents_metadata(
        self,
        *,
        keys_to_remove: list[str],
        content_infos: list[ContentInfo],
    ) -> list[ContentInfo]: ...

    @overload
    def remove_contents_metadata(
        self, *, keys_to_remove: list[str], metadata_filter: dict[str, Any]
    ) -> list[ContentInfo]: ...

    def remove_contents_metadata(
        self,
        *,
        keys_to_remove: list[str],
        metadata_filter: dict[str, Any] | None = None,
        content_infos: list[ContentInfo] | None = None,
    ) -> list[ContentInfo]:
        """Remove the specified keys irreversibly from the content metadata.

        Note: Keys are camelized before being removed as metadata keys are stored in camelCase.

        """

        if content_infos is None:
            content_infos = self.get_paginated_content_infos(
                metadata_filter=metadata_filter,
            ).content_infos

        for info in content_infos:
            self.remove_content_metadata(
                content_info=info, keys_to_remove=keys_to_remove
            )

        return content_infos

    # Delete
    # ------------------------------------------------------------------------------------------------

    @overload
    def delete_content(
        self,
        *,
        content_id: str,
    ) -> DeleteContentResponse: ...

    """Delete content by id"""

    @overload
    def delete_content(
        self,
        *,
        file_path: str,
    ) -> DeleteContentResponse: ...

    """Delete all content matching the file path"""

    def delete_content(
        self,
        *,
        content_id: str | None = None,
        file_path: str | None = None,
    ) -> DeleteContentResponse:
        """Delete content by id, file path or metadata filter."""
        return delete_content(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            file_path=file_path,
        )

    def delete_contents(
        self,
        *,
        metadata_filter: dict[str, Any],
    ) -> list[DeleteContentResponse]:
        """Delete all content matching the metadata filter."""
        resp: list[DeleteContentResponse] = []

        if metadata_filter:
            infos = self.get_paginated_content_infos(
                metadata_filter=metadata_filter,
            )

            for info in infos.content_infos:
                resp.append(
                    delete_content(
                        user_id=self._user_id,
                        company_id=self._company_id,
                        content_id=info.id,
                    )
                )

        return resp

    @overload
    async def delete_content_async(
        self,
        *,
        content_id: str,
    ) -> DeleteContentResponse: ...

    @overload
    async def delete_content_async(
        self,
        *,
        file_path: str,
    ) -> DeleteContentResponse: ...

    async def delete_content_async(
        self,
        *,
        content_id: str | None = None,
        file_path: str | None = None,
    ) -> DeleteContentResponse:
        return await delete_content_async(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=content_id,
            file_path=file_path,
        )

    async def delete_contents_async(
        self,
        *,
        metadata_filter: dict[str, Any],
    ) -> list[DeleteContentResponse]:
        """Delete all content matching the metadata filter."""
        if not metadata_filter:
            return []

        infos = self.get_paginated_content_infos(
            metadata_filter=metadata_filter,
        )

        # Create all delete tasks without awaiting them
        delete_tasks = [
            delete_content_async(
                user_id=self._user_id,
                company_id=self._company_id,
                content_id=info.id,
            )
            for info in infos.content_infos
        ]

        # Await all delete operations concurrently
        resp = await asyncio.gather(*delete_tasks)

        return list(resp)

    def _get_knowledge_base_location(
        self, *, scope_id: str
    ) -> tuple[PurePath, list[str]]:
        """
        Get the path of a folder from a scope id.

        Args:
            scope_id (str): The scope id of the folder.

        Returns:
            PurePath: The path of the folder.
            list[str]: The list of scope ids from root to the folder.
        """

        list_of_folder_names: list[str] = []
        list_of_scope_ids: list[str] = []
        folder_info = self.get_folder_info(scope_id=scope_id)
        list_of_scope_ids.append(folder_info.id)
        if folder_info.parent_id is not None:
            list_of_folder_names.append(folder_info.name)
        else:
            return PurePath("/" + folder_info.name), list_of_scope_ids

        while folder_info.parent_id is not None:
            parent_scope_id = folder_info.parent_id
            folder_info = self.get_folder_info(scope_id=parent_scope_id)
            list_of_folder_names.append(folder_info.name)
            list_of_scope_ids.append(folder_info.id)

        list_of_scope_ids.reverse()
        return PurePath("/" + "/".join(list_of_folder_names[::-1])), list_of_scope_ids

    # Utility Functions
    # ------------------------------------------------------------------------------------------------

    def get_folder_path(self, *, scope_id: str) -> PurePath:
        """
        Get the path of a folder from a scope id.
        Args:
            scope_id (str): The scope id of the folder.

        Returns:
            PurePath: The path of the folder.
        """
        folder_path, _ = self._get_knowledge_base_location(scope_id=scope_id)
        return folder_path

    def get_scope_id_path(self, *, scope_id: str) -> list[str]:
        """
        Get the path of a folder from a scope id.
        Args:
            scope_id (str): The scope id of the folder.

        Returns:
            list[str]: The list of scope ids from root to the folder.
        """
        _, list_of_scope_ids = self._get_knowledge_base_location(scope_id=scope_id)
        return list_of_scope_ids

__init__(company_id, user_id, metadata_filter=None)

Initialize the KnowledgeBaseService with a company_id, user_id and chat_id.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(
    self,
    company_id: str,
    user_id: str,
    metadata_filter: dict[str, Any] | None = None,
):
    """
    Initialize the KnowledgeBaseService with a company_id, user_id and chat_id.
    """

    self._metadata_filter = None
    [company_id, user_id] = validate_required_values([company_id, user_id])
    self._company_id = company_id
    self._user_id = user_id
    self._metadata_filter = metadata_filter

batch_file_upload(*, local_files, remote_folders, overwrite=False, metadata_generator=None)

Upload files to the knowledge base into corresponding folders

Parameters:

Name Type Description Default
local_files list[Path]

The local files to upload

required
remote_folders list[PurePath]

The remote folders to upload the files to

required
overwrite bool

Whether to overwrite existing files

False
metadata_generator Callable[[Path, PurePath], dict[str, Any]] | None

The metadata generator function

None

Returns:

Type Description
None

None

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
def batch_file_upload(
    self,
    *,
    local_files: list[Path],
    remote_folders: list[PurePath],
    overwrite: bool = False,
    metadata_generator: Callable[[Path, PurePath], dict[str, Any]] | None = None,
) -> None:
    """
    Upload files to the knowledge base into corresponding folders

    Args:
        local_files (list[Path]): The local files to upload
        remote_folders (list[PurePath]): The remote folders to upload the files to
        overwrite (bool): Whether to overwrite existing files
        metadata_generator (Callable[[Path, PurePath], dict[str, Any]] | None): The metadata generator function

    Returns:
        None
    """

    if len(local_files) != len(remote_folders):
        raise ValueError(
            "The number of local files and remote folders must be the same"
        )

    creation_result = self.create_folders(paths=remote_folders)

    folders_path_to_scope_id = {
        folder_path: result.id
        for folder_path, result in zip(remote_folders, creation_result)
    }

    _old_scope_id = None
    _existing_file_names: list[str] = []

    for remote_folder_path, local_file_path in zip(remote_folders, local_files):
        scope_id = folders_path_to_scope_id[remote_folder_path]
        mime_type = mimetypes.guess_type(local_file_path.name)[0]

        if mime_type is None:
            _LOGGER.warning(
                f"No mime type found for file {local_file_path.name}, skipping"
            )
            continue

        if not overwrite:
            if _old_scope_id is None or _old_scope_id != scope_id:
                _LOGGER.debug(f"Switching to new folder {scope_id}")
                _old_scope_id = scope_id
                _existing_file_names = self.get_file_names_in_folder(
                    scope_id=scope_id
                )

            if local_file_path.name in _existing_file_names:
                _LOGGER.warning(
                    f"File {local_file_path.name} already exists in folder {scope_id}, skipping"
                )
                continue

        metadata = None
        if metadata_generator is not None:
            metadata = metadata_generator(local_file_path, remote_folder_path)

        self.upload_content(
            path_to_content=str(local_file_path),
            content_name=local_file_path.name,
            mime_type=mime_type,
            scope_id=scope_id,
            metadata=metadata,
        )

create_folders(*, paths)

Create folders in the knowledge base if the path does not exists.

Parameters:

Name Type Description Default
paths list[PurePath]

The paths to create the folders at

required

Returns:

Type Description
list[BaseFolderInfo]

list[BaseFolderInfo]: The information about the created folders or existing folders

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
def create_folders(self, *, paths: list[PurePath]) -> list[BaseFolderInfo]:
    """
    Create folders in the knowledge base if the path does not exists.

    Args:
        paths (list[PurePath]): The paths to create the folders at

    Returns:
        list[BaseFolderInfo]: The information about the created folders or existing folders
    """
    result = unique_sdk.Folder.create_paths(
        user_id=self._user_id,
        company_id=self._company_id,
        paths=[path.as_posix() for path in paths],
    )
    return [
        BaseFolderInfo.model_validate(folder, by_alias=True, by_name=True)
        for folder in result["createdFolders"]
    ]

delete_content(*, content_id=None, file_path=None)

delete_content(*, content_id: str) -> DeleteContentResponse
delete_content(*, file_path: str) -> DeleteContentResponse

Delete content by id, file path or metadata filter.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
def delete_content(
    self,
    *,
    content_id: str | None = None,
    file_path: str | None = None,
) -> DeleteContentResponse:
    """Delete content by id, file path or metadata filter."""
    return delete_content(
        user_id=self._user_id,
        company_id=self._company_id,
        content_id=content_id,
        file_path=file_path,
    )

delete_contents(*, metadata_filter)

Delete all content matching the metadata filter.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
def delete_contents(
    self,
    *,
    metadata_filter: dict[str, Any],
) -> list[DeleteContentResponse]:
    """Delete all content matching the metadata filter."""
    resp: list[DeleteContentResponse] = []

    if metadata_filter:
        infos = self.get_paginated_content_infos(
            metadata_filter=metadata_filter,
        )

        for info in infos.content_infos:
            resp.append(
                delete_content(
                    user_id=self._user_id,
                    company_id=self._company_id,
                    content_id=info.id,
                )
            )

    return resp

delete_contents_async(*, metadata_filter) async

Delete all content matching the metadata filter.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
async def delete_contents_async(
    self,
    *,
    metadata_filter: dict[str, Any],
) -> list[DeleteContentResponse]:
    """Delete all content matching the metadata filter."""
    if not metadata_filter:
        return []

    infos = self.get_paginated_content_infos(
        metadata_filter=metadata_filter,
    )

    # Create all delete tasks without awaiting them
    delete_tasks = [
        delete_content_async(
            user_id=self._user_id,
            company_id=self._company_id,
            content_id=info.id,
        )
        for info in infos.content_infos
    ]

    # Await all delete operations concurrently
    resp = await asyncio.gather(*delete_tasks)

    return list(resp)

download_content_to_bytes(*, content_id)

Downloads content to memory

Parameters:

Name Type Description Default
content_id str

The id of the uploaded content.

required

Returns:

Name Type Description
bytes bytes

The downloaded content.

Raises:

Type Description
Exception

If the download fails.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def download_content_to_bytes(
    self,
    *,
    content_id: str,
) -> bytes:
    """
    Downloads content to memory

    Args:
        content_id (str): The id of the uploaded content.

    Returns:
        bytes: The downloaded content.

    Raises:
        Exception: If the download fails.
    """

    return download_content_to_bytes(
        user_id=self._user_id,
        company_id=self._company_id,
        content_id=content_id,
        chat_id=None,
    )

download_content_to_bytes_async(*, content_id) async

Asynchronously downloads content to memory.

Parameters:

Name Type Description Default
content_id str

The id of the uploaded content.

required

Returns:

Name Type Description
bytes bytes

The downloaded content.

Raises:

Type Description
Exception

If the download fails.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
async def download_content_to_bytes_async(
    self,
    *,
    content_id: str,
) -> bytes:
    """
    Asynchronously downloads content to memory.

    Args:
        content_id (str): The id of the uploaded content.

    Returns:
        bytes: The downloaded content.

    Raises:
        Exception: If the download fails.
    """

    return await download_content_to_bytes_async(
        user_id=self._user_id,
        company_id=self._company_id,
        content_id=content_id,
        chat_id=None,
    )

download_content_to_file(*, content_id, output_dir_path=None, output_filename=None)

Downloads content from a chat and saves it to a file.

Parameters:

Name Type Description Default
content_id str

The ID of the content to download.

required
output_filename str | None

The name of the file to save the content as. If not provided, the original filename will be used. Defaults to None.

None
output_dir_path str | Path | None

The path to the temporary directory where the content will be saved. Defaults to "/tmp".

None

Returns:

Name Type Description
Path Path

The path to the downloaded file.

Raises:

Type Description
Exception

If the download fails or the filename cannot be determined.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
def download_content_to_file(
    self,
    *,
    content_id: str,
    output_dir_path: Path | None = None,
    output_filename: str | None = None,
) -> Path:
    """
    Downloads content from a chat and saves it to a file.

    Args:
        content_id (str): The ID of the content to download.
        output_filename (str | None): The name of the file to save the content as. If not provided, the original filename will be used. Defaults to None.
        output_dir_path (str | Path | None): The path to the temporary directory where the content will be saved. Defaults to "/tmp".

    Returns:
        Path: The path to the downloaded file.

    Raises:
        Exception: If the download fails or the filename cannot be determined.
    """

    return download_content_to_file_by_id(
        user_id=self._user_id,
        company_id=self._company_id,
        content_id=content_id,
        chat_id="",
        filename=output_filename,
        tmp_dir_path=output_dir_path,
    )

extract_scope_ids(content_infos) staticmethod

Extracts all unique scope IDs from the folderIdPath metadata field.

Parameters:

Name Type Description Default
content_infos list[ContentInfo]

The content infos to extract scope IDs from.

required

Returns:

Type Description
set[str]

set[str]: All unique scope IDs found across content infos.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
@staticmethod
def extract_scope_ids(content_infos: list[ContentInfo]) -> set[str]:
    """Extracts all unique scope IDs from the ``folderIdPath`` metadata field.

    Args:
        content_infos: The content infos to extract scope IDs from.

    Returns:
        set[str]: All unique scope IDs found across content infos.
    """
    scope_ids: set[str] = set()
    for content_info in content_infos:
        if (
            content_info.metadata
            and (folder_id_path := content_info.metadata.get("folderIdPath"))
            is not None
            and isinstance(folder_id_path, str)
        ):
            scope_ids.update(
                sid
                for sid in folder_id_path.replace("uniquepathid://", "").split("/")
                if sid
            )
    return scope_ids

from_context(context) classmethod

Create a KnowledgeBaseService from a :class:UniqueContext.

This is the preferred constructor when using the service factory pattern.

Parameters:

Name Type Description Default
context UniqueContext

The request context carrying auth and chat information.

required
Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@classmethod
def from_context(cls, context: UniqueContext) -> Self:
    """Create a KnowledgeBaseService from a :class:`UniqueContext`.

    This is the preferred constructor when using the service factory pattern.

    Args:
        context: The request context carrying auth and chat information.
    """
    metadata_filter = (
        context.chat.metadata_filter if context.chat is not None else None
    )
    return cls(
        company_id=context.auth.get_confidential_company_id(),
        user_id=context.auth.get_confidential_user_id(),
        metadata_filter=metadata_filter,
    )

from_event(event) classmethod

Initialize the ContentService with an event.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@classmethod
@deprecated(
    "Use UniqueContext.from_chat_event(event) (if you have a ChatEvent) or "
    "UniqueContext.from_event(event) (for any BaseEvent) with UniqueServiceFactory instead."
)
def from_event(cls, event: BaseEvent[Any]):
    """
    Initialize the ContentService with an event.
    """
    metadata_filter = None

    if isinstance(event, (ChatEvent | Event)):
        metadata_filter = event.payload.metadata_filter

    return cls(
        company_id=event.company_id,
        user_id=event.user_id,
        metadata_filter=metadata_filter,
    )

from_settings(settings=None, metadata_filter=None, **kwargs) classmethod

Initialize the ContentService with a settings object and metadata filter.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@classmethod
def from_settings(
    cls,
    settings: UniqueSettings | str | None = None,
    metadata_filter: dict[str, Any] | None = None,
    **kwargs: Any,
):
    """
    Initialize the ContentService with a settings object and metadata filter.
    """

    if settings is None:
        settings = UniqueSettings.from_env_auto_with_sdk_init()
    elif isinstance(settings, str):
        settings = UniqueSettings.from_env_auto_with_sdk_init(filename=settings)

    if metadata_filter is None and settings.context.chat is not None:
        metadata_filter = settings.context.chat.metadata_filter

    return cls(
        company_id=settings.authcontext.get_confidential_company_id(),
        user_id=settings.authcontext.get_confidential_user_id(),
        metadata_filter=metadata_filter,
    )

get_content_infos_async(*, metadata_filter=None, step_size=100, max_concurrent_requests=10) async

Fetches all content infos from the knowledge base using parallel pagination. The API limits responses to 100 items per request, so this method fetches the total count first, then retrieves all pages concurrently (bounded by max_concurrent_requests to avoid rate limiting or connection exhaustion).

Parameters:

Name Type Description Default
metadata_filter dict[str, Any] | None

The metadata filter to use. Defaults to None.

None
step_size int

Number of items per page. Defaults to 100.

100
max_concurrent_requests int

Maximum number of concurrent API calls. Defaults to 10.

10

Returns:

Type Description
list[ContentInfo]

list[ContentInfo]: All content infos visible to the user.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
async def get_content_infos_async(
    self,
    *,
    metadata_filter: dict[str, Any] | None = None,
    step_size: int = 100,
    max_concurrent_requests: int = 10,
) -> list[ContentInfo]:
    """
    Fetches all content infos from the knowledge base using parallel pagination.
    The API limits responses to 100 items per request, so this method fetches
    the total count first, then retrieves all pages concurrently (bounded by
    ``max_concurrent_requests`` to avoid rate limiting or connection exhaustion).

    Args:
        metadata_filter (dict[str, Any] | None): The metadata filter to use. Defaults to None.
        step_size (int): Number of items per page. Defaults to 100.
        max_concurrent_requests (int): Maximum number of concurrent API calls.
            Defaults to 10.

    Returns:
        list[ContentInfo]: All content infos visible to the user.
    """

    info_for_count_of_total_content = await self.get_paginated_content_infos_async(
        metadata_filter=metadata_filter,
        take=1,
    )

    total_count = info_for_count_of_total_content.total_count

    semaphore = asyncio.Semaphore(max_concurrent_requests)

    async def _fetch_page(skip: int) -> PaginatedContentInfos:
        async with semaphore:
            return await self.get_paginated_content_infos_async(
                metadata_filter=metadata_filter,
                skip=skip,
                take=step_size,
            )

    results: list[PaginatedContentInfos | BaseException] = await asyncio.gather(
        *[_fetch_page(i) for i in range(0, total_count, step_size)],
        return_exceptions=True,
    )

    for result in results:
        if isinstance(result, BaseException):
            _LOGGER.error("Error fetching paginated content infos", exc_info=result)

    return [
        content_info
        for result in results
        if not isinstance(result, BaseException)
        for content_info in result.content_infos
    ]

get_file_names_in_folder(*, scope_id)

Get the list of file names in a knowledge base folder

Parameters:

Name Type Description Default
scope_id str

The scope id of the folder

required

Returns:

Type Description
list[str]

list[str]: The list of file names in the folder

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def get_file_names_in_folder(self, *, scope_id: str) -> list[str]:
    """
    Get the list of file names in a knowledge base folder

    Args:
        scope_id (str): The scope id of the folder

    Returns:
        list[str]: The list of file names in the folder
    """
    smart_rule = Statement(
        operator=Operator.EQUALS, value=scope_id, path=["folderId"]
    )
    infos = self.get_paginated_content_infos(
        metadata_filter=smart_rule.model_dump(mode="json")
    )
    return [i.key for i in infos.content_infos]

get_folder_path(*, scope_id)

Get the path of a folder from a scope id. Args: scope_id (str): The scope id of the folder.

Returns:

Name Type Description
PurePath PurePath

The path of the folder.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
def get_folder_path(self, *, scope_id: str) -> PurePath:
    """
    Get the path of a folder from a scope id.
    Args:
        scope_id (str): The scope id of the folder.

    Returns:
        PurePath: The path of the folder.
    """
    folder_path, _ = self._get_knowledge_base_location(scope_id=scope_id)
    return folder_path

get_scope_id_path(*, scope_id)

Get the path of a folder from a scope id. Args: scope_id (str): The scope id of the folder.

Returns:

Type Description
list[str]

list[str]: The list of scope ids from root to the folder.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
def get_scope_id_path(self, *, scope_id: str) -> list[str]:
    """
    Get the path of a folder from a scope id.
    Args:
        scope_id (str): The scope id of the folder.

    Returns:
        list[str]: The list of scope ids from root to the folder.
    """
    _, list_of_scope_ids = self._get_knowledge_base_location(scope_id=scope_id)
    return list_of_scope_ids

remove_content_metadata(*, content_info, keys_to_remove)

Removes the specified keys irreversibly from the content metadata.

Note: Keys are camelized before being removed as metadata keys are stored in camelCase.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
def remove_content_metadata(
    self,
    *,
    content_info: ContentInfo,
    keys_to_remove: list[str],
) -> ContentInfo:
    """
    Removes the specified keys irreversibly from the content metadata.

    Note: Keys are camelized before being removed as metadata keys are stored in camelCase.
    """

    if content_info.metadata is None:
        _LOGGER.warning(f"Content metadata is None for content {content_info.id}")
        return content_info

    for key in keys_to_remove:
        content_info.metadata[humps.camelize(key)] = None

    return update_content(
        user_id=self._user_id,
        company_id=self._company_id,
        content_id=content_info.id,
        metadata=content_info.metadata or {},
    )

remove_contents_metadata(*, keys_to_remove, metadata_filter=None, content_infos=None)

remove_contents_metadata(
    *,
    keys_to_remove: list[str],
    content_infos: list[ContentInfo],
) -> list[ContentInfo]
remove_contents_metadata(
    *,
    keys_to_remove: list[str],
    metadata_filter: dict[str, Any],
) -> list[ContentInfo]

Remove the specified keys irreversibly from the content metadata.

Note: Keys are camelized before being removed as metadata keys are stored in camelCase.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
def remove_contents_metadata(
    self,
    *,
    keys_to_remove: list[str],
    metadata_filter: dict[str, Any] | None = None,
    content_infos: list[ContentInfo] | None = None,
) -> list[ContentInfo]:
    """Remove the specified keys irreversibly from the content metadata.

    Note: Keys are camelized before being removed as metadata keys are stored in camelCase.

    """

    if content_infos is None:
        content_infos = self.get_paginated_content_infos(
            metadata_filter=metadata_filter,
        ).content_infos

    for info in content_infos:
        self.remove_content_metadata(
            content_info=info, keys_to_remove=keys_to_remove
        )

    return content_infos

resolve_visible_file_paths_async(*, metadata_filter=None) async

Resolves file paths visible to the current user asynchronously.

Returns each content item paired with its resolved file path segments.

Parameters:

Name Type Description Default
metadata_filter dict[str, Any] | None

Optional metadata filter to narrow the content scope.

None

Returns:

Type Description
list[tuple[ContentInfo, list[str]]]

list[tuple[ContentInfo, list[str]]]: Each tuple is (content_info, [folder1, folder2, ..., filename]).

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
async def resolve_visible_file_paths_async(
    self,
    *,
    metadata_filter: dict[str, Any] | None = None,
) -> list[tuple[ContentInfo, list[str]]]:
    """Resolves file paths visible to the current user asynchronously.

    Returns each content item paired with its resolved file path segments.

    Args:
        metadata_filter: Optional metadata filter to narrow the content scope.

    Returns:
        list[tuple[ContentInfo, list[str]]]: Each tuple is
            ``(content_info, [folder1, folder2, ..., filename])``.
    """
    content_infos = await self.get_content_infos_async(
        metadata_filter=metadata_filter,
    )
    scope_ids = self.extract_scope_ids(content_infos)
    scope_id_to_folder_name = await self._translate_scope_ids_async(scope_ids)

    resolved: list[tuple[ContentInfo, list[str]]] = []
    for content_info in content_infos:
        if (
            content_info.metadata
            and (folder_id_path := content_info.metadata.get("folderIdPath"))
            is not None
            and isinstance(folder_id_path, str)
        ):
            file_path = [
                scope_id_to_folder_name.get(sid, sid)
                for sid in folder_id_path.replace("uniquepathid://", "").split("/")
                if sid
            ]
        else:
            file_path = ["_no_folder_path"]

        file_path.append(content_info.key)
        resolved.append((content_info, file_path))

    return resolved

search_content_chunks(*, search_string, search_type, limit, search_language=DEFAULT_SEARCH_LANGUAGE, reranker_config=None, scope_ids=None, metadata_filter=None, content_ids=None, score_threshold=None)

search_content_chunks(
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    metadata_filter: dict[str, Any],
    score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
) -> list[ContentChunk]
search_content_chunks(
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    metadata_filter: dict[str, Any],
    content_ids: list[str],
    score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
) -> list[ContentChunk]

Performs a synchronous search for content chunks in the knowledge base.

Parameters:

Name Type Description Default
search_string str

The search string.

required
search_type ContentSearchType

The type of search to perform.

required
limit int

The maximum number of results to return.

required
search_language str

The language for the full-text search. Defaults to "english".

DEFAULT_SEARCH_LANGUAGE
reranker_config ContentRerankerConfig | None

The reranker configuration. Defaults to None.

None
scope_ids list[str] | None

Deprecated. Folded into metadata_filter as a folderId in [scope_ids] clause; do not use for new code.

None
metadata_filter dict | None

UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.

None
content_ids list[str] | None

The content IDs to search within. Defaults to None.

None
score_threshold float | None

Sets the minimum similarity score for search results to be considered. Defaults to 0.

None

Returns:

Type Description
list[ContentChunk]

list[ContentChunk]: The search results.

Raises:

Type Description
Exception

If there's an error during the search operation.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
def search_content_chunks(
    self,
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
    scope_ids: list[str] | None = None,
    metadata_filter: dict[str, Any] | None = None,
    content_ids: list[str] | None = None,
    score_threshold: float | None = None,
) -> list[ContentChunk]:
    """
    Performs a synchronous search for content chunks in the knowledge base.

    Args:
        search_string (str): The search string.
        search_type (ContentSearchType): The type of search to perform.
        limit (int): The maximum number of results to return.
        search_language (str, optional): The language for the full-text search. Defaults to "english".
        reranker_config (ContentRerankerConfig | None, optional): The reranker configuration. Defaults to None.
        scope_ids (list[str] | None, optional): Deprecated. Folded into ``metadata_filter``
            as a ``folderId in [scope_ids]`` clause; do not use for new code.
        metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
        content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
        score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.

    Returns:
        list[ContentChunk]: The search results.

    Raises:
        Exception: If there's an error during the search operation.
    """

    if metadata_filter is None:
        metadata_filter = self._metadata_filter

    if scope_ids:
        warnings.warn(
            "Passing scope_ids to KnowledgeBaseService.search_content_chunks is "
            "deprecated; use metadata_filter with folderId operator 'in' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        clause = build_folder_id_in_clause(scope_ids)
        metadata_filter = merge_scope_clause_into_metadata_filter(
            clause, metadata_filter
        )
        scope_ids = None

    try:
        searches = search_content_chunks(
            user_id=self._user_id,
            company_id=self._company_id,
            chat_id="",
            search_string=search_string,
            search_type=search_type,
            limit=limit,
            search_language=search_language,
            reranker_config=reranker_config,
            chat_only=False,
            metadata_filter=metadata_filter,
            content_ids=content_ids,
            score_threshold=score_threshold,
        )
        return searches
    except Exception as e:
        _LOGGER.error(f"Error while searching content chunks: {e}")
        raise e

search_content_chunks_async(*, search_string, search_type, limit, search_language=DEFAULT_SEARCH_LANGUAGE, reranker_config=None, scope_ids=None, metadata_filter=None, content_ids=None, score_threshold=None) async

search_content_chunks_async(
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    metadata_filter: dict[str, Any],
    score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
) -> list[ContentChunk]
search_content_chunks_async(
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    metadata_filter: dict[str, Any],
    content_ids: list[str],
    score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
) -> list[ContentChunk]

Performs an asynchronous search for content chunks in the knowledge base.

Parameters:

Name Type Description Default
search_string str

The search string.

required
search_type ContentSearchType

The type of search to perform.

required
limit int

The maximum number of results to return.

required
search_language str

The language for the full-text search. Defaults to "english".

DEFAULT_SEARCH_LANGUAGE
reranker_config ContentRerankerConfig | None

The reranker configuration. Defaults to None.

None
scope_ids list[str] | None

Deprecated. Folded into metadata_filter as a folderId in [scope_ids] clause; do not use for new code.

None
metadata_filter dict | None

UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.

None
content_ids list[str] | None

The content IDs to search within. Defaults to None.

None
score_threshold float | None

Sets the minimum similarity score for search results to be considered. Defaults to 0.

None

Returns:

Type Description

list[ContentChunk]: The search results.

Raises:

Type Description
Exception

If there's an error during the search operation.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
async def search_content_chunks_async(
    self,
    *,
    search_string: str,
    search_type: ContentSearchType,
    limit: int,
    search_language: str = DEFAULT_SEARCH_LANGUAGE,
    reranker_config: ContentRerankerConfig | None = None,
    scope_ids: list[str] | None = None,
    metadata_filter: dict[str, Any] | None = None,
    content_ids: list[str] | None = None,
    score_threshold: float | None = None,
):
    """
    Performs an asynchronous search for content chunks in the knowledge base.

    Args:
        search_string (str): The search string.
        search_type (ContentSearchType): The type of search to perform.
        limit (int): The maximum number of results to return.
        search_language (str, optional): The language for the full-text search. Defaults to "english".
        reranker_config (ContentRerankerConfig | None, optional): The reranker configuration. Defaults to None.
        scope_ids (list[str] | None, optional): Deprecated. Folded into ``metadata_filter``
            as a ``folderId in [scope_ids]`` clause; do not use for new code.
        metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
        content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
        score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.

    Returns:
        list[ContentChunk]: The search results.

    Raises:
        Exception: If there's an error during the search operation.
    """
    if metadata_filter is None:
        metadata_filter = self._metadata_filter

    if scope_ids:
        warnings.warn(
            "Passing scope_ids to KnowledgeBaseService.search_content_chunks_async is "
            "deprecated; use metadata_filter with folderId operator 'in' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        clause = build_folder_id_in_clause(scope_ids)
        metadata_filter = merge_scope_clause_into_metadata_filter(
            clause, metadata_filter
        )
        scope_ids = None

    try:
        searches = await search_content_chunks_async(
            user_id=self._user_id,
            company_id=self._company_id,
            chat_id="",
            search_string=search_string,
            search_type=search_type,
            limit=limit,
            search_language=search_language,
            reranker_config=reranker_config,
            chat_only=False,
            metadata_filter=metadata_filter,
            content_ids=content_ids,
            score_threshold=score_threshold,
        )
        return searches
    except Exception as e:
        _LOGGER.error(f"Error while searching content chunks: {e}")
        raise e

search_contents(*, where, include_failed_content=False)

Performs a search in the knowledge base by filter (and not a smilarity search) This function loads complete content of the files from the knowledge base in contrast to search_content_chunks.

Parameters:

Name Type Description Default
where dict

The search criteria.

required

Returns:

Type Description
list[Content]

list[Content]: The search results.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def search_contents(
    self,
    *,
    where: dict[str, Any],
    include_failed_content: bool = False,
) -> list[Content]:
    """
    Performs a search in the knowledge base by filter (and not a smilarity search)
    This function loads complete content of the files from the knowledge base in contrast to search_content_chunks.

    Args:
        where (dict): The search criteria.

    Returns:
        list[Content]: The search results.
    """

    return search_contents(
        user_id=self._user_id,
        company_id=self._company_id,
        chat_id="",
        where=where,
        include_failed_content=include_failed_content,
    )

search_contents_async(*, where, include_failed_content=False) async

Performs an asynchronous search for content files in the knowledge base by filter.

Parameters:

Name Type Description Default
where dict

The search criteria.

required

Returns:

Type Description
list[Content]

list[Content]: The search results.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
async def search_contents_async(
    self,
    *,
    where: dict[str, Any],
    include_failed_content: bool = False,
) -> list[Content]:
    """
    Performs an asynchronous search for content files in the knowledge base by filter.

    Args:
        where (dict): The search criteria.

    Returns:
        list[Content]: The search results.
    """

    return await search_contents_async(
        user_id=self._user_id,
        company_id=self._company_id,
        chat_id="",
        where=where,
        include_failed_content=include_failed_content,
    )

update_contents_metadata(*, additional_metadata, metadata_filter=None, content_infos=None)

update_contents_metadata(
    *,
    additional_metadata: dict[str, Any],
    content_infos: list[ContentInfo],
) -> list[ContentInfo]
update_contents_metadata(
    *,
    additional_metadata: dict[str, Any],
    metadata_filter: dict[str, Any],
) -> list[ContentInfo]

Update the metadata of the contents matching the metadata filter.

Note: Keys are camelized before being updated as metadata keys are stored in camelCase.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
def update_contents_metadata(
    self,
    *,
    additional_metadata: dict[str, Any],
    metadata_filter: dict[str, Any] | None = None,
    content_infos: list[ContentInfo] | None = None,
) -> list[ContentInfo]:
    """Update the metadata of the contents matching the metadata filter.

    Note: Keys are camelized before being updated as metadata keys are stored in camelCase.
    """

    additional_metadata_camelized = humps.camelize(additional_metadata)
    additional_metadata_camelized = self._pop_forbidden_metadata_keys(
        additional_metadata_camelized
    )

    if content_infos is None:
        content_infos = self.get_paginated_content_infos(
            metadata_filter=metadata_filter,
        ).content_infos

    for info in content_infos:
        self.update_content_metadata(
            content_info=info, additional_metadata=additional_metadata_camelized
        )

    return content_infos

upload_content(path_to_content, content_name, mime_type, scope_id, skip_ingestion=False, skip_excel_ingestion=False, ingestion_config=None, metadata=None)

Uploads content to the knowledge base.

Parameters:

Name Type Description Default
path_to_content str

The path to the content to upload.

required
content_name str

The name of the content.

required
mime_type str

The MIME type of the content.

required
scope_id str | None

The scope ID. Defaults to None.

required
skip_ingestion bool

Whether to skip ingestion. Defaults to False.

False
skip_excel_ingestion bool

Whether to skip excel ingestion. Defaults to False.

False
ingestion_config IngestionConfig | None

The ingestion configuration. Defaults to None.

None
metadata dict[str, Any] | None

The metadata to associate with the content. Defaults to None.

None

Returns:

Name Type Description
Content Content

The uploaded content.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
def upload_content(
    self,
    path_to_content: str,
    content_name: str,
    mime_type: str,
    scope_id: str,
    skip_ingestion: bool = False,
    skip_excel_ingestion: bool = False,
    ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
    metadata: dict[str, Any] | None = None,
) -> Content:
    """
    Uploads content to the knowledge base.

    Args:
        path_to_content (str): The path to the content to upload.
        content_name (str): The name of the content.
        mime_type (str): The MIME type of the content.
        scope_id (str | None): The scope ID. Defaults to None.
        skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
        skip_excel_ingestion (bool): Whether to skip excel ingestion. Defaults to False.
        ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
        metadata (dict[str, Any] | None): The metadata to associate with the content. Defaults to None.

    Returns:
        Content: The uploaded content.
    """

    return upload_content(
        user_id=self._user_id,
        company_id=self._company_id,
        path_to_content=path_to_content,
        content_name=content_name,
        mime_type=mime_type,
        scope_id=scope_id,
        chat_id="",
        skip_ingestion=skip_ingestion,
        skip_excel_ingestion=skip_excel_ingestion,
        ingestion_config=ingestion_config,
        metadata=metadata,
    )

upload_content_from_bytes(content, *, content_name, mime_type, scope_id, skip_ingestion=False, ingestion_config=None, metadata=None)

Uploads content to the knowledge base.

Parameters:

Name Type Description Default
content bytes

The content to upload.

required
content_name str

The name of the content.

required
mime_type str

The MIME type of the content.

required
scope_id str | None

The scope ID. Defaults to None.

required
skip_ingestion bool

Whether to skip ingestion. Defaults to False.

False
ingestion_config IngestionConfig | None

The ingestion configuration. Defaults to None.

None
metadata dict | None

The metadata to associate with the content. Defaults to None.

None

Returns:

Name Type Description
Content Content

The uploaded content.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
def upload_content_from_bytes(
    self,
    content: bytes,
    *,
    content_name: str,
    mime_type: str,
    scope_id: str,
    skip_ingestion: bool = False,
    ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
    metadata: dict[str, Any] | None = None,
) -> Content:
    """
    Uploads content to the knowledge base.

    Args:
        content (bytes): The content to upload.
        content_name (str): The name of the content.
        mime_type (str): The MIME type of the content.
        scope_id (str | None): The scope ID. Defaults to None.
        skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
        ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
        metadata (dict | None): The metadata to associate with the content. Defaults to None.

    Returns:
        Content: The uploaded content.
    """

    return upload_content_from_bytes(
        user_id=self._user_id,
        company_id=self._company_id,
        content=content,
        content_name=content_name,
        mime_type=mime_type,
        scope_id=scope_id,
        chat_id="",
        skip_ingestion=skip_ingestion,
        ingestion_config=ingestion_config,
        metadata=metadata,
    )

upload_content_from_bytes_async(content, *, content_name, mime_type, scope_id, skip_ingestion=False, ingestion_config=None, metadata=None) async

Uploads content to the knowledge base.

Parameters:

Name Type Description Default
content bytes

The content to upload.

required
content_name str

The name of the content.

required
mime_type str

The MIME type of the content.

required
scope_id str | None

The scope ID. Defaults to None.

required
skip_ingestion bool

Whether to skip ingestion. Defaults to False.

False
skip_excel_ingestion bool

Whether to skip excel ingestion. Defaults to False.

required
ingestion_config IngestionConfig | None

The ingestion configuration. Defaults to None.

None
metadata dict | None

The metadata to associate with the content. Defaults to None.

None

Returns:

Name Type Description
Content Content

The uploaded content.

Source code in unique_toolkit/unique_toolkit/services/knowledge_base.py
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
async def upload_content_from_bytes_async(
    self,
    content: bytes,
    *,
    content_name: str,
    mime_type: str,
    scope_id: str,
    skip_ingestion: bool = False,
    ingestion_config: unique_sdk.Content.IngestionConfig | None = None,
    metadata: dict[str, Any] | None = None,
) -> Content:
    """
    Uploads content to the knowledge base.

    Args:
        content (bytes): The content to upload.
        content_name (str): The name of the content.
        mime_type (str): The MIME type of the content.
        scope_id (str | None): The scope ID. Defaults to None.
        skip_ingestion (bool): Whether to skip ingestion. Defaults to False.
        skip_excel_ingestion (bool): Whether to skip excel ingestion. Defaults to False.
        ingestion_config (unique_sdk.Content.IngestionConfig | None): The ingestion configuration. Defaults to None.
        metadata (dict | None): The metadata to associate with the content. Defaults to None.

    Returns:
        Content: The uploaded content.
    """

    return await upload_content_from_bytes_async(
        user_id=self._user_id,
        company_id=self._company_id,
        content=content,
        content_name=content_name,
        mime_type=mime_type,
        scope_id=scope_id,
        chat_id="",
        skip_ingestion=skip_ingestion,
        ingestion_config=ingestion_config,
        metadata=metadata,
    )