ateliq 1.0.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.
- ateliq-1.0.0/.gitignore +6 -0
- ateliq-1.0.0/LICENSE +21 -0
- ateliq-1.0.0/PKG-INFO +129 -0
- ateliq-1.0.0/README.md +97 -0
- ateliq-1.0.0/pyproject.toml +64 -0
- ateliq-1.0.0/src/ateliq/__init__.py +31 -0
- ateliq-1.0.0/src/ateliq/__main__.py +6 -0
- ateliq-1.0.0/src/ateliq/_version.py +1 -0
- ateliq-1.0.0/src/ateliq/cli.py +206 -0
- ateliq-1.0.0/src/ateliq/client.py +354 -0
- ateliq-1.0.0/src/ateliq/py.typed +0 -0
- ateliq-1.0.0/tests/test_client.py +241 -0
ateliq-1.0.0/.gitignore
ADDED
ateliq-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PWIN Technologies Pvt Ltd
|
|
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.
|
ateliq-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ateliq
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Ateliq API SDK and CLI: search ateliq.co, get Ateliq products, prices and AI agents for fashion and jewellery brands, and request a demo. No key needed.
|
|
5
|
+
Project-URL: Homepage, https://ateliq.co/docs/sdk/
|
|
6
|
+
Project-URL: Documentation, https://ateliq.co/docs/api/
|
|
7
|
+
Project-URL: Repository, https://github.com/PWIN-Technologies-Pvt-Ltd/ateliq-agent-plugin
|
|
8
|
+
Project-URL: Issues, https://ateliq.co/contact/
|
|
9
|
+
Author-email: PWIN Technologies Pvt Ltd <pb@ateliq.co>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agents,api,ateliq,cli,fashion,gold-price,jewellery,mcp,retail,sdk,virtual-try-on
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Topic :: Office/Business
|
|
28
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
29
|
+
Classifier: Typing :: Typed
|
|
30
|
+
Requires-Python: >=3.9
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# ateliq
|
|
34
|
+
|
|
35
|
+
The official Python SDK and command line for the [Ateliq API](https://ateliq.co/docs/api/). Ateliq is AI for fashion and jewellery brands: an in-store AI stylist with live try-on (the Ateliq Mirror and Counter) and twelve AI agents for trends, design, shoots and campaigns.
|
|
36
|
+
|
|
37
|
+
Search ateliq.co, read any page, get products, prices and agents, read the gold spot price, and request a demo. No key is needed.
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
pip install ateliq
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Needs Python 3.9 or later. No dependencies: it uses only the standard library.
|
|
44
|
+
|
|
45
|
+
## SDK
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from ateliq import Ateliq
|
|
49
|
+
|
|
50
|
+
ateliq = Ateliq()
|
|
51
|
+
|
|
52
|
+
hits = ateliq.search("virtual try-on mirror")
|
|
53
|
+
pricing = ateliq.get_pricing()
|
|
54
|
+
mirror = ateliq.get_product("mirror")
|
|
55
|
+
page = ateliq.get_page("product/mirror")
|
|
56
|
+
|
|
57
|
+
gold = ateliq.get_gold_price()
|
|
58
|
+
print(gold["per_gram"]["22k"]["INR"]) # per gram, in USD, INR, GBP and AED
|
|
59
|
+
# The international spot price, not a shop's retail rate.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Every list follows `pagination.next_cursor`. `paginate` walks all of it for you:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
for agent in ateliq.paginate(ateliq.list_agents):
|
|
66
|
+
print(agent["name"])
|
|
67
|
+
|
|
68
|
+
for hit in ateliq.paginate(ateliq.search, q="jewellery try-on", limit=20):
|
|
69
|
+
print(hit["url"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Request a demo for a person who asked for one. Test it first with `Ateliq(sandbox=True)`: the sandbox checks the request and answers the same way, but keeps and sends nothing.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
ateliq.create_demo_request(
|
|
76
|
+
{"name": "Asha Rao", "email": "asha@example.com", "brand": "Example Jewellers", "sells": "Jewellery"},
|
|
77
|
+
idempotency_key="a-unique-key",
|
|
78
|
+
)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Errors raise `AteliqError` with `status`, `code`, `title`, `detail` (how to fix it), `errors` and, on a 429, `retry_after` in seconds.
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from ateliq import Ateliq, AteliqError
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
Ateliq().get_product("no-such-product")
|
|
88
|
+
except AteliqError as e:
|
|
89
|
+
print(e.status, e.code, e.detail)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
| Method | API |
|
|
93
|
+
| --- | --- |
|
|
94
|
+
| `search(q, section=None, limit=None, cursor=None)` | `GET /search` |
|
|
95
|
+
| `list_pages()`, `get_page(path)`, `list_sections()` | `GET /pages`, `/pages/{path}`, `/sections` |
|
|
96
|
+
| `list_products()`, `get_product(id)` | `GET /products`, `/products/{id}` |
|
|
97
|
+
| `get_pricing()` | `GET /pricing` |
|
|
98
|
+
| `list_agents()`, `get_agent(id)` | `GET /agents`, `/agents/{id}` |
|
|
99
|
+
| `get_gold_price()` | `GET /gold-price` |
|
|
100
|
+
| `create_demo_request(input, idempotency_key=None)`, `get_demo_request(id)` | `POST /demo-requests`, `GET /demo-requests/{id}` |
|
|
101
|
+
| `index()` | `GET /` |
|
|
102
|
+
|
|
103
|
+
Options: `Ateliq(base_url=..., sandbox=False, timeout=30, user_agent=..., transport=...)`. `transport` is a callable `(method, url, headers, body, timeout) -> (status, headers, body)`; pass your own for tests or a different HTTP library. Type hints are included (`py.typed`).
|
|
104
|
+
|
|
105
|
+
## CLI
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
ateliq search "jewellery try-on"
|
|
109
|
+
ateliq pricing
|
|
110
|
+
ateliq gold-price
|
|
111
|
+
ateliq page product/mirror
|
|
112
|
+
ateliq products
|
|
113
|
+
ateliq agents
|
|
114
|
+
ateliq demo-status <id>
|
|
115
|
+
ateliq mcp # how to add the Ateliq MCP server to your agent
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Add `--json` for the raw answer and `--sandbox` for the sandbox. `python -m ateliq` works too.
|
|
119
|
+
|
|
120
|
+
## Links
|
|
121
|
+
|
|
122
|
+
- SDK docs: https://ateliq.co/docs/sdk/
|
|
123
|
+
- API docs: https://ateliq.co/docs/api/
|
|
124
|
+
- OpenAPI: https://ateliq.co/openapi.json
|
|
125
|
+
- MCP server: https://ateliq.co/docs/mcp/
|
|
126
|
+
- JavaScript SDK: [`ateliq` on npm](https://www.npmjs.com/package/ateliq)
|
|
127
|
+
- Agent plugin for Claude Code, Codex, Cursor and Gemini CLI: https://github.com/PWIN-Technologies-Pvt-Ltd/ateliq-agent-plugin
|
|
128
|
+
|
|
129
|
+
MIT licence. Made by PWIN Technologies Pvt Ltd.
|
ateliq-1.0.0/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# ateliq
|
|
2
|
+
|
|
3
|
+
The official Python SDK and command line for the [Ateliq API](https://ateliq.co/docs/api/). Ateliq is AI for fashion and jewellery brands: an in-store AI stylist with live try-on (the Ateliq Mirror and Counter) and twelve AI agents for trends, design, shoots and campaigns.
|
|
4
|
+
|
|
5
|
+
Search ateliq.co, read any page, get products, prices and agents, read the gold spot price, and request a demo. No key is needed.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install ateliq
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Needs Python 3.9 or later. No dependencies: it uses only the standard library.
|
|
12
|
+
|
|
13
|
+
## SDK
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from ateliq import Ateliq
|
|
17
|
+
|
|
18
|
+
ateliq = Ateliq()
|
|
19
|
+
|
|
20
|
+
hits = ateliq.search("virtual try-on mirror")
|
|
21
|
+
pricing = ateliq.get_pricing()
|
|
22
|
+
mirror = ateliq.get_product("mirror")
|
|
23
|
+
page = ateliq.get_page("product/mirror")
|
|
24
|
+
|
|
25
|
+
gold = ateliq.get_gold_price()
|
|
26
|
+
print(gold["per_gram"]["22k"]["INR"]) # per gram, in USD, INR, GBP and AED
|
|
27
|
+
# The international spot price, not a shop's retail rate.
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Every list follows `pagination.next_cursor`. `paginate` walks all of it for you:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
for agent in ateliq.paginate(ateliq.list_agents):
|
|
34
|
+
print(agent["name"])
|
|
35
|
+
|
|
36
|
+
for hit in ateliq.paginate(ateliq.search, q="jewellery try-on", limit=20):
|
|
37
|
+
print(hit["url"])
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Request a demo for a person who asked for one. Test it first with `Ateliq(sandbox=True)`: the sandbox checks the request and answers the same way, but keeps and sends nothing.
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
ateliq.create_demo_request(
|
|
44
|
+
{"name": "Asha Rao", "email": "asha@example.com", "brand": "Example Jewellers", "sells": "Jewellery"},
|
|
45
|
+
idempotency_key="a-unique-key",
|
|
46
|
+
)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Errors raise `AteliqError` with `status`, `code`, `title`, `detail` (how to fix it), `errors` and, on a 429, `retry_after` in seconds.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from ateliq import Ateliq, AteliqError
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
Ateliq().get_product("no-such-product")
|
|
56
|
+
except AteliqError as e:
|
|
57
|
+
print(e.status, e.code, e.detail)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
| Method | API |
|
|
61
|
+
| --- | --- |
|
|
62
|
+
| `search(q, section=None, limit=None, cursor=None)` | `GET /search` |
|
|
63
|
+
| `list_pages()`, `get_page(path)`, `list_sections()` | `GET /pages`, `/pages/{path}`, `/sections` |
|
|
64
|
+
| `list_products()`, `get_product(id)` | `GET /products`, `/products/{id}` |
|
|
65
|
+
| `get_pricing()` | `GET /pricing` |
|
|
66
|
+
| `list_agents()`, `get_agent(id)` | `GET /agents`, `/agents/{id}` |
|
|
67
|
+
| `get_gold_price()` | `GET /gold-price` |
|
|
68
|
+
| `create_demo_request(input, idempotency_key=None)`, `get_demo_request(id)` | `POST /demo-requests`, `GET /demo-requests/{id}` |
|
|
69
|
+
| `index()` | `GET /` |
|
|
70
|
+
|
|
71
|
+
Options: `Ateliq(base_url=..., sandbox=False, timeout=30, user_agent=..., transport=...)`. `transport` is a callable `(method, url, headers, body, timeout) -> (status, headers, body)`; pass your own for tests or a different HTTP library. Type hints are included (`py.typed`).
|
|
72
|
+
|
|
73
|
+
## CLI
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
ateliq search "jewellery try-on"
|
|
77
|
+
ateliq pricing
|
|
78
|
+
ateliq gold-price
|
|
79
|
+
ateliq page product/mirror
|
|
80
|
+
ateliq products
|
|
81
|
+
ateliq agents
|
|
82
|
+
ateliq demo-status <id>
|
|
83
|
+
ateliq mcp # how to add the Ateliq MCP server to your agent
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Add `--json` for the raw answer and `--sandbox` for the sandbox. `python -m ateliq` works too.
|
|
87
|
+
|
|
88
|
+
## Links
|
|
89
|
+
|
|
90
|
+
- SDK docs: https://ateliq.co/docs/sdk/
|
|
91
|
+
- API docs: https://ateliq.co/docs/api/
|
|
92
|
+
- OpenAPI: https://ateliq.co/openapi.json
|
|
93
|
+
- MCP server: https://ateliq.co/docs/mcp/
|
|
94
|
+
- JavaScript SDK: [`ateliq` on npm](https://www.npmjs.com/package/ateliq)
|
|
95
|
+
- Agent plugin for Claude Code, Codex, Cursor and Gemini CLI: https://github.com/PWIN-Technologies-Pvt-Ltd/ateliq-agent-plugin
|
|
96
|
+
|
|
97
|
+
MIT licence. Made by PWIN Technologies Pvt Ltd.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ateliq"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official Ateliq API SDK and CLI: search ateliq.co, get Ateliq products, prices and AI agents for fashion and jewellery brands, and request a demo. No key needed."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "PWIN Technologies Pvt Ltd", email = "pb@ateliq.co" }]
|
|
14
|
+
keywords = [
|
|
15
|
+
"ateliq",
|
|
16
|
+
"sdk",
|
|
17
|
+
"api",
|
|
18
|
+
"cli",
|
|
19
|
+
"fashion",
|
|
20
|
+
"jewellery",
|
|
21
|
+
"virtual-try-on",
|
|
22
|
+
"retail",
|
|
23
|
+
"ai-agents",
|
|
24
|
+
"mcp",
|
|
25
|
+
"gold-price",
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Development Status :: 5 - Production/Stable",
|
|
29
|
+
"Environment :: Console",
|
|
30
|
+
"Intended Audience :: Developers",
|
|
31
|
+
"Operating System :: OS Independent",
|
|
32
|
+
"Programming Language :: Python",
|
|
33
|
+
"Programming Language :: Python :: 3",
|
|
34
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
35
|
+
"Programming Language :: Python :: 3.9",
|
|
36
|
+
"Programming Language :: Python :: 3.10",
|
|
37
|
+
"Programming Language :: Python :: 3.11",
|
|
38
|
+
"Programming Language :: Python :: 3.12",
|
|
39
|
+
"Programming Language :: Python :: 3.13",
|
|
40
|
+
"Programming Language :: Python :: 3.14",
|
|
41
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
42
|
+
"Topic :: Office/Business",
|
|
43
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
44
|
+
"Typing :: Typed",
|
|
45
|
+
]
|
|
46
|
+
dependencies = []
|
|
47
|
+
|
|
48
|
+
[project.urls]
|
|
49
|
+
Homepage = "https://ateliq.co/docs/sdk/"
|
|
50
|
+
Documentation = "https://ateliq.co/docs/api/"
|
|
51
|
+
Repository = "https://github.com/PWIN-Technologies-Pvt-Ltd/ateliq-agent-plugin"
|
|
52
|
+
Issues = "https://ateliq.co/contact/"
|
|
53
|
+
|
|
54
|
+
[project.scripts]
|
|
55
|
+
ateliq = "ateliq.cli:run"
|
|
56
|
+
|
|
57
|
+
[tool.hatch.version]
|
|
58
|
+
path = "src/ateliq/_version.py"
|
|
59
|
+
|
|
60
|
+
[tool.hatch.build.targets.wheel]
|
|
61
|
+
packages = ["src/ateliq"]
|
|
62
|
+
|
|
63
|
+
[tool.hatch.build.targets.sdist]
|
|
64
|
+
include = ["src/ateliq", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The official Python SDK for the Ateliq API. https://ateliq.co/docs/api/
|
|
2
|
+
|
|
3
|
+
>>> from ateliq import Ateliq
|
|
4
|
+
>>> Ateliq().get_pricing() # doctest: +SKIP
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._version import __version__
|
|
8
|
+
from .client import (
|
|
9
|
+
LIVE_URL,
|
|
10
|
+
SANDBOX_URL,
|
|
11
|
+
VERSION,
|
|
12
|
+
Ateliq,
|
|
13
|
+
AteliqError,
|
|
14
|
+
DemoRequestInput,
|
|
15
|
+
HttpResponse,
|
|
16
|
+
Transport,
|
|
17
|
+
urllib_transport,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Ateliq",
|
|
22
|
+
"AteliqError",
|
|
23
|
+
"DemoRequestInput",
|
|
24
|
+
"HttpResponse",
|
|
25
|
+
"LIVE_URL",
|
|
26
|
+
"SANDBOX_URL",
|
|
27
|
+
"Transport",
|
|
28
|
+
"VERSION",
|
|
29
|
+
"__version__",
|
|
30
|
+
"urllib_transport",
|
|
31
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""The Ateliq command line: search ateliq.co, read pages, get prices,
|
|
2
|
+
products and agents. https://ateliq.co/docs/api/
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .client import Ateliq, AteliqError, Transport
|
|
15
|
+
|
|
16
|
+
MCP = """Add the Ateliq MCP server to your agent:
|
|
17
|
+
|
|
18
|
+
Remote (Streamable HTTP): https://ateliq.co/api/mcp
|
|
19
|
+
Claude Code: claude mcp add --transport http ateliq https://ateliq.co/api/mcp
|
|
20
|
+
Any stdio client: npx -y ateliq-mcp
|
|
21
|
+
|
|
22
|
+
Docs: https://ateliq.co/docs/mcp/
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
DESCRIPTION = "ateliq {}: the Ateliq API from the command line".format(__version__)
|
|
26
|
+
EPILOG = "No key is needed. Docs: https://ateliq.co/docs/api/"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _common(default: Any) -> argparse.ArgumentParser:
|
|
30
|
+
p = argparse.ArgumentParser(add_help=False)
|
|
31
|
+
p.add_argument("--json", action="store_true", default=default, help="print the raw JSON answer")
|
|
32
|
+
p.add_argument("--sandbox", action="store_true", default=default, help="use the sandbox API")
|
|
33
|
+
return p
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _list_opts(p: argparse.ArgumentParser, section: bool = False) -> None:
|
|
37
|
+
if section:
|
|
38
|
+
p.add_argument("--section", help="only this section")
|
|
39
|
+
p.add_argument("--limit", type=int, help="items per page")
|
|
40
|
+
p.add_argument("--cursor", help="next_cursor from an earlier answer")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
44
|
+
# The flags work before or after the command. SUPPRESS on the subcommand
|
|
45
|
+
# copies keeps a subcommand from resetting a flag given before it.
|
|
46
|
+
common = _common(argparse.SUPPRESS)
|
|
47
|
+
parser = argparse.ArgumentParser(
|
|
48
|
+
prog="ateliq",
|
|
49
|
+
description=DESCRIPTION,
|
|
50
|
+
epilog=EPILOG,
|
|
51
|
+
parents=[_common(False)],
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument("--version", "-v", action="version", version=__version__)
|
|
54
|
+
sub = parser.add_subparsers(dest="cmd", metavar="<command>")
|
|
55
|
+
|
|
56
|
+
p = sub.add_parser("search", parents=[common], help="search every page of ateliq.co")
|
|
57
|
+
p.add_argument("words", nargs="+", help="search words")
|
|
58
|
+
_list_opts(p, section=True)
|
|
59
|
+
|
|
60
|
+
p = sub.add_parser("page", parents=[common], help="one page in full, for example: ateliq page pricing")
|
|
61
|
+
p.add_argument("path", help="page path, like pricing or product/mirror")
|
|
62
|
+
|
|
63
|
+
p = sub.add_parser("pages", parents=[common], help="list pages")
|
|
64
|
+
_list_opts(p, section=True)
|
|
65
|
+
|
|
66
|
+
sub.add_parser("sections", parents=[common], help="the site's sections")
|
|
67
|
+
|
|
68
|
+
p = sub.add_parser("products", parents=[common], help="Ateliq's products")
|
|
69
|
+
_list_opts(p)
|
|
70
|
+
p = sub.add_parser("product", parents=[common], help="one product by id")
|
|
71
|
+
p.add_argument("id", help="product id, like mirror")
|
|
72
|
+
|
|
73
|
+
p = sub.add_parser("agents", parents=[common], help="the AI agents")
|
|
74
|
+
_list_opts(p)
|
|
75
|
+
p = sub.add_parser("agent", parents=[common], help="one agent by id")
|
|
76
|
+
p.add_argument("id", help="agent id")
|
|
77
|
+
|
|
78
|
+
sub.add_parser("pricing", parents=[common], help="plans, hardware and credit prices")
|
|
79
|
+
sub.add_parser("gold-price", parents=[common], help="the international gold spot price")
|
|
80
|
+
|
|
81
|
+
p = sub.add_parser("demo-status", parents=[common], help="a demo request's status")
|
|
82
|
+
p.add_argument("id", help="demo request id")
|
|
83
|
+
|
|
84
|
+
sub.add_parser("mcp", parents=[common], help="how to add the Ateliq MCP server to your agent")
|
|
85
|
+
sub.add_parser("help", help="show this help")
|
|
86
|
+
return parser
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _print_list(res: Any, line: Callable[[Any], str], out: Any) -> None:
|
|
90
|
+
items = res.get("data") if isinstance(res, dict) else None
|
|
91
|
+
for item in items or []:
|
|
92
|
+
out.write(line(item) + "\n")
|
|
93
|
+
pagination = res.get("pagination") if isinstance(res, dict) else None
|
|
94
|
+
if isinstance(pagination, dict) and pagination.get("has_more"):
|
|
95
|
+
out.write("(more: --cursor {})\n".format(pagination.get("next_cursor")))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _g(d: Any, *keys: str) -> str:
|
|
99
|
+
if not isinstance(d, dict):
|
|
100
|
+
return ""
|
|
101
|
+
for k in keys:
|
|
102
|
+
v = d.get(k)
|
|
103
|
+
if v:
|
|
104
|
+
return str(v)
|
|
105
|
+
return ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _search_line(h: Any) -> str:
|
|
109
|
+
s = "{}\n {}".format(_g(h, "title"), _g(h, "url"))
|
|
110
|
+
snippet = _g(h, "snippet")
|
|
111
|
+
if snippet:
|
|
112
|
+
s += "\n " + re.sub(r"\s+", " ", snippet)[:200]
|
|
113
|
+
return s
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def main(argv: Optional[Sequence[str]] = None, *, transport: Optional[Transport] = None) -> int:
|
|
117
|
+
"""Run the CLI. Returns the exit code."""
|
|
118
|
+
out = sys.stdout
|
|
119
|
+
parser = build_parser()
|
|
120
|
+
args = parser.parse_args(list(sys.argv[1:] if argv is None else argv))
|
|
121
|
+
cmd = args.cmd
|
|
122
|
+
if not cmd or cmd == "help":
|
|
123
|
+
parser.print_help(out)
|
|
124
|
+
return 0
|
|
125
|
+
if cmd == "mcp":
|
|
126
|
+
out.write(MCP)
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
client = Ateliq(
|
|
130
|
+
sandbox=bool(args.sandbox),
|
|
131
|
+
user_agent="ateliq-python-cli/{}".format(__version__),
|
|
132
|
+
transport=transport,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def lst(*names: str) -> Dict[str, Any]:
|
|
136
|
+
return {n: getattr(args, n, None) for n in names}
|
|
137
|
+
|
|
138
|
+
show: Optional[Callable[[], object]] = None
|
|
139
|
+
try:
|
|
140
|
+
if cmd == "search":
|
|
141
|
+
res = client.search(" ".join(args.words), **lst("section", "limit", "cursor"))
|
|
142
|
+
show = lambda: _print_list(res, _search_line, out) # noqa: E731
|
|
143
|
+
elif cmd == "page":
|
|
144
|
+
res = client.get_page(args.path)
|
|
145
|
+
show = lambda: out.write( # noqa: E731
|
|
146
|
+
(_g(res, "markdown", "content") or json.dumps(res, indent=2, ensure_ascii=False)) + "\n"
|
|
147
|
+
)
|
|
148
|
+
elif cmd == "pages":
|
|
149
|
+
res = client.list_pages(**lst("section", "limit", "cursor"))
|
|
150
|
+
show = lambda: _print_list(res, lambda p: "{} {}".format(_g(p, "path"), _g(p, "title")), out) # noqa: E731
|
|
151
|
+
elif cmd == "sections":
|
|
152
|
+
res = client.list_sections()
|
|
153
|
+
show = lambda: _print_list( # noqa: E731
|
|
154
|
+
res, lambda s: "{} {}".format(_g(s, "id", "section", "name"), _g(s, "title")).strip(), out
|
|
155
|
+
)
|
|
156
|
+
elif cmd == "products":
|
|
157
|
+
res = client.list_products(**lst("limit", "cursor"))
|
|
158
|
+
show = lambda: _print_list( # noqa: E731
|
|
159
|
+
res, lambda p: "{} {}".format(_g(p, "id"), _g(p, "name", "title")), out
|
|
160
|
+
)
|
|
161
|
+
elif cmd == "product":
|
|
162
|
+
res = client.get_product(args.id)
|
|
163
|
+
elif cmd == "agents":
|
|
164
|
+
res = client.list_agents(**lst("limit", "cursor"))
|
|
165
|
+
|
|
166
|
+
def agent_line(a: Any) -> str:
|
|
167
|
+
role = _g(a, "role")
|
|
168
|
+
return "{} {}{}".format(_g(a, "id"), _g(a, "name"), " ({})".format(role) if role else "")
|
|
169
|
+
|
|
170
|
+
show = lambda: _print_list(res, agent_line, out) # noqa: E731
|
|
171
|
+
elif cmd == "agent":
|
|
172
|
+
res = client.get_agent(args.id)
|
|
173
|
+
elif cmd == "pricing":
|
|
174
|
+
res = client.get_pricing()
|
|
175
|
+
elif cmd == "gold-price":
|
|
176
|
+
res = client.get_gold_price()
|
|
177
|
+
elif cmd == "demo-status":
|
|
178
|
+
res = client.get_demo_request(args.id)
|
|
179
|
+
else: # pragma: no cover - argparse rejects unknown commands
|
|
180
|
+
sys.stderr.write("ateliq: unknown command {}\n".format(cmd))
|
|
181
|
+
return 2
|
|
182
|
+
except AteliqError as e:
|
|
183
|
+
sys.stderr.write("ateliq: {}{}\n".format(e.message, " ({})".format(e.code) if e.code else ""))
|
|
184
|
+
return 1
|
|
185
|
+
except Exception as e: # network errors, timeouts
|
|
186
|
+
reason = getattr(e, "reason", None) or e
|
|
187
|
+
sys.stderr.write("ateliq: {}\n".format(reason))
|
|
188
|
+
return 1
|
|
189
|
+
|
|
190
|
+
if args.json or show is None:
|
|
191
|
+
out.write(json.dumps(res, indent=2, ensure_ascii=False) + "\n")
|
|
192
|
+
else:
|
|
193
|
+
show()
|
|
194
|
+
return 0
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def run() -> None:
|
|
198
|
+
"""Console-script entry point."""
|
|
199
|
+
sys.exit(main())
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__": # pragma: no cover
|
|
203
|
+
run()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
__all__: List[str] = ["main", "build_parser", "run"]
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Ateliq API client. https://ateliq.co/docs/api/
|
|
2
|
+
|
|
3
|
+
No key is needed. Standard library only.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from email.utils import parsedate_to_datetime
|
|
15
|
+
from typing import (
|
|
16
|
+
Any,
|
|
17
|
+
Callable,
|
|
18
|
+
Dict,
|
|
19
|
+
Iterator,
|
|
20
|
+
Literal,
|
|
21
|
+
Mapping,
|
|
22
|
+
NamedTuple,
|
|
23
|
+
Optional,
|
|
24
|
+
Tuple,
|
|
25
|
+
TypedDict,
|
|
26
|
+
Union,
|
|
27
|
+
cast,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
from ._version import __version__
|
|
31
|
+
|
|
32
|
+
LIVE_URL = "https://ateliq.co/api/v1"
|
|
33
|
+
SANDBOX_URL = "https://ateliq.co/api/sandbox/v1"
|
|
34
|
+
VERSION = __version__
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Ateliq",
|
|
38
|
+
"AteliqError",
|
|
39
|
+
"DemoRequestInput",
|
|
40
|
+
"HttpResponse",
|
|
41
|
+
"LIVE_URL",
|
|
42
|
+
"SANDBOX_URL",
|
|
43
|
+
"Transport",
|
|
44
|
+
"VERSION",
|
|
45
|
+
"urllib_transport",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
ApiObject = Dict[str, Any]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class HttpResponse(NamedTuple):
|
|
52
|
+
"""What a transport returns: the HTTP status, the response headers and the raw body."""
|
|
53
|
+
|
|
54
|
+
status: int
|
|
55
|
+
headers: Any # a dict or any mapping with .get(), such as http.client.HTTPMessage
|
|
56
|
+
body: bytes
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
Transport = Callable[
|
|
60
|
+
[str, str, Dict[str, str], Optional[bytes], Optional[float]],
|
|
61
|
+
Tuple[int, Any, bytes],
|
|
62
|
+
]
|
|
63
|
+
"""``transport(method, url, headers, body, timeout) -> (status, headers, body)``.
|
|
64
|
+
|
|
65
|
+
The default is :func:`urllib_transport`. Pass your own to the client for tests,
|
|
66
|
+
proxies or a different HTTP library. It must return non-2xx answers too, not raise.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _DemoRequestRequired(TypedDict):
|
|
71
|
+
name: str
|
|
72
|
+
email: str
|
|
73
|
+
brand: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class DemoRequestInput(_DemoRequestRequired, total=False):
|
|
77
|
+
role: Literal["Founder or CEO", "Head of retail", "Marketing", "Digital or CX", "Other"]
|
|
78
|
+
sells: Literal["Jewellery", "Fashion", "Both"]
|
|
79
|
+
stores: Literal["Online only", "1 to 4", "5 to 20", "21 to 100", "More than 100"]
|
|
80
|
+
message: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AteliqError(Exception):
|
|
84
|
+
"""A non-2xx answer from the Ateliq API (an RFC 9457 problem when the body is JSON)."""
|
|
85
|
+
|
|
86
|
+
status: int
|
|
87
|
+
code: Optional[str]
|
|
88
|
+
title: Optional[str]
|
|
89
|
+
detail: Optional[str]
|
|
90
|
+
errors: Any
|
|
91
|
+
retry_after: Optional[float]
|
|
92
|
+
problem: Any
|
|
93
|
+
|
|
94
|
+
def __init__(self, status: int, problem: Any = None) -> None:
|
|
95
|
+
p: Mapping[str, Any] = problem if isinstance(problem, dict) else {}
|
|
96
|
+
message = p.get("detail") or p.get("title") or "Ateliq API answered HTTP {}".format(status)
|
|
97
|
+
super().__init__(message)
|
|
98
|
+
self.message = str(message)
|
|
99
|
+
self.status = status
|
|
100
|
+
self.code = p.get("code") or None
|
|
101
|
+
self.title = p.get("title") or None
|
|
102
|
+
self.detail = p.get("detail") or None
|
|
103
|
+
self.errors = p.get("errors") or None
|
|
104
|
+
ra = p.get("retryAfter", p.get("retry_after"))
|
|
105
|
+
self.retry_after = _number(ra) if ra is not None else None
|
|
106
|
+
self.problem = problem
|
|
107
|
+
|
|
108
|
+
def __repr__(self) -> str:
|
|
109
|
+
return "AteliqError(status={!r}, code={!r}, message={!r})".format(self.status, self.code, self.message)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _number(value: Any) -> Optional[float]:
|
|
113
|
+
try:
|
|
114
|
+
n = float(value)
|
|
115
|
+
except (TypeError, ValueError):
|
|
116
|
+
return None
|
|
117
|
+
return int(n) if n.is_integer() else n
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _retry_after_seconds(header: str) -> Optional[float]:
|
|
121
|
+
n = _number(header)
|
|
122
|
+
if n is not None:
|
|
123
|
+
return n
|
|
124
|
+
try:
|
|
125
|
+
when = parsedate_to_datetime(header)
|
|
126
|
+
except (TypeError, ValueError, IndexError):
|
|
127
|
+
return None
|
|
128
|
+
if when is None: # pragma: no cover - older Pythons return None
|
|
129
|
+
return None
|
|
130
|
+
if when.tzinfo is None:
|
|
131
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
132
|
+
return max(0, int((when - datetime.now(timezone.utc)).total_seconds()))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _query(params: Mapping[str, Any]) -> str:
|
|
136
|
+
pairs = []
|
|
137
|
+
for k, v in params.items():
|
|
138
|
+
if v is None or v == "":
|
|
139
|
+
continue
|
|
140
|
+
if isinstance(v, bool):
|
|
141
|
+
v = "true" if v else "false"
|
|
142
|
+
pairs.append((k, str(v)))
|
|
143
|
+
s = urllib.parse.urlencode(pairs)
|
|
144
|
+
return "?" + s if s else ""
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _seg(s: Any) -> str:
|
|
148
|
+
# Same set of unescaped characters as JavaScript's encodeURIComponent.
|
|
149
|
+
return urllib.parse.quote(str(s), safe="-_.!~*'()")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _page_path(p: str) -> str:
|
|
153
|
+
return "/".join(_seg(part) for part in re.sub(r"^/+|/+$", "", str(p)).split("/"))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def urllib_transport(
|
|
157
|
+
method: str,
|
|
158
|
+
url: str,
|
|
159
|
+
headers: Dict[str, str],
|
|
160
|
+
body: Optional[bytes],
|
|
161
|
+
timeout: Optional[float],
|
|
162
|
+
) -> HttpResponse:
|
|
163
|
+
"""The default transport, built on :mod:`urllib.request`."""
|
|
164
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
165
|
+
try:
|
|
166
|
+
if timeout:
|
|
167
|
+
resp = urllib.request.urlopen(req, timeout=timeout)
|
|
168
|
+
else:
|
|
169
|
+
resp = urllib.request.urlopen(req)
|
|
170
|
+
with resp:
|
|
171
|
+
return HttpResponse(resp.status, resp.headers, resp.read())
|
|
172
|
+
except urllib.error.HTTPError as e:
|
|
173
|
+
try:
|
|
174
|
+
data = e.read()
|
|
175
|
+
finally:
|
|
176
|
+
e.close()
|
|
177
|
+
return HttpResponse(e.code, e.headers, data)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _header(headers: Any, name: str) -> Optional[str]:
|
|
181
|
+
if headers is None:
|
|
182
|
+
return None
|
|
183
|
+
getter = getattr(headers, "get", None)
|
|
184
|
+
if getter is not None:
|
|
185
|
+
v = getter(name)
|
|
186
|
+
if v is None and name.lower() != name:
|
|
187
|
+
v = getter(name.lower())
|
|
188
|
+
if v is not None:
|
|
189
|
+
return str(v)
|
|
190
|
+
try:
|
|
191
|
+
items = headers.items()
|
|
192
|
+
except AttributeError:
|
|
193
|
+
return None
|
|
194
|
+
for k, v in items:
|
|
195
|
+
if str(k).lower() == name.lower():
|
|
196
|
+
return str(v)
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class Ateliq:
|
|
201
|
+
"""The Ateliq API client.
|
|
202
|
+
|
|
203
|
+
>>> ateliq = Ateliq()
|
|
204
|
+
>>> ateliq.get_gold_price()["per_gram"]["22k"] # doctest: +SKIP
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
def __init__(
|
|
208
|
+
self,
|
|
209
|
+
*,
|
|
210
|
+
base_url: Optional[str] = None,
|
|
211
|
+
sandbox: bool = False,
|
|
212
|
+
timeout: Optional[float] = 30.0,
|
|
213
|
+
user_agent: Optional[str] = None,
|
|
214
|
+
transport: Optional[Transport] = None,
|
|
215
|
+
) -> None:
|
|
216
|
+
"""
|
|
217
|
+
:param base_url: Defaults to https://ateliq.co/api/v1, or the sandbox when ``sandbox`` is true.
|
|
218
|
+
:param sandbox: Use https://ateliq.co/api/sandbox/v1: demo requests are checked but nothing is kept or sent.
|
|
219
|
+
:param timeout: Seconds. Default 30. ``0`` or ``None`` turns the timeout off.
|
|
220
|
+
:param user_agent: Default ``ateliq-python/<version>``.
|
|
221
|
+
:param transport: ``transport(method, url, headers, body, timeout) -> (status, headers, body)``.
|
|
222
|
+
"""
|
|
223
|
+
self.base_url = (base_url or (SANDBOX_URL if sandbox else LIVE_URL)).rstrip("/")
|
|
224
|
+
self.timeout = timeout
|
|
225
|
+
self.user_agent = user_agent or "ateliq-python/{}".format(__version__)
|
|
226
|
+
self._transport: Transport = transport or urllib_transport
|
|
227
|
+
|
|
228
|
+
def request(
|
|
229
|
+
self,
|
|
230
|
+
method: str,
|
|
231
|
+
path: str,
|
|
232
|
+
*,
|
|
233
|
+
body: Any = None,
|
|
234
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
235
|
+
) -> Any:
|
|
236
|
+
"""Send one request and return the parsed JSON answer (or text, or ``None`` for an empty body)."""
|
|
237
|
+
h: Dict[str, str] = {"Accept": "application/json", "User-Agent": self.user_agent}
|
|
238
|
+
if headers:
|
|
239
|
+
h.update(headers)
|
|
240
|
+
data: Optional[bytes] = None
|
|
241
|
+
if body is not None:
|
|
242
|
+
h["Content-Type"] = "application/json"
|
|
243
|
+
data = json.dumps(body).encode("utf-8")
|
|
244
|
+
status, res_headers, raw = self._transport(method, self.base_url + path, h, data, self.timeout or None)
|
|
245
|
+
if isinstance(raw, str):
|
|
246
|
+
text = raw
|
|
247
|
+
else:
|
|
248
|
+
text = (raw or b"").decode("utf-8", errors="replace")
|
|
249
|
+
parsed: Any = None
|
|
250
|
+
if text:
|
|
251
|
+
try:
|
|
252
|
+
parsed = json.loads(text)
|
|
253
|
+
except ValueError:
|
|
254
|
+
parsed = text
|
|
255
|
+
if not 200 <= int(status) < 300:
|
|
256
|
+
err = AteliqError(int(status), parsed)
|
|
257
|
+
ra = _header(res_headers, "Retry-After")
|
|
258
|
+
if ra:
|
|
259
|
+
seconds = _retry_after_seconds(ra)
|
|
260
|
+
if seconds is not None:
|
|
261
|
+
err.retry_after = seconds
|
|
262
|
+
raise err
|
|
263
|
+
return parsed
|
|
264
|
+
|
|
265
|
+
def _get(self, path: str) -> ApiObject:
|
|
266
|
+
return cast(ApiObject, self.request("GET", path))
|
|
267
|
+
|
|
268
|
+
def index(self) -> ApiObject:
|
|
269
|
+
"""The API's index: its operations and links."""
|
|
270
|
+
return self._get("/")
|
|
271
|
+
|
|
272
|
+
def search(
|
|
273
|
+
self,
|
|
274
|
+
q: str,
|
|
275
|
+
section: Optional[str] = None,
|
|
276
|
+
limit: Optional[int] = None,
|
|
277
|
+
cursor: Optional[str] = None,
|
|
278
|
+
) -> ApiObject:
|
|
279
|
+
"""Search every page of ateliq.co."""
|
|
280
|
+
return self._get("/search" + _query({"q": q, "section": section, "limit": limit, "cursor": cursor}))
|
|
281
|
+
|
|
282
|
+
def list_pages(
|
|
283
|
+
self,
|
|
284
|
+
section: Optional[str] = None,
|
|
285
|
+
limit: Optional[int] = None,
|
|
286
|
+
cursor: Optional[str] = None,
|
|
287
|
+
) -> ApiObject:
|
|
288
|
+
"""List pages, optionally one section's."""
|
|
289
|
+
return self._get("/pages" + _query({"section": section, "limit": limit, "cursor": cursor}))
|
|
290
|
+
|
|
291
|
+
def get_page(self, path: str) -> ApiObject:
|
|
292
|
+
"""One page in full. ``path`` like ``"pricing"`` or ``"product/mirror"``."""
|
|
293
|
+
return self._get("/pages/" + _page_path(path))
|
|
294
|
+
|
|
295
|
+
def list_sections(self) -> ApiObject:
|
|
296
|
+
"""The site's sections."""
|
|
297
|
+
return self._get("/sections")
|
|
298
|
+
|
|
299
|
+
def list_products(self, limit: Optional[int] = None, cursor: Optional[str] = None) -> ApiObject:
|
|
300
|
+
"""Ateliq's products: the Mirror, Counter, Studio and the rest."""
|
|
301
|
+
return self._get("/products" + _query({"limit": limit, "cursor": cursor}))
|
|
302
|
+
|
|
303
|
+
def get_product(self, id: str) -> ApiObject:
|
|
304
|
+
"""One product by id, for example ``"mirror"``."""
|
|
305
|
+
return self._get("/products/" + _seg(id))
|
|
306
|
+
|
|
307
|
+
def get_pricing(self) -> ApiObject:
|
|
308
|
+
"""Current plans, hardware and credit prices, in US dollars."""
|
|
309
|
+
return self._get("/pricing")
|
|
310
|
+
|
|
311
|
+
def list_agents(self, limit: Optional[int] = None, cursor: Optional[str] = None) -> ApiObject:
|
|
312
|
+
"""The twelve AI agents."""
|
|
313
|
+
return self._get("/agents" + _query({"limit": limit, "cursor": cursor}))
|
|
314
|
+
|
|
315
|
+
def get_agent(self, id: str) -> ApiObject:
|
|
316
|
+
"""One agent by id."""
|
|
317
|
+
return self._get("/agents/" + _seg(id))
|
|
318
|
+
|
|
319
|
+
def get_gold_price(self) -> ApiObject:
|
|
320
|
+
"""The international gold spot price (not a retail rate)."""
|
|
321
|
+
return self._get("/gold-price")
|
|
322
|
+
|
|
323
|
+
def create_demo_request(
|
|
324
|
+
self,
|
|
325
|
+
input: Union[DemoRequestInput, Mapping[str, Any]],
|
|
326
|
+
idempotency_key: Optional[str] = None,
|
|
327
|
+
) -> ApiObject:
|
|
328
|
+
"""Request a demo for a person who asked for one. Try it with ``Ateliq(sandbox=True)`` first."""
|
|
329
|
+
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
|
|
330
|
+
return cast(ApiObject, self.request("POST", "/demo-requests", body=dict(input), headers=headers))
|
|
331
|
+
|
|
332
|
+
def get_demo_request(self, id: str) -> ApiObject:
|
|
333
|
+
"""A demo request's status."""
|
|
334
|
+
return self._get("/demo-requests/" + _seg(id))
|
|
335
|
+
|
|
336
|
+
def paginate(self, list_fn: Callable[..., Any], **opts: Any) -> Iterator[Any]:
|
|
337
|
+
"""Every item of a list, following ``pagination.next_cursor``.
|
|
338
|
+
|
|
339
|
+
>>> for agent in ateliq.paginate(ateliq.list_agents): # doctest: +SKIP
|
|
340
|
+
... print(agent["name"])
|
|
341
|
+
>>> for hit in ateliq.paginate(ateliq.search, q="try-on"): # doctest: +SKIP
|
|
342
|
+
... print(hit["url"])
|
|
343
|
+
"""
|
|
344
|
+
cursor = opts.pop("cursor", None)
|
|
345
|
+
while True:
|
|
346
|
+
res = list_fn(**dict(opts, cursor=cursor))
|
|
347
|
+
items = res.get("data") if isinstance(res, dict) else None
|
|
348
|
+
for item in items or []:
|
|
349
|
+
yield item
|
|
350
|
+
pagination = res.get("pagination") if isinstance(res, dict) else None
|
|
351
|
+
nxt = pagination.get("next_cursor") if isinstance(pagination, dict) and pagination.get("has_more") else None
|
|
352
|
+
if not nxt:
|
|
353
|
+
return
|
|
354
|
+
cursor = nxt
|
|
File without changes
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
|
|
10
|
+
|
|
11
|
+
import ateliq # noqa: E402
|
|
12
|
+
from ateliq import Ateliq, AteliqError, __version__ # noqa: E402
|
|
13
|
+
from ateliq.cli import main # noqa: E402
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Fake:
|
|
17
|
+
"""A transport that records calls and answers from a handler. No network."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, handler=None):
|
|
20
|
+
self.calls = []
|
|
21
|
+
self.handler = handler or (lambda call: {})
|
|
22
|
+
|
|
23
|
+
def __call__(self, method, url, headers, body, timeout):
|
|
24
|
+
call = {"method": method, "url": url, "headers": dict(headers), "body": body, "timeout": timeout}
|
|
25
|
+
self.calls.append(call)
|
|
26
|
+
r = self.handler(call) or {}
|
|
27
|
+
status = r.get("status", 200)
|
|
28
|
+
hdrs = r.get("headers", {})
|
|
29
|
+
if "raw" in r:
|
|
30
|
+
raw = r["raw"].encode("utf-8")
|
|
31
|
+
else:
|
|
32
|
+
raw = json.dumps(r.get("body", {})).encode("utf-8")
|
|
33
|
+
return status, hdrs, raw
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ClientTests(unittest.TestCase):
|
|
37
|
+
def test_version_exports(self):
|
|
38
|
+
self.assertEqual(__version__, "1.0.0")
|
|
39
|
+
self.assertEqual(ateliq.VERSION, "1.0.0")
|
|
40
|
+
self.assertTrue(issubclass(AteliqError, Exception))
|
|
41
|
+
|
|
42
|
+
def test_builds_urls_and_query_strings(self):
|
|
43
|
+
f = Fake(lambda c: {"body": {"data": []}})
|
|
44
|
+
c = Ateliq(transport=f)
|
|
45
|
+
c.search("try on", limit=2, section=None)
|
|
46
|
+
c.get_page("/product/mirror/")
|
|
47
|
+
c.get_product("a b")
|
|
48
|
+
c.list_pages(section="blog", cursor="")
|
|
49
|
+
c.get_agent("x/y?z")
|
|
50
|
+
c.index()
|
|
51
|
+
urls = [x["url"] for x in f.calls]
|
|
52
|
+
self.assertEqual(urls[0], "https://ateliq.co/api/v1/search?q=try+on&limit=2")
|
|
53
|
+
self.assertEqual(urls[1], "https://ateliq.co/api/v1/pages/product/mirror")
|
|
54
|
+
self.assertEqual(urls[2], "https://ateliq.co/api/v1/products/a%20b")
|
|
55
|
+
self.assertEqual(urls[3], "https://ateliq.co/api/v1/pages?section=blog")
|
|
56
|
+
self.assertEqual(urls[4], "https://ateliq.co/api/v1/agents/x%2Fy%3Fz")
|
|
57
|
+
self.assertEqual(urls[5], "https://ateliq.co/api/v1/")
|
|
58
|
+
self.assertTrue(all(x["method"] == "GET" and x["body"] is None for x in f.calls))
|
|
59
|
+
|
|
60
|
+
def test_every_method_hits_its_path(self):
|
|
61
|
+
f = Fake(lambda c: {"body": {}})
|
|
62
|
+
c = Ateliq(transport=f)
|
|
63
|
+
c.list_sections()
|
|
64
|
+
c.list_products(limit=5, cursor="c1")
|
|
65
|
+
c.get_pricing()
|
|
66
|
+
c.list_agents()
|
|
67
|
+
c.get_gold_price()
|
|
68
|
+
c.get_demo_request("d 1")
|
|
69
|
+
paths = [x["url"][len("https://ateliq.co/api/v1"):] for x in f.calls]
|
|
70
|
+
self.assertEqual(
|
|
71
|
+
paths,
|
|
72
|
+
["/sections", "/products?limit=5&cursor=c1", "/pricing", "/agents", "/gold-price", "/demo-requests/d%201"],
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def test_page_path_segments_are_encoded(self):
|
|
76
|
+
f = Fake()
|
|
77
|
+
Ateliq(transport=f).get_page("//blog/ünï code/a&b//")
|
|
78
|
+
self.assertEqual(f.calls[0]["url"], "https://ateliq.co/api/v1/pages/blog/%C3%BCn%C3%AF%20code/a%26b")
|
|
79
|
+
|
|
80
|
+
def test_headers_timeout_and_user_agent(self):
|
|
81
|
+
f = Fake()
|
|
82
|
+
Ateliq(transport=f).get_pricing()
|
|
83
|
+
h = f.calls[0]["headers"]
|
|
84
|
+
self.assertEqual(h["Accept"], "application/json")
|
|
85
|
+
self.assertEqual(h["User-Agent"], "ateliq-python/1.0.0")
|
|
86
|
+
self.assertNotIn("Content-Type", h)
|
|
87
|
+
self.assertEqual(f.calls[0]["timeout"], 30.0)
|
|
88
|
+
Ateliq(transport=f, timeout=0, user_agent="me/1").get_pricing()
|
|
89
|
+
self.assertIsNone(f.calls[1]["timeout"])
|
|
90
|
+
self.assertEqual(f.calls[1]["headers"]["User-Agent"], "me/1")
|
|
91
|
+
|
|
92
|
+
def test_sandbox_post_body_and_idempotency_key(self):
|
|
93
|
+
f = Fake(lambda c: {"status": 201, "body": {"id": "d1"}})
|
|
94
|
+
c = Ateliq(transport=f, sandbox=True)
|
|
95
|
+
r = c.create_demo_request({"name": "A", "email": "a@b.co", "brand": "B"}, idempotency_key="k1")
|
|
96
|
+
self.assertEqual(r["id"], "d1")
|
|
97
|
+
call = f.calls[0]
|
|
98
|
+
self.assertEqual(call["url"], ateliq.SANDBOX_URL + "/demo-requests")
|
|
99
|
+
self.assertEqual(call["url"], "https://ateliq.co/api/sandbox/v1/demo-requests")
|
|
100
|
+
self.assertEqual(call["method"], "POST")
|
|
101
|
+
self.assertEqual(call["headers"]["Idempotency-Key"], "k1")
|
|
102
|
+
self.assertEqual(call["headers"]["Content-Type"], "application/json")
|
|
103
|
+
self.assertEqual(json.loads(call["body"].decode("utf-8")), {"name": "A", "email": "a@b.co", "brand": "B"})
|
|
104
|
+
|
|
105
|
+
def test_no_idempotency_header_without_key(self):
|
|
106
|
+
f = Fake(lambda c: {"status": 201, "body": {"id": "d2"}})
|
|
107
|
+
Ateliq(transport=f, sandbox=True).create_demo_request({"name": "A", "email": "a@b.co", "brand": "B"})
|
|
108
|
+
self.assertNotIn("Idempotency-Key", f.calls[0]["headers"])
|
|
109
|
+
|
|
110
|
+
def test_base_url_wins_and_trailing_slash_dropped(self):
|
|
111
|
+
f = Fake()
|
|
112
|
+
Ateliq(transport=f, base_url="http://localhost:3000/api/v1///", sandbox=True).get_pricing()
|
|
113
|
+
self.assertEqual(f.calls[0]["url"], "http://localhost:3000/api/v1/pricing")
|
|
114
|
+
|
|
115
|
+
def test_problem_json_becomes_ateliq_error_with_retry_after_header(self):
|
|
116
|
+
f = Fake(
|
|
117
|
+
lambda c: {
|
|
118
|
+
"status": 429,
|
|
119
|
+
"body": {"title": "Too many", "code": "rate_limited", "detail": "Wait 10 seconds."},
|
|
120
|
+
"headers": {"Retry-After": "10"},
|
|
121
|
+
}
|
|
122
|
+
)
|
|
123
|
+
with self.assertRaises(AteliqError) as cm:
|
|
124
|
+
Ateliq(transport=f).get_pricing()
|
|
125
|
+
e = cm.exception
|
|
126
|
+
self.assertEqual(e.status, 429)
|
|
127
|
+
self.assertEqual(e.code, "rate_limited")
|
|
128
|
+
self.assertEqual(e.title, "Too many")
|
|
129
|
+
self.assertEqual(e.detail, "Wait 10 seconds.")
|
|
130
|
+
self.assertEqual(e.retry_after, 10)
|
|
131
|
+
self.assertEqual(str(e), "Wait 10 seconds.")
|
|
132
|
+
self.assertEqual(e.problem["code"], "rate_limited")
|
|
133
|
+
|
|
134
|
+
def test_retry_after_header_is_case_insensitive_and_body_value_used(self):
|
|
135
|
+
f = Fake(lambda c: {"status": 503, "body": {"title": "Busy", "retryAfter": 5}, "headers": {}})
|
|
136
|
+
with self.assertRaises(AteliqError) as cm:
|
|
137
|
+
Ateliq(transport=f).get_gold_price()
|
|
138
|
+
self.assertEqual(cm.exception.retry_after, 5)
|
|
139
|
+
self.assertEqual(str(cm.exception), "Busy")
|
|
140
|
+
f2 = Fake(lambda c: {"status": 429, "body": {}, "headers": {"retry-after": "3"}})
|
|
141
|
+
with self.assertRaises(AteliqError) as cm2:
|
|
142
|
+
Ateliq(transport=f2).get_gold_price()
|
|
143
|
+
self.assertEqual(cm2.exception.retry_after, 3)
|
|
144
|
+
|
|
145
|
+
def test_validation_errors_kept(self):
|
|
146
|
+
errs = [{"field": "email", "detail": "Give an email."}]
|
|
147
|
+
f = Fake(lambda c: {"status": 422, "body": {"title": "Invalid", "code": "invalid_request", "errors": errs}})
|
|
148
|
+
with self.assertRaises(AteliqError) as cm:
|
|
149
|
+
Ateliq(transport=f, sandbox=True).create_demo_request({"name": "A", "email": "", "brand": "B"})
|
|
150
|
+
self.assertEqual(cm.exception.errors, errs)
|
|
151
|
+
self.assertIsNone(cm.exception.retry_after)
|
|
152
|
+
|
|
153
|
+
def test_non_json_error_body_kept_as_text(self):
|
|
154
|
+
f = Fake(lambda c: {"status": 502, "raw": "<html>Bad gateway</html>"})
|
|
155
|
+
with self.assertRaises(AteliqError) as cm:
|
|
156
|
+
Ateliq(transport=f).get_pricing()
|
|
157
|
+
e = cm.exception
|
|
158
|
+
self.assertEqual(e.status, 502)
|
|
159
|
+
self.assertEqual(e.problem, "<html>Bad gateway</html>")
|
|
160
|
+
self.assertIsNone(e.code)
|
|
161
|
+
self.assertEqual(str(e), "Ateliq API answered HTTP 502")
|
|
162
|
+
|
|
163
|
+
def test_non_json_and_empty_success_bodies(self):
|
|
164
|
+
f = Fake(lambda c: {"raw": "plain text"})
|
|
165
|
+
self.assertEqual(Ateliq(transport=f).index(), "plain text")
|
|
166
|
+
f2 = Fake(lambda c: {"status": 204, "raw": ""})
|
|
167
|
+
self.assertIsNone(Ateliq(transport=f2).index())
|
|
168
|
+
|
|
169
|
+
def test_paginate_follows_next_cursor(self):
|
|
170
|
+
def handler(c):
|
|
171
|
+
if "cursor=c2" in c["url"]:
|
|
172
|
+
return {"body": {"data": [3], "pagination": {"has_more": False, "next_cursor": None}}}
|
|
173
|
+
return {"body": {"data": [1, 2], "pagination": {"has_more": True, "next_cursor": "c2"}}}
|
|
174
|
+
|
|
175
|
+
f = Fake(handler)
|
|
176
|
+
c = Ateliq(transport=f)
|
|
177
|
+
self.assertEqual(list(c.paginate(c.list_agents, limit=2)), [1, 2, 3])
|
|
178
|
+
self.assertEqual(
|
|
179
|
+
[x["url"] for x in f.calls],
|
|
180
|
+
["https://ateliq.co/api/v1/agents?limit=2", "https://ateliq.co/api/v1/agents?limit=2&cursor=c2"],
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def test_paginate_search_with_keyword_q_and_stops_without_has_more(self):
|
|
184
|
+
f = Fake(lambda c: {"body": {"data": ["a"], "pagination": {"has_more": False, "next_cursor": "ignored"}}})
|
|
185
|
+
c = Ateliq(transport=f)
|
|
186
|
+
self.assertEqual(list(c.paginate(c.search, q="mirror")), ["a"])
|
|
187
|
+
self.assertEqual(len(f.calls), 1)
|
|
188
|
+
self.assertEqual(f.calls[0]["url"], "https://ateliq.co/api/v1/search?q=mirror")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class CliTests(unittest.TestCase):
|
|
192
|
+
def run_cli(self, argv, handler):
|
|
193
|
+
f = Fake(handler)
|
|
194
|
+
out, err = io.StringIO(), io.StringIO()
|
|
195
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
196
|
+
code = main(argv, transport=f)
|
|
197
|
+
return code, out.getvalue(), err.getvalue(), f
|
|
198
|
+
|
|
199
|
+
def test_gold_price_json(self):
|
|
200
|
+
body = {"object": "gold_price", "currency": "INR", "per_gram": {"22k": 12345.6, "24k": 13468.0}}
|
|
201
|
+
code, out, err, f = self.run_cli(["gold-price", "--json"], lambda c: {"body": body})
|
|
202
|
+
self.assertEqual(code, 0)
|
|
203
|
+
self.assertEqual(json.loads(out), body)
|
|
204
|
+
self.assertEqual(f.calls[0]["url"], "https://ateliq.co/api/v1/gold-price")
|
|
205
|
+
self.assertTrue(f.calls[0]["headers"]["User-Agent"].startswith("ateliq-python-cli/"))
|
|
206
|
+
|
|
207
|
+
def test_sandbox_flag_before_command(self):
|
|
208
|
+
code, out, err, f = self.run_cli(["--sandbox", "--json", "pricing"], lambda c: {"body": {"plans": []}})
|
|
209
|
+
self.assertEqual(code, 0)
|
|
210
|
+
self.assertEqual(f.calls[0]["url"], "https://ateliq.co/api/sandbox/v1/pricing")
|
|
211
|
+
self.assertEqual(json.loads(out), {"plans": []})
|
|
212
|
+
|
|
213
|
+
def test_search_text_output_and_more_hint(self):
|
|
214
|
+
body = {
|
|
215
|
+
"data": [{"title": "Mirror", "url": "https://ateliq.co/product/mirror/", "snippet": "Try on\nlive"}],
|
|
216
|
+
"pagination": {"has_more": True, "next_cursor": "n1"},
|
|
217
|
+
}
|
|
218
|
+
code, out, err, f = self.run_cli(["search", "try", "on", "--limit", "1"], lambda c: {"body": body})
|
|
219
|
+
self.assertEqual(code, 0)
|
|
220
|
+
self.assertEqual(f.calls[0]["url"], "https://ateliq.co/api/v1/search?q=try+on&limit=1")
|
|
221
|
+
self.assertEqual(out, "Mirror\n https://ateliq.co/product/mirror/\n Try on live\n(more: --cursor n1)\n")
|
|
222
|
+
|
|
223
|
+
def test_error_exit_code(self):
|
|
224
|
+
code, out, err, f = self.run_cli(
|
|
225
|
+
["product", "nope"], lambda c: {"status": 404, "body": {"detail": "No such product.", "code": "not_found"}}
|
|
226
|
+
)
|
|
227
|
+
self.assertEqual(code, 1)
|
|
228
|
+
self.assertEqual(err, "ateliq: No such product. (not_found)\n")
|
|
229
|
+
|
|
230
|
+
def test_mcp_and_help_need_no_network(self):
|
|
231
|
+
code, out, err, f = self.run_cli(["mcp"], None)
|
|
232
|
+
self.assertEqual(code, 0)
|
|
233
|
+
self.assertIn("https://ateliq.co/api/mcp", out)
|
|
234
|
+
code, out, err, f = self.run_cli([], None)
|
|
235
|
+
self.assertEqual(code, 0)
|
|
236
|
+
self.assertTrue(re.search(r"gold-price", out))
|
|
237
|
+
self.assertEqual(f.calls, [])
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
if __name__ == "__main__":
|
|
241
|
+
unittest.main()
|