violet-sdk 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.
Files changed (42) hide show
  1. violet_sdk-0.1.0/.github/workflows/publish.yml +56 -0
  2. violet_sdk-0.1.0/.gitignore +38 -0
  3. violet_sdk-0.1.0/CHANGELOG.md +12 -0
  4. violet_sdk-0.1.0/LICENSE +21 -0
  5. violet_sdk-0.1.0/PKG-INFO +316 -0
  6. violet_sdk-0.1.0/README.md +296 -0
  7. violet_sdk-0.1.0/SAMPLES.md +94 -0
  8. violet_sdk-0.1.0/cookbook/classify_batch.py +72 -0
  9. violet_sdk-0.1.0/cookbook/cost_report.py +93 -0
  10. violet_sdk-0.1.0/cookbook/extract_structured.py +97 -0
  11. violet_sdk-0.1.0/cookbook/rag_minimal.py +123 -0
  12. violet_sdk-0.1.0/cookbook/streaming_repl.py +90 -0
  13. violet_sdk-0.1.0/cookbook/tool_agent.py +192 -0
  14. violet_sdk-0.1.0/examples/_common.py +28 -0
  15. violet_sdk-0.1.0/examples/api_key_chat.py +47 -0
  16. violet_sdk-0.1.0/examples/chat.py +41 -0
  17. violet_sdk-0.1.0/examples/count_tokens.py +44 -0
  18. violet_sdk-0.1.0/examples/logout.py +19 -0
  19. violet_sdk-0.1.0/examples/rate_limit_probe.py +339 -0
  20. violet_sdk-0.1.0/examples/stream.py +29 -0
  21. violet_sdk-0.1.0/examples/structured_output.py +76 -0
  22. violet_sdk-0.1.0/examples/tool_use.py +82 -0
  23. violet_sdk-0.1.0/examples/usage.py +39 -0
  24. violet_sdk-0.1.0/examples/whoami.py +30 -0
  25. violet_sdk-0.1.0/pyproject.toml +33 -0
  26. violet_sdk-0.1.0/scripts/publish-check.ps1 +276 -0
  27. violet_sdk-0.1.0/tests/test_api_key_workspace.py +33 -0
  28. violet_sdk-0.1.0/tests/test_async.py +153 -0
  29. violet_sdk-0.1.0/tests/test_shapes.py +184 -0
  30. violet_sdk-0.1.0/violet/__init__.py +75 -0
  31. violet_sdk-0.1.0/violet/_async.py +503 -0
  32. violet_sdk-0.1.0/violet/_streaming.py +147 -0
  33. violet_sdk-0.1.0/violet/_transport.py +187 -0
  34. violet_sdk-0.1.0/violet/auth.py +432 -0
  35. violet_sdk-0.1.0/violet/client.py +180 -0
  36. violet_sdk-0.1.0/violet/errors.py +150 -0
  37. violet_sdk-0.1.0/violet/fixtures.py +169 -0
  38. violet_sdk-0.1.0/violet/resources.py +211 -0
  39. violet_sdk-0.1.0/violet/types.py +185 -0
  40. violet_sdk-0.1.0/webchat/README.md +74 -0
  41. violet_sdk-0.1.0/webchat/app.py +176 -0
  42. violet_sdk-0.1.0/webchat/static/index.html +158 -0
