vijil 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vijil-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
vijil-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.1
2
+ Name: vijil
3
+ Version: 0.1.0
4
+ Summary: Python Client for Vijil
5
+ Author: Subho Majumdar
6
+ Author-email: subho@vijil.ai
7
+ Requires-Python: >=3.11,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Requires-Dist: fastparquet (>=2024.5.0,<2025.0.0)
12
+ Requires-Dist: fpdf2 (>=2.7.9,<3.0.0)
13
+ Requires-Dist: jinja2 (>=3.1.4,<4.0.0)
14
+ Requires-Dist: pandas (>=2.2.2,<3.0.0)
15
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
16
+ Requires-Dist: requests (>=2.32.2,<3.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # vijil-python
20
+ Python Client for Vijil
21
+
22
+
23
+ ## Setup
24
+
25
+ ```bash
26
+ pip install git+https://github.com/vijilAI/vijil-python
27
+ ```
28
+
29
+ Then initialize the client using
30
+
31
+ ```python
32
+ from vijil import Vijil
33
+
34
+ client = Vijil()
35
+ ```
36
+
37
+
38
+ Requires a `VIJIL_API_KEY`, either loaded in the environment or suppllied as `api_key` argument above.
39
+
40
+ ## Run Evaluations
41
+
42
+ ```python
43
+ client.evaluations.create(
44
+ model_hub="openai",
45
+ model_name="gpt-3.5-turbo",
46
+ model_params={"temperature": 0},
47
+ harnesses=["ethics","hallucination"],
48
+ harness_params={"sample_size": 5}
49
+ )
50
+ ```
51
+
52
+ See the [minimal example](tutorials/minimal_example.ipynb) for more functionalities.
53
+
vijil-0.1.0/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # vijil-python
2
+ Python Client for Vijil
3
+
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ pip install git+https://github.com/vijilAI/vijil-python
9
+ ```
10
+
11
+ Then initialize the client using
12
+
13
+ ```python
14
+ from vijil import Vijil
15
+
16
+ client = Vijil()
17
+ ```
18
+
19
+
20
+ Requires a `VIJIL_API_KEY`, either loaded in the environment or suppllied as `api_key` argument above.
21
+
22
+ ## Run Evaluations
23
+
24
+ ```python
25
+ client.evaluations.create(
26
+ model_hub="openai",
27
+ model_name="gpt-3.5-turbo",
28
+ model_params={"temperature": 0},
29
+ harnesses=["ethics","hallucination"],
30
+ harness_params={"sample_size": 5}
31
+ )
32
+ ```
33
+
34
+ See the [minimal example](tutorials/minimal_example.ipynb) for more functionalities.
@@ -0,0 +1,28 @@
1
+ [tool.poetry]
2
+ name = "vijil"
3
+ version = "0.1.0"
4
+ description = "Python Client for Vijil"
5
+ authors = [
6
+ "Subho Majumdar <subho@vijil.ai>",
7
+ "Leif Hancox-Li <leif@vijil.ai>",
8
+ "Harsh Raj <harsh@vijil.ai>",
9
+ "Aditya Karan <aditya@vijil.ai>"
10
+ ]
11
+ readme = "README.md"
12
+
13
+ [tool.poetry.dependencies]
14
+ python = "^3.11"
15
+ requests = "^2.32.2"
16
+ python-dotenv = "^1.0.1"
17
+ pandas = "^2.2.2"
18
+ jinja2 = "^3.1.4"
19
+ fpdf2 = "^2.7.9"
20
+ fastparquet = "^2024.5.0"
21
+
22
+
23
+ [tool.poetry.group.dev.dependencies]
24
+ ipykernel = "^6.29.4"
25
+
26
+ [build-system]
27
+ requires = ["poetry-core"]
28
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1 @@
1
+ from ._client import Vijil
@@ -0,0 +1,724 @@
1
+ import os
2
+ import uuid
3
+ import pandas as pd
4
+ import json
5
+ import numpy as np
6
+ from typing import List
7
+ from datetime import datetime, timezone
8
+ import jinja2
9
+ from fpdf import FPDF
10
+
11
+ from vijil.api import make_api_request, get_api_proxy_dict, BASE_URL, SUPPORTED_HUBS
12
+ from vijil.types import VijilClient
13
+
14
+
15
+ class APIKeys:
16
+ """
17
+ Class for managing model hub API keys, which are required to query models.
18
+
19
+ :param client: The Vijil client instance.
20
+ :type client: VijilClient
21
+ """
22
+
23
+ def __init__(self, client: VijilClient) -> None:
24
+ """Constructor class
25
+
26
+ :param client: The Vijil client instance.
27
+ :type client: VijilClient
28
+ """
29
+ self.endpoint = "api-keys"
30
+ self.client = client
31
+ pass
32
+
33
+ def list(self):
34
+ """List all stored model hub API keys.
35
+
36
+ :return: List of dictionaries. Each dictionary contains information about an API key.
37
+ :rtype: List(dict)
38
+ """
39
+ response = make_api_request(base_url=self.client.base_url, endpoint=self.endpoint, token=self.client.api_key)
40
+ return response
41
+
42
+ def get_id_by_name(self, name: str):
43
+ """ Get the id of a key by its name. Used by other functions to get the id of a key to modify.
44
+
45
+ :param name: The name of the key.
46
+ :type name: str
47
+ :return: The id of the key.
48
+ :rtype: str
49
+ """
50
+
51
+ if not self.name_exists(name):
52
+ raise ValueError(f"Key '{name}' does not exist. Please specify an existing name.")
53
+
54
+ #get id of key to modify
55
+ response = self.list()
56
+ return [item['id'] for item in response if item['name'] == name][0]
57
+
58
+ def check_model_hub(self, model_hub: str):
59
+ """Used by other functions to check that the model hub is valid and the key name is unique
60
+
61
+ :param model_hub: The name of the model hub.
62
+ :type model_hub: str
63
+ :raises ValueError: If the model hub is not supported.
64
+ """
65
+
66
+ # check if model_hub is valid
67
+ if (model_hub is not None) and (model_hub not in SUPPORTED_HUBS.keys()):
68
+ raise ValueError(f"Model hub {model_hub} is not supported.")
69
+
70
+ def name_exists(self, name: str):
71
+ """Check whether the API key name already exists. Some functions need it to be exist, others need it to not exist.
72
+
73
+ :param name: The name of the key.
74
+ :type name: str
75
+ :return: True if the name exists among the stored API keys, False otherwise.
76
+ :rtype: bool
77
+ """
78
+
79
+ response = self.list()
80
+ if name in [item['name'] for item in response]:
81
+ return True
82
+ else:
83
+ return False
84
+
85
+ def create(self, name: str, model_hub: str, api_key: str, rate_limit_per_interval=60, rate_limit_interval=10):
86
+ """Create a new model hub API key.
87
+
88
+ :param name: Name for the API key. This must be unique.
89
+ :type name: str
90
+ :param model_hub: Name of the model hub. Current supported values are 'openai', 'together', 'octo'.
91
+ :type model_hub: str
92
+ :param api_key: The API key.
93
+ :type api_key: str
94
+ :param rate_limit_per_interval: The maximum amount of times Vijil will query the model hub in the specified rate_limit_interval, defaults to 60
95
+ :type rate_limit_per_interval: int, optional
96
+ :param rate_limit_interval: The size of the interval (in seconds) defining maximum queries to model hub in said interval. For example, if rate_limit_per_interval is 60 and rate_limit_interval is 10, then Vijil will query the model hub at most 60 times in 10 seconds. Defaults to 10
97
+ :type rate_limit_interval: int, optional
98
+ :raises ValueError: If you try to create a key with a name that belongs to an existing key.
99
+ :return: Response to the API request.
100
+ :rtype: dict
101
+ """
102
+ #check that model hub is supported
103
+ self.check_model_hub(model_hub=model_hub)
104
+
105
+ if self.name_exists(name):
106
+ raise ValueError(f"Key name '{name}' already exists. Please specify a different name.")
107
+
108
+ payload = {
109
+ "name": name,
110
+ "hub": model_hub,
111
+ "rate_limit_per_interval": rate_limit_per_interval,
112
+ "rate_limit_interval": rate_limit_interval,
113
+ "value": api_key,
114
+ }
115
+
116
+ return make_api_request(
117
+ base_url=self.client.base_url,
118
+ endpoint=self.endpoint,
119
+ method="post",
120
+ data=payload,
121
+ token=self.client.api_key
122
+ )
123
+
124
+ def rename(self, name: str, new_name: str):
125
+ """Rename a stored API key
126
+
127
+ :param name: The current name of the key.
128
+ :type name: str
129
+ :param new_name: The new name of the key.
130
+ :type new_name: str
131
+ """
132
+
133
+ key_id = self.get_id_by_name(name=name)
134
+
135
+ payload = {
136
+ "name": new_name
137
+ }
138
+
139
+ return make_api_request(
140
+ base_url=self.client.base_url,
141
+ endpoint=self.endpoint + "/" + key_id,
142
+ method="put",
143
+ data=payload,
144
+ token=self.client.api_key
145
+ )
146
+
147
+
148
+ def modify(self, name: str, model_hub: str=None, api_key:str =None, rate_limit_per_interval=None, rate_limit_interval=None):
149
+ """Modify model hub, key, or rate limits of a stored API key. Cannot be used to rename key.
150
+
151
+ :param name: The name of the key you want to modify.
152
+ :type name: str
153
+ :param model_hub: Name of the model hub. Current supported values are 'openai', 'together', 'octo'.
154
+ :type model_hub: str, optional
155
+ :param api_key: The API key.
156
+ :type api_key: str, optional
157
+ :param rate_limit_per_interval: The maximum amount of times Vijil will query the model hub in the specified rate_limit_interval, defaults to 60
158
+ :type rate_limit_per_interval: int, optional
159
+ :param rate_limit_interval: The size of the interval (in seconds) defining maximum queries to model hub in said interval. For example, if rate_limit_per_interval is 60 and rate_limit_interval is 10, then Vijil will query the model hub at most 60 times in 10 seconds. Defaults to 10
160
+ :type rate_limit_interval: int, optional
161
+ """
162
+
163
+ #check that model hub is supported and key name refers to existing name
164
+ if model_hub is not None:
165
+ self.check_model_hub(model_hub=model_hub)
166
+
167
+ key_id = self.get_id_by_name(name=name)
168
+
169
+ payload = {
170
+ "name": name,
171
+ "hub": model_hub,
172
+ "rate_limit_per_interval": rate_limit_per_interval,
173
+ "rate_limit_interval": rate_limit_interval,
174
+ "value": api_key,
175
+ }
176
+
177
+ #remove None values
178
+ payload = {k: v for k, v in payload.items() if v is not None}
179
+
180
+ return make_api_request(
181
+ base_url=self.client.base_url,
182
+ endpoint=self.endpoint + "/" + key_id,
183
+ method="put",
184
+ data=payload,
185
+ token=self.client.api_key
186
+ )
187
+
188
+ def delete(self, name: str):
189
+ """Delete API key with specified name
190
+
191
+ :param name: The name of the key you want to delete
192
+ :type name: str
193
+ :return: Response to the API request.
194
+ :rtype: dict
195
+ """
196
+
197
+ key_id = self.get_id_by_name(name=name)
198
+
199
+ return make_api_request(
200
+ base_url=self.client.base_url,
201
+ endpoint=self.endpoint + "/" + key_id,
202
+ method="delete",
203
+ token=self.client.api_key
204
+ )
205
+
206
+
207
+ class Harnesses:
208
+ """Class for handling harnesses API requests.
209
+
210
+ :param client: The VijilClient instance.
211
+ :type client: VijilClient
212
+ """
213
+
214
+ def __init__(self, client: VijilClient) -> None:
215
+ """Initialize the Harnesses class.
216
+
217
+ :param VijilClient client: The VijilClient instance.
218
+ :type client: VijilClient
219
+ """
220
+ self.endpoint = "harness-configs"
221
+ self.client = client
222
+ pass
223
+
224
+ def list(self):
225
+ """List all harnesses.
226
+
227
+ :return: List of dicts where each dict contains the metadata for a harness.
228
+ :rtype: List(dict)
229
+ """
230
+ response = make_api_request(base_url=self.client.base_url, endpoint=self.endpoint, token=self.client.api_key)
231
+ return response["results"]
232
+
233
+ def create(self, harness_name: str, component_list: List[str], component_type: str = "probe"):
234
+ """Not implemented yet.
235
+ """
236
+ raise NotImplementedError("Create harnesses is not implemented yet.")
237
+
238
+ if component_type not in ["probe", "scenario"]:
239
+ raise ValueError("component_type must be either 'probe' or 'scenario'")
240
+ payload = {
241
+ "id": str(uuid.uuid4()),
242
+ "harness_name": harness_name,
243
+ "component_list": component_list,
244
+ "component_type": component_type
245
+ }
246
+
247
+ #if request is succeessful, return the harness id, name, and a "submitted" message
248
+ return make_api_request(
249
+ base_url=self.client.base_url,
250
+ endpoint=self.endpoint,
251
+ method="post",
252
+ data=payload,
253
+ token=self.client.api_key
254
+ )
255
+ def delete(self, harness_id: str):
256
+ """
257
+ Not implemented yet.
258
+ """
259
+ raise NotImplementedError("Delete harnesses is not implemented yet.")
260
+
261
+ #if request is succeessful, return the harness id, name, and a "submitted" message
262
+ return make_api_request(
263
+ base_url=self.client.base_url,
264
+ endpoint=f"harness-configs/{harness_id}",
265
+ method="delete",
266
+ token=self.client.api_key
267
+ )
268
+
269
+
270
+
271
+ class Evaluations:
272
+ """Class for handling evaluations API requests.
273
+
274
+ :param client: The VijilClient instance.
275
+ :type client: VijilClient
276
+ """
277
+
278
+ def __init__(
279
+ self,
280
+ client: VijilClient
281
+ ) -> None:
282
+ self.endpoint = "evaluations"
283
+ self.client = client
284
+ self.api_proxy_dict = None
285
+
286
+ def list(self, limit=10):
287
+ """List all valuations. Will return only 10 evaluations unless specified.
288
+
289
+ :param limit: The number of evaluations to return, defaults to 10.
290
+ :type limit: int, optional
291
+ """
292
+
293
+ response = make_api_request(base_url=self.client.base_url, endpoint=self.endpoint+"?limit="+str(limit), token=self.client.api_key)
294
+ return response['results']
295
+
296
+ def create(self, api_key_name: str=None, model_hub: str="openai", model_name: str="gpt-3.5-turbo", model_params={}, harness_params={}, harnesses=[]):
297
+ """Create a new evaluation.
298
+
299
+ :param api_key_name: The name of the model hub API key you want to use. If not specified, will use the first key we find for the specified model_hub.
300
+ :type api_key_name: str, optional
301
+ :param model_hub: The model hub you want to use. Supported options are "openai", "together", "octo". Defaults to "openai"
302
+ :type model_hub: str, optional
303
+ :param model_name: The name of the model you want to use. Check the model hub's API documentation to find valid names. Defaults to "gpt-3.5-turbo"
304
+ :type model_name: str, optional
305
+ :param model_params: A dictionary specifying inference parameters like temperature and top_p. If none are specified, model hub defaults will be used. Defaults to {}
306
+ :type model_params: dict, optional
307
+ :param harness_params: Set optional parameters like is_lite, defaults to {}
308
+ :type harness_params: dict, optional
309
+ :param harnesses: A list of harnesses you want to include in the evaluation, defaults to []
310
+ :type harnesses: List[str], optional
311
+ :raises TypeError: If you have no API keys stored.
312
+ :raises ValueError: If you have no API keys stored for the specified model hub.
313
+ :raises ValueError: If you supply an api_key_name that does not exist.
314
+ :raises ValueError: If you specify lite mode for any harness other than ethics.
315
+ :return: API response containing evaluation ID of the newly created evaluation.
316
+ :rtype: dict
317
+ """
318
+
319
+
320
+ # store all api keys in a dictionary if not there
321
+ if self.api_proxy_dict is None:
322
+ try:
323
+ self.api_proxy_dict = get_api_proxy_dict(base_url=self.client.base_url, token=self.client.api_key)
324
+ except TypeError:
325
+ raise TypeError("No API keys found. Please upload an API key first.")
326
+
327
+ # get api key proxy for the model hub
328
+ try:
329
+ hub_api_proxy_dict = self.api_proxy_dict[model_hub]
330
+ except KeyError:
331
+ raise ValueError(f"No API key stored for model hub {model_hub}")
332
+
333
+ # get api key proxy for the model hub
334
+ if api_key_name is not None:
335
+ #find api key id for the api key name
336
+ if api_key_name not in hub_api_proxy_dict.keys():
337
+ raise ValueError(f"No API key found for name {api_key_name}")
338
+ else:
339
+ api_key_proxy = hub_api_proxy_dict[api_key_name]
340
+ else: #if no key specified, use first value in hub dictionary
341
+ api_key_proxy = next(iter(hub_api_proxy_dict.values()))
342
+
343
+ # create the payload
344
+ payload = {
345
+ "id": str(uuid.uuid4()),
346
+ "hub": model_hub,
347
+ "model": model_name,
348
+ "api_key_proxy": api_key_proxy,
349
+ "scenario_config_filters": []
350
+ }
351
+ if model_params:
352
+ payload['agent_params'] = model_params
353
+ if model_params.get("num_generations"):
354
+ payload["num_generations"] = model_params["num_generations"]
355
+ if harness_params.get('sample_size'):
356
+ payload['sample_size'] = harness_params['sample_size']
357
+ if harness_params.get('is_lite')==True:
358
+ if harnesses == ['ethics']:
359
+ harnesses = ['ethics_lite']
360
+ else:
361
+ raise ValueError("Lite mode is only available for the ethics harness.")
362
+ if "trust_score" in harnesses:
363
+ if len(harnesses)==1:
364
+ harnesses_modified = ["security","privacy","hallucination","robustness","toxicity","stereotype","fairness","ethics","OpenLLM"]
365
+ else:
366
+ raise ValueError("The `trust_score` harness is available only as a standalone harness.")
367
+ else:
368
+ harnesses_modified = harnesses
369
+ payload["harness_config_ids"] = [f"vijil.harnesses.{h}" for h in harnesses_modified]
370
+
371
+
372
+ return make_api_request(
373
+ base_url=self.client.base_url,
374
+ endpoint=self.endpoint,
375
+ method="post",
376
+ data=payload,
377
+ token=self.client.api_key
378
+ )
379
+
380
+ def get_status(self, evaluation_id: str):
381
+ """Retrieve the status of an evaluation
382
+
383
+ :param evaluation_id: The unique ID of the evaluation
384
+ :type evaluation_id: str
385
+ :return: A dict with the id, status, and other metadata of the evaluation
386
+ :rtype: dict
387
+ """
388
+
389
+ response = make_api_request(base_url=self.client.base_url, endpoint=f"evaluations/{evaluation_id}", token=self.client.api_key)
390
+ return response
391
+
392
+ def summarize(self, evaluation_id: str):
393
+ """
394
+ Return summary dataframe of the evaluation results, aggregated at every level
395
+ (overall eval, dimension, scenario, probe)
396
+
397
+ :param evaluation_id: The unique ID of the evaluation
398
+ :type evaluation_id: str
399
+ :return: A dataframe with the level, level_name, and score of the evaluation
400
+ :rtype: pandas.DataFrame
401
+ """
402
+
403
+ #initalize list of dicts where keys are level, level_name, score
404
+ summary_rows = []
405
+
406
+ # get status of evaluation
407
+ try:
408
+ status_dict = self.get_status(evaluation_id=evaluation_id)
409
+ except ValueError as e: # for when evaluation doesn't exist
410
+ return e
411
+
412
+ # evaluation level
413
+ if status_dict['status']=='COMPLETED':
414
+ row = dict()
415
+ row['level'] = 'overall'
416
+ row['level_name'] = 'evaluation'
417
+ row['score'] = round(status_dict['score']*100, 2)
418
+ summary_rows.append(row)
419
+ else:
420
+ return ValueError("Evaluation is not completed yet, check back later.")
421
+
422
+ # harness level
423
+ response = make_api_request(base_url=self.client.base_url, endpoint=f"harness?evaluation_id={evaluation_id}", token=self.client.api_key)
424
+ for harness in response['results']:
425
+ if harness['harness_type']=='DIMENSION' and harness['score'] is not None:
426
+ row = dict()
427
+ row['level'] = 'harness'
428
+ row['level_name'] = harness['name']
429
+ row['score'] = round(harness['score']*100, 2)
430
+ summary_rows.append(row)
431
+
432
+ # scenario level
433
+ response = make_api_request(base_url=self.client.base_url, endpoint=f"scenarios?evaluation_id={evaluation_id}", token=self.client.api_key)
434
+ for scenario in response['results']:
435
+ if scenario['score'] is not None:
436
+ row = dict()
437
+ row['level'] = 'scenario'
438
+ row['level_name'] = scenario['name']
439
+ row['score'] = round(scenario['score']*100, 2)
440
+ summary_rows.append(row)
441
+
442
+ # probe level
443
+ response = make_api_request(base_url=self.client.base_url, endpoint=f"probes?evaluation_id={evaluation_id}", token=self.client.api_key)
444
+ for probe in response['results']:
445
+ if probe['score'] is not None:
446
+ row = dict()
447
+ row['level'] = 'probe'
448
+ row['level_name'] = probe['name']
449
+ row['score'] = round(probe['score']*100, 2)
450
+ summary_rows.append(row)
451
+
452
+ return pd.DataFrame(summary_rows)
453
+
454
+ def export_summary(self, evaluation_id: str, output_dir: str = './', format: str='pdf'):
455
+ """
456
+ Export a PDF or HTML report of the evaluation results containing evaluation metadata
457
+ plus stats from summarize() function
458
+
459
+ :param evaluation_id: The unique ID of the evaluation
460
+ :type evaluation_id: str
461
+ :param output_dir: The directory to save the report to. Defaults to current directory
462
+ :type output_dir: str
463
+ :param format: The format of the report. Defaults to pdf. Options are 'pdf' and 'html'
464
+ :type format: str
465
+ :raises ValueError: If specified format is not 'pdf' or 'html'
466
+ """
467
+ #get dataframe of summary stats
468
+ summary = self.summarize(evaluation_id=evaluation_id)
469
+
470
+ #get evaluation metadata
471
+ status_dict = self.get_status(evaluation_id=evaluation_id)
472
+
473
+ #set jinja settings
474
+ HOME = os.path.join(os.path.dirname(__file__), ".")
475
+ templateLoader = jinja2.FileSystemLoader(
476
+ searchpath=HOME + "/templates"
477
+ )
478
+ templateEnv = jinja2.Environment(loader=templateLoader)
479
+ header_template = templateEnv.get_template("vijil_header.jinja")
480
+ footer_template = templateEnv.get_template("vijil_footer.jinja")
481
+ pdf_template = templateEnv.get_template("whole_pdf.jinja")
482
+
483
+ filename = evaluation_id + '_summary.' + format
484
+
485
+ data_fields = {
486
+ "reportfile": filename,
487
+ "run_uuid": evaluation_id,
488
+ "start_time": str(datetime.fromtimestamp(status_dict['created_at'], tz=timezone.utc)) + " UTC",
489
+ "created_by": status_dict['created_by'],
490
+ "end_time": str(datetime.fromtimestamp(status_dict['completed_at'], tz=timezone.utc)) + " UTC",
491
+ "model_name": status_dict["model"],
492
+ 'total_test_count': status_dict['total_test_count'],
493
+ 'completed_test_count': status_dict['completed_test_count'],
494
+ 'error_test_count': status_dict['error_test_count'],
495
+ "results": summary.to_html(index=False)
496
+ }
497
+
498
+ #write to file
499
+ if format=='html': #use header and footer templates for html
500
+
501
+ # render the header.
502
+ digest_content = header_template.render(data_fields)
503
+ # render the footer
504
+ digest_content += footer_template.render()
505
+
506
+ with open(os.path.join(output_dir, filename), "w") as f:
507
+ f.write(digest_content)
508
+
509
+ elif format=='pdf': #use whole_pdf template which leaves out CSS and JS
510
+ digest_content = pdf_template.render(data_fields)
511
+ pdf = FPDF()
512
+ pdf.add_page()
513
+ pdf.write_html(digest_content)
514
+ pdf.output(os.path.join(output_dir, filename))
515
+ else:
516
+ raise ValueError("format must be 'html' or 'pdf'")
517
+
518
+ def describe(self, evaluation_id: str, limit: int = 1000, format: str = "dataframe", prettify: bool = True):
519
+ """
520
+ Return either list or dataframe of prompt-level metadata and evaluation results,
521
+ with metadata and evaluation scores for each prompt/response in the given evaluation id.
522
+
523
+ :param evaluation_id: The unique ID of the evaluation
524
+ :type evaluation_id: str
525
+ :param limit: The maximum number of prompts to include in description. Defaults to 1000.
526
+ :type limit: int, optional
527
+ :param format: The format of the output. Defaults to "dataframe". Options are "dataframe" and "list"
528
+ :type format: str, optional
529
+ :param prettify: If True, will remove the "vijil.probes." prefix from the probe names to make it more readable. Defaults to True.
530
+ :type prettify: bool, optional
531
+ :raises ValueError: If specified format is not 'dataframe' or 'list'
532
+ """
533
+ if limit is None:
534
+ limit = 1000000
535
+
536
+ response = make_api_request(base_url=self.client.base_url, endpoint=f"responses?evaluation_id={evaluation_id}&limit={limit}", token=self.client.api_key)
537
+
538
+ # change detector ids to list if it is a string
539
+ results = response['results']
540
+ if len(results) == 0:
541
+ raise ValueError(f"No results found for evaluation id {evaluation_id}. Please check that you have the correct id.")
542
+ for idx, res in enumerate(results):
543
+ if isinstance(res['detector_ids'], str):
544
+ results[idx]['detector_ids'] = [res['detector_ids']]
545
+
546
+ prompt_list = [
547
+ {
548
+ "probe": res['probe_config_id'].replace("vijil.probes.", "") if prettify else res['probe_config_id'],
549
+ "input_prompt_id": res['input_prompt_id'],
550
+ "prompt": res['input_prompt'],
551
+ "response": res['response'],
552
+ "detectors": [
553
+ det.replace("garak.detectors.", "").replace("autoredteam.detectors.", "")
554
+ for det in res['detector_ids']
555
+ ],
556
+ "score": res['detector_scores'],
557
+ 'generation': res['generation'],
558
+ 'status': res['status'],
559
+ 'error_message': res['error_message']
560
+ }
561
+ for res in results
562
+ ]
563
+
564
+ #calculate summary stats for detectors
565
+ prompt_list_df = pd.DataFrame(prompt_list)
566
+ prompt_list_df['avg_detector_score'] = prompt_list_df['score'].apply(lambda x: sum([sum(list(item.values())) for item in x]) / len(x) if len(x) and not any(['ERROR' in item for item in x]) else np.nan)
567
+ prompt_list_df['min_detector_score'] = prompt_list_df['score'].apply(lambda x: min([min(list(item.values())) for item in x]) / len(x) if len(x) and not any(['ERROR' in item for item in x]) else np.nan)
568
+ prompt_list_df['max_detector_score'] = prompt_list_df['score'].apply(lambda x: max([max(list(item.values())) for item in x]) / len(x) if len(x) and not any(['ERROR' in item for item in x]) else np.nan)
569
+ prompt_list_df.sort_values('probe', inplace=True)
570
+
571
+ if format=='list':
572
+ return prompt_list_df.to_dict(orient='records')
573
+ elif format=='dataframe':
574
+ return prompt_list_df
575
+ else:
576
+ raise ValueError("format must be 'list' or 'dataframe'")
577
+
578
+
579
+ def export_report(self, evaluation_id: str, limit: int=1000000, format: str='csv', output_dir: str = './'):
580
+ """
581
+ Exports output of describe() into csv, jsonl, json, or parquet
582
+
583
+ :param evaluation_id: The unique ID of the evaluation
584
+ :type evaluation_id: str
585
+ :param limit: The maximum number of prompts to include in the report. Defaults to 1000000.
586
+ :type limit: int, optional
587
+ :param format: The format of the output. Defaults to "csv". Options are "csv", "parquet", "json" and "jsonl"
588
+ :type format: str, optional
589
+ :param output_dir: The directory to save the report. Defaults to the current directory.
590
+ :type output_dir: str, optional
591
+ :raises ValueError: If specified format is not 'csv', 'parquet', 'json' or 'jsonl'
592
+ """
593
+
594
+ if format=='csv':
595
+ prompt_list_df = self.describe(evaluation_id=evaluation_id, limit=limit, format="dataframe")
596
+ filename = evaluation_id + '_report.csv'
597
+ filepath = os.path.join(output_dir, filename)
598
+ prompt_list_df.to_csv(filepath, index=False)
599
+ print("report exported to " + filepath)
600
+ elif format=='json':
601
+ prompt_list = self.describe(evaluation_id=evaluation_id, limit=limit, format="list")
602
+ filename = evaluation_id + '_report.json'
603
+ filepath = os.path.join(output_dir, filename)
604
+ with open(filepath, 'w') as f:
605
+ json.dump(prompt_list, f, indent=4)
606
+ print("report exported to " + filepath)
607
+ elif format=='jsonl':
608
+ prompt_list = self.describe(evaluation_id=evaluation_id, limit=limit, format="list")
609
+ filename = evaluation_id + '_report.jsonl'
610
+ filepath = os.path.join(output_dir, filename)
611
+ with open(filepath, 'w') as f:
612
+ for item in prompt_list:
613
+ f.write(json.dumps(item) + '\n')
614
+ print("report exported to " + filepath)
615
+ elif format=='parquet':
616
+ prompt_list_df = self.describe(evaluation_id=evaluation_id, limit=limit, format="dataframe")
617
+ filename = evaluation_id + '_report.parquet'
618
+ filepath = os.path.join(output_dir, filename)
619
+ prompt_list_df.to_parquet(filepath, index=False)
620
+ print("report exported to " + filepath)
621
+ else:
622
+ raise ValueError("format must be 'csv', 'parquet', 'json', or 'jsonl'")
623
+
624
+ def cancel(self, evaluation_id: str):
625
+ """
626
+ Cancels an in-progress evaluation
627
+
628
+ :param evaluation_id: The unique ID of the evaluation
629
+ :type evaluation_id: str
630
+ :raises ValueError: If the evaluation is not in progress
631
+ :returns: The response from the API
632
+ :rtype: dict
633
+ """
634
+
635
+ #check eval status
636
+ try:
637
+ status_dict = self.get_status(evaluation_id=evaluation_id)
638
+ except ValueError as e:
639
+ return e
640
+
641
+ if status_dict['status'] != 'IN_PROGRESS':
642
+ raise ValueError(f"Evaluation {evaluation_id} is not in progress. Cannot cancel.")
643
+
644
+ payload = {
645
+ "type": "CANCEL_EVALUATION",
646
+ "data": {
647
+ "evaluation_id": evaluation_id
648
+ }
649
+ }
650
+
651
+ return make_api_request(
652
+ base_url=self.client.base_url,
653
+ endpoint="events",
654
+ method="post",
655
+ data=payload,
656
+ token=self.client.api_key
657
+ )
658
+
659
+ def delete(self, evaluation_id: str):
660
+ """
661
+ Deletes an evaluation
662
+
663
+ :param evaluation_id: The unique ID of the evaluation
664
+ :type evaluation_id: str
665
+ :raises ValueError: If the evaluation does not exist
666
+ :returns: The response from the API
667
+ :rtype: dict
668
+ """
669
+
670
+ #check eval status. This will raise an error if the eval doesn't exist.
671
+ try:
672
+ status_dict = self.get_status(evaluation_id=evaluation_id)
673
+ except ValueError as e:
674
+ return e
675
+
676
+ payload = {
677
+ "type": "DELETE_EVALUATION",
678
+ "data": {
679
+ "evaluation_id": evaluation_id
680
+ }
681
+ }
682
+
683
+ return make_api_request(
684
+ base_url=self.client.base_url,
685
+ endpoint="events",
686
+ method="post",
687
+ data=payload,
688
+ token=self.client.api_key
689
+ )
690
+
691
+ class Vijil:
692
+ """Base class for the Vijil API client.
693
+
694
+ :param base_url: The base URL for the Vijil API
695
+ :type base_url: str
696
+ :param api_key: The API key for the Vijil API
697
+ :type api_key: str
698
+ """
699
+ client: VijilClient
700
+ evaluations: Evaluations
701
+ harnesses: Harnesses
702
+ api_keys: APIKeys
703
+
704
+ def __init__(self, base_url: str = BASE_URL, api_key: str = None):
705
+ """Constructor class for VijilClient
706
+
707
+ :param base_url: Base URL for API, defaults to BASE_URL as specified in `api.py`
708
+ :type base_url: str, optional
709
+ :param api_key: Vijil API key, defaults to None
710
+ :type api_key: str, optional
711
+ :raises ValueError: if no Vijil API key is provided in api_key and VIJIL_API_KEY is not set as an environment variable
712
+ """
713
+
714
+ if api_key is None:
715
+ api_key = os.environ["VIJIL_API_KEY"]
716
+ if api_key is None:
717
+ raise ValueError(
718
+ "No API key found! Please set VIJIL_API_KEY as environment variable or supply the `api_key` parameter."
719
+ )
720
+
721
+ self.client = VijilClient(base_url=base_url, api_key=api_key)
722
+ self.evaluations = Evaluations(self.client)
723
+ self.harnesses = Harnesses(self.client)
724
+ self.api_keys = APIKeys(self.client)
@@ -0,0 +1,62 @@
1
+ # api_handler.py
2
+ import requests
3
+ import os
4
+ import logging
5
+
6
+ BASE_URL = "https://api-stage.vijil.ai/v1"
7
+
8
+ SUPPORTED_HUBS = {
9
+ "openai": "OpenAI",
10
+ "together": "Together",
11
+ "octo": "OctoAI",
12
+ }
13
+
14
+ # Set up logging
15
+ HIDDEN_DIR_NAME = ".vijil"
16
+ LOG_FILE_NAME = "vijil.log"
17
+ LOG_FILE_PATH = os.path.join(os.path.expanduser('~'), HIDDEN_DIR_NAME, LOG_FILE_NAME)
18
+ os.makedirs(os.path.dirname(LOG_FILE_PATH), exist_ok=True)
19
+ logging.basicConfig(level=logging.ERROR, filename=LOG_FILE_PATH, filemode='a',
20
+ format='%(asctime)s - %(levelname)s - %(message)s')
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def make_api_request(base_url, endpoint, method="get", token=None, params=None, data=None):
25
+ url = f"{base_url}/{endpoint}"
26
+ if token is not None:
27
+ headers = {"Authorization": f"Bearer {token}"}
28
+ else:
29
+ headers = {}
30
+
31
+ try:
32
+ if method.lower() == "get":
33
+ response = requests.get(url, params=params, headers=headers)
34
+ # print("GET request made") # code to test if the request is being made
35
+ elif method.lower()=='put':
36
+ response = requests.put(url, json=data, params=params, headers=headers)
37
+ elif method.lower() == "delete":
38
+ response = requests.delete(url, params=params, headers=headers)
39
+ elif method.lower() == "post":
40
+ response = requests.post(url, json=data, params=params, headers=headers)
41
+ # print(f"POST request made to {url} with payload {data}") # code to test if the request is being made
42
+ else:
43
+ raise ValueError("Invalid HTTP method. Use 'get', 'put', 'delete', or 'post'.")
44
+
45
+ response.raise_for_status()
46
+ return response.json()
47
+ except:
48
+ print(f"Error: {response.text}")
49
+ pass
50
+
51
+ def get_api_proxy_dict(base_url, token=None):
52
+
53
+ response = make_api_request(base_url=base_url, endpoint="api-keys", token=token)
54
+
55
+ unique_hubs = set([r['hub'] for r in response])
56
+ hubs_dict = {hub: {} for hub in unique_hubs}
57
+ for hub in unique_hubs:
58
+ for r in response:
59
+ if r['hub'] == hub:
60
+ hubs_dict[hub][r['name']] = r['id']
61
+
62
+ return hubs_dict
@@ -0,0 +1,27 @@
1
+
2
+ <script>
3
+ var acc = document.getElementsByClassName("accordion");
4
+ var i;
5
+
6
+ for (i = 0; i < acc.length; i++) {
7
+ acc[i].addEventListener("click", function() {
8
+ /* Toggle between adding and removing the "active" class,
9
+ to highlight the button that controls the panel */
10
+ this.classList.toggle("active");
11
+
12
+ /* Toggle between hiding and showing the active panel */
13
+ var panel = this.nextElementSibling;
14
+ if (panel.style.display === "block") {
15
+ panel.style.display = "none";
16
+ } else {
17
+ panel.style.display = "block";
18
+ }
19
+ });
20
+ }</script>
21
+ </body>
22
+
23
+ <p style="height:400px; padding-top: 100px">
24
+ generated with <a href="https://vijil.ai">Vijil</a>
25
+ </p>
26
+
27
+ </html>
@@ -0,0 +1,79 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta charset="UTF-8" />
7
+ <style>
8
+ body {font-family: sans-serif}
9
+ .defcon1 {background-color: #f94144; text-color: #000}
10
+ .defcon2 {background-color: #f8961e; text-color: #000}
11
+ .defcon3 {background-color: #ccc; text-color: #000}
12
+ .defcon4 {background-color: #ddd; text-color: #000}
13
+ .defcon5 {background-color: #f7f7f7; text-color: #000}
14
+ .probe {padding-left: 40pt}
15
+ .detector {padding-left: 65pt}
16
+ h2 {padding-left: 20pt}
17
+ h3 {padding-left: 40pt}
18
+ h4 {padding-left: 60pt}
19
+ h2,h3,h4 {padding-top: 10px; padding-bottom: 10px}
20
+ th, td {
21
+ padding: 5px;
22
+ text-align: left;
23
+ }
24
+ tr {
25
+ border-bottom: 1px solid #ddd;
26
+ }
27
+
28
+ /* Style the buttons that are used to open and close the accordion panel */
29
+ .accordion {
30
+ // background-color: #eee;
31
+ color: #444;
32
+ cursor: pointer;
33
+ padding: 18px;
34
+ width: 100%;
35
+ text-align: left;
36
+ border: none;
37
+ outline: none;
38
+ transition: 0.4s;
39
+ margin: 1pt;
40
+ }
41
+
42
+ /* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
43
+ .active, .accordion:hover {
44
+ background-color: #ccf;
45
+ }
46
+
47
+ /* Style the accordion panel. Note: hidden by default */
48
+ .panel {
49
+ padding: 0 18px;
50
+ background-color: white;
51
+ display: none;
52
+ overflow: hidden;
53
+ }
54
+ </style>
55
+ <title>Trust Report: {{model_name}}</title>
56
+ <meta name="description" content="" />
57
+ </head>
58
+
59
+ <body>
60
+
61
+ <h1>Trust Report: {{model_name}}</h1>
62
+ <button class="accordion">⚙ Config</button>
63
+ <div style="border:solid black 1px; padding: 5px; margin: 5px" class="panel">
64
+ <h2>Config</h2>
65
+ <p>Filename: {{reportfile}}</p>
66
+ <p>Evaluation ID: {{run_uuid}}</p>
67
+ <p>Model name: {{model_name}}</p>
68
+ <p>Evaluation started: {{start_time}}</p>
69
+ <p>Evaluation ended: {{end_time}}</p>
70
+ <p>Created by: {{created_by}}</p>
71
+ <p>Total tests: {{total_test_count}}</p>
72
+ <p>Completed tests: {{completed_test_count}}</p>
73
+ <p>Tests with errors: {{error_test_count}}</p>
74
+ </div>
75
+
76
+ <h3>Model name: {{model_name}}</h3>
77
+ <h3>Evaluation Time: {{start_time}}</h3>
78
+
79
+ {{ results | safe}}
@@ -0,0 +1,35 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta charset="UTF-8" />
7
+ </head>
8
+
9
+ <body>
10
+
11
+ <h1>Trust Report: {{model_name}}</h1>
12
+ <div style="border:solid black 1px; padding: 5px; margin: 5px" class="panel">
13
+ <h2>Configuration details</h2>
14
+ <p>Filename: {{reportfile}}</p>
15
+ <p>Evaluation ID: {{run_uuid}}</p>
16
+ <p>Model name: {{model_name}}</p>
17
+ <p>Evaluation started: {{start_time}}</p>
18
+ <p>Evaluation ended: {{end_time}}</p>
19
+ <p>Created by: {{created_by}}</p>
20
+ <p>Total tests: {{total_test_count}}</p>
21
+ <p>Completed tests: {{completed_test_count}}</p>
22
+ <p>Tests with errors: {{error_test_count}}</p>
23
+ </div>
24
+
25
+ <br>
26
+
27
+ {{ results | safe}}
28
+
29
+ </body>
30
+
31
+ <p style="height:400px; padding-top: 100px">
32
+ generated with <a href="https://vijil.ai">Vijil</a>
33
+ </p>
34
+
35
+ </html>
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+
3
+ from vijil.api import BASE_URL
4
+
5
+
6
+ @dataclass
7
+ class VijilClient:
8
+ base_url: str = BASE_URL
9
+ api_key: str = None