Skip to content

Library convenience methods

This is an automatic generated API reference of the library convenience methods for AI Atlas Nexus

AIAtlasNexus

A AIAtlasNexus object

Source code in src/ai_atlas_nexus/library.py
  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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
class AIAtlasNexus:
    """A AIAtlasNexus object"""

    # Load the schema
    directory = os.path.dirname(os.path.abspath(__file__))
    fn = os.path.join(
        directory,
        "ai_risk_ontology/schema/ai-risk-ontology.yaml",
    )
    schema_view = SchemaView(yaml.safe_load(fn))

    def __init__(self, base_dir: Optional[str] = None):
        """Create a new AIAtlasNexus object

        Args:
            base_dir: str
                (Optional) add an alternative source of date
        """
        if base_dir is not None:
            if type(base_dir) != str:
                raise ValueError(
                    "Base directory must be a string",
                    base_dir,
                )
            if not os.path.isdir(base_dir):
                logger.error(
                    f"Directory %s does not exist.",
                    base_dir,
                )
                raise FileNotFoundError(
                    "Base directory is not found",
                    base_dir,
                )

        ontology = load_yamls_to_container(base_dir)
        self._ontology = ontology
        self._atlas_explorer = AtlasExplorer(ontology)
        self._shacl_engine = SHACLEngine.from_discovery(base_dir, ontology)
        self._ox = PyoxigraphExplorer(self._ontology)
        logger.info(
            f"Created AIAtlasNexus instance. Base_dir: %s",
            base_dir,
        )

    def get_shacl_engine(self):
        """Return the loaded SHACLEngine, or None when no shapes were discovered.

        Returns:
            Optional["SHACLEngine"]
        """
        return self._shacl_engine

    def _apply_rules_check(self, instances, apply_rules):
        """Run SHACL inference and augment instances when apply_rules is True.
        If no shapes have been loaded, returns instances unchanged.

        Arguments:
            instances: list
                Data instances
            apply_rules: bool
                Boolean describing whether to apply rules
        Returns:
            list
        """
        if (
            not apply_rules
            or not self._shacl_engine
            or not self._shacl_engine.has_shapes()
        ):
            return instances
        derived = self._shacl_engine.infer(self._ox._store)
        return self._shacl_engine.augment_objects(instances, derived)

    def export(cls, export_path):
        """Export AIAtlasNexus configuration to file.

        Args:
            export_path: str
                The path to the directory where the artifact will be exported to.

        """
        if not os.path.isdir(export_path):
            logger.error(
                f"Directory %s does not exist.",
                export_path,
            )
            raise FileNotFoundError(
                "Export directory is not found",
                export_path,
            )

        export_file_path = os.path.join(export_path, "ai-risk-ontology.yaml")

        with open(
            export_file_path,
            "+tw",
            encoding="utf-8",
        ) as output_file:
            print(
                YAMLDumper().dumps(cls._ontology),
                file=output_file,
            )
            output_file.close()

    @classmethod
    def get_schema(cls):
        """Get schema

        Returns:
            schema
        """
        return cls.schema_view

    @classmethod
    def get_version(cls):
        """Get library version

        Returns:
            dict: Version number
        """
        response = {"version": version("ai_atlas_nexus")}
        return response

    def get_all_classes(cls):
        """
        Get all the available classes

        Returns:
            List[str]
                List of classes
        """
        classes: List[str] = cls._atlas_explorer.get_all_classes()
        return classes

    def get_all(
        cls, class_name, taxonomy=None, vocabulary=None, document=None
    ):
        """
        Get all the instances of a specified class.

        Args:
            class_name: str
                Name of the class (the collection key in data)
            taxonomy: Optional[Union[str, List[str]]]
                (Optional) The string id for a taxonomy or list of taxonomy ids
            vocabulary:
                (Optional) The string id for a vocabulary
            document:
                (Optional) The string id for a document

        Returns:
            List[Dict[str, Any]]
                List of instances
        """
        value_check(
            "<RAN0948RVB6E>",
            class_name,
            "Please provide a class_name",
        )
        instances: list[Any] = cls._atlas_explorer.get_all(
            class_name, taxonomy, vocabulary, document
        )
        return instances

    def get_by_id(cls, class_name, identifier):
        """
        Get a single instance by its identifier.

        Args:
            class_name: str
                Name of the class (the collection key in data)
            identifier: str
                Value of the identifier field

        Returns:
            Optional[Dict[str, Any]]
                The matching instance or None
        """
        instance = cls._atlas_explorer.get_by_id(class_name, identifier)
        return instance

    def get_by_attribute(cls, class_name, attribute, value):
        """
        Get a single instance by its identifier.

        Args:
            class_name: str
                Name of the class (the collection key in data)
            attribute: str
                Attribute name to filter by
            value: Any
                Value to match

        Returns:
            Optional[Dict[str, Any]]
                The matching instance or None
        """
        instance = cls._atlas_explorer.get_by_attribute(
            class_name, attribute, value
        )
        return instance

    def query(cls, class_name, **kwargs):
        """
        Query instances using keyword arguments.

        Args:
            class_name: Union[str | list]:
                Name of the class (the collection key in data)
            **kwargs:
                The attribute-value pairs to filter by

        Returns:
            List[Dict[str, Any]]
                List of matching instances
        """
        return cls._atlas_explorer.query(class_name, **kwargs)

    def get_all_risks(cls, taxonomy=None, apply_rules: bool = False):
        """Get all risk definitions from the LinkML

        Args:
            taxonomy: Optional[Union[str, List[str]]]
                (Optional) The string label for a taxonomy or list of taxonomy labels
            apply_rules: bool
                (Optional) When True, run loaded SHACL rules and attach derived
                attributes (accessible via ``instance.derived_attrs``) to each result.

        Returns:
            list[Risk]
                Result containing a list of AI risks
        """
        type_check(
            "<RANEACF44A7E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        risk_instances = cls.get_all("risks", taxonomy=taxonomy)
        return cls._apply_rules_check(risk_instances, apply_rules)

    def get_risk(
        cls,
        tag=None,
        id=None,
        name=None,
        taxonomy=None,
        apply_rules: bool = False,
    ):
        """Get risk definition from the LinkML, filtered by risk atlas id, tag, name

        Args:
            id: (Optional) str
                The string ID identifying the risk
            tag: (Optional) str
                The string tag identifying the risk
            name: (Optional) str
                The string name identifying the risk
            taxonomy: Optional[Union[str, List[str]]]
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            Risk
                Result containing a list of AI risks
        """
        type_check(
            "<RAND62C1B3AE>",
            Union[str, List],
            allow_none=True,
            tag=tag,
            id=id,
            name=name,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN14D4D967E>",
            tag or id or name,
            "Please provide tag, id, or name",
        )

        risk: Risk | None = cls._atlas_explorer.query(
            "risks",
            tag=tag,
            id=id,
            name=name,
            taxonomy=taxonomy,
        )
        if risk and len(risk) > 0:
            risk = risk[0]
        else:
            return None
        augmented = cls._apply_rules_check([risk], apply_rules)
        return augmented[0] if augmented else None

    def get_related_risks(
        cls,
        risk=None,
        tag=None,
        id=None,
        name=None,
        taxonomy=None,
        apply_rules: bool = False,
    ):
        """Get related risks from the LinkML, filtered by risk id, tag, or name

        Args:
            risk: (Optional) Risk
                The risk
            id: (Optional) str
                The string ID identifying the risk
            tag: (Optional) str
                The string tag identifying the risk
            name: (Optional) str
                The string name identifying the risk
            taxonomy: Optional[Union[str, List[str]]]
                (Optional) The string label for a taxonomy or list of strings
        Returns:
            List[str]
                Result containing a list of AI risk IDs
        """
        type_check(
            "<RAN283B72CAE>",
            Risk,
            allow_none=True,
            risk=risk,
        )
        type_check(
            "<RANC9FDCC45E>",
            Union[str | List],
            allow_none=True,
            tag=tag,
            id=id,
            name=name,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN0748ECB7E>",
            risk or tag or id or name,
            "Please provide tag, id, or name",
        )

        if id:
            risk = cls.get_risk(id=id)
        elif tag:
            risk = cls.get_risk(tag=tag)

        # just get all the related risks from the risk, these should have been added during lifting
        options = [
            risk.close_mappings or [],
            risk.exact_mappings or [],
            risk.broad_mappings or [],
            risk.narrow_mappings or [],
            risk.related_mappings or [],
        ]
        related_risk_ids = [x for x_list in options for x in x_list]
        related_risk_instances = [
            risk_instance
            for risk_instance in [
                cls.get_risk(id=x, apply_rules=apply_rules)
                for x in related_risk_ids
            ]
            if risk_instance is not None
        ]
        return cls._apply_rules_check(related_risk_instances, apply_rules)

    def get_related_actions(
        cls,
        risk=None,
        tag=None,
        id=None,
        name=None,
        taxonomy=None,
        apply_rules: bool = False,
    ):
        """Get actions for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

        Args:
            risk: (Optional) Risk
                The risk
            id: (Optional) str
                The string ID identifying the risk
            tag: (Optional) str
                The string tag identifying the risk
            name: (Optional) str
                The string name identifying the risk
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Risk
                Result containing a list of AI actions
        """
        type_check(
            "<RANEDB39EABE>",
            Risk,
            allow_none=True,
            risk=risk,
        )
        type_check(
            "<RANC49E332BE>",
            str,
            allow_none=True,
            tag=tag,
            id=id,
            name=name,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN7154EE0FE>",
            risk or tag or id or name,
            "Please provide risk, tag, id, or name",
        )

        if id:
            risk = cls.get_risk(id=id, apply_rules=apply_rules)
        elif tag:
            risk = cls.get_risk(tag=tag, apply_rules=apply_rules)
        elif name:
            risk = cls.get_risk(name=name, apply_rules=apply_rules)

        related_action_ids = risk.hasRelatedAction
        if related_action_ids:
            actions = [
                cls._atlas_explorer.get_by_id(
                    class_name="actions",
                    identifier=x,
                )
                for x in related_action_ids
            ]
        else:
            actions = []
        return cls._apply_rules_check(actions, apply_rules)

    def get_all_actions(
        cls,
        taxonomy: Optional[Union[str, List[str]]] = None,
        apply_rules: bool = False,
    ):
        """Get all action definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels
            apply_rules: bool
                (Optional) When True, run loaded SHACL rules and attach derived
                attributes (accessible via ``instance.derived_attrs``) to each result.

        Returns:
            list[Action]
                Result containing a list of AI actions
        """
        type_check(
            "<RAN1C9A35ADE>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        action_instances: list[Action] = cls.get_all(
            "actions", taxonomy=taxonomy
        )
        return cls._apply_rules_check(action_instances, apply_rules)

    def get_action_by_id(
        cls, id, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get an action definition from the LinkML, filtered by action id

        Args:
            id: str
                The string id identifying the action
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            Action
                Result containing an action
        """
        type_check(
            "<RAN66203B1FE>",
            str,
            allow_none=False,
            id=id,
        )
        type_check(
            "<RAN869039B6E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        action: Action | None = cls._atlas_explorer.get_by_id(
            class_name="actions", identifier=id
        )
        return action

    def get_related_risk_controls(
        cls,
        risk=None,
        tag=None,
        id=None,
        name=None,
        taxonomy=None,
    ):
        """Get related risk controls for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

        Args:
            risk: (Optional) Risk
                The risk
            id: (Optional) str
                The string ID identifying the risk
            tag: (Optional) str
                The string tag identifying the risk
            name: (Optional) str
                The string name identifying the risk
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Risk
                Result containing a list of AI actions
        """
        type_check(
            "<RAN4E03158FE>",
            Risk,
            allow_none=True,
            risk=risk,
        )
        type_check(
            "<RAN55784808E>",
            str,
            allow_none=True,
            tag=tag,
            id=id,
            name=name,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN5DCADG95E>",
            risk or tag or id or name,
            "Please provide risk, tag, id, or name",
        )

        if id:
            risk = cls.get_risk(id=id)
        elif tag:
            risk = cls.get_risk(tag=tag)
        elif name:
            risk = cls.get_risk(name=name)

        risk_controls = [
            cls._atlas_explorer.get_by_id(
                class_name="riskcontrols", identifier=x
            )
            for x in risk.isDetectedBy or []
        ]
        return risk_controls

    def get_all_risk_controls(
        cls,
        taxonomy: Optional[Union[str, List[str]]] = None,
        apply_rules: bool = False,
    ):
        """Get all risk control definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels
            apply_rules: bool
                (Optional) When True, run loaded SHACL rules and attach derived
                attributes (accessible via ``instance.derived_attrs``) to each result.

        Returns:
            list[RiskControl]
                Result containing a list of RiskControls
        """
        type_check(
            "<RAN129A1692E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        risk_control_instances: list[RiskControl] = cls.get_all(
            "riskcontrols", taxonomy=taxonomy
        )
        return cls._apply_rules_check(risk_control_instances, apply_rules)

    def get_risk_control(
        cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get an action definition from the LinkML, filtered by risk control id

        Args:
            id: str
                The string id identifying the risk control
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            Action
                Result containing a risk control.
        """
        type_check(
            "<RAN9785FFE3E>",
            str,
            allow_none=False,
            id=id,
        )
        type_check(
            "<RAN5A157049E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        risk_control: RiskControl | None = cls._atlas_explorer.get_by_id(
            class_name="riskcontrols", identifier=id
        )
        return risk_control

    @handle_exception(exceptions=[RiskInferenceError])
    def identify_risks_from_usecases(
        cls,
        usecases: List[str],
        inference_engine: InferenceEngine,
        taxonomy: str | list[str] | List[str] | None = None,
        cot_examples: Optional[Dict[str, List]] = None,
        max_risk: Optional[int] = None,
        zero_shot_only: bool = False,
        batch_inference: bool = True,
        use_dspy_prompt: bool = False,
    ) -> List[List[Risk]]:
        """Identify potential risks from a usecase description

        Args:
            usecases (List[str]):
                A List of strings describing AI usecases
            inference_engine (InferenceEngine):
                An LLM inference engine to infer risks from the usecases.
            taxonomy (str, optional):
                The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.
            cot_examples (Dict[str, List], optional):
                If the user wants to improve risk identification via a Few-shot approach, `cot_examples` can be
                provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json.
                If the `cot_examples` is omitted, the API default to a Zero-Shot approach.
            max_risk (int, optional):
                The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.
            zero_shot_only (bool): If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field `cot_examples` will be ignored.
            batch_inference (bool): Whether to run risk inference service in batch mode or at each risk level. Defaults to True.
            use_dspy_prompt (bool): Use per-risk DSPy optmized prompt instructions for risk identification. When enabled, `batch_inference` flag is ignored.
        Returns:
            List[List[Risk]]:
                Result containing a list of risks
        """
        type_check(
            "<RANE02D314BE>",
            List,
            allow_none=False,
            usecases=usecases,
        )
        type_check(
            "<RANE023914BE>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RANB72CAE6EE>",
            Union[str, list, List, None],
            allow_none=True,
            taxonomy=taxonomy,
        )
        type_check(
            "<RAN80975498E>",
            int,
            allow_none=True,
            max_risk=max_risk,
        )
        value_check(
            "<RAN4717CF18E>",
            all([isinstance(usecase, str) for usecase in usecases]),
            "Usecases must be a list of string.",
        )

        # if not providing taxonomy, set to IBM AI risk atlas
        taxonomies = []

        if taxonomy is None:
            logger.warning(
                f"<RAN47375G12W>",
                f"Taxonomy was not provided, defaulting to ibm-risk-atlas.",
            )
            taxonomies = ["ibm-risk-atlas"]
        elif isinstance(taxonomy, str):
            taxonomies.append(taxonomy)
        else:
            taxonomies = taxonomy

        if taxonomy is None:
            logger.warning(
                f"<RAN47375G12W>",
                f"Taxonomy was not provided, defaulting to ibm-risk-atlas.",
            )

        combined_processed_examples = None
        combined_risks = []

        for tx in taxonomies:

            if tx == "ibm-attack-risk-atlas":
                risks = [
                    risk
                    for risk in cls.get_all("risks", taxonomy="ibm-risk-atlas")
                    if risk.tag.endswith("-attack")
                ]
            else:
                risks = cls.get_all("risks", taxonomy=tx)

            combined_risks.extend(risks)

            if len(taxonomies) > 1:
                logger.debug(
                    f"When there is more than one taxonomy given, `zero_shot_only` flag is enabled.",
                )
                zero_shot_only = True

            if zero_shot_only:
                logger.debug(
                    f"The `zero_shot_only` flag is enabled. The system will use the Zero shot method. Any provided `cot_examples` will be disregarded.",
                )
            else:
                # For the given taxonomy type, check if the user has provided 'cot_examples'. If not,
                # retrieve the default cot examples from the master. If no examples exist in the master,
                # set it as None. The CoT examples include risk-related questions that have been synthetically generated for this task.
                processed_examples = (
                    cot_examples and cot_examples.get(tx, None)
                ) or RISK_IDENTIFICATION_COT.get(tx, None)
                if (
                    combined_processed_examples
                    and type(combined_processed_examples) == list
                ):
                    combined_processed_examples.append(processed_examples)
                else:
                    combined_processed_examples = processed_examples

        if combined_processed_examples is None:
            logger.warning(
                f"<RAN47275F12W> Chain of Thought (CoT) examples were not provided, or do not exist in the master for this taxonomy. The API will use the Zero shot method. To improve the accuracy of risk identification, please provide CoT examples in `cot_examples` when calling this API. You may also consider raising an issue to permanently add these examples to the AI Atlas Nexus master."
            )

        risk_detector = GenericRiskDetector(
            risks=combined_risks,
            inference_engine=inference_engine,
            cot_examples=combined_processed_examples,
            max_risk=max_risk,
            batch_inference=batch_inference,
            use_dspy_prompt=use_dspy_prompt,
        )

        return risk_detector.detect(usecases)

    @handle_exception(exceptions=[RiskInferenceError])
    def identify_risks_and_actions_from_usecases(
        cls,
        usecases: List[str],
        inference_engine: InferenceEngine,
        taxonomy: str | list[str] | List[str] | None = None,
        cot_examples: Optional[Dict[str, List]] = None,
        max_risk: Optional[int] = None,
        zero_shot_only: bool = False,
    ):
        """Identify potential risks from a usecase description

        Args:
            usecases (List[str]):
                A List of strings describing AI usecases
            inference_engine (InferenceEngine):
                An LLM inference engine to infer risks from the usecases.
            taxonomy (str | list[str] | List[str] | None = None):
                The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.
            cot_examples (Dict[str, List], optional):
                If the user wants to improve risk identification via a Few-shot approach, `cot_examples` can be
                provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json.
                If the `cot_examples` is omitted, the API default to a Zero-Shot approach.
            max_risk (int, optional):
                The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.
            zero_shot_only (bool): If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field `cot_examples` will be ignored.
        Returns:
            List[List[Risk]]:
                Result containing a list of risks
        """
        type_check(
            "<RANE053314BE>",
            List,
            allow_none=False,
            usecases=usecases,
        )
        type_check(
            "<RANE023614CE>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RANB72CPE6BE>",
            Union[str, list, List, None],
            allow_none=True,
            taxonomy=taxonomy,
        )
        type_check(
            "<RAND098498E>",
            int,
            allow_none=True,
            max_risk=max_risk,
        )
        value_check(
            "<RAN6717CP18E>",
            all([isinstance(usecase, str) for usecase in usecases]),
            "Usecases must be a list of string.",
        )

        risks = cls.identify_risks_from_usecases(
            usecases,
            inference_engine,
            taxonomy,
            cot_examples,
            max_risk,
            zero_shot_only,
        )[0]
        control_ids = []
        actions = []
        detectors = []

        for risk in risks:
            if risk.hasRelatedAction:
                risk_actions = (
                    risk.hasRelatedAction
                    if isinstance(risk.hasRelatedAction, list)
                    else [risk.hasRelatedAction]
                )
                actions.extend(risk_actions)

            if risk.isDetectedBy:
                risk_detections = (
                    risk.isDetectedBy
                    if isinstance(risk.isDetectedBy, list)
                    else [risk.isDetectedBy]
                )
                detectors.extend(risk_detections)

            mappings = list(
                itertools.chain(
                    risk.related_mappings or [],
                    risk.broad_mappings or [],
                    risk.close_mappings or [],
                    risk.exact_mappings or [],
                    risk.hasRelatedAction or [],
                    risk.isDetectedBy or [],
                )
            )

            control_ids.extend(
                cls._atlas_explorer.filter_ids_by_type(
                    ids=mappings, disallowed_types=["Risk"]
                )
            )
            control_ids = list(set(control_ids))

        summary_1 = {
            "risk_ids": [risk.id for risk in risks],
            "action_ids": actions,
            "detector_ids": detectors,
        }
        summary_2 = cls._atlas_explorer.arrange_ids_by_type(control_ids)
        summary = summary_1 | summary_2

        result = {
            "usecases": usecases,
            "model": inference_engine.model_name_or_path,
            "taxonomy": taxonomy,
            "summary": summary,
            "risks": risks,
            "mixed_control_items": [
                cls._atlas_explorer.get_by_id(None, identifier=item)
                for item in control_ids
            ],
        }
        return result

    def get_all_taxonomies(cls):
        """Get all taxonomy definitions from the LinkML

        Returns:
            List[Taxonomy]
                Result containing a list of taxonomies
        """
        taxonomy_instances: list[RiskTaxonomy] = cls.get_all("taxonomies")
        return taxonomy_instances

    def get_taxonomy_by_id(cls, id):
        """Get taxonomy definitions from the LinkML filtered by taxonomy id

        Args:
            id: str
                The string id for a taxonomy

        Returns:
            Taxonomy
                An AI taxonomy
        """
        type_check(
            "<RANBFB574E3E>",
            str,
            allow_none=False,
            id=id,
        )

        taxonomy: RiskTaxonomy | None = cls._atlas_explorer.get_by_id(
            class_name="taxonomies", identifier=id
        )
        return taxonomy

    def generate_zero_shot_risk_questionnaire_output(
        cls,
        usecase: str,
        risk_questionnaire: List[Dict[str, str]],
        inference_engine: InferenceEngine,
        verbose=True,
    ):
        """Get prediction using the zero shot approach.

        Args:
            usecase (str): A string describing an AI usecase
            risk_questionnaire: List[Dict[str, str]]: A risk questionnaire
                Check example below.
                ```
                [
                    "In which environment is the system used?",
                ]
                ```
            inference_engine (InferenceEngine):
                An LLM inference engine to predict the output based on the given use case.

        Returns:
            List[str]: List of LLM predictions.
        """
        type_check(
            "<RANF7EFFADAE>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RANB9FDEA04E>",
            str,
            allow_none=False,
            usecase=usecase,
        )
        type_check(
            "<RANF7256EC3E>",
            List,
            allow_none=False,
            questions=risk_questionnaire,
        )
        value_check(
            "<RANC49F00D3E>",
            inference_engine and risk_questionnaire,
            "Please provide questions and inference_engine",
        )

        # Extract only questions
        risk_questionnaire = [
            question_data["question"] for question_data in risk_questionnaire
        ]

        # Prepare zero shots inference prompts
        prompts = [
            ZeroShotPromptBuilder(
                QUESTIONNAIRE_COT_TEMPLATE,
            ).build(usecase=usecase, question=question)
            for question in risk_questionnaire
        ]

        # Invoke inference service
        return inference_engine.generate(
            prompts,
            response_format=QuestionnaireOutput,
            postprocessors=["json_object"],
            verbose=verbose,
        )

    def generate_few_shot_risk_questionnaire_output(
        cls,
        usecase: str,
        risk_questionnaire: List[Dict[str, Any]],
        inference_engine: InferenceEngine,
        verbose=True,
    ):
        """Get prediction using the few shot (Chain of Thought) examples.

        Args:
            usecase (str): A string describing an AI usecase
            risk_questionnaire (List[Dict]): Chain of Thought data for risk questionnaire.
                Each question is associated with a list of example intents and
                corresponding answers. Check example JSON below.
                ```
                [
                    {
                        "question": "In which environment is the system used?",
                        "examples": [
                            "intent": "Find patterns in healthcare insurance claims",
                            "answer": "Insurance Claims Processing or Risk Management or Data Analytics",
                            "explanation": "The system might be used by an insurance company's claims processing department to analyze and identify patterns in healthcare insurance claims."
                        ]
                    }
                ]
            inference_engine (InferenceEngine):
                An LLM inference engine to predict the output based on the given use case.
            filter_cot_data_by (Dict[str, str]):
                A dictionary to filter CoT examples with key as CoT field and value as filter string.
                ```

        Returns:
            List[str]: List of LLM predictions.
        """
        type_check(
            "<RAN19989483E>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RAN17812927E>",
            str,
            allow_none=False,
            usecase=usecase,
        )
        type_check(
            "<RAN46376875E>",
            List,
            allow_none=False,
            questions=risk_questionnaire,
        )
        value_check(
            "<RAN59638961E>",
            inference_engine and risk_questionnaire,
            "Please provide risk_questionnaire_cot and inference_engine",
        )

        assert (
            risk_questionnaire and len(risk_questionnaire) > 0
        ), "`Chain of Thought (risk_questionnaire_cot)` data cannot be None or empty."

        # Prepare few shots inference prompts from CoT Data
        prompts = [
            FewShotPromptBuilder(QUESTIONNAIRE_COT_TEMPLATE).build(
                cot_examples=question_data["cot_examples"],
                usecase=usecase,
                question=question_data["question"],
            )
            for question_data in risk_questionnaire
        ]

        # Invoke inference service
        return inference_engine.generate(
            prompts,
            response_format=QuestionnaireOutput,
            postprocessors=["json_object"],
            verbose=verbose,
        )

    def identify_ai_tasks_from_usecases(
        cls,
        usecases: List[str],
        inference_engine: InferenceEngine,
        verbose=True,
    ) -> List[List[str]]:
        """Identify potential risks from a usecase description

        Args:
            usecases (List[str]):
                A List of strings describing AI usecases
            inference_engine (InferenceEngine):
                An LLM inference engine to identify AI tasks from usecases.
            verbose (bool, optional): prints detailed output during the inference process. Defaults to True.

        Returns:
            List[List[str]]:
                Result containing a list of AI tasks
        """
        type_check(
            "<RAN3B9CD886E>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check("<RAN4CDA6852E>", List, allow_none=False, usecases=usecases)
        value_check(
            "<RAN0E435F50E>",
            inference_engine and usecases,
            "Please provide usecases and inference_engine",
        )

        # Load HF tasks from the template dir
        hf_ai_tasks = [
            {"task_label": task.name, "task_description": task.description}
            for task in cls.get_all(
                class_name="aitasks", taxonomy="hf-ml-tasks"
            )
        ]

        prompts = [
            (
                {
                    "description": "Classify the given use case into one or more AI Tasks that describes it best. Use the AI tasks definitions to make your decision. Provide a brief explanation for choosing a particular AI Task.",
                    "prefix": "You are an AI Task Classifier. You are clear and deterministic in your response. You always give classification label based on a plausible explanation. Study and understand the JSON below containing a list of AI task and its description.",
                    "requirements": [
                        "Give one or more AI tasks that best describes the use case",
                        "Provide a brief, plausible explanation for your choice",
                        "Be clear and deterministic in your classification",
                        "The AI task should only be from the AI Task Definitions. Do not include any other task type.",
                    ],
                    "grounding_context": {
                        "Use case": usecase,
                        "AI Task Definitions": json.dumps(
                            hf_ai_tasks, indent=2
                        ),
                    },
                }
                if inference_engine.backend._backend_type == BackendType.MELLEA
                else Template(AI_TASKS_TEMPLATE).render(
                    usecase=usecase,
                    hf_ai_tasks=hf_ai_tasks,
                    limit=len(hf_ai_tasks),
                )
            )
            for usecase in usecases
        ]

        # Invoke inference service
        return inference_engine.generate(
            prompts=prompts,
            response_format=AITaskList,
            postprocessors=["json_object"],
            verbose=verbose,
        )

    def generate_proposed_mappings(
        cls,
        new_risks: List[Risk],
        existing_risks: List[Risk],
        inference_engine: InferenceEngine,
        new_prefix: str,
        mapping_method: MappingMethod = MappingMethod.SEMANTIC,
    ) -> List[Mapping]:
        """Identify mappings between a new set of risks and risks that exist in the Risk Atlas

        Args:
            new_risks: List[Risk]
                A new set of risks
            existing_risks: List[Risk]
                Secondary list, this should be the list of existing risks in RAN
            inference_engine: (Optional)Union[InferenceEngine | None]:
                An LLM inference engine to infer risks from the use cases.
            new_prefix: str
                The CURIE prefix for the new list of risks
            mapping_method: MappingMethod
                The possible values for type of risk mapping method

        Returns:
            List[Mapping]
                Result containing a list of mappings
        """
        type_check(
            "<RAN28959363E>",
            InferenceEngine,
            allow_none=True,
            inference_engine=inference_engine,
        )
        value_check(
            "<RAN85167315E>",
            new_risks and existing_risks,
            "Please provide new_risks and existing_risks",
        )
        value_check(
            "<RAN49187395E>",
            len(new_risks) > 0 and len(existing_risks) > 0,
            "The new and existing risks must not be empty",
        )
        risk_mapper = RiskMapper(
            new_risks=new_risks,
            existing_risks=existing_risks,
            inference_engine=inference_engine,
            new_prefix=new_prefix,
            mapping_method=mapping_method,
        )

        return risk_mapper.generate(
            new_risks=new_risks,
            existing_risks=existing_risks,
            inference_engine=inference_engine,
            new_prefix=new_prefix,
            mapping_method=mapping_method,
        )

    def get_risk_incidents(
        cls, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get risk incident instances, optionally filtered by taxonomy

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            List[RiskIncident]
                Result containing a list of AI Risk Incidents
        """
        type_check(
            "<RAN04811131E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        risk_incident_instances: List[RiskIncident] = cls.get_all(
            "riskincidents", taxonomy=taxonomy
        )
        return risk_incident_instances

    def get_risk_incident(
        cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get an risk incident instance filtered by risk incident id

        Args:
            id: str
                The string id identifying the risk incident
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            RiskIncident
                Result containing a risk incident.
        """
        type_check(
            "<RAN97353068E>",
            str,
            allow_none=False,
            id=id,
        )
        type_check(
            "<RAN38198685E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        risk_incident: RiskIncident | None = cls._atlas_explorer.get_by_id(
            class_name="riskincidents", identifier=id
        )
        return risk_incident

    def get_related_risk_incidents(
        cls,
        risk=None,
        risk_id=None,
        taxonomy=None,
    ):
        """Get related risk incident filtered by risk id

        Args:
            risk: (Optional) Risk
                The risk
            risk_id: (Optional) str
                The string ID identifying the risk
            taxonomy: str
                (Optional) The string label for a taxonomy
        Returns:
            List[RiskIncident]
                Result containing a list of AI risk incidents
        """
        type_check(
            "<RAN40791379E>",
            Risk,
            allow_none=True,
            risk=risk,
        )
        type_check(
            "<RANC9FDCC45E>",
            str,
            allow_none=True,
            risk_id=risk_id,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN79007538E>",
            risk or risk_id,
            "Please provide risk or id",
        )

        if risk_id:
            risk = cls.get_risk(id=risk_id)

        related_risk_incidents = cls._atlas_explorer.query(
            "riskincidents",
            refersToRisk=risk.id,
            taxonomy=taxonomy,
        )
        return related_risk_incidents

    def get_all_evaluations(
        cls, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get all evaluation definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[AiEval]
                Result containing a list of AiEval
        """
        type_check(
            "<RAN18094995E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        evaluation_instances: list[AiEval] = cls.get_all(
            "evaluations", taxonomy=taxonomy
        )
        return evaluation_instances

    def get_evaluation(
        cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get an evaluation definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the evaluation
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            Action
                Result containing an evaluation.
        """
        type_check("<RAN84465757E>", str, allow_none=False, id=id)
        type_check(
            "<RAN29906222E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        evaluation: AiEval | None = cls._atlas_explorer.get_by_id(
            class_name="evaluations", identifier=id
        )
        return evaluation

    def get_related_evaluations(
        cls,
        risk=None,
        risk_id=None,
        taxonomy: Optional[Union[str, List[str]]] = None,
    ):
        """Get related evaluations filtered by risk id

        Args:
            risk: (Optional) Risk
                The risk
            risk_id: (Optional) str
                The string ID identifying the risk
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels
        Returns:
            List[AiEval]
                Result containing a list of AI evaluations
        """
        type_check("<RAN04616807E>", Risk, allow_none=True, risk=risk)
        type_check(
            "<RAN05640166E>",
            Union[str, List],
            allow_none=True,
            risk_id=risk_id,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN39630388E>",
            risk or risk_id,
            "Please provide risk or id",
        )

        if risk_id:
            risk = cls.get_risk(id=risk_id)

        related_evaluations = cls._atlas_explorer.query(
            "evaluations", hasRelatedRisk=risk.id, taxonomy=taxonomy
        )
        return related_evaluations

    def get_benchmark_metadata_cards(
        cls,
        risk=None,
        risk_id=None,
        taxonomy: Optional[Union[str, List[str]]] = None,
    ):
        """Get all benchmark metadata definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[BenchmarkMetadataCard]
                Result containing a list of BenchmarkMetadataCards
        """
        type_check(
            "<RAN07894687E>",
            Union[str, List],
            allow_none=True,
            risk_id=risk_id,
            taxonomy=taxonomy,
        )
        type_check("<RAN30190075E>", Risk, allow_none=True, risk=risk)

        benchmark_metatdata_card_instances: list[BenchmarkMetadataCard] = (
            cls.get_all("benchmarkmetadatacards", taxonomy=taxonomy)
        )
        return benchmark_metatdata_card_instances

    def get_benchmark_metadata_card(cls, id=str):
        """Get an benchmark_metadata_card definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the benchmark_metadata_card
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            BenchmarkMetadataCard
                Result containing a benchmark_metadata_card.
        """
        type_check(
            "<RAN30946549E>",
            str,
            allow_none=False,
            id=id,
        )

        benchmark_metadata_card: BenchmarkMetadataCard | None = (
            cls._atlas_explorer.get_by_id(
                class_name="benchmarkmetadatacards", identifier=id
            )
        )
        return benchmark_metadata_card

    def get_documents(cls, taxonomy: Optional[Union[str, List[str]]] = None):
        """Get all document definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[Documentation]
                Result containing a list of Documentation
        """
        type_check(
            "<RAN61770043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        document_instances: list[Documentation] = cls.get_all(
            "documents", taxonomy=taxonomy
        )
        return document_instances

    def get_document(cls, id=str):
        """Get a document definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the documentation entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Documentation
                Result containing a document.
        """
        type_check(
            "<RAN12472418E>",
            str,
            allow_none=False,
            id=id,
        )

        document: Documentation | None = cls._atlas_explorer.get_by_id(
            "documents", identifier=id
        )
        return document

    def get_datasets(cls, taxonomy: Optional[Union[str, List[str]]] = None):
        """Get all dataset definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[Dataset]
                Result containing a list of Dataset entries
        """
        type_check(
            "<RAN61770043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        dataset_instances: list[Dataset] = cls.get_all(
            "datasets", taxonomy=taxonomy
        )
        return dataset_instances

    def get_dataset(cls, id=str):
        """Get a dataset definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the dataset entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Dataset
                Result containing a dataset.
        """
        type_check(
            "<RAN12472418E>",
            str,
            allow_none=False,
            id=id,
        )

        dataset: Dataset | None = cls._atlas_explorer.get_by_id(
            "datasets", identifier=id
        )
        return dataset

    def get_stakeholders(
        cls, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get all stakeholder definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[Stakeholder]
                Result containing a list of Stakeholder entries
        """
        type_check(
            "<RAN61770043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        stakeholder_instances: list[Stakeholder] = cls.get_all(
            "stakeholders", taxonomy=taxonomy
        )
        return stakeholder_instances

    def get_stakeholder(cls, id: str):
        """Get a stakeholder definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the stakeholder entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Stakeholder
                Result containing a stakeholder.
        """
        type_check(
            "<RAN12472418E>",
            str,
            allow_none=False,
            id=id,
        )

        stakeholder: Stakeholder | None = cls._atlas_explorer.get_by_id(
            "stakeholders", identifier=id
        )
        return stakeholder

    def get_intrinsics(cls, taxonomy: Optional[Union[str, List[str]]] = None):
        """Get all intrinsic definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[LLMIntrinsic]
                Result containing a list of LLMIntrinsic entries
        """
        type_check(
            "<RAN61770043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        intrinsic_instances: list[LLMIntrinsic] = cls.get_all(
            "llmintrinsics", taxonomy=taxonomy
        )
        return intrinsic_instances

    def get_intrinsic(cls, id: str):
        """Get an intrinsic definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the intrinsic entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            LLMIntrinsic
                Result containing a intrinsic.
        """
        type_check(
            "<RAN12472418E>",
            str,
            allow_none=False,
            id=id,
        )

        intrinsic: LLMIntrinsic | None = cls._atlas_explorer.get_by_id(
            "llmintrinsics", identifier=id
        )
        return intrinsic

    def get_related_intrinsics(
        cls,
        risk=None,
        tag=None,
        risk_id=None,
        aitask=None,
        aitask_id=None,
        task_id=None,
        name=None,
        taxonomy=None,
    ):
        """Get related intrinsics for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

        Args:
            risk: (Optional) Risk
                The risk
            risk_id: (Optional) str
                The string ID identifying the risk
            aitask: (Optional) str
                The aitask
            aitask_id: (Optional) str
                The string ID identifying the ai task
            tag: (Optional) str
                The string tag identifying the risk
            name: (Optional) str
                The string name identifying the risk
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            List
                Result containing a list of Intrinsics
        """
        type_check(
            "<RAN4E03158FE>",
            Risk,
            allow_none=True,
            risk=risk,
        )
        type_check(
            "<RAN4E93178FE>",
            AiTask,
            allow_none=True,
            aitask=aitask,
        )
        type_check(
            "<RAN55784808E>",
            str,
            allow_none=True,
            tag=tag,
            risk_id=risk_id,
            aitask_id=aitask_id,
            name=name,
            taxonomy=taxonomy,
        )
        value_check(
            "<RAN5DCADF94E>",
            risk or tag or aitask or aitask_id or risk_id or name,
            "Please provide risk, tag, aitask, aitask_id, risk_id, or name",
        )

        if aitask or aitask_id:
            if aitask_id:
                aitask = cls.get_by_id(
                    class_name="aitasks", identifier=aitask_id
                )

            related_llmintrinsics = []
            capability_ids = (
                cls._atlas_explorer.get_attribute(
                    class_name="aitasks",
                    identifier=aitask.id,
                    attribute="requiresCapability",
                )
                or []
            )
            for cap in capability_ids:
                related_llmintrinsics += cls._atlas_explorer.query(
                    "llmintrinsics", c=cap.id, taxonomy=taxonomy
                )
        else:
            if risk_id:
                risk = cls.get_risk(id=risk_id)
            elif tag:
                risk = cls.get_risk(tag=tag)
            elif name:
                risk = cls.get_risk(name=name)

            related_llmintrinsics = cls._atlas_explorer.query(
                "llmintrinsics", hasRelatedRisk=risk.id, taxonomy=taxonomy
            )

        return related_llmintrinsics

    def get_adapters(cls, taxonomy: Optional[Union[str, List[str]]] = None):
        """Get all adapter definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[Adapter]
                Result containing a list of Adapter entries
        """
        type_check(
            "<RAN61770043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        adapter_instances: list[Adapter] = cls.get_all("adapters", taxonomy)
        return adapter_instances

    def get_adapter(cls, id=str):
        """Get an adapter definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the stakeholder entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            Adapter
                Result containing a adapter.
        """
        type_check(
            "<RAN12472418E>",
            str,
            allow_none=False,
            id=id,
        )

        adapter: Adapter | None = cls._atlas_explorer.get_by_id(
            "adapters", identifier=id
        )
        return adapter

    def get_llm_question_policies(
        cls, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get all LLM Quesiton Policy definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[LLMQuestionPolicy]
                Result containing a list of LLMQuestionPolicy entries
        """
        type_check(
            "<RAN61796043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        llm_question_policy_instances: list[LLMQuestionPolicy] = cls.get_all(
            "llmquestionpolicies", taxonomy
        )
        return llm_question_policy_instances

    def get_llm_question_policy(cls, id=str):
        """Get an LLM Question Policy definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the LLM question policy entry
            taxonomy: str
                (Optional) The string label for a taxonomy

        Returns:
            LLMQuestionPolicy
                Result containing an LLM Question Policy.
        """
        type_check(
            "<RAN32462418E>",
            str,
            allow_none=False,
            id=id,
        )

        llm_question_policy: LLMQuestionPolicy | None = (
            cls._atlas_explorer.get_by_id("llmquestionPolicies", identifier=id)
        )
        return llm_question_policy

    def get_principles(
        cls, taxonomy: Optional[Union[str, List[str]]] = None, document=None
    ):
        """Get all Principle definitions from the LinkML

        Args:
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels
            document: str
                (Optional) The string label for a document


        Returns:
            list[Principle]
                Result containing a list of Principle entries
        """
        type_check(
            "<RAN61573043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )
        type_check(
            "<RAN62577043E>",
            str,
            allow_none=True,
            document=document,
        )

        principle_instances: list[Principle] = cls.get_all(
            "principles", taxonomy=taxonomy, document=document
        )
        return principle_instances

    def get_principle(cls, id=str):
        """Get a Principle definition from the LinkML, filtered by id

        Args:
            id: str
                The string id identifying the Principle entry

        Returns:
            Principle
                Result containing a Principle.
        """
        type_check(
            "<RAN97462678E>",
            str,
            allow_none=False,
            id=id,
        )

        principle: Principle | None = cls._atlas_explorer.get_by_id(
            "principles", identifier=id
        )
        return principle

    def get_instances(
        cls, target_class, taxonomy: Optional[Union[str, List[str]]] = None
    ):
        """Get all instance definitions from the LinkML

        Args:
            target_class: str
                (Optional) The string label for a target class
            taxonomy: str or list of str
                (Optional) The string label for a taxonomy or list of taxonomy labels

        Returns:
            list[Any]
                Result containing a list of instance entries
        """
        type_check(
            "<RAN92358069E>",
            str,
            allow_none=False,
            target_class=id,
        )
        type_check(
            "<RAN61877043E>",
            Union[str, List],
            allow_none=True,
            taxonomy=taxonomy,
        )

        instances: list[Any] = cls._atlas_explorer.get_instances(
            target_class, taxonomy
        )
        return instances

    def identify_domain_from_usecases(
        cls,
        usecases: List[str],
        inference_engine: InferenceEngine,
        verbose=True,
    ) -> List[List[str]]:
        """Identify potential risks from a usecase description

        Args:
            usecases (List[str]):
                A List of strings describing AI usecases
            inference_engine (InferenceEngine):
                An LLM inference engine to identify AI tasks from usecases.
            verbose (bool, optional): prints detailed output during the inference process. Defaults to True.

        Returns:
            List[List[str]]:
                Result containing a list of AI tasks
        """
        type_check(
            "<RAN3B9CD886E>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RAN4CDA6852E>",
            List,
            allow_none=False,
            usecases=usecases,
        )
        value_check(
            "<RAN0E435F50E>",
            inference_engine and usecases,
            "Please provide usecases and inference_engine",
        )

        # Load risk questionnaire CoT from the template dir
        risk_questionnaire = load_resource("risk_questionnaire_cot.json")

        # Retrieve domain question data
        domain_ques_data = risk_questionnaire[0]

        # Load ai domain defintions from the template dir
        AI_DOMAIN_DEFINITONS = load_resource("ai_domain_defintions.json")

        prompts = [
            (
                {
                    "description": "Classify the given use case into one of the AI Domains that describes it best. Use the AI domain definitions to make your decision. Provide a brief explanation for choosing a particular AI Domain. If no suitable domain exists, classify it as 'Other'",
                    "prefix": "You are an AI Domain Classifier. You are clear and deterministic in your response. You always give classification label based on a plausible explanation.",
                    "requirements": [
                        "Give the AI domain that best describes the use case",
                        "Provide a brief, plausible explanation for your choice",
                        "Be clear and deterministic in your classification",
                        "The AI domain should only be from the AI Domain Definitions. Do not include any other domain type.",
                    ],
                    "grounding_context": {
                        "Use case": usecase,
                        "AI Domain Definitions": json.dumps(
                            AI_DOMAIN_DEFINITONS, indent=2
                        ),
                    },
                }
                if inference_engine.backend._backend_type == BackendType.MELLEA
                else FewShotPromptBuilder(
                    prompt_template=QUESTIONNAIRE_COT_TEMPLATE,
                ).build(
                    cot_examples=domain_ques_data["cot_examples"],
                    usecase=usecase,
                    question=domain_ques_data["question"],
                )
            )
            for usecase in usecases
        ]

        # Invoke inference service
        return inference_engine.generate(
            prompts=prompts,
            response_format=DomainType,
            postprocessors=["json_object"],
            verbose=verbose,
        )

    def categorize_risk_severity(
        self,
        usecases: List[str],
        inference_engine: InferenceEngine,
    ):
        """Determine the severity of risks based on the use case description.
        Args:
            usecases (List[str]):
                A List of strings describing AI usecases
            inference_engine (InferenceEngine):
                An LLM inference engine
        Returns:
            results (List[Dict]):
                Results detailing risk categorization by usecase.
        """
        type_check(
            "<RAN75727859E>",
            InferenceEngine,
            allow_none=False,
            inference_engine=inference_engine,
        )
        type_check(
            "<RAN68734549E>",
            List,
            allow_none=False,
            usecases=usecases,
        )
        value_check(
            "<RAN30508300E>",
            inference_engine and usecases,
            "Please provide usecases and inference_engine",
        )

        # Create Risk Severity instance
        risk_severity = RiskSeverityCategorizer(inference_engine)

        # Load risk questionnaire from the template dir
        risk_questionnaire = load_resource("risk_questionnaire_cot.json")

        # Collecting required parameters for categorizing risk severity per usecase
        results = []
        for usecase in usecases:
            domains = self.identify_domain_from_usecases(
                [usecase], inference_engine=inference_engine, verbose=False
            )
            # Get AI Domain of the usecase
            domain_predictions = [
                domain.prediction["answer"] for domain in domains
            ]
            domain = (
                domain_predictions[0] if len(domain_predictions) == 1 else None
            )

            # Using a risk questionnaire to identify key attributes necessary for
            # constituting an AI system from the usecase.
            #
            # (Q4) AI User that interacts with the AI system
            # (Q5) Intended purpose of the AI System
            # (Q6) The capability of an AI system to do what it is designed to do
            # (Q7) AI Subject impacted by the AI System
            predictions = [
                response.prediction["answer"]
                for response in self.generate_few_shot_risk_questionnaire_output(
                    usecase,
                    list(
                        filter(
                            lambda question: question["no"]
                            in ["Q4", "Q5", "Q6", "Q7"],
                            risk_questionnaire,
                        )
                    ),
                    inference_engine=inference_engine,
                    verbose=False,
                )
            ]

            # Extracting predictions
            if len(predictions) == 4:
                ai_user = predictions[0]
                purpose = predictions[1]
                capability = predictions[2]
                ai_subject = predictions[3]
            else:
                raise Exception(
                    "Unable to retrieve all the required attributes from the usecase. Please try again."
                )

            # Calling the risk categorization API with the required attributes.
            results.append(
                risk_severity.categorize(
                    domain, purpose, capability, ai_user, ai_subject
                )
            )

        return results

    def run_ares_evaluation(
        cls, risks: List[Risk], inference_engine: InferenceEngine, target: Dict
    ) -> None:
        """Submit potential attack risks for ARES red-teaming evaluation.
        This API needs the `ran-ares-integration` extension. Please install this extension via
        `ran-extension install ran-ares-integration`. Refer `Readme` file for further information
        on `ai-atlas-nexus` extensions.

        Args:
            risks (List[Risk]):
                A List of attack risks
            inference_engine (InferenceEngine):
                An instance of the LLM inference engine
            target (Dict):
                A target AI model to perform the ARES red-teaming evaluation

        Returns:
            None
        """
        logger.info(
            f"Risks submitted for ARES evluation: {json.dumps([risk.name for risk in risks], indent=2)}"
        )

        # Load RAN-ARES extension
        ares_extension = Extension.load(
            "ran-ares-integration", inference_engine, target=target
        )

        # Run extension on the given risks
        for risk in risks:
            ares_extension.run(risk)

__init__(base_dir=None)

Create a new AIAtlasNexus object

Parameters:

Name Type Description Default
base_dir Optional[str]

str (Optional) add an alternative source of date

None
Source code in src/ai_atlas_nexus/library.py
 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
def __init__(self, base_dir: Optional[str] = None):
    """Create a new AIAtlasNexus object

    Args:
        base_dir: str
            (Optional) add an alternative source of date
    """
    if base_dir is not None:
        if type(base_dir) != str:
            raise ValueError(
                "Base directory must be a string",
                base_dir,
            )
        if not os.path.isdir(base_dir):
            logger.error(
                f"Directory %s does not exist.",
                base_dir,
            )
            raise FileNotFoundError(
                "Base directory is not found",
                base_dir,
            )

    ontology = load_yamls_to_container(base_dir)
    self._ontology = ontology
    self._atlas_explorer = AtlasExplorer(ontology)
    self._shacl_engine = SHACLEngine.from_discovery(base_dir, ontology)
    self._ox = PyoxigraphExplorer(self._ontology)
    logger.info(
        f"Created AIAtlasNexus instance. Base_dir: %s",
        base_dir,
    )

categorize_risk_severity(usecases, inference_engine)

Determine the severity of risks based on the use case description. Args: usecases (List[str]): A List of strings describing AI usecases inference_engine (InferenceEngine): An LLM inference engine Returns: results (List[Dict]): Results detailing risk categorization by usecase.

Source code in src/ai_atlas_nexus/library.py
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
def categorize_risk_severity(
    self,
    usecases: List[str],
    inference_engine: InferenceEngine,
):
    """Determine the severity of risks based on the use case description.
    Args:
        usecases (List[str]):
            A List of strings describing AI usecases
        inference_engine (InferenceEngine):
            An LLM inference engine
    Returns:
        results (List[Dict]):
            Results detailing risk categorization by usecase.
    """
    type_check(
        "<RAN75727859E>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RAN68734549E>",
        List,
        allow_none=False,
        usecases=usecases,
    )
    value_check(
        "<RAN30508300E>",
        inference_engine and usecases,
        "Please provide usecases and inference_engine",
    )

    # Create Risk Severity instance
    risk_severity = RiskSeverityCategorizer(inference_engine)

    # Load risk questionnaire from the template dir
    risk_questionnaire = load_resource("risk_questionnaire_cot.json")

    # Collecting required parameters for categorizing risk severity per usecase
    results = []
    for usecase in usecases:
        domains = self.identify_domain_from_usecases(
            [usecase], inference_engine=inference_engine, verbose=False
        )
        # Get AI Domain of the usecase
        domain_predictions = [
            domain.prediction["answer"] for domain in domains
        ]
        domain = (
            domain_predictions[0] if len(domain_predictions) == 1 else None
        )

        # Using a risk questionnaire to identify key attributes necessary for
        # constituting an AI system from the usecase.
        #
        # (Q4) AI User that interacts with the AI system
        # (Q5) Intended purpose of the AI System
        # (Q6) The capability of an AI system to do what it is designed to do
        # (Q7) AI Subject impacted by the AI System
        predictions = [
            response.prediction["answer"]
            for response in self.generate_few_shot_risk_questionnaire_output(
                usecase,
                list(
                    filter(
                        lambda question: question["no"]
                        in ["Q4", "Q5", "Q6", "Q7"],
                        risk_questionnaire,
                    )
                ),
                inference_engine=inference_engine,
                verbose=False,
            )
        ]

        # Extracting predictions
        if len(predictions) == 4:
            ai_user = predictions[0]
            purpose = predictions[1]
            capability = predictions[2]
            ai_subject = predictions[3]
        else:
            raise Exception(
                "Unable to retrieve all the required attributes from the usecase. Please try again."
            )

        # Calling the risk categorization API with the required attributes.
        results.append(
            risk_severity.categorize(
                domain, purpose, capability, ai_user, ai_subject
            )
        )

    return results

export(export_path)

Export AIAtlasNexus configuration to file.

Parameters:

Name Type Description Default
export_path

str The path to the directory where the artifact will be exported to.

required
Source code in src/ai_atlas_nexus/library.py
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
def export(cls, export_path):
    """Export AIAtlasNexus configuration to file.

    Args:
        export_path: str
            The path to the directory where the artifact will be exported to.

    """
    if not os.path.isdir(export_path):
        logger.error(
            f"Directory %s does not exist.",
            export_path,
        )
        raise FileNotFoundError(
            "Export directory is not found",
            export_path,
        )

    export_file_path = os.path.join(export_path, "ai-risk-ontology.yaml")

    with open(
        export_file_path,
        "+tw",
        encoding="utf-8",
    ) as output_file:
        print(
            YAMLDumper().dumps(cls._ontology),
            file=output_file,
        )
        output_file.close()

generate_few_shot_risk_questionnaire_output(usecase, risk_questionnaire, inference_engine, verbose=True)

Get prediction using the few shot (Chain of Thought) examples.

Parameters:

Name Type Description Default
usecase str

A string describing an AI usecase

required
risk_questionnaire List[Dict]

Chain of Thought data for risk questionnaire. Each question is associated with a list of example intents and corresponding answers. Check example JSON below. ``` [ { "question": "In which environment is the system used?", "examples": [ "intent": "Find patterns in healthcare insurance claims", "answer": "Insurance Claims Processing or Risk Management or Data Analytics", "explanation": "The system might be used by an insurance company's claims processing department to analyze and identify patterns in healthcare insurance claims." ] } ]

required
inference_engine InferenceEngine

An LLM inference engine to predict the output based on the given use case.

required
filter_cot_data_by Dict[str, str]

A dictionary to filter CoT examples with key as CoT field and value as filter string. ```

required

Returns:

Type Description

List[str]: List of LLM predictions.

Source code in src/ai_atlas_nexus/library.py
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
def generate_few_shot_risk_questionnaire_output(
    cls,
    usecase: str,
    risk_questionnaire: List[Dict[str, Any]],
    inference_engine: InferenceEngine,
    verbose=True,
):
    """Get prediction using the few shot (Chain of Thought) examples.

    Args:
        usecase (str): A string describing an AI usecase
        risk_questionnaire (List[Dict]): Chain of Thought data for risk questionnaire.
            Each question is associated with a list of example intents and
            corresponding answers. Check example JSON below.
            ```
            [
                {
                    "question": "In which environment is the system used?",
                    "examples": [
                        "intent": "Find patterns in healthcare insurance claims",
                        "answer": "Insurance Claims Processing or Risk Management or Data Analytics",
                        "explanation": "The system might be used by an insurance company's claims processing department to analyze and identify patterns in healthcare insurance claims."
                    ]
                }
            ]
        inference_engine (InferenceEngine):
            An LLM inference engine to predict the output based on the given use case.
        filter_cot_data_by (Dict[str, str]):
            A dictionary to filter CoT examples with key as CoT field and value as filter string.
            ```

    Returns:
        List[str]: List of LLM predictions.
    """
    type_check(
        "<RAN19989483E>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RAN17812927E>",
        str,
        allow_none=False,
        usecase=usecase,
    )
    type_check(
        "<RAN46376875E>",
        List,
        allow_none=False,
        questions=risk_questionnaire,
    )
    value_check(
        "<RAN59638961E>",
        inference_engine and risk_questionnaire,
        "Please provide risk_questionnaire_cot and inference_engine",
    )

    assert (
        risk_questionnaire and len(risk_questionnaire) > 0
    ), "`Chain of Thought (risk_questionnaire_cot)` data cannot be None or empty."

    # Prepare few shots inference prompts from CoT Data
    prompts = [
        FewShotPromptBuilder(QUESTIONNAIRE_COT_TEMPLATE).build(
            cot_examples=question_data["cot_examples"],
            usecase=usecase,
            question=question_data["question"],
        )
        for question_data in risk_questionnaire
    ]

    # Invoke inference service
    return inference_engine.generate(
        prompts,
        response_format=QuestionnaireOutput,
        postprocessors=["json_object"],
        verbose=verbose,
    )

generate_proposed_mappings(new_risks, existing_risks, inference_engine, new_prefix, mapping_method=MappingMethod.SEMANTIC)

Identify mappings between a new set of risks and risks that exist in the Risk Atlas

Parameters:

Name Type Description Default
new_risks List[Risk]

List[Risk] A new set of risks

required
existing_risks List[Risk]

List[Risk] Secondary list, this should be the list of existing risks in RAN

required
inference_engine InferenceEngine

(Optional)Union[InferenceEngine | None]: An LLM inference engine to infer risks from the use cases.

required
new_prefix str

str The CURIE prefix for the new list of risks

required
mapping_method MappingMethod

MappingMethod The possible values for type of risk mapping method

SEMANTIC

Returns:

Type Description
List[Mapping]

List[Mapping] Result containing a list of mappings

Source code in src/ai_atlas_nexus/library.py
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
def generate_proposed_mappings(
    cls,
    new_risks: List[Risk],
    existing_risks: List[Risk],
    inference_engine: InferenceEngine,
    new_prefix: str,
    mapping_method: MappingMethod = MappingMethod.SEMANTIC,
) -> List[Mapping]:
    """Identify mappings between a new set of risks and risks that exist in the Risk Atlas

    Args:
        new_risks: List[Risk]
            A new set of risks
        existing_risks: List[Risk]
            Secondary list, this should be the list of existing risks in RAN
        inference_engine: (Optional)Union[InferenceEngine | None]:
            An LLM inference engine to infer risks from the use cases.
        new_prefix: str
            The CURIE prefix for the new list of risks
        mapping_method: MappingMethod
            The possible values for type of risk mapping method

    Returns:
        List[Mapping]
            Result containing a list of mappings
    """
    type_check(
        "<RAN28959363E>",
        InferenceEngine,
        allow_none=True,
        inference_engine=inference_engine,
    )
    value_check(
        "<RAN85167315E>",
        new_risks and existing_risks,
        "Please provide new_risks and existing_risks",
    )
    value_check(
        "<RAN49187395E>",
        len(new_risks) > 0 and len(existing_risks) > 0,
        "The new and existing risks must not be empty",
    )
    risk_mapper = RiskMapper(
        new_risks=new_risks,
        existing_risks=existing_risks,
        inference_engine=inference_engine,
        new_prefix=new_prefix,
        mapping_method=mapping_method,
    )

    return risk_mapper.generate(
        new_risks=new_risks,
        existing_risks=existing_risks,
        inference_engine=inference_engine,
        new_prefix=new_prefix,
        mapping_method=mapping_method,
    )

generate_zero_shot_risk_questionnaire_output(usecase, risk_questionnaire, inference_engine, verbose=True)

Get prediction using the zero shot approach.

Parameters:

Name Type Description Default
usecase str

A string describing an AI usecase

required
risk_questionnaire List[Dict[str, str]]

List[Dict[str, str]]: A risk questionnaire Check example below.

[
    "In which environment is the system used?",
]

required
inference_engine InferenceEngine

An LLM inference engine to predict the output based on the given use case.

required

Returns:

Type Description

List[str]: List of LLM predictions.

Source code in src/ai_atlas_nexus/library.py
 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
def generate_zero_shot_risk_questionnaire_output(
    cls,
    usecase: str,
    risk_questionnaire: List[Dict[str, str]],
    inference_engine: InferenceEngine,
    verbose=True,
):
    """Get prediction using the zero shot approach.

    Args:
        usecase (str): A string describing an AI usecase
        risk_questionnaire: List[Dict[str, str]]: A risk questionnaire
            Check example below.
            ```
            [
                "In which environment is the system used?",
            ]
            ```
        inference_engine (InferenceEngine):
            An LLM inference engine to predict the output based on the given use case.

    Returns:
        List[str]: List of LLM predictions.
    """
    type_check(
        "<RANF7EFFADAE>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RANB9FDEA04E>",
        str,
        allow_none=False,
        usecase=usecase,
    )
    type_check(
        "<RANF7256EC3E>",
        List,
        allow_none=False,
        questions=risk_questionnaire,
    )
    value_check(
        "<RANC49F00D3E>",
        inference_engine and risk_questionnaire,
        "Please provide questions and inference_engine",
    )

    # Extract only questions
    risk_questionnaire = [
        question_data["question"] for question_data in risk_questionnaire
    ]

    # Prepare zero shots inference prompts
    prompts = [
        ZeroShotPromptBuilder(
            QUESTIONNAIRE_COT_TEMPLATE,
        ).build(usecase=usecase, question=question)
        for question in risk_questionnaire
    ]

    # Invoke inference service
    return inference_engine.generate(
        prompts,
        response_format=QuestionnaireOutput,
        postprocessors=["json_object"],
        verbose=verbose,
    )

get_action_by_id(id, taxonomy=None)

Get an action definition from the LinkML, filtered by action id

Parameters:

Name Type Description Default
id

str The string id identifying the action

required
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

Action Result containing an action

Source code in src/ai_atlas_nexus/library.py
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
def get_action_by_id(
    cls, id, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get an action definition from the LinkML, filtered by action id

    Args:
        id: str
            The string id identifying the action
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        Action
            Result containing an action
    """
    type_check(
        "<RAN66203B1FE>",
        str,
        allow_none=False,
        id=id,
    )
    type_check(
        "<RAN869039B6E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    action: Action | None = cls._atlas_explorer.get_by_id(
        class_name="actions", identifier=id
    )
    return action

get_adapter(id=str)

Get an adapter definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the stakeholder entry

str
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

Adapter Result containing a adapter.

Source code in src/ai_atlas_nexus/library.py
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
def get_adapter(cls, id=str):
    """Get an adapter definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the stakeholder entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Adapter
            Result containing a adapter.
    """
    type_check(
        "<RAN12472418E>",
        str,
        allow_none=False,
        id=id,
    )

    adapter: Adapter | None = cls._atlas_explorer.get_by_id(
        "adapters", identifier=id
    )
    return adapter

get_adapters(taxonomy=None)

Get all adapter definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[Adapter] Result containing a list of Adapter entries

Source code in src/ai_atlas_nexus/library.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
def get_adapters(cls, taxonomy: Optional[Union[str, List[str]]] = None):
    """Get all adapter definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[Adapter]
            Result containing a list of Adapter entries
    """
    type_check(
        "<RAN61770043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    adapter_instances: list[Adapter] = cls.get_all("adapters", taxonomy)
    return adapter_instances

get_all(class_name, taxonomy=None, vocabulary=None, document=None)

Get all the instances of a specified class.

Parameters:

Name Type Description Default
class_name

str Name of the class (the collection key in data)

required
taxonomy

Optional[Union[str, List[str]]] (Optional) The string id for a taxonomy or list of taxonomy ids

None
vocabulary

(Optional) The string id for a vocabulary

None
document

(Optional) The string id for a document

None

Returns:

Type Description

List[Dict[str, Any]] List of instances

Source code in src/ai_atlas_nexus/library.py
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
def get_all(
    cls, class_name, taxonomy=None, vocabulary=None, document=None
):
    """
    Get all the instances of a specified class.

    Args:
        class_name: str
            Name of the class (the collection key in data)
        taxonomy: Optional[Union[str, List[str]]]
            (Optional) The string id for a taxonomy or list of taxonomy ids
        vocabulary:
            (Optional) The string id for a vocabulary
        document:
            (Optional) The string id for a document

    Returns:
        List[Dict[str, Any]]
            List of instances
    """
    value_check(
        "<RAN0948RVB6E>",
        class_name,
        "Please provide a class_name",
    )
    instances: list[Any] = cls._atlas_explorer.get_all(
        class_name, taxonomy, vocabulary, document
    )
    return instances

get_all_actions(taxonomy=None, apply_rules=False)

Get all action definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None
apply_rules bool

bool (Optional) When True, run loaded SHACL rules and attach derived attributes (accessible via instance.derived_attrs) to each result.

False

Returns:

Type Description

list[Action] Result containing a list of AI actions

Source code in src/ai_atlas_nexus/library.py
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
def get_all_actions(
    cls,
    taxonomy: Optional[Union[str, List[str]]] = None,
    apply_rules: bool = False,
):
    """Get all action definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels
        apply_rules: bool
            (Optional) When True, run loaded SHACL rules and attach derived
            attributes (accessible via ``instance.derived_attrs``) to each result.

    Returns:
        list[Action]
            Result containing a list of AI actions
    """
    type_check(
        "<RAN1C9A35ADE>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    action_instances: list[Action] = cls.get_all(
        "actions", taxonomy=taxonomy
    )
    return cls._apply_rules_check(action_instances, apply_rules)

get_all_classes()

Get all the available classes

Returns:

Type Description

List[str] List of classes

Source code in src/ai_atlas_nexus/library.py
195
196
197
198
199
200
201
202
203
204
def get_all_classes(cls):
    """
    Get all the available classes

    Returns:
        List[str]
            List of classes
    """
    classes: List[str] = cls._atlas_explorer.get_all_classes()
    return classes

get_all_evaluations(taxonomy=None)

Get all evaluation definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[AiEval] Result containing a list of AiEval

Source code in src/ai_atlas_nexus/library.py
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
def get_all_evaluations(
    cls, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get all evaluation definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[AiEval]
            Result containing a list of AiEval
    """
    type_check(
        "<RAN18094995E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    evaluation_instances: list[AiEval] = cls.get_all(
        "evaluations", taxonomy=taxonomy
    )
    return evaluation_instances

get_all_risk_controls(taxonomy=None, apply_rules=False)

Get all risk control definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None
apply_rules bool

bool (Optional) When True, run loaded SHACL rules and attach derived attributes (accessible via instance.derived_attrs) to each result.

False

Returns:

Type Description

list[RiskControl] Result containing a list of RiskControls

Source code in src/ai_atlas_nexus/library.py
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
def get_all_risk_controls(
    cls,
    taxonomy: Optional[Union[str, List[str]]] = None,
    apply_rules: bool = False,
):
    """Get all risk control definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels
        apply_rules: bool
            (Optional) When True, run loaded SHACL rules and attach derived
            attributes (accessible via ``instance.derived_attrs``) to each result.

    Returns:
        list[RiskControl]
            Result containing a list of RiskControls
    """
    type_check(
        "<RAN129A1692E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    risk_control_instances: list[RiskControl] = cls.get_all(
        "riskcontrols", taxonomy=taxonomy
    )
    return cls._apply_rules_check(risk_control_instances, apply_rules)

get_all_risks(taxonomy=None, apply_rules=False)

Get all risk definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy

Optional[Union[str, List[str]]] (Optional) The string label for a taxonomy or list of taxonomy labels

None
apply_rules bool

bool (Optional) When True, run loaded SHACL rules and attach derived attributes (accessible via instance.derived_attrs) to each result.

False

Returns:

Type Description

list[Risk] Result containing a list of AI risks

Source code in src/ai_atlas_nexus/library.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def get_all_risks(cls, taxonomy=None, apply_rules: bool = False):
    """Get all risk definitions from the LinkML

    Args:
        taxonomy: Optional[Union[str, List[str]]]
            (Optional) The string label for a taxonomy or list of taxonomy labels
        apply_rules: bool
            (Optional) When True, run loaded SHACL rules and attach derived
            attributes (accessible via ``instance.derived_attrs``) to each result.

    Returns:
        list[Risk]
            Result containing a list of AI risks
    """
    type_check(
        "<RANEACF44A7E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    risk_instances = cls.get_all("risks", taxonomy=taxonomy)
    return cls._apply_rules_check(risk_instances, apply_rules)

get_all_taxonomies()

Get all taxonomy definitions from the LinkML

Returns:

Type Description

List[Taxonomy] Result containing a list of taxonomies

Source code in src/ai_atlas_nexus/library.py
963
964
965
966
967
968
969
970
971
def get_all_taxonomies(cls):
    """Get all taxonomy definitions from the LinkML

    Returns:
        List[Taxonomy]
            Result containing a list of taxonomies
    """
    taxonomy_instances: list[RiskTaxonomy] = cls.get_all("taxonomies")
    return taxonomy_instances

get_benchmark_metadata_card(id=str)

Get an benchmark_metadata_card definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the benchmark_metadata_card

str
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

BenchmarkMetadataCard Result containing a benchmark_metadata_card.

Source code in src/ai_atlas_nexus/library.py
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
def get_benchmark_metadata_card(cls, id=str):
    """Get an benchmark_metadata_card definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the benchmark_metadata_card
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        BenchmarkMetadataCard
            Result containing a benchmark_metadata_card.
    """
    type_check(
        "<RAN30946549E>",
        str,
        allow_none=False,
        id=id,
    )

    benchmark_metadata_card: BenchmarkMetadataCard | None = (
        cls._atlas_explorer.get_by_id(
            class_name="benchmarkmetadatacards", identifier=id
        )
    )
    return benchmark_metadata_card

get_benchmark_metadata_cards(risk=None, risk_id=None, taxonomy=None)

Get all benchmark metadata definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[BenchmarkMetadataCard] Result containing a list of BenchmarkMetadataCards

Source code in src/ai_atlas_nexus/library.py
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
def get_benchmark_metadata_cards(
    cls,
    risk=None,
    risk_id=None,
    taxonomy: Optional[Union[str, List[str]]] = None,
):
    """Get all benchmark metadata definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[BenchmarkMetadataCard]
            Result containing a list of BenchmarkMetadataCards
    """
    type_check(
        "<RAN07894687E>",
        Union[str, List],
        allow_none=True,
        risk_id=risk_id,
        taxonomy=taxonomy,
    )
    type_check("<RAN30190075E>", Risk, allow_none=True, risk=risk)

    benchmark_metatdata_card_instances: list[BenchmarkMetadataCard] = (
        cls.get_all("benchmarkmetadatacards", taxonomy=taxonomy)
    )
    return benchmark_metatdata_card_instances

get_by_attribute(class_name, attribute, value)

Get a single instance by its identifier.

Parameters:

Name Type Description Default
class_name

str Name of the class (the collection key in data)

required
attribute

str Attribute name to filter by

required
value

Any Value to match

required

Returns:

Type Description

Optional[Dict[str, Any]] The matching instance or None

Source code in src/ai_atlas_nexus/library.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def get_by_attribute(cls, class_name, attribute, value):
    """
    Get a single instance by its identifier.

    Args:
        class_name: str
            Name of the class (the collection key in data)
        attribute: str
            Attribute name to filter by
        value: Any
            Value to match

    Returns:
        Optional[Dict[str, Any]]
            The matching instance or None
    """
    instance = cls._atlas_explorer.get_by_attribute(
        class_name, attribute, value
    )
    return instance

get_by_id(class_name, identifier)

Get a single instance by its identifier.

Parameters:

Name Type Description Default
class_name

str Name of the class (the collection key in data)

required
identifier

str Value of the identifier field

required

Returns:

Type Description

Optional[Dict[str, Any]] The matching instance or None

Source code in src/ai_atlas_nexus/library.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def get_by_id(cls, class_name, identifier):
    """
    Get a single instance by its identifier.

    Args:
        class_name: str
            Name of the class (the collection key in data)
        identifier: str
            Value of the identifier field

    Returns:
        Optional[Dict[str, Any]]
            The matching instance or None
    """
    instance = cls._atlas_explorer.get_by_id(class_name, identifier)
    return instance

get_dataset(id=str)

Get a dataset definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the dataset entry

str
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

Dataset Result containing a dataset.

Source code in src/ai_atlas_nexus/library.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
def get_dataset(cls, id=str):
    """Get a dataset definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the dataset entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Dataset
            Result containing a dataset.
    """
    type_check(
        "<RAN12472418E>",
        str,
        allow_none=False,
        id=id,
    )

    dataset: Dataset | None = cls._atlas_explorer.get_by_id(
        "datasets", identifier=id
    )
    return dataset

get_datasets(taxonomy=None)

Get all dataset definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[Dataset] Result containing a list of Dataset entries

Source code in src/ai_atlas_nexus/library.py
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
def get_datasets(cls, taxonomy: Optional[Union[str, List[str]]] = None):
    """Get all dataset definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[Dataset]
            Result containing a list of Dataset entries
    """
    type_check(
        "<RAN61770043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    dataset_instances: list[Dataset] = cls.get_all(
        "datasets", taxonomy=taxonomy
    )
    return dataset_instances

get_document(id=str)

Get a document definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the documentation entry

str
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

Documentation Result containing a document.

Source code in src/ai_atlas_nexus/library.py
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
def get_document(cls, id=str):
    """Get a document definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the documentation entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Documentation
            Result containing a document.
    """
    type_check(
        "<RAN12472418E>",
        str,
        allow_none=False,
        id=id,
    )

    document: Documentation | None = cls._atlas_explorer.get_by_id(
        "documents", identifier=id
    )
    return document

get_documents(taxonomy=None)

Get all document definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[Documentation] Result containing a list of Documentation

Source code in src/ai_atlas_nexus/library.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
def get_documents(cls, taxonomy: Optional[Union[str, List[str]]] = None):
    """Get all document definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[Documentation]
            Result containing a list of Documentation
    """
    type_check(
        "<RAN61770043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    document_instances: list[Documentation] = cls.get_all(
        "documents", taxonomy=taxonomy
    )
    return document_instances

get_evaluation(id=None, taxonomy=None)

Get an evaluation definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the evaluation

None
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

Action Result containing an evaluation.

Source code in src/ai_atlas_nexus/library.py
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def get_evaluation(
    cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get an evaluation definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the evaluation
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        Action
            Result containing an evaluation.
    """
    type_check("<RAN84465757E>", str, allow_none=False, id=id)
    type_check(
        "<RAN29906222E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    evaluation: AiEval | None = cls._atlas_explorer.get_by_id(
        class_name="evaluations", identifier=id
    )
    return evaluation

get_instances(target_class, taxonomy=None)

Get all instance definitions from the LinkML

Parameters:

Name Type Description Default
target_class

str (Optional) The string label for a target class

required
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[Any] Result containing a list of instance entries

Source code in src/ai_atlas_nexus/library.py
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
def get_instances(
    cls, target_class, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get all instance definitions from the LinkML

    Args:
        target_class: str
            (Optional) The string label for a target class
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[Any]
            Result containing a list of instance entries
    """
    type_check(
        "<RAN92358069E>",
        str,
        allow_none=False,
        target_class=id,
    )
    type_check(
        "<RAN61877043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    instances: list[Any] = cls._atlas_explorer.get_instances(
        target_class, taxonomy
    )
    return instances

get_intrinsic(id)

Get an intrinsic definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id str

str The string id identifying the intrinsic entry

required
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

LLMIntrinsic Result containing a intrinsic.

Source code in src/ai_atlas_nexus/library.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
def get_intrinsic(cls, id: str):
    """Get an intrinsic definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the intrinsic entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        LLMIntrinsic
            Result containing a intrinsic.
    """
    type_check(
        "<RAN12472418E>",
        str,
        allow_none=False,
        id=id,
    )

    intrinsic: LLMIntrinsic | None = cls._atlas_explorer.get_by_id(
        "llmintrinsics", identifier=id
    )
    return intrinsic

get_intrinsics(taxonomy=None)

Get all intrinsic definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[LLMIntrinsic] Result containing a list of LLMIntrinsic entries

Source code in src/ai_atlas_nexus/library.py
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
def get_intrinsics(cls, taxonomy: Optional[Union[str, List[str]]] = None):
    """Get all intrinsic definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[LLMIntrinsic]
            Result containing a list of LLMIntrinsic entries
    """
    type_check(
        "<RAN61770043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    intrinsic_instances: list[LLMIntrinsic] = cls.get_all(
        "llmintrinsics", taxonomy=taxonomy
    )
    return intrinsic_instances

get_llm_question_policies(taxonomy=None)

Get all LLM Quesiton Policy definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[LLMQuestionPolicy] Result containing a list of LLMQuestionPolicy entries

Source code in src/ai_atlas_nexus/library.py
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
def get_llm_question_policies(
    cls, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get all LLM Quesiton Policy definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[LLMQuestionPolicy]
            Result containing a list of LLMQuestionPolicy entries
    """
    type_check(
        "<RAN61796043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    llm_question_policy_instances: list[LLMQuestionPolicy] = cls.get_all(
        "llmquestionpolicies", taxonomy
    )
    return llm_question_policy_instances

get_llm_question_policy(id=str)

Get an LLM Question Policy definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the LLM question policy entry

str
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

LLMQuestionPolicy Result containing an LLM Question Policy.

Source code in src/ai_atlas_nexus/library.py
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
def get_llm_question_policy(cls, id=str):
    """Get an LLM Question Policy definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the LLM question policy entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        LLMQuestionPolicy
            Result containing an LLM Question Policy.
    """
    type_check(
        "<RAN32462418E>",
        str,
        allow_none=False,
        id=id,
    )

    llm_question_policy: LLMQuestionPolicy | None = (
        cls._atlas_explorer.get_by_id("llmquestionPolicies", identifier=id)
    )
    return llm_question_policy

get_principle(id=str)

Get a Principle definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id

str The string id identifying the Principle entry

str

Returns:

Type Description

Principle Result containing a Principle.

Source code in src/ai_atlas_nexus/library.py
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
def get_principle(cls, id=str):
    """Get a Principle definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the Principle entry

    Returns:
        Principle
            Result containing a Principle.
    """
    type_check(
        "<RAN97462678E>",
        str,
        allow_none=False,
        id=id,
    )

    principle: Principle | None = cls._atlas_explorer.get_by_id(
        "principles", identifier=id
    )
    return principle

get_principles(taxonomy=None, document=None)

Get all Principle definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None
document

str (Optional) The string label for a document

None

Returns:

Type Description

list[Principle] Result containing a list of Principle entries

Source code in src/ai_atlas_nexus/library.py
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
def get_principles(
    cls, taxonomy: Optional[Union[str, List[str]]] = None, document=None
):
    """Get all Principle definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels
        document: str
            (Optional) The string label for a document


    Returns:
        list[Principle]
            Result containing a list of Principle entries
    """
    type_check(
        "<RAN61573043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )
    type_check(
        "<RAN62577043E>",
        str,
        allow_none=True,
        document=document,
    )

    principle_instances: list[Principle] = cls.get_all(
        "principles", taxonomy=taxonomy, document=document
    )
    return principle_instances

Get actions for a risk definition from the LinkML. The risk is identified by risk id, tag, or name

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
id

(Optional) str The string ID identifying the risk

None
tag

(Optional) str The string tag identifying the risk

None
name

(Optional) str The string name identifying the risk

None
taxonomy

str (Optional) The string label for a taxonomy

None

Returns:

Type Description

Risk Result containing a list of AI actions

Source code in src/ai_atlas_nexus/library.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
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
def get_related_actions(
    cls,
    risk=None,
    tag=None,
    id=None,
    name=None,
    taxonomy=None,
    apply_rules: bool = False,
):
    """Get actions for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

    Args:
        risk: (Optional) Risk
            The risk
        id: (Optional) str
            The string ID identifying the risk
        tag: (Optional) str
            The string tag identifying the risk
        name: (Optional) str
            The string name identifying the risk
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Risk
            Result containing a list of AI actions
    """
    type_check(
        "<RANEDB39EABE>",
        Risk,
        allow_none=True,
        risk=risk,
    )
    type_check(
        "<RANC49E332BE>",
        str,
        allow_none=True,
        tag=tag,
        id=id,
        name=name,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN7154EE0FE>",
        risk or tag or id or name,
        "Please provide risk, tag, id, or name",
    )

    if id:
        risk = cls.get_risk(id=id, apply_rules=apply_rules)
    elif tag:
        risk = cls.get_risk(tag=tag, apply_rules=apply_rules)
    elif name:
        risk = cls.get_risk(name=name, apply_rules=apply_rules)

    related_action_ids = risk.hasRelatedAction
    if related_action_ids:
        actions = [
            cls._atlas_explorer.get_by_id(
                class_name="actions",
                identifier=x,
            )
            for x in related_action_ids
        ]
    else:
        actions = []
    return cls._apply_rules_check(actions, apply_rules)

Get related evaluations filtered by risk id

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
risk_id

(Optional) str The string ID identifying the risk

None
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns: List[AiEval] Result containing a list of AI evaluations

Source code in src/ai_atlas_nexus/library.py
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
def get_related_evaluations(
    cls,
    risk=None,
    risk_id=None,
    taxonomy: Optional[Union[str, List[str]]] = None,
):
    """Get related evaluations filtered by risk id

    Args:
        risk: (Optional) Risk
            The risk
        risk_id: (Optional) str
            The string ID identifying the risk
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels
    Returns:
        List[AiEval]
            Result containing a list of AI evaluations
    """
    type_check("<RAN04616807E>", Risk, allow_none=True, risk=risk)
    type_check(
        "<RAN05640166E>",
        Union[str, List],
        allow_none=True,
        risk_id=risk_id,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN39630388E>",
        risk or risk_id,
        "Please provide risk or id",
    )

    if risk_id:
        risk = cls.get_risk(id=risk_id)

    related_evaluations = cls._atlas_explorer.query(
        "evaluations", hasRelatedRisk=risk.id, taxonomy=taxonomy
    )
    return related_evaluations

Get related intrinsics for a risk definition from the LinkML. The risk is identified by risk id, tag, or name

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
risk_id

(Optional) str The string ID identifying the risk

None
aitask

(Optional) str The aitask

None
aitask_id

(Optional) str The string ID identifying the ai task

None
tag

(Optional) str The string tag identifying the risk

None
name

(Optional) str The string name identifying the risk

None
taxonomy

str (Optional) The string label for a taxonomy

None

Returns:

Type Description

List Result containing a list of Intrinsics

Source code in src/ai_atlas_nexus/library.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
def get_related_intrinsics(
    cls,
    risk=None,
    tag=None,
    risk_id=None,
    aitask=None,
    aitask_id=None,
    task_id=None,
    name=None,
    taxonomy=None,
):
    """Get related intrinsics for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

    Args:
        risk: (Optional) Risk
            The risk
        risk_id: (Optional) str
            The string ID identifying the risk
        aitask: (Optional) str
            The aitask
        aitask_id: (Optional) str
            The string ID identifying the ai task
        tag: (Optional) str
            The string tag identifying the risk
        name: (Optional) str
            The string name identifying the risk
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        List
            Result containing a list of Intrinsics
    """
    type_check(
        "<RAN4E03158FE>",
        Risk,
        allow_none=True,
        risk=risk,
    )
    type_check(
        "<RAN4E93178FE>",
        AiTask,
        allow_none=True,
        aitask=aitask,
    )
    type_check(
        "<RAN55784808E>",
        str,
        allow_none=True,
        tag=tag,
        risk_id=risk_id,
        aitask_id=aitask_id,
        name=name,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN5DCADF94E>",
        risk or tag or aitask or aitask_id or risk_id or name,
        "Please provide risk, tag, aitask, aitask_id, risk_id, or name",
    )

    if aitask or aitask_id:
        if aitask_id:
            aitask = cls.get_by_id(
                class_name="aitasks", identifier=aitask_id
            )

        related_llmintrinsics = []
        capability_ids = (
            cls._atlas_explorer.get_attribute(
                class_name="aitasks",
                identifier=aitask.id,
                attribute="requiresCapability",
            )
            or []
        )
        for cap in capability_ids:
            related_llmintrinsics += cls._atlas_explorer.query(
                "llmintrinsics", c=cap.id, taxonomy=taxonomy
            )
    else:
        if risk_id:
            risk = cls.get_risk(id=risk_id)
        elif tag:
            risk = cls.get_risk(tag=tag)
        elif name:
            risk = cls.get_risk(name=name)

        related_llmintrinsics = cls._atlas_explorer.query(
            "llmintrinsics", hasRelatedRisk=risk.id, taxonomy=taxonomy
        )

    return related_llmintrinsics

Get related risk controls for a risk definition from the LinkML. The risk is identified by risk id, tag, or name

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
id

(Optional) str The string ID identifying the risk

None
tag

(Optional) str The string tag identifying the risk

None
name

(Optional) str The string name identifying the risk

None
taxonomy

str (Optional) The string label for a taxonomy

None

Returns:

Type Description

Risk Result containing a list of AI actions

Source code in src/ai_atlas_nexus/library.py
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
def get_related_risk_controls(
    cls,
    risk=None,
    tag=None,
    id=None,
    name=None,
    taxonomy=None,
):
    """Get related risk controls for a risk definition from the LinkML.  The risk is identified by risk id, tag, or name

    Args:
        risk: (Optional) Risk
            The risk
        id: (Optional) str
            The string ID identifying the risk
        tag: (Optional) str
            The string tag identifying the risk
        name: (Optional) str
            The string name identifying the risk
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Risk
            Result containing a list of AI actions
    """
    type_check(
        "<RAN4E03158FE>",
        Risk,
        allow_none=True,
        risk=risk,
    )
    type_check(
        "<RAN55784808E>",
        str,
        allow_none=True,
        tag=tag,
        id=id,
        name=name,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN5DCADG95E>",
        risk or tag or id or name,
        "Please provide risk, tag, id, or name",
    )

    if id:
        risk = cls.get_risk(id=id)
    elif tag:
        risk = cls.get_risk(tag=tag)
    elif name:
        risk = cls.get_risk(name=name)

    risk_controls = [
        cls._atlas_explorer.get_by_id(
            class_name="riskcontrols", identifier=x
        )
        for x in risk.isDetectedBy or []
    ]
    return risk_controls

Get related risk incident filtered by risk id

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
risk_id

(Optional) str The string ID identifying the risk

None
taxonomy

str (Optional) The string label for a taxonomy

None

Returns: List[RiskIncident] Result containing a list of AI risk incidents

Source code in src/ai_atlas_nexus/library.py
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
def get_related_risk_incidents(
    cls,
    risk=None,
    risk_id=None,
    taxonomy=None,
):
    """Get related risk incident filtered by risk id

    Args:
        risk: (Optional) Risk
            The risk
        risk_id: (Optional) str
            The string ID identifying the risk
        taxonomy: str
            (Optional) The string label for a taxonomy
    Returns:
        List[RiskIncident]
            Result containing a list of AI risk incidents
    """
    type_check(
        "<RAN40791379E>",
        Risk,
        allow_none=True,
        risk=risk,
    )
    type_check(
        "<RANC9FDCC45E>",
        str,
        allow_none=True,
        risk_id=risk_id,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN79007538E>",
        risk or risk_id,
        "Please provide risk or id",
    )

    if risk_id:
        risk = cls.get_risk(id=risk_id)

    related_risk_incidents = cls._atlas_explorer.query(
        "riskincidents",
        refersToRisk=risk.id,
        taxonomy=taxonomy,
    )
    return related_risk_incidents

Get related risks from the LinkML, filtered by risk id, tag, or name

Parameters:

Name Type Description Default
risk

(Optional) Risk The risk

None
id

(Optional) str The string ID identifying the risk

None
tag

(Optional) str The string tag identifying the risk

None
name

(Optional) str The string name identifying the risk

None
taxonomy

Optional[Union[str, List[str]]] (Optional) The string label for a taxonomy or list of strings

None

Returns: List[str] Result containing a list of AI risk IDs

Source code in src/ai_atlas_nexus/library.py
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
def get_related_risks(
    cls,
    risk=None,
    tag=None,
    id=None,
    name=None,
    taxonomy=None,
    apply_rules: bool = False,
):
    """Get related risks from the LinkML, filtered by risk id, tag, or name

    Args:
        risk: (Optional) Risk
            The risk
        id: (Optional) str
            The string ID identifying the risk
        tag: (Optional) str
            The string tag identifying the risk
        name: (Optional) str
            The string name identifying the risk
        taxonomy: Optional[Union[str, List[str]]]
            (Optional) The string label for a taxonomy or list of strings
    Returns:
        List[str]
            Result containing a list of AI risk IDs
    """
    type_check(
        "<RAN283B72CAE>",
        Risk,
        allow_none=True,
        risk=risk,
    )
    type_check(
        "<RANC9FDCC45E>",
        Union[str | List],
        allow_none=True,
        tag=tag,
        id=id,
        name=name,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN0748ECB7E>",
        risk or tag or id or name,
        "Please provide tag, id, or name",
    )

    if id:
        risk = cls.get_risk(id=id)
    elif tag:
        risk = cls.get_risk(tag=tag)

    # just get all the related risks from the risk, these should have been added during lifting
    options = [
        risk.close_mappings or [],
        risk.exact_mappings or [],
        risk.broad_mappings or [],
        risk.narrow_mappings or [],
        risk.related_mappings or [],
    ]
    related_risk_ids = [x for x_list in options for x in x_list]
    related_risk_instances = [
        risk_instance
        for risk_instance in [
            cls.get_risk(id=x, apply_rules=apply_rules)
            for x in related_risk_ids
        ]
        if risk_instance is not None
    ]
    return cls._apply_rules_check(related_risk_instances, apply_rules)

get_risk(tag=None, id=None, name=None, taxonomy=None, apply_rules=False)

Get risk definition from the LinkML, filtered by risk atlas id, tag, name

Parameters:

Name Type Description Default
id

(Optional) str The string ID identifying the risk

None
tag

(Optional) str The string tag identifying the risk

None
name

(Optional) str The string name identifying the risk

None
taxonomy

Optional[Union[str, List[str]]] (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

Risk Result containing a list of AI risks

Source code in src/ai_atlas_nexus/library.py
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
def get_risk(
    cls,
    tag=None,
    id=None,
    name=None,
    taxonomy=None,
    apply_rules: bool = False,
):
    """Get risk definition from the LinkML, filtered by risk atlas id, tag, name

    Args:
        id: (Optional) str
            The string ID identifying the risk
        tag: (Optional) str
            The string tag identifying the risk
        name: (Optional) str
            The string name identifying the risk
        taxonomy: Optional[Union[str, List[str]]]
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        Risk
            Result containing a list of AI risks
    """
    type_check(
        "<RAND62C1B3AE>",
        Union[str, List],
        allow_none=True,
        tag=tag,
        id=id,
        name=name,
        taxonomy=taxonomy,
    )
    value_check(
        "<RAN14D4D967E>",
        tag or id or name,
        "Please provide tag, id, or name",
    )

    risk: Risk | None = cls._atlas_explorer.query(
        "risks",
        tag=tag,
        id=id,
        name=name,
        taxonomy=taxonomy,
    )
    if risk and len(risk) > 0:
        risk = risk[0]
    else:
        return None
    augmented = cls._apply_rules_check([risk], apply_rules)
    return augmented[0] if augmented else None

get_risk_control(id=None, taxonomy=None)

Get an action definition from the LinkML, filtered by risk control id

Parameters:

Name Type Description Default
id

str The string id identifying the risk control

None
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

Action Result containing a risk control.

Source code in src/ai_atlas_nexus/library.py
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
def get_risk_control(
    cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get an action definition from the LinkML, filtered by risk control id

    Args:
        id: str
            The string id identifying the risk control
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        Action
            Result containing a risk control.
    """
    type_check(
        "<RAN9785FFE3E>",
        str,
        allow_none=False,
        id=id,
    )
    type_check(
        "<RAN5A157049E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    risk_control: RiskControl | None = cls._atlas_explorer.get_by_id(
        class_name="riskcontrols", identifier=id
    )
    return risk_control

get_risk_incident(id=None, taxonomy=None)

Get an risk incident instance filtered by risk incident id

Parameters:

Name Type Description Default
id

str The string id identifying the risk incident

None
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

RiskIncident Result containing a risk incident.

Source code in src/ai_atlas_nexus/library.py
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
def get_risk_incident(
    cls, id=None, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get an risk incident instance filtered by risk incident id

    Args:
        id: str
            The string id identifying the risk incident
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        RiskIncident
            Result containing a risk incident.
    """
    type_check(
        "<RAN97353068E>",
        str,
        allow_none=False,
        id=id,
    )
    type_check(
        "<RAN38198685E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    risk_incident: RiskIncident | None = cls._atlas_explorer.get_by_id(
        class_name="riskincidents", identifier=id
    )
    return risk_incident

get_risk_incidents(taxonomy=None)

Get risk incident instances, optionally filtered by taxonomy

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

List[RiskIncident] Result containing a list of AI Risk Incidents

Source code in src/ai_atlas_nexus/library.py
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
def get_risk_incidents(
    cls, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get risk incident instances, optionally filtered by taxonomy

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        List[RiskIncident]
            Result containing a list of AI Risk Incidents
    """
    type_check(
        "<RAN04811131E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    risk_incident_instances: List[RiskIncident] = cls.get_all(
        "riskincidents", taxonomy=taxonomy
    )
    return risk_incident_instances

get_schema() classmethod

Get schema

Returns:

Type Description

schema

Source code in src/ai_atlas_nexus/library.py
176
177
178
179
180
181
182
183
@classmethod
def get_schema(cls):
    """Get schema

    Returns:
        schema
    """
    return cls.schema_view

get_shacl_engine()

Return the loaded SHACLEngine, or None when no shapes were discovered.

Returns:

Type Description

Optional["SHACLEngine"]

Source code in src/ai_atlas_nexus/library.py
116
117
118
119
120
121
122
def get_shacl_engine(self):
    """Return the loaded SHACLEngine, or None when no shapes were discovered.

    Returns:
        Optional["SHACLEngine"]
    """
    return self._shacl_engine

get_stakeholder(id)

Get a stakeholder definition from the LinkML, filtered by id

Parameters:

Name Type Description Default
id str

str The string id identifying the stakeholder entry

required
taxonomy

str (Optional) The string label for a taxonomy

required

Returns:

Type Description

Stakeholder Result containing a stakeholder.

Source code in src/ai_atlas_nexus/library.py
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
def get_stakeholder(cls, id: str):
    """Get a stakeholder definition from the LinkML, filtered by id

    Args:
        id: str
            The string id identifying the stakeholder entry
        taxonomy: str
            (Optional) The string label for a taxonomy

    Returns:
        Stakeholder
            Result containing a stakeholder.
    """
    type_check(
        "<RAN12472418E>",
        str,
        allow_none=False,
        id=id,
    )

    stakeholder: Stakeholder | None = cls._atlas_explorer.get_by_id(
        "stakeholders", identifier=id
    )
    return stakeholder

get_stakeholders(taxonomy=None)

Get all stakeholder definitions from the LinkML

Parameters:

Name Type Description Default
taxonomy Optional[Union[str, List[str]]]

str or list of str (Optional) The string label for a taxonomy or list of taxonomy labels

None

Returns:

Type Description

list[Stakeholder] Result containing a list of Stakeholder entries

Source code in src/ai_atlas_nexus/library.py
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
def get_stakeholders(
    cls, taxonomy: Optional[Union[str, List[str]]] = None
):
    """Get all stakeholder definitions from the LinkML

    Args:
        taxonomy: str or list of str
            (Optional) The string label for a taxonomy or list of taxonomy labels

    Returns:
        list[Stakeholder]
            Result containing a list of Stakeholder entries
    """
    type_check(
        "<RAN61770043E>",
        Union[str, List],
        allow_none=True,
        taxonomy=taxonomy,
    )

    stakeholder_instances: list[Stakeholder] = cls.get_all(
        "stakeholders", taxonomy=taxonomy
    )
    return stakeholder_instances

get_taxonomy_by_id(id)

Get taxonomy definitions from the LinkML filtered by taxonomy id

Parameters:

Name Type Description Default
id

str The string id for a taxonomy

required

Returns:

Type Description

Taxonomy An AI taxonomy

Source code in src/ai_atlas_nexus/library.py
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
def get_taxonomy_by_id(cls, id):
    """Get taxonomy definitions from the LinkML filtered by taxonomy id

    Args:
        id: str
            The string id for a taxonomy

    Returns:
        Taxonomy
            An AI taxonomy
    """
    type_check(
        "<RANBFB574E3E>",
        str,
        allow_none=False,
        id=id,
    )

    taxonomy: RiskTaxonomy | None = cls._atlas_explorer.get_by_id(
        class_name="taxonomies", identifier=id
    )
    return taxonomy

get_version() classmethod

Get library version

Returns:

Name Type Description
dict

Version number

Source code in src/ai_atlas_nexus/library.py
185
186
187
188
189
190
191
192
193
@classmethod
def get_version(cls):
    """Get library version

    Returns:
        dict: Version number
    """
    response = {"version": version("ai_atlas_nexus")}
    return response

identify_ai_tasks_from_usecases(usecases, inference_engine, verbose=True)

Identify potential risks from a usecase description

Parameters:

Name Type Description Default
usecases List[str]

A List of strings describing AI usecases

required
inference_engine InferenceEngine

An LLM inference engine to identify AI tasks from usecases.

required
verbose bool

prints detailed output during the inference process. Defaults to True.

True

Returns:

Type Description
List[List[str]]

List[List[str]]: Result containing a list of AI tasks

Source code in src/ai_atlas_nexus/library.py
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
def identify_ai_tasks_from_usecases(
    cls,
    usecases: List[str],
    inference_engine: InferenceEngine,
    verbose=True,
) -> List[List[str]]:
    """Identify potential risks from a usecase description

    Args:
        usecases (List[str]):
            A List of strings describing AI usecases
        inference_engine (InferenceEngine):
            An LLM inference engine to identify AI tasks from usecases.
        verbose (bool, optional): prints detailed output during the inference process. Defaults to True.

    Returns:
        List[List[str]]:
            Result containing a list of AI tasks
    """
    type_check(
        "<RAN3B9CD886E>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check("<RAN4CDA6852E>", List, allow_none=False, usecases=usecases)
    value_check(
        "<RAN0E435F50E>",
        inference_engine and usecases,
        "Please provide usecases and inference_engine",
    )

    # Load HF tasks from the template dir
    hf_ai_tasks = [
        {"task_label": task.name, "task_description": task.description}
        for task in cls.get_all(
            class_name="aitasks", taxonomy="hf-ml-tasks"
        )
    ]

    prompts = [
        (
            {
                "description": "Classify the given use case into one or more AI Tasks that describes it best. Use the AI tasks definitions to make your decision. Provide a brief explanation for choosing a particular AI Task.",
                "prefix": "You are an AI Task Classifier. You are clear and deterministic in your response. You always give classification label based on a plausible explanation. Study and understand the JSON below containing a list of AI task and its description.",
                "requirements": [
                    "Give one or more AI tasks that best describes the use case",
                    "Provide a brief, plausible explanation for your choice",
                    "Be clear and deterministic in your classification",
                    "The AI task should only be from the AI Task Definitions. Do not include any other task type.",
                ],
                "grounding_context": {
                    "Use case": usecase,
                    "AI Task Definitions": json.dumps(
                        hf_ai_tasks, indent=2
                    ),
                },
            }
            if inference_engine.backend._backend_type == BackendType.MELLEA
            else Template(AI_TASKS_TEMPLATE).render(
                usecase=usecase,
                hf_ai_tasks=hf_ai_tasks,
                limit=len(hf_ai_tasks),
            )
        )
        for usecase in usecases
    ]

    # Invoke inference service
    return inference_engine.generate(
        prompts=prompts,
        response_format=AITaskList,
        postprocessors=["json_object"],
        verbose=verbose,
    )

identify_domain_from_usecases(usecases, inference_engine, verbose=True)

Identify potential risks from a usecase description

Parameters:

Name Type Description Default
usecases List[str]

A List of strings describing AI usecases

required
inference_engine InferenceEngine

An LLM inference engine to identify AI tasks from usecases.

required
verbose bool

prints detailed output during the inference process. Defaults to True.

True

Returns:

Type Description
List[List[str]]

List[List[str]]: Result containing a list of AI tasks

Source code in src/ai_atlas_nexus/library.py
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
def identify_domain_from_usecases(
    cls,
    usecases: List[str],
    inference_engine: InferenceEngine,
    verbose=True,
) -> List[List[str]]:
    """Identify potential risks from a usecase description

    Args:
        usecases (List[str]):
            A List of strings describing AI usecases
        inference_engine (InferenceEngine):
            An LLM inference engine to identify AI tasks from usecases.
        verbose (bool, optional): prints detailed output during the inference process. Defaults to True.

    Returns:
        List[List[str]]:
            Result containing a list of AI tasks
    """
    type_check(
        "<RAN3B9CD886E>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RAN4CDA6852E>",
        List,
        allow_none=False,
        usecases=usecases,
    )
    value_check(
        "<RAN0E435F50E>",
        inference_engine and usecases,
        "Please provide usecases and inference_engine",
    )

    # Load risk questionnaire CoT from the template dir
    risk_questionnaire = load_resource("risk_questionnaire_cot.json")

    # Retrieve domain question data
    domain_ques_data = risk_questionnaire[0]

    # Load ai domain defintions from the template dir
    AI_DOMAIN_DEFINITONS = load_resource("ai_domain_defintions.json")

    prompts = [
        (
            {
                "description": "Classify the given use case into one of the AI Domains that describes it best. Use the AI domain definitions to make your decision. Provide a brief explanation for choosing a particular AI Domain. If no suitable domain exists, classify it as 'Other'",
                "prefix": "You are an AI Domain Classifier. You are clear and deterministic in your response. You always give classification label based on a plausible explanation.",
                "requirements": [
                    "Give the AI domain that best describes the use case",
                    "Provide a brief, plausible explanation for your choice",
                    "Be clear and deterministic in your classification",
                    "The AI domain should only be from the AI Domain Definitions. Do not include any other domain type.",
                ],
                "grounding_context": {
                    "Use case": usecase,
                    "AI Domain Definitions": json.dumps(
                        AI_DOMAIN_DEFINITONS, indent=2
                    ),
                },
            }
            if inference_engine.backend._backend_type == BackendType.MELLEA
            else FewShotPromptBuilder(
                prompt_template=QUESTIONNAIRE_COT_TEMPLATE,
            ).build(
                cot_examples=domain_ques_data["cot_examples"],
                usecase=usecase,
                question=domain_ques_data["question"],
            )
        )
        for usecase in usecases
    ]

    # Invoke inference service
    return inference_engine.generate(
        prompts=prompts,
        response_format=DomainType,
        postprocessors=["json_object"],
        verbose=verbose,
    )

identify_risks_and_actions_from_usecases(usecases, inference_engine, taxonomy=None, cot_examples=None, max_risk=None, zero_shot_only=False)

Identify potential risks from a usecase description

Parameters:

Name Type Description Default
usecases List[str]

A List of strings describing AI usecases

required
inference_engine InferenceEngine

An LLM inference engine to infer risks from the usecases.

required
taxonomy str | list[str] | List[str] | None = None

The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.

None
cot_examples Dict[str, List]

If the user wants to improve risk identification via a Few-shot approach, cot_examples can be provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json. If the cot_examples is omitted, the API default to a Zero-Shot approach.

None
max_risk int

The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.

None
zero_shot_only bool

If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field cot_examples will be ignored.

False

Returns: List[List[Risk]]: Result containing a list of risks

Source code in src/ai_atlas_nexus/library.py
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
@handle_exception(exceptions=[RiskInferenceError])
def identify_risks_and_actions_from_usecases(
    cls,
    usecases: List[str],
    inference_engine: InferenceEngine,
    taxonomy: str | list[str] | List[str] | None = None,
    cot_examples: Optional[Dict[str, List]] = None,
    max_risk: Optional[int] = None,
    zero_shot_only: bool = False,
):
    """Identify potential risks from a usecase description

    Args:
        usecases (List[str]):
            A List of strings describing AI usecases
        inference_engine (InferenceEngine):
            An LLM inference engine to infer risks from the usecases.
        taxonomy (str | list[str] | List[str] | None = None):
            The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.
        cot_examples (Dict[str, List], optional):
            If the user wants to improve risk identification via a Few-shot approach, `cot_examples` can be
            provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json.
            If the `cot_examples` is omitted, the API default to a Zero-Shot approach.
        max_risk (int, optional):
            The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.
        zero_shot_only (bool): If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field `cot_examples` will be ignored.
    Returns:
        List[List[Risk]]:
            Result containing a list of risks
    """
    type_check(
        "<RANE053314BE>",
        List,
        allow_none=False,
        usecases=usecases,
    )
    type_check(
        "<RANE023614CE>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RANB72CPE6BE>",
        Union[str, list, List, None],
        allow_none=True,
        taxonomy=taxonomy,
    )
    type_check(
        "<RAND098498E>",
        int,
        allow_none=True,
        max_risk=max_risk,
    )
    value_check(
        "<RAN6717CP18E>",
        all([isinstance(usecase, str) for usecase in usecases]),
        "Usecases must be a list of string.",
    )

    risks = cls.identify_risks_from_usecases(
        usecases,
        inference_engine,
        taxonomy,
        cot_examples,
        max_risk,
        zero_shot_only,
    )[0]
    control_ids = []
    actions = []
    detectors = []

    for risk in risks:
        if risk.hasRelatedAction:
            risk_actions = (
                risk.hasRelatedAction
                if isinstance(risk.hasRelatedAction, list)
                else [risk.hasRelatedAction]
            )
            actions.extend(risk_actions)

        if risk.isDetectedBy:
            risk_detections = (
                risk.isDetectedBy
                if isinstance(risk.isDetectedBy, list)
                else [risk.isDetectedBy]
            )
            detectors.extend(risk_detections)

        mappings = list(
            itertools.chain(
                risk.related_mappings or [],
                risk.broad_mappings or [],
                risk.close_mappings or [],
                risk.exact_mappings or [],
                risk.hasRelatedAction or [],
                risk.isDetectedBy or [],
            )
        )

        control_ids.extend(
            cls._atlas_explorer.filter_ids_by_type(
                ids=mappings, disallowed_types=["Risk"]
            )
        )
        control_ids = list(set(control_ids))

    summary_1 = {
        "risk_ids": [risk.id for risk in risks],
        "action_ids": actions,
        "detector_ids": detectors,
    }
    summary_2 = cls._atlas_explorer.arrange_ids_by_type(control_ids)
    summary = summary_1 | summary_2

    result = {
        "usecases": usecases,
        "model": inference_engine.model_name_or_path,
        "taxonomy": taxonomy,
        "summary": summary,
        "risks": risks,
        "mixed_control_items": [
            cls._atlas_explorer.get_by_id(None, identifier=item)
            for item in control_ids
        ],
    }
    return result

identify_risks_from_usecases(usecases, inference_engine, taxonomy=None, cot_examples=None, max_risk=None, zero_shot_only=False, batch_inference=True, use_dspy_prompt=False)

Identify potential risks from a usecase description

Parameters:

Name Type Description Default
usecases List[str]

A List of strings describing AI usecases

required
inference_engine InferenceEngine

An LLM inference engine to infer risks from the usecases.

required
taxonomy str

The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.

None
cot_examples Dict[str, List]

If the user wants to improve risk identification via a Few-shot approach, cot_examples can be provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json. If the cot_examples is omitted, the API default to a Zero-Shot approach.

None
max_risk int

The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.

None
zero_shot_only bool

If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field cot_examples will be ignored.

False
batch_inference bool

Whether to run risk inference service in batch mode or at each risk level. Defaults to True.

True
use_dspy_prompt bool

Use per-risk DSPy optmized prompt instructions for risk identification. When enabled, batch_inference flag is ignored.

False

Returns: List[List[Risk]]: Result containing a list of risks

Source code in src/ai_atlas_nexus/library.py
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
@handle_exception(exceptions=[RiskInferenceError])
def identify_risks_from_usecases(
    cls,
    usecases: List[str],
    inference_engine: InferenceEngine,
    taxonomy: str | list[str] | List[str] | None = None,
    cot_examples: Optional[Dict[str, List]] = None,
    max_risk: Optional[int] = None,
    zero_shot_only: bool = False,
    batch_inference: bool = True,
    use_dspy_prompt: bool = False,
) -> List[List[Risk]]:
    """Identify potential risks from a usecase description

    Args:
        usecases (List[str]):
            A List of strings describing AI usecases
        inference_engine (InferenceEngine):
            An LLM inference engine to infer risks from the usecases.
        taxonomy (str, optional):
            The string label for a taxonomy. If not specified, the system will use "ibm-risk-atlas" as the default taxonomy.
        cot_examples (Dict[str, List], optional):
            If the user wants to improve risk identification via a Few-shot approach, `cot_examples` can be
            provided with the desired taxonomy as key. Please follow the example template at src/ai_atlas_nexus/data/templates/risk_generation_cot.json.
            If the `cot_examples` is omitted, the API default to a Zero-Shot approach.
        max_risk (int, optional):
            The maximum number of risks to extract. Pass None to allow the inference engine to determine the number of risks. Defaults to None.
        zero_shot_only (bool): If enabled, this flag allows the system to perform Zero Shot Risk identification, and the field `cot_examples` will be ignored.
        batch_inference (bool): Whether to run risk inference service in batch mode or at each risk level. Defaults to True.
        use_dspy_prompt (bool): Use per-risk DSPy optmized prompt instructions for risk identification. When enabled, `batch_inference` flag is ignored.
    Returns:
        List[List[Risk]]:
            Result containing a list of risks
    """
    type_check(
        "<RANE02D314BE>",
        List,
        allow_none=False,
        usecases=usecases,
    )
    type_check(
        "<RANE023914BE>",
        InferenceEngine,
        allow_none=False,
        inference_engine=inference_engine,
    )
    type_check(
        "<RANB72CAE6EE>",
        Union[str, list, List, None],
        allow_none=True,
        taxonomy=taxonomy,
    )
    type_check(
        "<RAN80975498E>",
        int,
        allow_none=True,
        max_risk=max_risk,
    )
    value_check(
        "<RAN4717CF18E>",
        all([isinstance(usecase, str) for usecase in usecases]),
        "Usecases must be a list of string.",
    )

    # if not providing taxonomy, set to IBM AI risk atlas
    taxonomies = []

    if taxonomy is None:
        logger.warning(
            f"<RAN47375G12W>",
            f"Taxonomy was not provided, defaulting to ibm-risk-atlas.",
        )
        taxonomies = ["ibm-risk-atlas"]
    elif isinstance(taxonomy, str):
        taxonomies.append(taxonomy)
    else:
        taxonomies = taxonomy

    if taxonomy is None:
        logger.warning(
            f"<RAN47375G12W>",
            f"Taxonomy was not provided, defaulting to ibm-risk-atlas.",
        )

    combined_processed_examples = None
    combined_risks = []

    for tx in taxonomies:

        if tx == "ibm-attack-risk-atlas":
            risks = [
                risk
                for risk in cls.get_all("risks", taxonomy="ibm-risk-atlas")
                if risk.tag.endswith("-attack")
            ]
        else:
            risks = cls.get_all("risks", taxonomy=tx)

        combined_risks.extend(risks)

        if len(taxonomies) > 1:
            logger.debug(
                f"When there is more than one taxonomy given, `zero_shot_only` flag is enabled.",
            )
            zero_shot_only = True

        if zero_shot_only:
            logger.debug(
                f"The `zero_shot_only` flag is enabled. The system will use the Zero shot method. Any provided `cot_examples` will be disregarded.",
            )
        else:
            # For the given taxonomy type, check if the user has provided 'cot_examples'. If not,
            # retrieve the default cot examples from the master. If no examples exist in the master,
            # set it as None. The CoT examples include risk-related questions that have been synthetically generated for this task.
            processed_examples = (
                cot_examples and cot_examples.get(tx, None)
            ) or RISK_IDENTIFICATION_COT.get(tx, None)
            if (
                combined_processed_examples
                and type(combined_processed_examples) == list
            ):
                combined_processed_examples.append(processed_examples)
            else:
                combined_processed_examples = processed_examples

    if combined_processed_examples is None:
        logger.warning(
            f"<RAN47275F12W> Chain of Thought (CoT) examples were not provided, or do not exist in the master for this taxonomy. The API will use the Zero shot method. To improve the accuracy of risk identification, please provide CoT examples in `cot_examples` when calling this API. You may also consider raising an issue to permanently add these examples to the AI Atlas Nexus master."
        )

    risk_detector = GenericRiskDetector(
        risks=combined_risks,
        inference_engine=inference_engine,
        cot_examples=combined_processed_examples,
        max_risk=max_risk,
        batch_inference=batch_inference,
        use_dspy_prompt=use_dspy_prompt,
    )

    return risk_detector.detect(usecases)

query(class_name, **kwargs)

Query instances using keyword arguments.

Parameters:

Name Type Description Default
class_name

Union[str | list]: Name of the class (the collection key in data)

required
**kwargs

The attribute-value pairs to filter by

{}

Returns:

Type Description

List[Dict[str, Any]] List of matching instances

Source code in src/ai_atlas_nexus/library.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def query(cls, class_name, **kwargs):
    """
    Query instances using keyword arguments.

    Args:
        class_name: Union[str | list]:
            Name of the class (the collection key in data)
        **kwargs:
            The attribute-value pairs to filter by

    Returns:
        List[Dict[str, Any]]
            List of matching instances
    """
    return cls._atlas_explorer.query(class_name, **kwargs)

run_ares_evaluation(risks, inference_engine, target)

Submit potential attack risks for ARES red-teaming evaluation. This API needs the ran-ares-integration extension. Please install this extension via ran-extension install ran-ares-integration. Refer Readme file for further information on ai-atlas-nexus extensions.

Parameters:

Name Type Description Default
risks List[Risk]

A List of attack risks

required
inference_engine InferenceEngine

An instance of the LLM inference engine

required
target Dict

A target AI model to perform the ARES red-teaming evaluation

required

Returns:

Type Description
None

None

Source code in src/ai_atlas_nexus/library.py
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
def run_ares_evaluation(
    cls, risks: List[Risk], inference_engine: InferenceEngine, target: Dict
) -> None:
    """Submit potential attack risks for ARES red-teaming evaluation.
    This API needs the `ran-ares-integration` extension. Please install this extension via
    `ran-extension install ran-ares-integration`. Refer `Readme` file for further information
    on `ai-atlas-nexus` extensions.

    Args:
        risks (List[Risk]):
            A List of attack risks
        inference_engine (InferenceEngine):
            An instance of the LLM inference engine
        target (Dict):
            A target AI model to perform the ARES red-teaming evaluation

    Returns:
        None
    """
    logger.info(
        f"Risks submitted for ARES evluation: {json.dumps([risk.name for risk in risks], indent=2)}"
    )

    # Load RAN-ARES extension
    ares_extension = Extension.load(
        "ran-ares-integration", inference_engine, target=target
    )

    # Run extension on the given risks
    for risk in risks:
        ares_extension.run(risk)

handler: python options: show_if_no_docstring: true show_submodules: true docstring_section_style: list filters: ["!^*"] heading_level: 2 inherited_members: true merge_init_into_class: true separate_signature: true show_root_heading: true show_root_full_path: false show_signature_annotations: true show_source: false show_symbol_type_heading: true show_symbol_type_toc: true signature_crossrefs: true summary: true