launchables 0.4.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,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,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: launchables
3
+ Version: 0.4.0
4
+ Summary: Python client for the Launchables Decision API
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://www.launchables.ai/docs
7
+ Project-URL: Documentation, https://www.launchables.ai/docs
8
+ Project-URL: Repository, https://github.com/launchables-ai/launchables-sdk
9
+ Project-URL: Issues, https://github.com/launchables-ai/launchables-sdk/issues
10
+ Keywords: launchables,decision,api,llm
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # launchables (Python)
19
+
20
+ Python client for the Launchables Decision API. Standard library only, Python 3.9+.
21
+
22
+ ```
23
+ pip install launchables
24
+ ```
25
+
26
+ ## Quick start
27
+
28
+ ```python
29
+ from launchables import Launchables, noul
30
+
31
+ client = Launchables() # reads LAUNCHABLES_API_TOKEN
32
+
33
+ resp = client.decide(
34
+ "Customer bought the item 12 days ago and has no receipt. "
35
+ "Policy: refunds within 30 days with proof of purchase.",
36
+ {"refund": noul("Is a refund permitted under the policy?")},
37
+ )
38
+
39
+ answer = resp.answers["refund"]
40
+ print(answer.probability) # probability of yes, e.g. 0.04
41
+ print(answer.decide(threshold_yes=0.9, threshold_no=0.1)) # "yes" | "no" | "person"
42
+ print(resp.usage.input_tokens, resp.model)
43
+ ```
44
+
45
+ `decide` returns a `DecisionResponse` with `.answers`, `.usage`, `.model` and `.raw` (the untouched JSON). `state` may be a string or a dict. To include images, see [Images](#images).
46
+
47
+ ### Question types
48
+
49
+ ```python
50
+ from launchables import noul, choice, score
51
+
52
+ questions = {
53
+ "refund": noul("Is a refund permitted?", true="Policy clearly allows it", false="Policy clearly forbids it"),
54
+ "topic": choice("What is this about?", ["billing", "returns", "other"]), # or {label: description}
55
+ "urgency": score("How urgent is it?", ["not urgent", "low", "medium", "high"]), # lowest level first, numbered from 0
56
+ }
57
+ resp = client.decide(state, questions)
58
+
59
+ resp.answers["topic"].choice # "returns"
60
+ resp.answers["topic"].probabilities # {"billing": 0.06, "returns": 0.89, ...}
61
+ resp.answers["urgency"].level # 2
62
+ resp.answers["urgency"].score # 1.92
63
+ resp.answers["urgency"].probabilities # {"0": 0.03, "1": 0.12, ...}
64
+ ```
65
+
66
+ Helpers validate locally and raise `ValidationError` before any request is sent: at most 16 questions per request, at most 26 options per choice, non-empty instructions.
67
+
68
+ ### Other calls
69
+
70
+ ```python
71
+ client.models() # [Model(id="myles-g-12b", ...)]
72
+ client.health() # {"status": "ok"}
73
+ ```
74
+
75
+ `models()` and `health()` need no token.
76
+
77
+ ## Images
78
+
79
+ Pass images in `assets`, keyed by a reference of your choosing, and write that reference wherever the model should see the image: in the state (a text state, or any string value in a JSON state), a question's instructions, or a criterion's description. Option labels are not searched.
80
+
81
+ ```python
82
+ from launchables import Image, Launchables, noul
83
+
84
+ client = Launchables()
85
+
86
+ resp = client.decide(
87
+ {"receipt": "receipt_photo", "note": "Customer asks for a refund"},
88
+ {"total_matches": noul("Does the total printed on receipt_photo equal 23.40?")},
89
+ assets={"receipt_photo": Image.from_path("receipt.jpg")},
90
+ image_budget=140, # optional: 70, 140 or 280 (the default)
91
+ )
92
+ ```
93
+
94
+ `Image.from_path(path)` and `Image.from_bytes(data)` detect PNG or JPEG from the file's first bytes; pass `format="png"`, `"jpg"` or `"jpeg"` to state it (it must match the bytes). A plain dict in the wire shape, `{"type": "image", "format": "jpeg", "data_base64": "..."}`, is accepted as it is. References are matched as plain, case-sensitive text; every place a reference appears shows the image there, and when one reference contains another the longer one wins.
95
+
96
+ `image_budget` is the most visual tokens one image may use. Lower is cheaper and faster but sees less detail (small print suffers first). Any value other than 70, 140 or 280 raises `ValidationError` before sending; leave it out to get the server default of 280.
97
+
98
+ Limits, checked by the server (each breach is an `InvalidRequestError` whose message names the asset):
99
+
100
+ - PNG or JPEG only, still images, and the bytes must match the format. The helper detects the format from the bytes and refuses anything else before sending.
101
+ - At most 16 MiB per image (the helper checks this too). Width and height each from 280 to 1568 pixels. Images are never resized or re-encoded, by the client or the server, so resize larger images yourself first.
102
+ - At most 8 assets per request, and at most 8 images shown in any one question (each use of a reference counts).
103
+ - Every asset must be referenced at least once. A reference inside a text state must fall within its first 20,000 characters.
104
+
105
+ Images count as input tokens and are included in `usage.input_tokens`. At budget 280 one image costs up to about 280 tokens, at 140 up to about 140, at 70 up to about 70. An image referenced in the state is billed once per request however many questions read it; one referenced in a question's instructions or criteria is billed for that question, once per use.
106
+
107
+ ## Key expiry
108
+
109
+ Every API key expires. The client reads the expiry date from each response, so your program can plan rotation instead of finding out when the key stops working.
110
+
111
+ ```python
112
+ def on_expiry(expiry):
113
+ # called once per key and expiry date when 14 days or fewer are left: alert your team, or start a rotation job
114
+ alert_team(f"Launchables key {expiry.key_id} expires on {expiry.expires_on} ({expiry.days_left} days left)")
115
+
116
+ client = Launchables(on_key_expiry=on_expiry)
117
+
118
+ client.key()
119
+ # KeyInfo(id="c_1a2b3c4d", name="prod", expires_on="2027-01-13", days_left=89, workspace=None,
120
+ # rate_limit_per_minute=600, daily_limit=10000000, paused=False, pause_reason=None)
121
+
122
+ client.key_expiry # KeyExpiry(key_id, expires_on, days_left) from the last response, or None
123
+ ```
124
+
125
+ Without `on_key_expiry`, the client issues one `KeyExpiryWarning` when 14 days or fewer are left. `key()` counts as no request and no tokens, and works for a paused key so you can see why it is paused (`pause_reason`). The expiry headers add nothing to your token count. To replace a key without downtime, roll it on the API keys page of the console: the old key keeps working until the end of the next day.
126
+
127
+ ## Managing keys
128
+
129
+ To rotate keys from your own scripts, use an admin key. An owner makes one on the API keys page of the console (two-step sign-in must be on). Admin keys start with `launchables_admin_`, always expire, and can only manage your organisation's API keys: they cannot call the Decision API.
130
+
131
+ ```python
132
+ client = Launchables(admin_key=os.environ["LAUNCHABLES_ADMIN_KEY"]) # or just set LAUNCHABLES_ADMIN_KEY
133
+
134
+ page = client.admin.keys.list() # {"data": [{"id", "name", "prefix", "workspace", "expires_on", "last_used_on", "status", ...}], "has_more", "next_before"}
135
+ for key in client.admin.keys.list_all():
136
+ print(key["id"], key["status"])
137
+
138
+ made = client.admin.keys.create("staging", expires_in_days=90) # workspace_id is optional
139
+ made["key"] # the full key, shown only this once
140
+
141
+ rolled = client.admin.keys.roll("c_1a2b3c4d")
142
+ rolled["key"] # the new key; rolled["replaces"]["expires_on"] is when the old one stops (the end of tomorrow)
143
+
144
+ client.admin.keys.revoke("c_1a2b3c4d")
145
+ ```
146
+
147
+ Key lifetimes are 30, 90, 180 or 365 days (90 by default), never longer than your organisation allows. These calls go to `https://console.launchables.ai` (`admin_base_url` to change it) and may be made 120 times a minute per admin key. A missing key or workspace raises `NotFoundError` (404); the key limit or an archived workspace raises `ConflictError` (409); both are kinds of `InvalidRequestError`. `create` and `roll` are retried only after a 429, so a retry never makes a second key. Every change shows in Activity in the console.
148
+
149
+ ## Error handling
150
+
151
+ All errors derive from `LaunchablesError` and carry `.status`, `.message` (the server's message), `.body` and `.type` (the server's error type, such as `"out_of_credit"`, or `None` if it sent none).
152
+
153
+ | Error | When |
154
+ | --- | --- |
155
+ | `AuthenticationError` | 401, or no key (or admin key) given or found |
156
+ | `OutOfCreditError` | 402: the account has run out of prepaid credit (`.type` `"out_of_credit"`, top up in the console), or the key's workspace has reached its monthly budget (`.type` `"budget_exceeded"`) |
157
+ | `PermissionDeniedError` | 403: the key's workspace may not use this model (`.type` `"model_not_allowed"`), or the admin key's maker is no longer an owner |
158
+ | `RateLimitError` | 429 (`.retry_after` seconds, if sent) |
159
+ | `InvalidRequestError` | 400, 411, 413, 422 and other 4xx; `ValidationError` is the local pre-flight subclass. `.type` says what was wrong with an image: `"invalid_assets"`, `"unsupported_image_format"`, `"invalid_image"`, `"image_too_large"`, `"image_dimensions"`, `"too_many_images"`, `"unreferenced_asset"` or `"image_reference_truncated"` (400), or `"invalid_image_budget"` (422). |
160
+ | `NotFoundError`, `ConflictError` | 404 and 409 from the key management API (subclasses of `InvalidRequestError`) |
161
+ | `APIError` | 5xx |
162
+ | `APIConnectionError` | could not reach the server (including timeouts) |
163
+
164
+ ```python
165
+ from launchables import OutOfCreditError, RateLimitError, InvalidRequestError, LaunchablesError
166
+
167
+ try:
168
+ resp = client.decide(state, questions)
169
+ except OutOfCreditError as e:
170
+ print("workspace budget reached" if e.type == "budget_exceeded" else "top up credit")
171
+ except RateLimitError as e:
172
+ print("slow down", e.retry_after)
173
+ except InvalidRequestError as e:
174
+ print(e.status, e.message)
175
+ except LaunchablesError as e:
176
+ print("failed:", e)
177
+ ```
178
+
179
+ ## Retries
180
+
181
+ 429, 502, 503 and connection errors are retried up to `max_retries` times (default 3) with exponential backoff of 0.5s, 1s, 2s. A `Retry-After` header (seconds) is honoured instead, capped at 60s. Other errors, including 402 and 403, are raised immediately. `timeout` (seconds, default 30) applies to each attempt.
182
+
183
+ ```python
184
+ client = Launchables(api_key="launchables_...", timeout=10, max_retries=5)
185
+ ```
186
+
187
+ ## Self-hosted endpoints
188
+
189
+ ```python
190
+ client = Launchables(base_url="https://decisions.internal.example.com")
191
+ ```
192
+
193
+ Requests carry `User-Agent: launchables-python/<version>`.
194
+
195
+ ## Tests
196
+
197
+ ```
198
+ PYTHONPATH=src python -m unittest discover -s tests -t .
199
+ ```
@@ -0,0 +1,182 @@
1
+ # launchables (Python)
2
+
3
+ Python client for the Launchables Decision API. Standard library only, Python 3.9+.
4
+
5
+ ```
6
+ pip install launchables
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```python
12
+ from launchables import Launchables, noul
13
+
14
+ client = Launchables() # reads LAUNCHABLES_API_TOKEN
15
+
16
+ resp = client.decide(
17
+ "Customer bought the item 12 days ago and has no receipt. "
18
+ "Policy: refunds within 30 days with proof of purchase.",
19
+ {"refund": noul("Is a refund permitted under the policy?")},
20
+ )
21
+
22
+ answer = resp.answers["refund"]
23
+ print(answer.probability) # probability of yes, e.g. 0.04
24
+ print(answer.decide(threshold_yes=0.9, threshold_no=0.1)) # "yes" | "no" | "person"
25
+ print(resp.usage.input_tokens, resp.model)
26
+ ```
27
+
28
+ `decide` returns a `DecisionResponse` with `.answers`, `.usage`, `.model` and `.raw` (the untouched JSON). `state` may be a string or a dict. To include images, see [Images](#images).
29
+
30
+ ### Question types
31
+
32
+ ```python
33
+ from launchables import noul, choice, score
34
+
35
+ questions = {
36
+ "refund": noul("Is a refund permitted?", true="Policy clearly allows it", false="Policy clearly forbids it"),
37
+ "topic": choice("What is this about?", ["billing", "returns", "other"]), # or {label: description}
38
+ "urgency": score("How urgent is it?", ["not urgent", "low", "medium", "high"]), # lowest level first, numbered from 0
39
+ }
40
+ resp = client.decide(state, questions)
41
+
42
+ resp.answers["topic"].choice # "returns"
43
+ resp.answers["topic"].probabilities # {"billing": 0.06, "returns": 0.89, ...}
44
+ resp.answers["urgency"].level # 2
45
+ resp.answers["urgency"].score # 1.92
46
+ resp.answers["urgency"].probabilities # {"0": 0.03, "1": 0.12, ...}
47
+ ```
48
+
49
+ Helpers validate locally and raise `ValidationError` before any request is sent: at most 16 questions per request, at most 26 options per choice, non-empty instructions.
50
+
51
+ ### Other calls
52
+
53
+ ```python
54
+ client.models() # [Model(id="myles-g-12b", ...)]
55
+ client.health() # {"status": "ok"}
56
+ ```
57
+
58
+ `models()` and `health()` need no token.
59
+
60
+ ## Images
61
+
62
+ Pass images in `assets`, keyed by a reference of your choosing, and write that reference wherever the model should see the image: in the state (a text state, or any string value in a JSON state), a question's instructions, or a criterion's description. Option labels are not searched.
63
+
64
+ ```python
65
+ from launchables import Image, Launchables, noul
66
+
67
+ client = Launchables()
68
+
69
+ resp = client.decide(
70
+ {"receipt": "receipt_photo", "note": "Customer asks for a refund"},
71
+ {"total_matches": noul("Does the total printed on receipt_photo equal 23.40?")},
72
+ assets={"receipt_photo": Image.from_path("receipt.jpg")},
73
+ image_budget=140, # optional: 70, 140 or 280 (the default)
74
+ )
75
+ ```
76
+
77
+ `Image.from_path(path)` and `Image.from_bytes(data)` detect PNG or JPEG from the file's first bytes; pass `format="png"`, `"jpg"` or `"jpeg"` to state it (it must match the bytes). A plain dict in the wire shape, `{"type": "image", "format": "jpeg", "data_base64": "..."}`, is accepted as it is. References are matched as plain, case-sensitive text; every place a reference appears shows the image there, and when one reference contains another the longer one wins.
78
+
79
+ `image_budget` is the most visual tokens one image may use. Lower is cheaper and faster but sees less detail (small print suffers first). Any value other than 70, 140 or 280 raises `ValidationError` before sending; leave it out to get the server default of 280.
80
+
81
+ Limits, checked by the server (each breach is an `InvalidRequestError` whose message names the asset):
82
+
83
+ - PNG or JPEG only, still images, and the bytes must match the format. The helper detects the format from the bytes and refuses anything else before sending.
84
+ - At most 16 MiB per image (the helper checks this too). Width and height each from 280 to 1568 pixels. Images are never resized or re-encoded, by the client or the server, so resize larger images yourself first.
85
+ - At most 8 assets per request, and at most 8 images shown in any one question (each use of a reference counts).
86
+ - Every asset must be referenced at least once. A reference inside a text state must fall within its first 20,000 characters.
87
+
88
+ Images count as input tokens and are included in `usage.input_tokens`. At budget 280 one image costs up to about 280 tokens, at 140 up to about 140, at 70 up to about 70. An image referenced in the state is billed once per request however many questions read it; one referenced in a question's instructions or criteria is billed for that question, once per use.
89
+
90
+ ## Key expiry
91
+
92
+ Every API key expires. The client reads the expiry date from each response, so your program can plan rotation instead of finding out when the key stops working.
93
+
94
+ ```python
95
+ def on_expiry(expiry):
96
+ # called once per key and expiry date when 14 days or fewer are left: alert your team, or start a rotation job
97
+ alert_team(f"Launchables key {expiry.key_id} expires on {expiry.expires_on} ({expiry.days_left} days left)")
98
+
99
+ client = Launchables(on_key_expiry=on_expiry)
100
+
101
+ client.key()
102
+ # KeyInfo(id="c_1a2b3c4d", name="prod", expires_on="2027-01-13", days_left=89, workspace=None,
103
+ # rate_limit_per_minute=600, daily_limit=10000000, paused=False, pause_reason=None)
104
+
105
+ client.key_expiry # KeyExpiry(key_id, expires_on, days_left) from the last response, or None
106
+ ```
107
+
108
+ Without `on_key_expiry`, the client issues one `KeyExpiryWarning` when 14 days or fewer are left. `key()` counts as no request and no tokens, and works for a paused key so you can see why it is paused (`pause_reason`). The expiry headers add nothing to your token count. To replace a key without downtime, roll it on the API keys page of the console: the old key keeps working until the end of the next day.
109
+
110
+ ## Managing keys
111
+
112
+ To rotate keys from your own scripts, use an admin key. An owner makes one on the API keys page of the console (two-step sign-in must be on). Admin keys start with `launchables_admin_`, always expire, and can only manage your organisation's API keys: they cannot call the Decision API.
113
+
114
+ ```python
115
+ client = Launchables(admin_key=os.environ["LAUNCHABLES_ADMIN_KEY"]) # or just set LAUNCHABLES_ADMIN_KEY
116
+
117
+ page = client.admin.keys.list() # {"data": [{"id", "name", "prefix", "workspace", "expires_on", "last_used_on", "status", ...}], "has_more", "next_before"}
118
+ for key in client.admin.keys.list_all():
119
+ print(key["id"], key["status"])
120
+
121
+ made = client.admin.keys.create("staging", expires_in_days=90) # workspace_id is optional
122
+ made["key"] # the full key, shown only this once
123
+
124
+ rolled = client.admin.keys.roll("c_1a2b3c4d")
125
+ rolled["key"] # the new key; rolled["replaces"]["expires_on"] is when the old one stops (the end of tomorrow)
126
+
127
+ client.admin.keys.revoke("c_1a2b3c4d")
128
+ ```
129
+
130
+ Key lifetimes are 30, 90, 180 or 365 days (90 by default), never longer than your organisation allows. These calls go to `https://console.launchables.ai` (`admin_base_url` to change it) and may be made 120 times a minute per admin key. A missing key or workspace raises `NotFoundError` (404); the key limit or an archived workspace raises `ConflictError` (409); both are kinds of `InvalidRequestError`. `create` and `roll` are retried only after a 429, so a retry never makes a second key. Every change shows in Activity in the console.
131
+
132
+ ## Error handling
133
+
134
+ All errors derive from `LaunchablesError` and carry `.status`, `.message` (the server's message), `.body` and `.type` (the server's error type, such as `"out_of_credit"`, or `None` if it sent none).
135
+
136
+ | Error | When |
137
+ | --- | --- |
138
+ | `AuthenticationError` | 401, or no key (or admin key) given or found |
139
+ | `OutOfCreditError` | 402: the account has run out of prepaid credit (`.type` `"out_of_credit"`, top up in the console), or the key's workspace has reached its monthly budget (`.type` `"budget_exceeded"`) |
140
+ | `PermissionDeniedError` | 403: the key's workspace may not use this model (`.type` `"model_not_allowed"`), or the admin key's maker is no longer an owner |
141
+ | `RateLimitError` | 429 (`.retry_after` seconds, if sent) |
142
+ | `InvalidRequestError` | 400, 411, 413, 422 and other 4xx; `ValidationError` is the local pre-flight subclass. `.type` says what was wrong with an image: `"invalid_assets"`, `"unsupported_image_format"`, `"invalid_image"`, `"image_too_large"`, `"image_dimensions"`, `"too_many_images"`, `"unreferenced_asset"` or `"image_reference_truncated"` (400), or `"invalid_image_budget"` (422). |
143
+ | `NotFoundError`, `ConflictError` | 404 and 409 from the key management API (subclasses of `InvalidRequestError`) |
144
+ | `APIError` | 5xx |
145
+ | `APIConnectionError` | could not reach the server (including timeouts) |
146
+
147
+ ```python
148
+ from launchables import OutOfCreditError, RateLimitError, InvalidRequestError, LaunchablesError
149
+
150
+ try:
151
+ resp = client.decide(state, questions)
152
+ except OutOfCreditError as e:
153
+ print("workspace budget reached" if e.type == "budget_exceeded" else "top up credit")
154
+ except RateLimitError as e:
155
+ print("slow down", e.retry_after)
156
+ except InvalidRequestError as e:
157
+ print(e.status, e.message)
158
+ except LaunchablesError as e:
159
+ print("failed:", e)
160
+ ```
161
+
162
+ ## Retries
163
+
164
+ 429, 502, 503 and connection errors are retried up to `max_retries` times (default 3) with exponential backoff of 0.5s, 1s, 2s. A `Retry-After` header (seconds) is honoured instead, capped at 60s. Other errors, including 402 and 403, are raised immediately. `timeout` (seconds, default 30) applies to each attempt.
165
+
166
+ ```python
167
+ client = Launchables(api_key="launchables_...", timeout=10, max_retries=5)
168
+ ```
169
+
170
+ ## Self-hosted endpoints
171
+
172
+ ```python
173
+ client = Launchables(base_url="https://decisions.internal.example.com")
174
+ ```
175
+
176
+ Requests carry `User-Agent: launchables-python/<version>`.
177
+
178
+ ## Tests
179
+
180
+ ```
181
+ PYTHONPATH=src python -m unittest discover -s tests -t .
182
+ ```
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "launchables"
7
+ dynamic = ["version"]
8
+ description = "Python client for the Launchables Decision API"
9
+ readme = "README.md"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.9"
12
+ license = "Apache-2.0"
13
+ dependencies = []
14
+ keywords = ["launchables", "decision", "api", "llm"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Typing :: Typed",
18
+ ]
19
+
20
+ [tool.setuptools.dynamic]
21
+ version = { attr = "launchables._version.__version__" }
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ launchables = ["py.typed"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://www.launchables.ai/docs"
31
+ Documentation = "https://www.launchables.ai/docs"
32
+ Repository = "https://github.com/launchables-ai/launchables-sdk"
33
+ Issues = "https://github.com/launchables-ai/launchables-sdk/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,39 @@
1
+ """Python client for the Launchables Decision API."""
2
+
3
+ from ._version import __version__
4
+ from .admin import AdminKeys
5
+ from .client import DEFAULT_ADMIN_BASE_URL, DEFAULT_BASE_URL, KEY_EXPIRY_WARNING_DAYS, KeyExpiryWarning, Launchables
6
+ from .errors import (
7
+ APIConnectionError,
8
+ APIError,
9
+ AuthenticationError,
10
+ ConflictError,
11
+ InvalidRequestError,
12
+ LaunchablesError,
13
+ NotFoundError,
14
+ OutOfCreditError,
15
+ PermissionDeniedError,
16
+ RateLimitError,
17
+ ValidationError,
18
+ )
19
+ from .images import IMAGE_BUDGETS, IMAGE_FORMATS, MAX_IMAGE_BYTES, Image
20
+ from .questions import choice, noul, score
21
+ from .responses import (
22
+ ChoiceAnswer,
23
+ DecisionResponse,
24
+ KeyExpiry,
25
+ KeyInfo,
26
+ Model,
27
+ NoulAnswer,
28
+ ScoreAnswer,
29
+ Usage,
30
+ )
31
+
32
+ __all__ = [
33
+ "__version__", "Launchables", "DEFAULT_BASE_URL", "DEFAULT_ADMIN_BASE_URL", "AdminKeys", "KEY_EXPIRY_WARNING_DAYS", "KeyExpiryWarning", "KeyInfo", "KeyExpiry",
34
+ "noul", "choice", "score", "Image", "IMAGE_BUDGETS", "IMAGE_FORMATS", "MAX_IMAGE_BYTES",
35
+ "DecisionResponse", "NoulAnswer", "ChoiceAnswer", "ScoreAnswer", "Usage", "Model",
36
+ "LaunchablesError", "AuthenticationError", "OutOfCreditError", "PermissionDeniedError",
37
+ "RateLimitError", "InvalidRequestError", "NotFoundError", "ConflictError",
38
+ "ValidationError", "APIError", "APIConnectionError",
39
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"