aadml-training 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.
@@ -0,0 +1,10 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: github-actions
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ - package-ecosystem: pip
8
+ directory: /
9
+ schedule:
10
+ interval: weekly
@@ -0,0 +1,25 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ matrix:
16
+ python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
17
+ steps:
18
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
19
+ with:
20
+ persist-credentials: false
21
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
22
+ with:
23
+ python-version: ${{ matrix.python }}
24
+ - run: python -m pip install ".[test]"
25
+ - run: python -m pytest -q
@@ -0,0 +1,47 @@
1
+ name: Release
2
+
3
+ # A tag v<version> builds the package and publishes it to pypi.org with PyPI's trusted publishing: no PyPI token is
4
+ # stored anywhere. The tag must match src/aadml_training/_version.py.
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ build:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
17
+ with:
18
+ persist-credentials: false
19
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
20
+ with:
21
+ python-version: "3.12"
22
+ - name: The tag matches the version
23
+ run: |
24
+ version=$(python -c "import re;print(re.search(r'\"(.+)\"', open('src/aadml_training/_version.py').read())[1])")
25
+ test "v$version" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME is not v$version"; exit 1; }
26
+ - run: python -m pip install ".[test]" build==1.2.2.post1
27
+ - run: python -m pytest -q
28
+ - run: python -m build
29
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
30
+ with:
31
+ name: dist
32
+ path: dist/
33
+
34
+ publish:
35
+ needs: build
36
+ runs-on: ubuntu-latest
37
+ environment:
38
+ name: pypi
39
+ url: https://pypi.org/project/aadml-training/
40
+ permissions:
41
+ id-token: write
42
+ steps:
43
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
44
+ with:
45
+ name: dist
46
+ path: dist/
47
+ - uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ venv/
8
+ .pytest_cache/
9
+ .env
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - `Client`: AADML's address and your app key (`AADML_API_KEY`, `AADML_API_URL`), timeouts and retries that never send
6
+ a request twice when it may have been processed.
7
+ - Photo models: `predict` (a file path, bytes, an open file, a URL or a Pillow image).
8
+ - Chat models: `chat`, `chat_text`, `chat_stream`, `models`, in OpenAI's chat completions format.
9
+ - One error kind per answer: `AuthenticationError`, `PermissionDeniedError`, `BadRequestError`,
10
+ `PayloadTooLargeError`, `RateLimitError`, `ModelUnavailableError`, `ServerError`, `ConnectionError`.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: aadml-training
3
+ Version: 0.1.0
4
+ Summary: Python SDK for AADML Training: call your trained photo and chat models from your own code.
5
+ Project-URL: Homepage, https://aadml.com
6
+ Project-URL: Source, https://github.com/sajid-the-backend-engineer/aadml-training
7
+ Project-URL: Issues, https://github.com/sajid-the-backend-engineer/aadml-training/issues
8
+ Project-URL: Changelog, https://github.com/sajid-the-backend-engineer/aadml-training/blob/main/CHANGELOG.md
9
+ Author: Northrays
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: aadml,computer vision,inference,llm,machine learning,sdk
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Requires-Dist: httpx<1,>=0.27
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest==8.3.5; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # aadml-training
32
+
33
+ The Python SDK for [AADML](https://aadml.com) Training: call the photo and chat models you trained and deployed in
34
+ AADML from your own code.
35
+
36
+ ```bash
37
+ pip install aadml-training
38
+ ```
39
+
40
+ Python 3.9 or newer. One dependency: [httpx](https://www.python-httpx.org/).
41
+
42
+ ## Your key
43
+
44
+ Make an app key on your project's **Deploy** page (Connected apps), and allow it the environment you will call
45
+ (staging or production). Keep it secret: anyone with the key can call your model, and calls may be charged.
46
+
47
+ ```bash
48
+ export AADML_API_KEY="your app key"
49
+ ```
50
+
51
+ ## Photo models
52
+
53
+ ```python
54
+ from aadml_training import Client
55
+
56
+ client = Client() # reads AADML_API_KEY; or Client(api_key="...")
57
+
58
+ result = client.predict(project_id=22, image="room.jpg") # production by default
59
+ for wall in result["walls"]:
60
+ print(wall["id"], wall["corners"])
61
+ for opening in result["openings"]:
62
+ print(opening["type"], opening["polygon"]) # windows and doors
63
+ ```
64
+
65
+ `image` can be a file path, bytes, an open binary file, a URL or a Pillow image: JPEG, PNG or WebP, at most 15 MB.
66
+ Coordinates are in the photo's own pixels. Pass `environment="staging"` to call the staging model, and your own
67
+ `request_id` / `capture_id` to find a call again later.
68
+
69
+ ## Chat models
70
+
71
+ A chat model's project answers in OpenAI's chat completions format.
72
+
73
+ ```python
74
+ messages = [{"role": "user", "content": "How do I return an order?"}]
75
+
76
+ print(client.chat_text(project_id=31, messages=messages))
77
+
78
+ for piece in client.chat_stream(project_id=31, messages=messages): # as the model writes it
79
+ print(piece, end="", flush=True)
80
+
81
+ answer = client.chat(project_id=31, messages=messages, max_tokens=200) # the whole completion
82
+ print(client.models(project_id=31)) # the models it answers with
83
+ ```
84
+
85
+ ## Errors
86
+
87
+ Every error is an `aadml_training.AADMLError`. An error answer from AADML is an `APIError` with `status_code`,
88
+ `message` and, when AADML names one, `field`:
89
+
90
+ | Error | When |
91
+ |---|---|
92
+ | `AuthenticationError` (401) | The key is missing, unknown or revoked |
93
+ | `PermissionDeniedError` (403) | The key has no access to that project and environment |
94
+ | `BadRequestError` (400) | The request was refused, for example a file that is not a photo |
95
+ | `PayloadTooLargeError` (413) | The photo is larger than 15 MB |
96
+ | `RateLimitError` (429) | Too many requests for this key; `retry_after` says how long to wait |
97
+ | `ModelUnavailableError` (503) | No model is deployed to that environment yet, or it is starting |
98
+ | `ServerError` (5xx) | AADML or the model failed to answer |
99
+ | `ConnectionError` | AADML could not be reached |
100
+
101
+ ```python
102
+ from aadml_training import ModelUnavailableError
103
+
104
+ try:
105
+ result = client.predict(project_id=22, image="room.jpg")
106
+ except ModelUnavailableError as error:
107
+ print("Not ready yet:", error.message, "try again in", error.retry_after, "seconds")
108
+ ```
109
+
110
+ ## Retries
111
+
112
+ A request AADML refused **without processing it** (429, 503) or that never reached AADML is sent again, waiting as
113
+ AADML asks (at most 30 seconds), up to `max_retries` times (2 by default). A request that may have been processed is
114
+ never sent twice, so you are never charged twice for one call.
115
+
116
+ ```python
117
+ client = Client(timeout=30, max_retries=0)
118
+ ```
119
+
120
+ ## Settings
121
+
122
+ | Setting | Argument | Environment variable | Default |
123
+ |---|---|---|---|
124
+ | API key | `api_key` | `AADML_API_KEY` | none: required |
125
+ | AADML's address | `api_url` | `AADML_API_URL` | `https://aadml.com` |
126
+ | Seconds to wait for an answer | `timeout` | | 60 |
127
+ | Times a request is sent again | `max_retries` | | 2 |
128
+
129
+ ## About this package
130
+
131
+ `aadml-training` covers AADML Training. It will become part of the general `aadml` SDK; this package will then point
132
+ to it.
133
+
134
+ Licence: Apache 2.0. Report a security problem privately (see [SECURITY.md](SECURITY.md)).
@@ -0,0 +1,104 @@
1
+ # aadml-training
2
+
3
+ The Python SDK for [AADML](https://aadml.com) Training: call the photo and chat models you trained and deployed in
4
+ AADML from your own code.
5
+
6
+ ```bash
7
+ pip install aadml-training
8
+ ```
9
+
10
+ Python 3.9 or newer. One dependency: [httpx](https://www.python-httpx.org/).
11
+
12
+ ## Your key
13
+
14
+ Make an app key on your project's **Deploy** page (Connected apps), and allow it the environment you will call
15
+ (staging or production). Keep it secret: anyone with the key can call your model, and calls may be charged.
16
+
17
+ ```bash
18
+ export AADML_API_KEY="your app key"
19
+ ```
20
+
21
+ ## Photo models
22
+
23
+ ```python
24
+ from aadml_training import Client
25
+
26
+ client = Client() # reads AADML_API_KEY; or Client(api_key="...")
27
+
28
+ result = client.predict(project_id=22, image="room.jpg") # production by default
29
+ for wall in result["walls"]:
30
+ print(wall["id"], wall["corners"])
31
+ for opening in result["openings"]:
32
+ print(opening["type"], opening["polygon"]) # windows and doors
33
+ ```
34
+
35
+ `image` can be a file path, bytes, an open binary file, a URL or a Pillow image: JPEG, PNG or WebP, at most 15 MB.
36
+ Coordinates are in the photo's own pixels. Pass `environment="staging"` to call the staging model, and your own
37
+ `request_id` / `capture_id` to find a call again later.
38
+
39
+ ## Chat models
40
+
41
+ A chat model's project answers in OpenAI's chat completions format.
42
+
43
+ ```python
44
+ messages = [{"role": "user", "content": "How do I return an order?"}]
45
+
46
+ print(client.chat_text(project_id=31, messages=messages))
47
+
48
+ for piece in client.chat_stream(project_id=31, messages=messages): # as the model writes it
49
+ print(piece, end="", flush=True)
50
+
51
+ answer = client.chat(project_id=31, messages=messages, max_tokens=200) # the whole completion
52
+ print(client.models(project_id=31)) # the models it answers with
53
+ ```
54
+
55
+ ## Errors
56
+
57
+ Every error is an `aadml_training.AADMLError`. An error answer from AADML is an `APIError` with `status_code`,
58
+ `message` and, when AADML names one, `field`:
59
+
60
+ | Error | When |
61
+ |---|---|
62
+ | `AuthenticationError` (401) | The key is missing, unknown or revoked |
63
+ | `PermissionDeniedError` (403) | The key has no access to that project and environment |
64
+ | `BadRequestError` (400) | The request was refused, for example a file that is not a photo |
65
+ | `PayloadTooLargeError` (413) | The photo is larger than 15 MB |
66
+ | `RateLimitError` (429) | Too many requests for this key; `retry_after` says how long to wait |
67
+ | `ModelUnavailableError` (503) | No model is deployed to that environment yet, or it is starting |
68
+ | `ServerError` (5xx) | AADML or the model failed to answer |
69
+ | `ConnectionError` | AADML could not be reached |
70
+
71
+ ```python
72
+ from aadml_training import ModelUnavailableError
73
+
74
+ try:
75
+ result = client.predict(project_id=22, image="room.jpg")
76
+ except ModelUnavailableError as error:
77
+ print("Not ready yet:", error.message, "try again in", error.retry_after, "seconds")
78
+ ```
79
+
80
+ ## Retries
81
+
82
+ A request AADML refused **without processing it** (429, 503) or that never reached AADML is sent again, waiting as
83
+ AADML asks (at most 30 seconds), up to `max_retries` times (2 by default). A request that may have been processed is
84
+ never sent twice, so you are never charged twice for one call.
85
+
86
+ ```python
87
+ client = Client(timeout=30, max_retries=0)
88
+ ```
89
+
90
+ ## Settings
91
+
92
+ | Setting | Argument | Environment variable | Default |
93
+ |---|---|---|---|
94
+ | API key | `api_key` | `AADML_API_KEY` | none: required |
95
+ | AADML's address | `api_url` | `AADML_API_URL` | `https://aadml.com` |
96
+ | Seconds to wait for an answer | `timeout` | | 60 |
97
+ | Times a request is sent again | `max_retries` | | 2 |
98
+
99
+ ## About this package
100
+
101
+ `aadml-training` covers AADML Training. It will become part of the general `aadml` SDK; this package will then point
102
+ to it.
103
+
104
+ Licence: Apache 2.0. Report a security problem privately (see [SECURITY.md](SECURITY.md)).
@@ -0,0 +1,8 @@
1
+ # Security
2
+
3
+ Please report a security problem privately, never in a public issue: use GitHub's **Report a vulnerability** on this
4
+ repository's Security tab. Say what you found, how to reproduce it, and which version you used. We answer as soon as we
5
+ can and tell you when it is fixed.
6
+
7
+ Never include a real API key in a report, an issue or an example. If you published one by mistake, revoke it on your
8
+ project's Deploy page and make a new one.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "aadml-training"
7
+ dynamic = ["version"]
8
+ description = "Python SDK for AADML Training: call your trained photo and chat models from your own code."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Northrays" }]
14
+ keywords = ["aadml", "machine learning", "computer vision", "llm", "inference", "sdk"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = ["httpx>=0.27,<1"]
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest==8.3.5"]
33
+
34
+ [project.urls]
35
+ Homepage = "https://aadml.com"
36
+ Source = "https://github.com/sajid-the-backend-engineer/aadml-training"
37
+ Issues = "https://github.com/sajid-the-backend-engineer/aadml-training/issues"
38
+ Changelog = "https://github.com/sajid-the-backend-engineer/aadml-training/blob/main/CHANGELOG.md"
39
+
40
+ [tool.hatch.version]
41
+ path = "src/aadml_training/_version.py"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/aadml_training"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,16 @@
1
+ """AADML Training's Python SDK: call your trained photo and chat models from your own code.
2
+
3
+ from aadml_training import Client
4
+
5
+ client = Client(api_key="...")
6
+ result = client.predict(project_id=22, image="room.jpg")
7
+ """
8
+ from ._version import __version__
9
+ from .client import DEFAULT_API_URL, Client
10
+ from .errors import (AADMLError, APIError, AuthenticationError, BadRequestError, ConfigurationError, ConnectionError,
11
+ ModelUnavailableError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError,
12
+ ServerError)
13
+
14
+ __all__ = ["Client", "DEFAULT_API_URL", "__version__", "AADMLError", "APIError", "AuthenticationError",
15
+ "BadRequestError", "ConfigurationError", "ConnectionError", "ModelUnavailableError", "NotFoundError",
16
+ "PayloadTooLargeError", "PermissionDeniedError", "RateLimitError", "ServerError"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,192 @@
1
+ """The client: one object that holds AADML's address and your API key, with one method per thing you can ask.
2
+
3
+ from aadml_training import Client
4
+
5
+ client = Client(api_key="...") # or set AADML_API_KEY
6
+ walls = client.predict(project_id=22, image="room.jpg")
7
+ reply = client.chat(project_id=31, messages=[{"role": "user", "content": "How do I return an order?"}])
8
+
9
+ The key is an app key made on the project's Deploy page (Connected apps); it is sent as ``Authorization: Bearer``
10
+ and never written to a log or a repr.
11
+ """
12
+ import json
13
+ import os
14
+ import time
15
+ from contextlib import contextmanager
16
+ from typing import Any, Dict, Iterator, List, Optional
17
+
18
+ import httpx
19
+
20
+ from . import errors
21
+ from ._version import __version__
22
+ from .images import ImageInput, load
23
+
24
+ DEFAULT_API_URL = "https://aadml.com"
25
+ ENVIRONMENTS = ("staging", "production")
26
+ #: Statuses that mean the request was NOT processed, so sending it again cannot do (or charge for) the work twice.
27
+ _RETRY_STATUSES = (429, 503)
28
+ _MAX_WAIT = 30.0
29
+
30
+
31
+ class Client:
32
+ """AADML Training's API.
33
+
34
+ ``api_key``: an app key from the project's Deploy page; ``AADML_API_KEY`` when not given.
35
+ ``api_url``: AADML's address; ``AADML_API_URL`` or https://aadml.com when not given.
36
+ ``timeout``: seconds to wait for one answer. ``max_retries``: how many times a request that AADML refused
37
+ without processing it (429 too many requests, 503 model not ready) or that never reached AADML is sent again,
38
+ waiting as AADML asks (at most 30 seconds each time)."""
39
+
40
+ def __init__(self, api_key: Optional[str] = None, api_url: Optional[str] = None, *, timeout: float = 60.0,
41
+ max_retries: int = 2, http_client: Optional[httpx.Client] = None):
42
+ key = api_key if api_key is not None else os.environ.get("AADML_API_KEY", "")
43
+ if not key or not key.strip():
44
+ raise errors.ConfigurationError("No API key: pass api_key=... or set AADML_API_KEY.")
45
+ url = (api_url or os.environ.get("AADML_API_URL") or DEFAULT_API_URL).rstrip("/")
46
+ if not url.startswith(("https://", "http://")):
47
+ raise errors.ConfigurationError(f"api_url must start with https:// (got {url!r}).")
48
+ self.api_url = url
49
+ self.timeout = timeout
50
+ self.max_retries = max(0, int(max_retries))
51
+ self.__key = key.strip()
52
+ self._http = http_client or httpx.Client(timeout=timeout)
53
+ self._owns_http = http_client is None
54
+
55
+ def __repr__(self) -> str:
56
+ return f"Client(api_url={self.api_url!r}, api_key='{self.__key[:4]}…')"
57
+
58
+ def close(self) -> None:
59
+ if self._owns_http:
60
+ self._http.close()
61
+
62
+ def __enter__(self) -> "Client":
63
+ return self
64
+
65
+ def __exit__(self, *exc) -> None:
66
+ self.close()
67
+
68
+ # ── photo models ─────────────────────────────────────────────────────────────────────────────────────────────
69
+ def predict(self, project_id: int, image: ImageInput, *, environment: str = "production",
70
+ request_id: Optional[str] = None, capture_id: Optional[str] = None) -> Dict[str, Any]:
71
+ """Send one photo to the model deployed in a project's ``environment`` and return what it found: ``walls``
72
+ (each with its corners), ``openings`` (windows and doors), in the photo's own pixels, with ``model``,
73
+ ``request_id``, ``warnings`` and ``timing_ms``.
74
+
75
+ ``image``: a file path, bytes, an open binary file, a URL or a Pillow image (JPEG, PNG or WebP, at most 15 MB).
76
+ ``request_id`` / ``capture_id``: your own ids (at most 128 characters), returned in the answer."""
77
+ data, content_type, name = load(image, timeout=self.timeout)
78
+ payload = {key: value for key, value in (("request_id", request_id), ("capture_id", capture_id)) if value}
79
+ form = {"payload": json.dumps(payload)} if payload else None
80
+ return self._send("POST", self._project_path(project_id, environment, "predict/"),
81
+ files={"file": (name, data, content_type)}, data=form).json()
82
+
83
+ # ── chat models ──────────────────────────────────────────────────────────────────────────────────────────────
84
+ def chat(self, project_id: int, messages: List[Dict[str, Any]], *, environment: str = "production",
85
+ **options: Any) -> Dict[str, Any]:
86
+ """Ask a project's deployed chat model, in OpenAI's chat completions format; returns the completion
87
+ (``answer["choices"][0]["message"]["content"]`` is the reply). ``options`` go into the request as they are
88
+ (``max_tokens``, ``temperature``, …)."""
89
+ body = {"messages": messages, **options, "stream": False}
90
+ return self._send("POST", self._project_path(project_id, environment, "v1/chat/completions"), json=body).json()
91
+
92
+ def chat_text(self, project_id: int, messages: List[Dict[str, Any]], **kwargs: Any) -> str:
93
+ """``chat``, returning only the reply's text."""
94
+ answer = self.chat(project_id, messages, **kwargs)
95
+ return (answer.get("choices") or [{}])[0].get("message", {}).get("content") or ""
96
+
97
+ def chat_stream(self, project_id: int, messages: List[Dict[str, Any]], *, environment: str = "production",
98
+ **options: Any) -> Iterator[str]:
99
+ """``chat``, yielding the reply's text piece by piece as the model writes it."""
100
+ body = {"messages": messages, **options, "stream": True}
101
+ path = self._project_path(project_id, environment, "v1/chat/completions")
102
+ with self._stream("POST", path, json=body) as answer:
103
+ for line in answer.iter_lines():
104
+ if not line.startswith("data:"):
105
+ continue
106
+ data = line[5:].strip()
107
+ if data == "[DONE]":
108
+ return
109
+ try:
110
+ chunk = json.loads(data)
111
+ except ValueError:
112
+ continue
113
+ if chunk.get("error"):
114
+ raise errors.ServerError(str(chunk["error"].get("message") or chunk["error"]), 502, body=chunk)
115
+ for choice in chunk.get("choices") or []:
116
+ piece = (choice.get("delta") or {}).get("content")
117
+ if piece:
118
+ yield piece
119
+
120
+ def models(self, project_id: int, *, environment: str = "production") -> List[Dict[str, Any]]:
121
+ """The chat models a project's ``environment`` answers with (OpenAI's model list)."""
122
+ return self._send("GET", self._project_path(project_id, environment, "v1/models")).json().get("data", [])
123
+
124
+ # ── plumbing ─────────────────────────────────────────────────────────────────────────────────────────────────
125
+ def _project_path(self, project_id: int, environment: str, rest: str) -> str:
126
+ if environment not in ENVIRONMENTS:
127
+ raise errors.ConfigurationError(f"environment must be one of {', '.join(ENVIRONMENTS)} (got {environment!r}).")
128
+ if isinstance(project_id, bool) or not str(project_id).isdigit():
129
+ raise errors.ConfigurationError(f"project_id is the project's number (got {project_id!r}).")
130
+ return f"/api/training-data/v1/projects/{int(project_id)}/environments/{environment}/{rest}"
131
+
132
+ def _headers(self) -> Dict[str, str]:
133
+ return {"Authorization": f"Bearer {self.__key}", "User-Agent": f"aadml-training-python/{__version__}",
134
+ "Accept": "application/json"}
135
+
136
+ def _send(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
137
+ attempt = 0
138
+ while True:
139
+ try:
140
+ answer = self._http.request(method, self.api_url + path, headers=self._headers(), timeout=self.timeout,
141
+ **kwargs)
142
+ except httpx.ConnectError as failure: # never reached AADML: safe to send again
143
+ if attempt < self.max_retries:
144
+ attempt += 1
145
+ time.sleep(min(2 ** attempt, _MAX_WAIT))
146
+ continue
147
+ raise errors.ConnectionError(f"Could not reach {self.api_url}: {failure}") from None
148
+ except httpx.TimeoutException:
149
+ raise errors.ConnectionError(f"No answer from {self.api_url} within {self.timeout} seconds.") from None
150
+ if answer.status_code < 400:
151
+ return answer
152
+ failure = _error(answer)
153
+ if answer.status_code in _RETRY_STATUSES and attempt < self.max_retries:
154
+ attempt += 1
155
+ time.sleep(min(failure.retry_after or 2 ** attempt, _MAX_WAIT))
156
+ continue
157
+ raise failure
158
+
159
+ @contextmanager
160
+ def _stream(self, method: str, path: str, **kwargs: Any) -> Iterator[httpx.Response]:
161
+ try:
162
+ with self._http.stream(method, self.api_url + path, headers=self._headers(), timeout=self.timeout,
163
+ **kwargs) as answer:
164
+ if answer.status_code >= 400:
165
+ answer.read()
166
+ raise _error(answer)
167
+ yield answer
168
+ except httpx.ConnectError as failure:
169
+ raise errors.ConnectionError(f"Could not reach {self.api_url}: {failure}") from None
170
+ except httpx.TimeoutException:
171
+ raise errors.ConnectionError(f"No answer from {self.api_url} within {self.timeout} seconds.") from None
172
+
173
+
174
+ def _error(answer: httpx.Response) -> errors.APIError:
175
+ """The APIError for an error answer: AADML's ``{"error", "field"}`` or OpenAI's ``{"error": {"message"}}``."""
176
+ try:
177
+ body = answer.json()
178
+ except ValueError:
179
+ body = {}
180
+ raw = body.get("error") if isinstance(body, dict) else None
181
+ if isinstance(raw, dict):
182
+ message, field = raw.get("message") or "", raw.get("param")
183
+ else:
184
+ message, field = raw or "", body.get("field") if isinstance(body, dict) else None
185
+ retry = answer.headers.get("Retry-After")
186
+ try:
187
+ retry_after = float(retry) if retry else None
188
+ except ValueError:
189
+ retry_after = None
190
+ kind = errors.error_for(answer.status_code)
191
+ return kind(message or f"AADML answered {answer.status_code}.", answer.status_code, field=field,
192
+ retry_after=retry_after, body=body if isinstance(body, dict) else {})
@@ -0,0 +1,81 @@
1
+ """The errors the client raises. Every one is an ``AADMLError``; an answer from AADML that is not a success is an
2
+ ``APIError`` (or one of its kinds) with the HTTP status and AADML's own message."""
3
+ from typing import Optional
4
+
5
+
6
+ class AADMLError(Exception):
7
+ """Anything that went wrong in this SDK."""
8
+
9
+
10
+ class ConfigurationError(AADMLError):
11
+ """The client cannot be used as it was set up: no API key, or an address that is not http(s)."""
12
+
13
+
14
+ class ConnectionError(AADMLError): # noqa: A001 - the SDK's own name, imported from this package
15
+ """AADML could not be reached: no answer came back."""
16
+
17
+
18
+ class APIError(AADMLError):
19
+ """AADML answered with an error.
20
+
21
+ ``status_code`` is the HTTP status, ``message`` AADML's explanation, ``field`` the request field it is about
22
+ (when there is one) and ``retry_after`` the seconds AADML asked to wait before trying again (when it said)."""
23
+
24
+ def __init__(self, message: str, status_code: int, field: Optional[str] = None,
25
+ retry_after: Optional[float] = None, body: Optional[dict] = None):
26
+ super().__init__(message)
27
+ self.message = message
28
+ self.status_code = status_code
29
+ self.field = field
30
+ self.retry_after = retry_after
31
+ self.body = body or {}
32
+
33
+ def __repr__(self) -> str:
34
+ return f"{type(self).__name__}(status_code={self.status_code}, message={self.message!r}, field={self.field!r})"
35
+
36
+ def __str__(self) -> str:
37
+ where = f" (field: {self.field})" if self.field else ""
38
+ return f"{self.status_code}: {self.message}{where}"
39
+
40
+
41
+ class BadRequestError(APIError):
42
+ """400: the request itself was refused, for example a photo that is not a JPEG, PNG or WebP."""
43
+
44
+
45
+ class AuthenticationError(APIError):
46
+ """401: the API key is missing, unknown or revoked."""
47
+
48
+
49
+ class PermissionDeniedError(APIError):
50
+ """403: the key is valid but has no access to that project and environment."""
51
+
52
+
53
+ class NotFoundError(APIError):
54
+ """404: there is no such project or environment."""
55
+
56
+
57
+ class PayloadTooLargeError(APIError):
58
+ """413: the photo is larger than AADML accepts."""
59
+
60
+
61
+ class RateLimitError(APIError):
62
+ """429: too many requests for this key. ``retry_after`` says how long to wait."""
63
+
64
+
65
+ class ModelUnavailableError(APIError):
66
+ """503: no model is deployed to that environment yet, or it is starting. ``retry_after`` says when to try again."""
67
+
68
+
69
+ class ServerError(APIError):
70
+ """5xx: AADML or the model failed to answer."""
71
+
72
+
73
+ _BY_STATUS = {400: BadRequestError, 401: AuthenticationError, 403: PermissionDeniedError, 404: NotFoundError,
74
+ 413: PayloadTooLargeError, 429: RateLimitError, 503: ModelUnavailableError}
75
+
76
+
77
+ def error_for(status_code: int) -> type:
78
+ """The APIError kind of an HTTP status."""
79
+ if status_code in _BY_STATUS:
80
+ return _BY_STATUS[status_code]
81
+ return ServerError if status_code >= 500 else APIError
@@ -0,0 +1,73 @@
1
+ """Turning what a caller gives as a photo into bytes: a file path, bytes, an open binary file, a URL, or a Pillow
2
+ image. Nothing here is sent anywhere; ``Client.predict`` sends the bytes to AADML."""
3
+ import io
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any, Tuple, Union
7
+
8
+ import httpx
9
+
10
+ from .errors import BadRequestError, PayloadTooLargeError
11
+
12
+ #: The largest photo AADML accepts (its prediction API refuses anything larger).
13
+ MAX_BYTES = 15 * 1024 * 1024
14
+ _TYPES = {b"\xff\xd8\xff": ("image/jpeg", ".jpg"), b"\x89PNG": ("image/png", ".png")}
15
+
16
+ ImageInput = Union[str, os.PathLike, bytes, bytearray, Any]
17
+
18
+
19
+ def _kind(data: bytes) -> Tuple[str, str]:
20
+ for magic, kind in _TYPES.items():
21
+ if data.startswith(magic):
22
+ return kind
23
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
24
+ return "image/webp", ".webp"
25
+ raise BadRequestError("The photo must be a JPEG, PNG or WebP image.", 400, field="image")
26
+
27
+
28
+ def _checked(data: bytes) -> Tuple[bytes, str, str]:
29
+ if not data:
30
+ raise BadRequestError("The photo is empty.", 400, field="image")
31
+ if len(data) > MAX_BYTES:
32
+ raise PayloadTooLargeError(f"The photo is larger than {MAX_BYTES // (1024 * 1024)} MB.", 413, field="image")
33
+ content_type, suffix = _kind(data)
34
+ return data, content_type, suffix
35
+
36
+
37
+ def _download(url: str, timeout: float) -> bytes:
38
+ with httpx.stream("GET", url, timeout=timeout, follow_redirects=True) as answer:
39
+ answer.raise_for_status()
40
+ chunks, size = [], 0
41
+ for chunk in answer.iter_bytes():
42
+ size += len(chunk)
43
+ if size > MAX_BYTES:
44
+ raise PayloadTooLargeError(f"The photo at {url} is larger than {MAX_BYTES // (1024 * 1024)} MB.", 413,
45
+ field="image")
46
+ chunks.append(chunk)
47
+ return b"".join(chunks)
48
+
49
+
50
+ def load(image: ImageInput, timeout: float = 30.0) -> Tuple[bytes, str, str]:
51
+ """``(bytes, content type, file name)`` of the photo ``image``."""
52
+ if isinstance(image, (bytes, bytearray)):
53
+ data, content_type, suffix = _checked(bytes(image))
54
+ return data, content_type, "image" + suffix
55
+ if isinstance(image, str) and image.startswith(("http://", "https://")):
56
+ data, content_type, suffix = _checked(_download(image, timeout))
57
+ return data, content_type, "image" + suffix
58
+ if isinstance(image, (str, os.PathLike)):
59
+ path = Path(image)
60
+ if not path.is_file():
61
+ raise BadRequestError(f"There is no file at {path}.", 400, field="image")
62
+ data, content_type, _suffix = _checked(path.read_bytes())
63
+ return data, content_type, path.name
64
+ if hasattr(image, "read"):
65
+ data, content_type, suffix = _checked(image.read())
66
+ return data, content_type, Path(getattr(image, "name", "image" + suffix)).name
67
+ if hasattr(image, "save") and hasattr(image, "mode"): # a Pillow image
68
+ out = io.BytesIO()
69
+ image.convert("RGB").save(out, format="JPEG", quality=95)
70
+ data, content_type, _suffix = _checked(out.getvalue())
71
+ return data, content_type, "image.jpg"
72
+ raise BadRequestError("Give the photo as a file path, bytes, an open binary file, a URL or a Pillow image.", 400,
73
+ field="image")
File without changes
@@ -0,0 +1,191 @@
1
+ """The client against a stand-in AADML (httpx.MockTransport): nothing goes over the network."""
2
+ import io
3
+ import json
4
+
5
+ import httpx
6
+ import pytest
7
+
8
+ import aadml_training
9
+ from aadml_training import Client, errors
10
+ from aadml_training import client as client_module
11
+
12
+ JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 64
13
+ PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
14
+ KEY = "tmd_app_secretkey123"
15
+ ANSWER = {"status": "ok", "walls": [{"id": 1, "corners": [[1, 1], [9, 1], [9, 9], [1, 9]]}], "openings": [],
16
+ "request_id": "req_1", "capture_id": None, "model": {"name": "m", "version": 1}, "warnings": [],
17
+ "timing_ms": {"model": 5, "total": 9}}
18
+
19
+
20
+ def make(handler, **kwargs):
21
+ return Client(api_key=KEY, api_url="https://aadml.test", http_client=httpx.Client(transport=httpx.MockTransport(handler)),
22
+ **kwargs)
23
+
24
+
25
+ @pytest.fixture(autouse=True)
26
+ def no_sleep(monkeypatch):
27
+ slept = []
28
+ monkeypatch.setattr(client_module.time, "sleep", slept.append)
29
+ return slept
30
+
31
+
32
+ def test_predict_sends_the_photo_with_the_key_to_the_project_environment():
33
+ seen = {}
34
+
35
+ def handler(request):
36
+ seen.update(url=str(request.url), auth=request.headers["Authorization"], agent=request.headers["User-Agent"],
37
+ body=request.read())
38
+ return httpx.Response(200, json=ANSWER)
39
+
40
+ result = make(handler).predict(22, JPEG, environment="staging", request_id="r-7")
41
+ assert result["walls"][0]["corners"][0] == [1, 1]
42
+ assert seen["url"] == "https://aadml.test/api/training-data/v1/projects/22/environments/staging/predict/"
43
+ assert seen["auth"] == f"Bearer {KEY}"
44
+ assert seen["agent"] == f"aadml-training-python/{aadml_training.__version__}"
45
+ assert JPEG in seen["body"] and b'name="file"' in seen["body"]
46
+ assert b'{"request_id": "r-7"}' in seen["body"]
47
+
48
+
49
+ def test_a_photo_can_be_a_path_an_open_file_or_bytes(tmp_path):
50
+ names = []
51
+
52
+ def handler(request):
53
+ names.append(request.read().split(b'filename="')[1].split(b'"')[0])
54
+ return httpx.Response(200, json=ANSWER)
55
+
56
+ client = make(handler)
57
+ path = tmp_path / "room.png"
58
+ path.write_bytes(PNG)
59
+ client.predict(1, str(path))
60
+ client.predict(1, path)
61
+ client.predict(1, io.BytesIO(JPEG))
62
+ client.predict(1, bytearray(JPEG))
63
+ assert names == [b"room.png", b"room.png", b"image.jpg", b"image.jpg"]
64
+
65
+
66
+ def test_a_photo_that_is_not_an_image_is_refused_before_anything_is_sent():
67
+ def handler(request):
68
+ raise AssertionError("nothing should be sent")
69
+
70
+ client = make(handler)
71
+ with pytest.raises(errors.BadRequestError) as refused:
72
+ client.predict(1, b"%PDF-1.4 not a photo")
73
+ assert refused.value.field == "image"
74
+ with pytest.raises(errors.BadRequestError):
75
+ client.predict(1, b"")
76
+ with pytest.raises(errors.BadRequestError):
77
+ client.predict(1, "no/such/file.jpg")
78
+
79
+
80
+ def test_errors_carry_aadmls_message_and_field():
81
+ def handler(request):
82
+ return httpx.Response(400, json={"error": "payload is not valid JSON.", "field": "payload"})
83
+
84
+ with pytest.raises(errors.BadRequestError) as refused:
85
+ make(handler).predict(1, JPEG)
86
+ assert (refused.value.status_code, refused.value.message, refused.value.field) == (400, "payload is not valid JSON.",
87
+ "payload")
88
+
89
+
90
+ @pytest.mark.parametrize("status, kind", [(401, errors.AuthenticationError), (403, errors.PermissionDeniedError),
91
+ (404, errors.NotFoundError), (413, errors.PayloadTooLargeError),
92
+ (502, errors.ServerError), (418, errors.APIError)])
93
+ def test_each_status_has_its_error(status, kind):
94
+ with pytest.raises(kind):
95
+ make(lambda request: httpx.Response(status, json={"error": "no"})).predict(1, JPEG)
96
+
97
+
98
+ def test_a_request_aadml_did_not_process_is_sent_again_as_it_asks(no_sleep):
99
+ answers = iter([httpx.Response(429, json={"error": "Too many requests."}, headers={"Retry-After": "3"}),
100
+ httpx.Response(503, json={"error": "starting"}, headers={"Retry-After": "120"}),
101
+ httpx.Response(200, json=ANSWER)])
102
+ assert make(lambda request: next(answers)).predict(1, JPEG)["status"] == "ok"
103
+ assert no_sleep == [3.0, 30.0] # AADML's wait, never more than 30 seconds
104
+
105
+
106
+ def test_a_request_that_may_have_been_processed_is_never_sent_twice():
107
+ calls = []
108
+
109
+ def handler(request):
110
+ calls.append(1)
111
+ return httpx.Response(502, json={"error": "The model did not answer."})
112
+
113
+ with pytest.raises(errors.ServerError):
114
+ make(handler).predict(1, JPEG)
115
+ assert len(calls) == 1 # it may have been charged: not sent again
116
+
117
+
118
+ def test_retries_end_with_the_error():
119
+ calls = []
120
+
121
+ def handler(request):
122
+ calls.append(1)
123
+ return httpx.Response(503, json={"error": "No model is deployed to production for this project yet."},
124
+ headers={"Retry-After": "5"})
125
+
126
+ with pytest.raises(errors.ModelUnavailableError) as refused:
127
+ make(handler, max_retries=1).predict(1, JPEG)
128
+ assert (len(calls), refused.value.retry_after) == (2, 5.0)
129
+
130
+
131
+ def test_unreachable_aadml_is_a_connection_error():
132
+ def handler(request):
133
+ raise httpx.ConnectError("refused")
134
+
135
+ with pytest.raises(errors.ConnectionError):
136
+ make(handler, max_retries=1).predict(1, JPEG)
137
+
138
+
139
+ def test_chat_uses_the_openai_format_and_chat_text_returns_the_reply():
140
+ seen = {}
141
+
142
+ def handler(request):
143
+ seen.update(url=str(request.url), body=json.loads(request.read()))
144
+ return httpx.Response(200, json={"choices": [{"message": {"role": "assistant", "content": "Use the Returns page."}}]})
145
+
146
+ client = make(handler)
147
+ messages = [{"role": "user", "content": "How do I return an order?"}]
148
+ assert client.chat_text(31, messages, max_tokens=50) == "Use the Returns page."
149
+ assert seen["url"] == "https://aadml.test/api/training-data/v1/projects/31/environments/production/v1/chat/completions"
150
+ assert seen["body"] == {"messages": messages, "max_tokens": 50, "stream": False}
151
+
152
+
153
+ def test_chat_stream_yields_the_reply_as_it_is_written():
154
+ events = ('data: {"choices":[{"delta":{"role":"assistant"}}]}\n\n'
155
+ 'data: {"choices":[{"delta":{"content":"Use the "}}]}\n\n'
156
+ ': keep-alive\n\n'
157
+ 'data: {"choices":[{"delta":{"content":"Returns page."}}]}\n\n'
158
+ 'data: [DONE]\n\n')
159
+ client = make(lambda request: httpx.Response(200, text=events, headers={"Content-Type": "text/event-stream"}))
160
+ assert "".join(client.chat_stream(31, [{"role": "user", "content": "?"}])) == "Use the Returns page."
161
+
162
+
163
+ def test_chat_stream_error_answer_raises():
164
+ client = make(lambda request: httpx.Response(401, json={"error": {"message": "Unknown key", "type": "auth"}}))
165
+ with pytest.raises(errors.AuthenticationError) as refused:
166
+ list(client.chat_stream(31, [{"role": "user", "content": "?"}]))
167
+ assert refused.value.message == "Unknown key"
168
+
169
+
170
+ def test_models_lists_the_environments_chat_models():
171
+ client = make(lambda request: httpx.Response(200, json={"object": "list", "data": [{"id": "chat-v2"}]}))
172
+ assert client.models(31) == [{"id": "chat-v2"}]
173
+
174
+
175
+ def test_the_key_comes_from_the_environment_and_is_never_shown(monkeypatch):
176
+ monkeypatch.setenv("AADML_API_KEY", KEY)
177
+ client = Client()
178
+ assert KEY not in repr(client) and client.api_url == "https://aadml.com"
179
+ monkeypatch.delenv("AADML_API_KEY")
180
+ with pytest.raises(errors.ConfigurationError):
181
+ Client()
182
+
183
+
184
+ def test_bad_settings_are_refused():
185
+ with pytest.raises(errors.ConfigurationError):
186
+ Client(api_key=KEY, api_url="ftp://aadml.com")
187
+ client = make(lambda request: httpx.Response(200, json=ANSWER))
188
+ with pytest.raises(errors.ConfigurationError):
189
+ client.predict(1, JPEG, environment="prod")
190
+ with pytest.raises(errors.ConfigurationError):
191
+ client.predict("../2", JPEG)