@@ -0,0 +1,56 @@
1
+ # Publish violet-sdk to PyPI via Trusted Publishing (OIDC).
2
+ # No PyPI API token is stored in GitHub secrets.
3
+ #
4
+ # Trigger: publish a GitHub Release (tag should match __version__).
5
+ # PyPI trusted publisher must match:
6
+ # project=violet-sdk, owner=violetaica, repo=violet-client-sdk-python,
7
+ # workflow=publish.yml, environment=pypi
8
+
9
+ name: Publish to PyPI
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ build:
20
+ name: Build distributions
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - uses: actions/setup-python@v5
26
+ with:
27
+ python-version: "3.12"
28
+
29
+ - name: Install build tooling
30
+ run: python -m pip install --upgrade pip build
31
+
32
+ - name: Build sdist and wheel
33
+ run: python -m build
34
+
35
+ - uses: actions/upload-artifact@v4
36
+ with:
37
+ name: dist
38
+ path: dist/
39
+
40
+ publish:
41
+ name: Upload to PyPI
42
+ needs: build
43
+ runs-on: ubuntu-latest
44
+ environment:
45
+ name: pypi
46
+ url: https://pypi.org/p/violet-sdk
47
+ permissions:
48
+ id-token: write # required for Trusted Publishing
49
+ steps:
50
+ - uses: actions/download-artifact@v4
51
+ with:
52
+ name: dist
53
+ path: dist/
54
+
55
+ - name: Publish package distributions to PyPI
56
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,38 @@
1
+ # Byte-compiled / cache
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.pyo
6
+
7
+ # Virtual environments
8
+ .venv/
9
+ venv/
10
+ .env/
11
+ .envrc
12
+
13
+ # Packaging / build
14
+ build/
15
+ dist/
16
+ *.egg-info/
17
+ *.egg
18
+ .eggs/
19
+
20
+ # Test / tooling
21
+ .pytest_cache/
22
+ .mypy_cache/
23
+ .ruff_cache/
24
+ .coverage
25
+ htmlcov/
26
+ .tox/
27
+ .nox/
28
+
29
+ # Editor / OS
30
+ .idea/
31
+ .vscode/
32
+ *.swp
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # Local secrets / credentials
37
+ .env
38
+ *.pem
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ All notable changes to **`violet-sdk`** (import name: `violet`) are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-10-04
9
+
10
+ First version of Violet Messages API Client SDK.
11
+
12
+ [0.1.0]: https://github.com/violetaica/violet-client-sdk-python/releases/tag/v0.1.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 violetaica
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,316 @@
1
+ Metadata-Version: 2.5
2
+ Name: violet-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Violet Messages API with keyless (Auth0, API key) authentication.
5
+ Project-URL: Homepage, https://github.com/violetaica/violet-client-sdk-python
6
+ Project-URL: Changelog, https://github.com/violetaica/violet-client-sdk-python/blob/main/CHANGELOG.md
7
+ Author: Violet
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: auth0,llm,messages,oauth,pkce,violet
11
+ Requires-Python: >=3.9
12
+ Provides-Extra: async
13
+ Requires-Dist: aiohttp; extra == 'async'
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == 'dev'
16
+ Provides-Extra: web
17
+ Requires-Dist: fastapi; extra == 'web'
18
+ Requires-Dist: uvicorn[standard]; extra == 'web'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Violet Messages API — Python Client SDK
22
+
23
+ A small, dependency-free Python client for the **Violet Messages API** —
24
+ `client.messages.create(...)`, `msg.content[0].text`, `client.messages.stream(...)`,
25
+ and typed error classes. *(Familiar if you know the Anthropic Messages SDK surface;
26
+ this package is Violet-native and talks to the Violet gateway.)*
27
+
28
+ ```python
29
+ from violet import Violet
30
+
31
+ client = Violet(workspace_id="ws_…") # Auth0 browser login on first call
32
+ # CI / server — workspace API key (Settings → API keys):
33
+ # client = Violet(api_key="vio_sk_…") # or VIOLET_API_KEY
34
+ # model= is required by the API shape; the gateway chooses the served model.
35
+ msg = client.messages.create(model="Violet Test Model", max_tokens=64,
36
+ messages=[{"role": "user", "content": "Say hi"}])
37
+ print(msg.content[0].text)
38
+ ```
39
+
40
+ Authentication is **dual**:
41
+
42
+ - **Auth0 JWT** (default when no API key is set) — interactive humans via PKCE /
43
+ Device Code / credential cache. Same as the web and desktop apps.
44
+ - **Workspace API key** (`api_key=` / `VIOLET_API_KEY`) — opaque `vio_sk_…`
45
+ secret for CI, servers, and partner backends. Minted in Settings → API keys.
46
+
47
+ ## Auth priority
48
+
49
+ | Order | Mode | When to use |
50
+ |---|---|---|
51
+ | 0 | `api_key=` / `VIOLET_API_KEY` | CI, servers, headless jobs |
52
+ | 1 | `AUTH_TOKEN` / `auth_token=` (pre-supplied Auth0 JWT) | Devtools / scripts |
53
+ | 2 | Cached access token from a prior login | Steady state after browser login |
54
+ | 3 | Refresh token (`offline_access`) → silent re-mint | Steady state |
55
+ | 4 | **Interactive login**: Authorization Code + PKCE (default) or Device Code | Laptops / demos |
56
+
57
+ Auth0 refresh + access tokens are cached at `~/.violet/credentials.json`
58
+ (mode `600`), keyed by `(domain, client_id, audience)`. API keys are **not**
59
+ cached by the SDK — store them in your secret manager.
60
+
61
+ ## Install
62
+
63
+ ```powershell
64
+ pip install -e . # or: pip install -e ".[dev]"
65
+ ```
66
+
67
+ Requires Python 3.9+. No third-party packages.
68
+
69
+ ## Surface
70
+
71
+ | Call | Endpoint |
72
+ |---|---|
73
+ | `Violet(...)` / `AsyncViolet(...)` | — |
74
+ | `client.messages.create(...) -> Message` | `POST /api/v1/messages` |
75
+ | `client.messages.stream(...)` → `.text_stream`, `.get_final_message()` | `POST /api/v1/messages` (SSE) |
76
+ | `client.messages.create(..., stream=True)` → event iterator | SSE |
77
+ | `client.messages.count_tokens(...) -> .input_tokens` | `POST /api/v1/messages/count_tokens` |
78
+ | `client.messages.parse(..., output_format=…) -> .parsed_output` | structured output |
79
+ | `Message`, `TextBlock`, `ThinkingBlock`, `ToolUseBlock`, `Usage` | — |
80
+ | `BadRequestError` / `AuthenticationError` / `PermissionDeniedError` / `NotFoundError` / `RateLimitError` / `InternalServerError` → `APIError` | — |
81
+ | `client.with_options(timeout=, max_retries=)` | — |
82
+
83
+ **Violet extensions:**
84
+ `client.auth.login()/logout()/signup()/profile()`, `client.usage.get()` (monthly USD spend),
85
+ `client.health()`. Errors also carry `.code` (e.g. `user_not_provisioned`).
86
+
87
+ Auth is Auth0 login **or** a workspace `api_key=` (`vio_sk_…`, not a provider key)
88
+ plus `workspace_id`. The **gateway sets the served model** — client `model=` is
89
+ required by the API shape but does not choose inference.
90
+
91
+ ## Quick start
92
+
93
+ ```python
94
+ from violet import Violet
95
+
96
+ client = Violet() # auth + base URL + workspace from env / defaults
97
+
98
+ msg = client.messages.create( # first call triggers a one-time browser sign-in
99
+ model="Violet Test Model", # placeholder — gateway sets the real model
100
+ max_tokens=64,
101
+ messages=[{"role": "user", "content": "Say hello in 3 words."}],
102
+ )
103
+ print(msg.content[0].text)
104
+ print(msg.usage.input_tokens, msg.usage.output_tokens, msg.stop_reason)
105
+ ```
106
+
107
+ Streaming:
108
+
109
+ ```python
110
+ with client.messages.stream(
111
+ model="Violet Test Model", max_tokens=128,
112
+ messages=[{"role": "user", "content": "Write a haiku about violets."}],
113
+ ) as stream:
114
+ for text in stream.text_stream:
115
+ print(text, end="", flush=True)
116
+ final = stream.get_final_message()
117
+ ```
118
+
119
+ Errors:
120
+
121
+ ```python
122
+ from violet import RateLimitError, PermissionDeniedError, APIError
123
+ try:
124
+ client.messages.create(...)
125
+ except RateLimitError as e:
126
+ ... # 429
127
+ except PermissionDeniedError as e:
128
+ print(e.code) # e.g. "user_not_provisioned"
129
+ except APIError as e:
130
+ print(e.status_code, e.message)
131
+ ```
132
+
133
+ ### Async
134
+
135
+ `AsyncViolet` is a **native-async** client — non-blocking I/O via **aiohttp**,
136
+ an optional extra: `pip install violet-sdk[async]`. The sync `Violet` stays
137
+ stdlib-only; importing `violet` never
138
+ requires aiohttp. Same surface as `Violet`, just `await`-ed:
139
+
140
+ ```python
141
+ import asyncio
142
+ from violet import AsyncViolet
143
+
144
+ async def main():
145
+ async with AsyncViolet(workspace_id="ws_…") as client:
146
+ msg = await client.messages.create(
147
+ model="Violet Test Model", max_tokens=64, # gateway sets the model
148
+ messages=[{"role": "user", "content": "Say hi"}],
149
+ )
150
+ print(msg.content[0].text)
151
+
152
+ async with client.messages.stream(
153
+ model="Violet Test Model", max_tokens=128,
154
+ messages=[{"role": "user", "content": "Write a haiku."}],
155
+ ) as stream:
156
+ async for text in stream.text_stream:
157
+ print(text, end="", flush=True)
158
+ final = await stream.get_final_message()
159
+
160
+ asyncio.run(main())
161
+ ```
162
+
163
+ Use `async with AsyncViolet(...)` (or call `await client.aclose()`) so the
164
+ underlying HTTP session is closed. The rare Auth0 token resolution runs in a
165
+ thread; the message/stream calls are genuinely async.
166
+
167
+ Run the bundled examples:
168
+
169
+ ```powershell
170
+ python -m examples.chat
171
+ python -m examples.stream
172
+ python -m examples.whoami # diagnose auth/provisioning
173
+ ```
174
+
175
+ **Sample apps** — per-method `examples/`, technique `cookbook/` recipes, and a
176
+ full-stack `webchat/` showcase are cataloged in **[SAMPLES.md](SAMPLES.md)**
177
+ (with the shared prereqs and the backend-reality caveats).
178
+
179
+ ## Configuration
180
+
181
+ All via constructor args or env vars (env shown):
182
+
183
+ | Var | Default | Purpose |
184
+ |---|---|---|
185
+ | `MESSAGES_API_URL` | `https://api.violetai.ca` | Gateway base URL |
186
+ | `WORKSPACE_ID` | Auth0: auto via `/api/auth/login`; API key: omit (gateway injects) | Tenant scope (`X-Workspace-Id`) |
187
+ | `AUTH0_DOMAIN` | `dev-8vv5angslahu4n7h.ca.auth0.com` | Auth0 tenant |
188
+ | `AUTH0_CLIENT_ID` | web SPA client id | Public OAuth client (no secret) |
189
+ | `AUTH0_AUDIENCE` | `https://api.prodkraft.com` | Token audience the gateway validates |
190
+ | `AUTH_TOKEN` | *(unset)* | Skip login; use this access token verbatim |
191
+ | `VIOLET_REDIRECT_URI` | `http://localhost:5174/callback` | PKCE loopback redirect (registered in Auth0) |
192
+ | `VIOLET_CRED_CACHE` | `~/.violet/credentials.json` | Token cache location |
193
+ | `VIOLET_USER_AGENT` | browser-like UA | Sent on gateway calls so Cloudflare doesn't 403 the client as a bot |
194
+
195
+ Pick the interactive flow explicitly:
196
+
197
+ ```python
198
+ from violet import Authenticator, Violet
199
+
200
+ client = Violet(auth=Authenticator(flow="pkce")) # default; or flow="device"
201
+ client.auth.force_login() # force interactive sign-in now
202
+ client.auth.logout() # clear cached credentials
203
+ ```
204
+
205
+ ## Logging out
206
+
207
+ ```python
208
+ client.auth.logout() # revoke refresh token at Auth0 + delete local cache
209
+ client.auth.logout(browser=True) # also end the Auth0 SSO session (next login re-prompts)
210
+ client.auth.logout(revoke=False) # local-only: just forget the cached tokens
211
+ ```
212
+
213
+ Or from the CLI:
214
+
215
+ ```powershell
216
+ python -m examples.logout # revoke + clear local cache
217
+ python -m examples.logout --browser # also clear the Auth0 session cookie
218
+ ```
219
+
220
+ Three layers, pick what you need:
221
+
222
+ | Goal | Call |
223
+ |---|---|
224
+ | Forget tokens on this machine | `client.auth.logout(revoke=False)` |
225
+ | …and invalidate the refresh token server-side | `client.auth.logout()` *(default)* |
226
+ | …and force the next login to re-prompt (switch accounts) | `client.auth.logout(browser=True)` |
227
+
228
+ The `browser=True` step matters because Auth0 keeps an SSO session cookie — without
229
+ clearing it, the next PKCE login silently re-authenticates the *same* user and
230
+ "logout" looks like it did nothing. (A `return_to` URL passed here must be in the
231
+ app's **Allowed Logout URLs**, or Auth0 shows an error page.)
232
+
233
+ > **`AUTH_TOKEN` caveat:** if you signed in via the pre-supplied-token path, `logout`
234
+ > can't revoke that token (it isn't ours) and the env var still wins on the next call.
235
+ > Unset it to fully sign out: `Remove-Item Env:AUTH_TOKEN`.
236
+
237
+ ## Auth0 application prerequisites (one-time, tenant owner)
238
+
239
+ The defaults point at Violet's production tenant and the **same public SPA client
240
+ the web/desktop apps use** (`Tk1qTB6fvVRuKZw5d0W6EWVK5Exm0CI1`), which supports
241
+ Authorization Code + PKCE.
242
+
243
+ - **PKCE loopback (default)** → works out of the box: the SDK redirects to
244
+ `http://localhost:5174/callback`, which is registered in the Auth0 SPA app.
245
+ Packaged Violet Electron uses `http://127.0.0.1:5174/callback` (same port,
246
+ different host) — that URL must also be in **Allowed Callback URLs**,
247
+ **Allowed Logout URLs**, and **Allowed Web Origins**. If you change
248
+ `VIOLET_REDIRECT_URI`, add that exact URL or login fails with *Callback URL
249
+ mismatch*. Port `5174` must be free during login (stop the desktop
250
+ dev/packaged loopback server if it's running).
251
+ - **Device Code** flow → **not enabled on the SPA client** (you'll get
252
+ `unauthorized_client: Grant type 'device_code' not allowed`). To use it,
253
+ register a **Native** Auth0 app with the *Device Code* grant enabled and pass
254
+ its id via `AUTH0_CLIENT_ID`.
255
+ - Either flow → the Messages API (`AUTH0_AUDIENCE`) must be authorized for the app.
256
+
257
+ To skip interactive login entirely, set `AUTH_TOKEN` with a token grabbed from the
258
+ web app's dev tools (DevTools → Network → any `/api/v1/*` request → the
259
+ `Authorization: Bearer …` header).
260
+
261
+ ## Cloudflare `403 error code: 1010`
262
+
263
+ The prod gateway (`api.violetai.ca`) is behind **Cloudflare bot protection**, which
264
+ bans the default `Python-urllib/x` user-agent. The SDK sends a browser-like
265
+ `User-Agent` by default to avoid it. If you still see `1010`:
266
+
267
+ - Override the UA: `Violet(user_agent="…")` or `$env:VIOLET_USER_AGENT = "…"`.
268
+ - Cloudflare may also fingerprint at the TLS layer (JA3) — if a UA alone doesn't get
269
+ through, you're hitting stricter bot management; ask the API team to allowlist
270
+ your client.
271
+
272
+ ## Provisioning & 403s
273
+
274
+ **Login succeeding but inference returning `403` is normal for a brand-new account.**
275
+ Auth0 only proves *who you are*; the Violet gateway separately checks that the
276
+ identity is a **provisioned account** with a **paid workspace**. Two distinct gates:
277
+
278
+ ```powershell
279
+ python -m examples.whoami # tells you exactly which gate you're failing
280
+ ```
281
+
282
+ | Symptom | Meaning | Fix |
283
+ |---|---|---|
284
+ | `403 user_not_provisioned` | Valid Auth0 token, but no Violet account row | `client.auth.signup()` to provision the account row |
285
+ | Signed in, `default_workspace` is null | Provisioned, but no workspace | Subscribe/create a workspace in the **web app** (signup alone doesn't — billing does), then retry |
286
+ | `403 Not a member of this workspace` | The `WORKSPACE_ID` you sent isn't one you belong to | Use a workspace you're a member of (leave `WORKSPACE_ID` unset to auto-resolve your default) |
287
+ | `403 subscription_required` | `POST /api/workspaces` without a paid plan | Complete checkout in the web app |
288
+
289
+ ```python
290
+ client = Violet()
291
+ client.auth.signup() # provision the account row (idempotent)
292
+ print(client.auth.login()) # inspect sub / default_workspace / memberships_count
293
+ # If you already know your workspace id, skip auto-resolution:
294
+ client = Violet(workspace_id="ws-...") # or set WORKSPACE_ID env
295
+ ```
296
+
297
+ With Auth0, the SDK auto-resolves your workspace from `/api/auth/login` on the
298
+ first member call. With a workspace API key (`vio_sk_…`), the header is omitted
299
+ and the gateway injects the key's bound workspace — so narrow scopes
300
+ (`messages:write`, `usage:read`) work without a full-access key. If Auth0
301
+ login finds no provisioned account or workspace, the SDK raises a **clear**
302
+ `VioletError` instead of a bare `403`.
303
+
304
+ ## Endpoints behind the surface
305
+
306
+ | Surface call | Endpoint |
307
+ |---|---|
308
+ | `client.messages.create/stream` | `POST /api/v1/messages` |
309
+ | `client.messages.count_tokens` | `POST /api/v1/messages/count_tokens` |
310
+ | `client.usage.get` | `GET /api/v1/usage/me` (monthly billing snapshot) |
311
+ | `client.auth.login/signup/profile` | `/api/auth/login`, `/api/auth/signup`, `/api/auth/profile` |
312
+ | `client.health()` | `GET /api/health` (+ fallbacks) |
313
+
314
+ Errors use the typed classes (`BadRequestError` … `RateLimitError`,
315
+ all `APIError`/`APIStatusError`) plus `.code`; auth-flow failures raise
316
+ `AuthError`. All subclass `VioletError`.