i2v-ai 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.
- i2v_ai-0.1.0/PKG-INFO +122 -0
- i2v_ai-0.1.0/README.md +103 -0
- i2v_ai-0.1.0/pyproject.toml +33 -0
- i2v_ai-0.1.0/setup.cfg +4 -0
- i2v_ai-0.1.0/src/i2v/__init__.py +25 -0
- i2v_ai-0.1.0/src/i2v/client.py +327 -0
- i2v_ai-0.1.0/src/i2v/errors.py +55 -0
- i2v_ai-0.1.0/src/i2v/webhook.py +92 -0
- i2v_ai-0.1.0/src/i2v_ai.egg-info/PKG-INFO +122 -0
- i2v_ai-0.1.0/src/i2v_ai.egg-info/SOURCES.txt +12 -0
- i2v_ai-0.1.0/src/i2v_ai.egg-info/dependency_links.txt +1 -0
- i2v_ai-0.1.0/src/i2v_ai.egg-info/top_level.txt +1 -0
- i2v_ai-0.1.0/tests/test_client.py +228 -0
- i2v_ai-0.1.0/tests/test_webhook.py +77 -0
i2v_ai-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: i2v-ai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Server-side Python client for the i2v.ai image and video API.
|
|
5
|
+
Author: i2v.ai
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://i2v.ai
|
|
8
|
+
Project-URL: Documentation, https://i2v.ai/docs
|
|
9
|
+
Project-URL: Source, https://github.com/i2v-ai/i2v-agent-tools
|
|
10
|
+
Keywords: i2v,ai-video,ai-image,media-api
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# i2v-ai Python SDK
|
|
21
|
+
|
|
22
|
+
Server-side Python client for the [i2v.ai](https://i2v.ai) image and video API. It mirrors the TypeScript SDK: quote before submitting, keep a stable idempotency key, and tell a pending submission apart from a definitive conflict.
|
|
23
|
+
|
|
24
|
+
- Python 3.10 or newer, no runtime dependencies.
|
|
25
|
+
- Covers model discovery, account balance and usage, quotes, uploads, task creation, polling, recovery, cancellation, and signed webhook verification.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install ./packages/python-sdk
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The package is not on PyPI yet; install it from this repository until it is.
|
|
34
|
+
|
|
35
|
+
## Quickstart
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from i2v import I2VClient
|
|
40
|
+
|
|
41
|
+
client = I2VClient(api_key=os.environ["I2V_API_KEY"])
|
|
42
|
+
|
|
43
|
+
models = client.list_models().data["data"]
|
|
44
|
+
print([m["id"] for m in models if m["mediaType"] == "image"][:5])
|
|
45
|
+
|
|
46
|
+
quote = client.quote("gpt-image-2", {"prompt": "A ceramic mug on an oak table"}).data
|
|
47
|
+
print(quote["maximum"]) # maximum USD reservation for these inputs
|
|
48
|
+
print(quote["expectedRevision"]) # agree to this revision when submitting
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`list_models` is public: it works without a key.
|
|
52
|
+
|
|
53
|
+
## Submit inside a budget
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
receipt = client.create_task(
|
|
57
|
+
"gpt-image-2",
|
|
58
|
+
{"prompt": "A ceramic mug on an oak table"},
|
|
59
|
+
max_cost_usd="0.20",
|
|
60
|
+
expected_revision=quote["expectedRevision"],
|
|
61
|
+
idempotency_key="order-1234-image",
|
|
62
|
+
).data
|
|
63
|
+
print(receipt["taskId"])
|
|
64
|
+
|
|
65
|
+
result = client.wait_for_task(receipt["taskId"], timeout=900).data
|
|
66
|
+
print(result["status"], result.get("result"))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`max_cost_usd` is a decimal string. If the quote exceeds it, the API rejects the request before a task exists.
|
|
70
|
+
|
|
71
|
+
## Recovery
|
|
72
|
+
|
|
73
|
+
A submission whose response was lost may still have been accepted. Look up the original receipt with the same key instead of sending a new request:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
try:
|
|
77
|
+
task = client.create_task(..., idempotency_key="order-1234-image")
|
|
78
|
+
except I2VSubmissionUnknownError as error:
|
|
79
|
+
receipt = client.recover_submission(error.idempotency_key).data
|
|
80
|
+
# receipt["status"]: accepted | pending | retryable | missing
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`I2VSubmissionUnknownError.cause` holds the original HTTP or network error, including `retry_after_ms` and `request_id` when the API sent them.
|
|
84
|
+
|
|
85
|
+
## Webhooks
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from i2v import verify_webhook
|
|
89
|
+
|
|
90
|
+
secrets = {"key_1": os.environ["I2V_WEBHOOK_SECRET"]}
|
|
91
|
+
|
|
92
|
+
verified = verify_webhook(
|
|
93
|
+
request.body, # exact raw bytes, before parsing
|
|
94
|
+
request.headers, # dict-like with the X-I2V-* headers
|
|
95
|
+
secrets.get,
|
|
96
|
+
max_age_seconds=300,
|
|
97
|
+
)
|
|
98
|
+
if verified is None:
|
|
99
|
+
raise PermissionError("untrusted delivery")
|
|
100
|
+
event = verified["body"] # eventId matches the header
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The signature covers the timestamp, a dot, and the raw body, and the event ID in the body must match the header.
|
|
104
|
+
|
|
105
|
+
## Errors
|
|
106
|
+
|
|
107
|
+
| Exception | Meaning |
|
|
108
|
+
| --- | --- |
|
|
109
|
+
| `I2VHttpError` | Non-2xx response. Carries `status`, `code`, `reason`, `request_id`, `retry_after_ms`. |
|
|
110
|
+
| `I2VSubmissionUnknownError` | The submission may be accepted (5xx, network failure, or HTTP 409 with `submission_pending`). Use `recover_submission`. |
|
|
111
|
+
| `I2VWaitTimeoutError` | The wait ended before the task reached a terminal state. |
|
|
112
|
+
| `I2VNetworkError` | No HTTP response. |
|
|
113
|
+
| `TypeError` / `ValueError` | Invalid local arguments, such as a non-HTTPS origin or a malformed budget. |
|
|
114
|
+
|
|
115
|
+
## Tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
cd packages/python-sdk
|
|
119
|
+
python -m unittest discover -s tests -v
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The tests run against a local HTTP server; they never call the real API and need no credentials.
|
i2v_ai-0.1.0/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# i2v-ai Python SDK
|
|
2
|
+
|
|
3
|
+
Server-side Python client for the [i2v.ai](https://i2v.ai) image and video API. It mirrors the TypeScript SDK: quote before submitting, keep a stable idempotency key, and tell a pending submission apart from a definitive conflict.
|
|
4
|
+
|
|
5
|
+
- Python 3.10 or newer, no runtime dependencies.
|
|
6
|
+
- Covers model discovery, account balance and usage, quotes, uploads, task creation, polling, recovery, cancellation, and signed webhook verification.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install ./packages/python-sdk
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The package is not on PyPI yet; install it from this repository until it is.
|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import os
|
|
20
|
+
from i2v import I2VClient
|
|
21
|
+
|
|
22
|
+
client = I2VClient(api_key=os.environ["I2V_API_KEY"])
|
|
23
|
+
|
|
24
|
+
models = client.list_models().data["data"]
|
|
25
|
+
print([m["id"] for m in models if m["mediaType"] == "image"][:5])
|
|
26
|
+
|
|
27
|
+
quote = client.quote("gpt-image-2", {"prompt": "A ceramic mug on an oak table"}).data
|
|
28
|
+
print(quote["maximum"]) # maximum USD reservation for these inputs
|
|
29
|
+
print(quote["expectedRevision"]) # agree to this revision when submitting
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`list_models` is public: it works without a key.
|
|
33
|
+
|
|
34
|
+
## Submit inside a budget
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
receipt = client.create_task(
|
|
38
|
+
"gpt-image-2",
|
|
39
|
+
{"prompt": "A ceramic mug on an oak table"},
|
|
40
|
+
max_cost_usd="0.20",
|
|
41
|
+
expected_revision=quote["expectedRevision"],
|
|
42
|
+
idempotency_key="order-1234-image",
|
|
43
|
+
).data
|
|
44
|
+
print(receipt["taskId"])
|
|
45
|
+
|
|
46
|
+
result = client.wait_for_task(receipt["taskId"], timeout=900).data
|
|
47
|
+
print(result["status"], result.get("result"))
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`max_cost_usd` is a decimal string. If the quote exceeds it, the API rejects the request before a task exists.
|
|
51
|
+
|
|
52
|
+
## Recovery
|
|
53
|
+
|
|
54
|
+
A submission whose response was lost may still have been accepted. Look up the original receipt with the same key instead of sending a new request:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
try:
|
|
58
|
+
task = client.create_task(..., idempotency_key="order-1234-image")
|
|
59
|
+
except I2VSubmissionUnknownError as error:
|
|
60
|
+
receipt = client.recover_submission(error.idempotency_key).data
|
|
61
|
+
# receipt["status"]: accepted | pending | retryable | missing
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`I2VSubmissionUnknownError.cause` holds the original HTTP or network error, including `retry_after_ms` and `request_id` when the API sent them.
|
|
65
|
+
|
|
66
|
+
## Webhooks
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from i2v import verify_webhook
|
|
70
|
+
|
|
71
|
+
secrets = {"key_1": os.environ["I2V_WEBHOOK_SECRET"]}
|
|
72
|
+
|
|
73
|
+
verified = verify_webhook(
|
|
74
|
+
request.body, # exact raw bytes, before parsing
|
|
75
|
+
request.headers, # dict-like with the X-I2V-* headers
|
|
76
|
+
secrets.get,
|
|
77
|
+
max_age_seconds=300,
|
|
78
|
+
)
|
|
79
|
+
if verified is None:
|
|
80
|
+
raise PermissionError("untrusted delivery")
|
|
81
|
+
event = verified["body"] # eventId matches the header
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The signature covers the timestamp, a dot, and the raw body, and the event ID in the body must match the header.
|
|
85
|
+
|
|
86
|
+
## Errors
|
|
87
|
+
|
|
88
|
+
| Exception | Meaning |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `I2VHttpError` | Non-2xx response. Carries `status`, `code`, `reason`, `request_id`, `retry_after_ms`. |
|
|
91
|
+
| `I2VSubmissionUnknownError` | The submission may be accepted (5xx, network failure, or HTTP 409 with `submission_pending`). Use `recover_submission`. |
|
|
92
|
+
| `I2VWaitTimeoutError` | The wait ended before the task reached a terminal state. |
|
|
93
|
+
| `I2VNetworkError` | No HTTP response. |
|
|
94
|
+
| `TypeError` / `ValueError` | Invalid local arguments, such as a non-HTTPS origin or a malformed budget. |
|
|
95
|
+
|
|
96
|
+
## Tests
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
cd packages/python-sdk
|
|
100
|
+
python -m unittest discover -s tests -v
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The tests run against a local HTTP server; they never call the real API and need no credentials.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "i2v-ai"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Server-side Python client for the i2v.ai image and video API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "i2v.ai" }]
|
|
13
|
+
keywords = ["i2v", "ai-video", "ai-image", "media-api"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.10",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
]
|
|
22
|
+
dependencies = []
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://i2v.ai"
|
|
26
|
+
Documentation = "https://i2v.ai/docs"
|
|
27
|
+
Source = "https://github.com/i2v-ai/i2v-agent-tools"
|
|
28
|
+
|
|
29
|
+
[tool.setuptools]
|
|
30
|
+
package-dir = { "" = "src" }
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
i2v_ai-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Server-side Python client for the i2v.ai image and video API."""
|
|
2
|
+
|
|
3
|
+
from .client import DEFAULT_BASE_URL, I2VClient, Result
|
|
4
|
+
from .errors import (
|
|
5
|
+
I2VError,
|
|
6
|
+
I2VHttpError,
|
|
7
|
+
I2VNetworkError,
|
|
8
|
+
I2VSubmissionUnknownError,
|
|
9
|
+
I2VWaitTimeoutError,
|
|
10
|
+
)
|
|
11
|
+
from .webhook import verify_webhook
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DEFAULT_BASE_URL",
|
|
15
|
+
"I2VClient",
|
|
16
|
+
"I2VError",
|
|
17
|
+
"I2VHttpError",
|
|
18
|
+
"I2VNetworkError",
|
|
19
|
+
"I2VSubmissionUnknownError",
|
|
20
|
+
"I2VWaitTimeoutError",
|
|
21
|
+
"Result",
|
|
22
|
+
"verify_webhook",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Server-side client for the i2v.ai image and video API.
|
|
2
|
+
|
|
3
|
+
The client mirrors the TypeScript SDK: quote before submitting, keep the
|
|
4
|
+
idempotency key stable, and distinguish a pending submission from a
|
|
5
|
+
definitive conflict.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.parse
|
|
15
|
+
import urllib.request
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from email.utils import parsedate_to_datetime
|
|
19
|
+
from typing import Any, Dict, Iterable, Mapping, Optional, Tuple, Union
|
|
20
|
+
|
|
21
|
+
from .errors import (
|
|
22
|
+
I2VError,
|
|
23
|
+
I2VHttpError,
|
|
24
|
+
I2VNetworkError,
|
|
25
|
+
I2VSubmissionUnknownError,
|
|
26
|
+
I2VWaitTimeoutError,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
DEFAULT_BASE_URL = "https://api.i2v.ai"
|
|
30
|
+
DEFAULT_TIMEOUT_SECONDS = 20.0
|
|
31
|
+
DEFAULT_WAIT_SECONDS = 900.0
|
|
32
|
+
USER_AGENT = "i2v-ai-python/0.1.0"
|
|
33
|
+
|
|
34
|
+
_IDEMPOTENCY_KEY = re.compile(r"^[\x21-\x7e]{1,200}$")
|
|
35
|
+
_USD_AMOUNT = re.compile(r"^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$")
|
|
36
|
+
_ERROR_IDENTIFIER = re.compile(r"^[a-zA-Z0-9_-]{1,100}$")
|
|
37
|
+
_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Result:
|
|
42
|
+
"""A successful API response with transport metadata."""
|
|
43
|
+
|
|
44
|
+
data: Any
|
|
45
|
+
request_id: Optional[str] = None
|
|
46
|
+
retry_after_ms: Optional[int] = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
50
|
+
"""Reject redirects so credentials never follow an unexpected location."""
|
|
51
|
+
|
|
52
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
|
|
53
|
+
raise urllib.error.HTTPError(newurl, code, msg, headers, fp)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _parse_retry_after(value: Optional[str]) -> Optional[int]:
|
|
57
|
+
if not value:
|
|
58
|
+
return None
|
|
59
|
+
value = value.strip()
|
|
60
|
+
if value.isdigit():
|
|
61
|
+
seconds = int(value)
|
|
62
|
+
return seconds * 1000 if seconds <= 2_147_483 else None
|
|
63
|
+
try:
|
|
64
|
+
when = parsedate_to_datetime(value)
|
|
65
|
+
except (TypeError, ValueError):
|
|
66
|
+
return None
|
|
67
|
+
if when.tzinfo is None:
|
|
68
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
69
|
+
return max(0, int((when - datetime.now(timezone.utc)).total_seconds() * 1000))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _error_identifiers(body: Any) -> Tuple[Optional[str], Optional[str]]:
|
|
73
|
+
if not isinstance(body, dict):
|
|
74
|
+
return None, None
|
|
75
|
+
detail = body.get("error")
|
|
76
|
+
nested = detail.get("code") if isinstance(detail, dict) else None
|
|
77
|
+
candidates = [nested, body.get("code"), body.get("reason")]
|
|
78
|
+
identifiers = [c for c in candidates if isinstance(c, str) and _ERROR_IDENTIFIER.match(c)]
|
|
79
|
+
code = identifiers[0] if identifiers else None
|
|
80
|
+
reason = body.get("reason") if isinstance(body.get("reason"), str) else None
|
|
81
|
+
return code, reason
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _require_idempotency_key(key: str) -> str:
|
|
85
|
+
if not isinstance(key, str) or not _IDEMPOTENCY_KEY.match(key):
|
|
86
|
+
raise TypeError(
|
|
87
|
+
"Use a stable idempotency key of up to 200 visible ASCII characters."
|
|
88
|
+
)
|
|
89
|
+
return key
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class I2VClient:
|
|
93
|
+
"""Minimal, dependency-free client for https://api.i2v.ai."""
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
api_key: Optional[str] = None,
|
|
98
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
99
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
100
|
+
) -> None:
|
|
101
|
+
parsed = urllib.parse.urlsplit(base_url)
|
|
102
|
+
is_loopback = parsed.hostname in _LOOPBACK_HOSTS
|
|
103
|
+
if parsed.scheme != "https" and not (is_loopback and parsed.scheme == "http"):
|
|
104
|
+
raise TypeError("base_url must be an HTTPS origin or a local HTTP test origin.")
|
|
105
|
+
if parsed.path not in ("", "/") or parsed.query or parsed.fragment or parsed.username:
|
|
106
|
+
raise TypeError("base_url must be an origin without a path, query or credentials.")
|
|
107
|
+
if not isinstance(timeout, (int, float)) or timeout <= 0:
|
|
108
|
+
raise ValueError("timeout must be a positive number of seconds.")
|
|
109
|
+
self.api_key = api_key
|
|
110
|
+
self.base_url = base_url.rstrip("/")
|
|
111
|
+
self.timeout = float(timeout)
|
|
112
|
+
self._opener = urllib.request.build_opener(_NoRedirect())
|
|
113
|
+
|
|
114
|
+
# -- transport ---------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def _request(
|
|
117
|
+
self,
|
|
118
|
+
path: str,
|
|
119
|
+
*,
|
|
120
|
+
method: str = "GET",
|
|
121
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
122
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
123
|
+
public: bool = False,
|
|
124
|
+
) -> Result:
|
|
125
|
+
url = self.base_url + path
|
|
126
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
127
|
+
request = urllib.request.Request(url, data=data, method=method)
|
|
128
|
+
request.add_header("Accept", "application/json")
|
|
129
|
+
request.add_header("User-Agent", USER_AGENT)
|
|
130
|
+
if not public:
|
|
131
|
+
if not self.api_key:
|
|
132
|
+
raise TypeError("An i2v.ai API key is required.")
|
|
133
|
+
request.add_header("Authorization", f"Bearer {self.api_key}")
|
|
134
|
+
if data is not None:
|
|
135
|
+
request.add_header("Content-Type", "application/json")
|
|
136
|
+
for name, value in (headers or {}).items():
|
|
137
|
+
request.add_header(name, value)
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
with self._opener.open(request, timeout=self.timeout) as response:
|
|
141
|
+
raw = response.read()
|
|
142
|
+
return Result(
|
|
143
|
+
data=json.loads(raw) if raw else None,
|
|
144
|
+
request_id=response.headers.get("X-Request-ID"),
|
|
145
|
+
retry_after_ms=_parse_retry_after(response.headers.get("Retry-After")),
|
|
146
|
+
)
|
|
147
|
+
except urllib.error.HTTPError as error:
|
|
148
|
+
raw = error.read()
|
|
149
|
+
parsed: Any = None
|
|
150
|
+
try:
|
|
151
|
+
parsed = json.loads(raw) if raw else None
|
|
152
|
+
except ValueError:
|
|
153
|
+
parsed = None
|
|
154
|
+
code, reason = _error_identifiers(parsed)
|
|
155
|
+
raise I2VHttpError(
|
|
156
|
+
status=error.code,
|
|
157
|
+
code=code,
|
|
158
|
+
request_id=error.headers.get("X-Request-ID") if error.headers else None,
|
|
159
|
+
retry_after_ms=_parse_retry_after(
|
|
160
|
+
error.headers.get("Retry-After") if error.headers else None
|
|
161
|
+
),
|
|
162
|
+
reason=reason,
|
|
163
|
+
body=parsed,
|
|
164
|
+
) from None
|
|
165
|
+
except urllib.error.URLError as error:
|
|
166
|
+
raise I2VNetworkError(f"The request to i2v.ai failed: {error.reason}") from error
|
|
167
|
+
|
|
168
|
+
# -- catalog -----------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def list_models(self) -> Result:
|
|
171
|
+
"""Read the public image and video model catalog."""
|
|
172
|
+
return self._request("/api/v1/generation-models", public=True)
|
|
173
|
+
|
|
174
|
+
def get_model(self, model: str) -> Optional[Dict[str, Any]]:
|
|
175
|
+
for item in self.list_models().data.get("data", []):
|
|
176
|
+
if item.get("id") == model:
|
|
177
|
+
return item
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
# -- generation --------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
def quote(self, model: str, inputs: Mapping[str, Any]) -> Result:
|
|
183
|
+
"""Quote exact inputs and return the maximum USD reservation."""
|
|
184
|
+
return self._request(
|
|
185
|
+
"/api/v1/jobs/quote", method="POST", body={"model": model, "inputs": dict(inputs)}
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def create_task(
|
|
189
|
+
self,
|
|
190
|
+
model: str,
|
|
191
|
+
inputs: Mapping[str, Any],
|
|
192
|
+
*,
|
|
193
|
+
max_cost_usd: str,
|
|
194
|
+
expected_revision: int,
|
|
195
|
+
idempotency_key: str,
|
|
196
|
+
callback_url: Optional[str] = None,
|
|
197
|
+
) -> Result:
|
|
198
|
+
"""Submit a paid task inside an explicit USD ceiling."""
|
|
199
|
+
_require_idempotency_key(idempotency_key)
|
|
200
|
+
if not isinstance(max_cost_usd, str) or not _USD_AMOUNT.match(max_cost_usd):
|
|
201
|
+
raise TypeError("Use a USD decimal string with at most eight decimal places.")
|
|
202
|
+
if not isinstance(expected_revision, int) or expected_revision < 0:
|
|
203
|
+
raise TypeError("Use the expectedRevision returned by the quote.")
|
|
204
|
+
payload: Dict[str, Any] = {
|
|
205
|
+
"model": model,
|
|
206
|
+
"inputs": dict(inputs),
|
|
207
|
+
"maxCostUsd": max_cost_usd,
|
|
208
|
+
"expectedRevision": expected_revision,
|
|
209
|
+
}
|
|
210
|
+
if callback_url:
|
|
211
|
+
payload["callBackUrl"] = callback_url
|
|
212
|
+
try:
|
|
213
|
+
result = self._request(
|
|
214
|
+
"/api/v1/jobs/createTask",
|
|
215
|
+
method="POST",
|
|
216
|
+
body=payload,
|
|
217
|
+
headers={"Idempotency-Key": idempotency_key},
|
|
218
|
+
)
|
|
219
|
+
except I2VHttpError as error:
|
|
220
|
+
definitive = error.status < 500 and not (
|
|
221
|
+
error.status == 409 and error.reason == "submission_pending"
|
|
222
|
+
)
|
|
223
|
+
if definitive:
|
|
224
|
+
raise
|
|
225
|
+
raise I2VSubmissionUnknownError(idempotency_key, error) from error
|
|
226
|
+
except I2VNetworkError as error:
|
|
227
|
+
raise I2VSubmissionUnknownError(idempotency_key, error) from error
|
|
228
|
+
task_id = (result.data or {}).get("taskId")
|
|
229
|
+
if not isinstance(task_id, str) or not task_id:
|
|
230
|
+
raise I2VError("The API returned an invalid task ID.")
|
|
231
|
+
return result
|
|
232
|
+
|
|
233
|
+
def recover_submission(self, idempotency_key: str) -> Result:
|
|
234
|
+
"""Look up the receipt of an original submission by its key."""
|
|
235
|
+
_require_idempotency_key(idempotency_key)
|
|
236
|
+
return self._request(
|
|
237
|
+
"/api/v1/jobs/submission",
|
|
238
|
+
method="POST",
|
|
239
|
+
body={},
|
|
240
|
+
headers={"Idempotency-Key": idempotency_key},
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def get_task(self, task_id: str) -> Result:
|
|
244
|
+
query = urllib.parse.urlencode({"taskId": task_id})
|
|
245
|
+
return self._request(f"/api/v1/jobs/recordInfo?{query}")
|
|
246
|
+
|
|
247
|
+
def cancel_task(self, task_id: str) -> Result:
|
|
248
|
+
return self._request(
|
|
249
|
+
"/api/v1/jobs/cancel", method="POST", body={"taskId": task_id}
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# -- account -----------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
def get_account(self) -> Result:
|
|
255
|
+
return self._request("/api/v1/account")
|
|
256
|
+
|
|
257
|
+
def get_usage(self, range: str = "30d") -> Result:
|
|
258
|
+
query = urllib.parse.urlencode({"range": range})
|
|
259
|
+
return self._request(f"/api/v1/account/usage?{query}")
|
|
260
|
+
|
|
261
|
+
# -- uploads -----------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
def upload_asset(
|
|
264
|
+
self, path: str, content_type: str = "application/octet-stream"
|
|
265
|
+
) -> Result:
|
|
266
|
+
"""Request a signed ticket, upload the file, and confirm it."""
|
|
267
|
+
import os
|
|
268
|
+
|
|
269
|
+
file_name = os.path.basename(path)
|
|
270
|
+
file_size = os.path.getsize(path)
|
|
271
|
+
ticket = self._request(
|
|
272
|
+
"/api/v1/assets",
|
|
273
|
+
method="POST",
|
|
274
|
+
body={"fileName": file_name, "fileSize": file_size, "contentType": content_type},
|
|
275
|
+
).data
|
|
276
|
+
upload_url = ticket.get("uploadUrl") if isinstance(ticket, dict) else None
|
|
277
|
+
if not isinstance(upload_url, str):
|
|
278
|
+
raise I2VError("The upload ticket is missing a storage URL.")
|
|
279
|
+
parsed = urllib.parse.urlsplit(upload_url)
|
|
280
|
+
loopback_storage = parsed.hostname in _LOOPBACK_HOSTS and parsed.scheme == "http"
|
|
281
|
+
if (parsed.scheme != "https" and not loopback_storage) or parsed.username or parsed.password:
|
|
282
|
+
raise TypeError("The upload ticket must contain an HTTPS storage URL.")
|
|
283
|
+
with open(path, "rb") as handle:
|
|
284
|
+
payload = handle.read()
|
|
285
|
+
put = urllib.request.Request(upload_url, data=payload, method="PUT")
|
|
286
|
+
put.add_header("Content-Type", ticket.get("contentType") or content_type)
|
|
287
|
+
try:
|
|
288
|
+
with self._opener.open(put, timeout=self.timeout):
|
|
289
|
+
pass
|
|
290
|
+
except urllib.error.HTTPError as error:
|
|
291
|
+
raise I2VHttpError(status=error.code, code="asset_upload_failed") from None
|
|
292
|
+
asset_id = urllib.parse.quote(str(ticket.get("assetId")), safe="")
|
|
293
|
+
return self._request(
|
|
294
|
+
f"/api/v1/assets/{asset_id}/complete", method="POST", body={}
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
# -- polling -----------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
def wait_for_task(
|
|
300
|
+
self,
|
|
301
|
+
task_id: str,
|
|
302
|
+
*,
|
|
303
|
+
timeout: float = DEFAULT_WAIT_SECONDS,
|
|
304
|
+
poll_interval: float = 2.0,
|
|
305
|
+
) -> Result:
|
|
306
|
+
"""Poll until the task succeeds or fails, honoring Retry-After."""
|
|
307
|
+
if timeout <= 0:
|
|
308
|
+
raise ValueError("timeout must be positive.")
|
|
309
|
+
deadline = time.monotonic() + timeout
|
|
310
|
+
delay = poll_interval
|
|
311
|
+
while True:
|
|
312
|
+
suggested = 0.0
|
|
313
|
+
try:
|
|
314
|
+
result = self.get_task(task_id)
|
|
315
|
+
task = result.data or {}
|
|
316
|
+
if task.get("status") in ("success", "fail"):
|
|
317
|
+
return result
|
|
318
|
+
lifecycle = task.get("lifecycle") or {}
|
|
319
|
+
suggested = float(lifecycle.get("pollAfterSeconds") or 0)
|
|
320
|
+
except I2VHttpError as error:
|
|
321
|
+
if error.status != 429 and error.status < 500:
|
|
322
|
+
raise
|
|
323
|
+
suggested = (error.retry_after_ms or 0) / 1000
|
|
324
|
+
if time.monotonic() + delay >= deadline:
|
|
325
|
+
raise I2VWaitTimeoutError(task_id)
|
|
326
|
+
time.sleep(max(delay, suggested))
|
|
327
|
+
delay = min(30.0, delay * 1.5)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Errors raised by the i2v.ai client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class I2VError(Exception):
|
|
9
|
+
"""Base class for every i2v.ai client error."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class I2VNetworkError(I2VError):
|
|
13
|
+
"""The request did not produce an HTTP response."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class I2VHttpError(I2VError):
|
|
17
|
+
"""The API answered with a non-2xx status."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
status: int,
|
|
22
|
+
code: Optional[str] = None,
|
|
23
|
+
request_id: Optional[str] = None,
|
|
24
|
+
retry_after_ms: Optional[int] = None,
|
|
25
|
+
reason: Optional[str] = None,
|
|
26
|
+
body: Any = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
suffix = f": {code}" if code else ""
|
|
29
|
+
super().__init__(f"i2v.ai request failed (HTTP {status}){suffix}")
|
|
30
|
+
self.status = status
|
|
31
|
+
self.code = code
|
|
32
|
+
self.request_id = request_id
|
|
33
|
+
self.retry_after_ms = retry_after_ms
|
|
34
|
+
self.reason = reason
|
|
35
|
+
self.body = body
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class I2VSubmissionUnknownError(I2VError):
|
|
39
|
+
"""The submission may have been accepted, but its result is unknown."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, idempotency_key: str, cause: Optional[BaseException] = None) -> None:
|
|
42
|
+
super().__init__(
|
|
43
|
+
"Submission could not be confirmed. Look up the original receipt with "
|
|
44
|
+
"the same idempotency key and credential."
|
|
45
|
+
)
|
|
46
|
+
self.idempotency_key = idempotency_key
|
|
47
|
+
self.cause = cause
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class I2VWaitTimeoutError(I2VError):
|
|
51
|
+
"""The wait ended before the task reached a terminal state."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, task_id: str) -> None:
|
|
54
|
+
super().__init__("The wait ended before the task reached a terminal state.")
|
|
55
|
+
self.task_id = task_id
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Verify signed i2v.ai webhook deliveries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Callable, Mapping, Optional, Union
|
|
11
|
+
|
|
12
|
+
_SIGNATURE = re.compile(r"^v1=([a-f0-9]{64})$")
|
|
13
|
+
_TIMESTAMP = re.compile(r"^[0-9]{1,13}$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _header(headers: Union[Mapping[str, str], Any], name: str) -> Optional[str]:
|
|
17
|
+
if headers is None:
|
|
18
|
+
return None
|
|
19
|
+
getter = getattr(headers, "get", None)
|
|
20
|
+
if callable(getter):
|
|
21
|
+
value = getter(name)
|
|
22
|
+
if value is not None:
|
|
23
|
+
return str(value)
|
|
24
|
+
lowered = name.lower()
|
|
25
|
+
try:
|
|
26
|
+
for key, candidate in dict(headers).items(): # type: ignore[arg-type]
|
|
27
|
+
if str(key).lower() == lowered:
|
|
28
|
+
return str(candidate)
|
|
29
|
+
except (TypeError, ValueError):
|
|
30
|
+
return None
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _clock(now: Optional[float]) -> int:
|
|
35
|
+
if now is None:
|
|
36
|
+
return int(time.time())
|
|
37
|
+
return int(now / 1000) if now > 10_000_000_000 else int(now)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def verify_webhook(
|
|
41
|
+
raw_body: Union[str, bytes],
|
|
42
|
+
headers: Union[Mapping[str, str], Any],
|
|
43
|
+
get_secret: Callable[[str], Optional[Union[str, bytes]]],
|
|
44
|
+
*,
|
|
45
|
+
now: Optional[float] = None,
|
|
46
|
+
max_age_seconds: int = 300,
|
|
47
|
+
) -> Optional[dict]:
|
|
48
|
+
"""Return the verified event, or None when the delivery is not trusted.
|
|
49
|
+
|
|
50
|
+
Pass the exact bytes received. The signature covers the timestamp, a
|
|
51
|
+
literal dot, and those bytes.
|
|
52
|
+
"""
|
|
53
|
+
event_id = _header(headers, "X-I2V-Event-ID")
|
|
54
|
+
key_id = _header(headers, "X-I2V-Key-ID")
|
|
55
|
+
timestamp_header = _header(headers, "X-I2V-Timestamp")
|
|
56
|
+
signature = _header(headers, "X-I2V-Signature")
|
|
57
|
+
if not event_id or not key_id or not timestamp_header or not signature:
|
|
58
|
+
return None
|
|
59
|
+
if not _TIMESTAMP.match(timestamp_header):
|
|
60
|
+
return None
|
|
61
|
+
match = _SIGNATURE.match(signature)
|
|
62
|
+
if not match:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
timestamp = int(timestamp_header)
|
|
66
|
+
if abs(_clock(now) - timestamp) > max_age_seconds:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
secret = get_secret(key_id)
|
|
70
|
+
if not secret:
|
|
71
|
+
return None
|
|
72
|
+
secret_bytes = secret.encode("utf-8") if isinstance(secret, str) else secret
|
|
73
|
+
body_bytes = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
|
|
74
|
+
expected = hmac.new(secret_bytes, digestmod=hashlib.sha256)
|
|
75
|
+
expected.update(timestamp_header.encode("utf-8"))
|
|
76
|
+
expected.update(b".")
|
|
77
|
+
expected.update(body_bytes)
|
|
78
|
+
if not hmac.compare_digest(expected.hexdigest(), match.group(1)):
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
body = json.loads(body_bytes)
|
|
83
|
+
except ValueError:
|
|
84
|
+
return None
|
|
85
|
+
if not isinstance(body, dict) or body.get("eventId") != event_id:
|
|
86
|
+
return None
|
|
87
|
+
return {
|
|
88
|
+
"eventId": event_id,
|
|
89
|
+
"keyId": key_id,
|
|
90
|
+
"timestamp": timestamp,
|
|
91
|
+
"body": body,
|
|
92
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: i2v-ai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Server-side Python client for the i2v.ai image and video API.
|
|
5
|
+
Author: i2v.ai
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://i2v.ai
|
|
8
|
+
Project-URL: Documentation, https://i2v.ai/docs
|
|
9
|
+
Project-URL: Source, https://github.com/i2v-ai/i2v-agent-tools
|
|
10
|
+
Keywords: i2v,ai-video,ai-image,media-api
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# i2v-ai Python SDK
|
|
21
|
+
|
|
22
|
+
Server-side Python client for the [i2v.ai](https://i2v.ai) image and video API. It mirrors the TypeScript SDK: quote before submitting, keep a stable idempotency key, and tell a pending submission apart from a definitive conflict.
|
|
23
|
+
|
|
24
|
+
- Python 3.10 or newer, no runtime dependencies.
|
|
25
|
+
- Covers model discovery, account balance and usage, quotes, uploads, task creation, polling, recovery, cancellation, and signed webhook verification.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install ./packages/python-sdk
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The package is not on PyPI yet; install it from this repository until it is.
|
|
34
|
+
|
|
35
|
+
## Quickstart
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from i2v import I2VClient
|
|
40
|
+
|
|
41
|
+
client = I2VClient(api_key=os.environ["I2V_API_KEY"])
|
|
42
|
+
|
|
43
|
+
models = client.list_models().data["data"]
|
|
44
|
+
print([m["id"] for m in models if m["mediaType"] == "image"][:5])
|
|
45
|
+
|
|
46
|
+
quote = client.quote("gpt-image-2", {"prompt": "A ceramic mug on an oak table"}).data
|
|
47
|
+
print(quote["maximum"]) # maximum USD reservation for these inputs
|
|
48
|
+
print(quote["expectedRevision"]) # agree to this revision when submitting
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`list_models` is public: it works without a key.
|
|
52
|
+
|
|
53
|
+
## Submit inside a budget
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
receipt = client.create_task(
|
|
57
|
+
"gpt-image-2",
|
|
58
|
+
{"prompt": "A ceramic mug on an oak table"},
|
|
59
|
+
max_cost_usd="0.20",
|
|
60
|
+
expected_revision=quote["expectedRevision"],
|
|
61
|
+
idempotency_key="order-1234-image",
|
|
62
|
+
).data
|
|
63
|
+
print(receipt["taskId"])
|
|
64
|
+
|
|
65
|
+
result = client.wait_for_task(receipt["taskId"], timeout=900).data
|
|
66
|
+
print(result["status"], result.get("result"))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`max_cost_usd` is a decimal string. If the quote exceeds it, the API rejects the request before a task exists.
|
|
70
|
+
|
|
71
|
+
## Recovery
|
|
72
|
+
|
|
73
|
+
A submission whose response was lost may still have been accepted. Look up the original receipt with the same key instead of sending a new request:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
try:
|
|
77
|
+
task = client.create_task(..., idempotency_key="order-1234-image")
|
|
78
|
+
except I2VSubmissionUnknownError as error:
|
|
79
|
+
receipt = client.recover_submission(error.idempotency_key).data
|
|
80
|
+
# receipt["status"]: accepted | pending | retryable | missing
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`I2VSubmissionUnknownError.cause` holds the original HTTP or network error, including `retry_after_ms` and `request_id` when the API sent them.
|
|
84
|
+
|
|
85
|
+
## Webhooks
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from i2v import verify_webhook
|
|
89
|
+
|
|
90
|
+
secrets = {"key_1": os.environ["I2V_WEBHOOK_SECRET"]}
|
|
91
|
+
|
|
92
|
+
verified = verify_webhook(
|
|
93
|
+
request.body, # exact raw bytes, before parsing
|
|
94
|
+
request.headers, # dict-like with the X-I2V-* headers
|
|
95
|
+
secrets.get,
|
|
96
|
+
max_age_seconds=300,
|
|
97
|
+
)
|
|
98
|
+
if verified is None:
|
|
99
|
+
raise PermissionError("untrusted delivery")
|
|
100
|
+
event = verified["body"] # eventId matches the header
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The signature covers the timestamp, a dot, and the raw body, and the event ID in the body must match the header.
|
|
104
|
+
|
|
105
|
+
## Errors
|
|
106
|
+
|
|
107
|
+
| Exception | Meaning |
|
|
108
|
+
| --- | --- |
|
|
109
|
+
| `I2VHttpError` | Non-2xx response. Carries `status`, `code`, `reason`, `request_id`, `retry_after_ms`. |
|
|
110
|
+
| `I2VSubmissionUnknownError` | The submission may be accepted (5xx, network failure, or HTTP 409 with `submission_pending`). Use `recover_submission`. |
|
|
111
|
+
| `I2VWaitTimeoutError` | The wait ended before the task reached a terminal state. |
|
|
112
|
+
| `I2VNetworkError` | No HTTP response. |
|
|
113
|
+
| `TypeError` / `ValueError` | Invalid local arguments, such as a non-HTTPS origin or a malformed budget. |
|
|
114
|
+
|
|
115
|
+
## Tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
cd packages/python-sdk
|
|
119
|
+
python -m unittest discover -s tests -v
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The tests run against a local HTTP server; they never call the real API and need no credentials.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/i2v/__init__.py
|
|
4
|
+
src/i2v/client.py
|
|
5
|
+
src/i2v/errors.py
|
|
6
|
+
src/i2v/webhook.py
|
|
7
|
+
src/i2v_ai.egg-info/PKG-INFO
|
|
8
|
+
src/i2v_ai.egg-info/SOURCES.txt
|
|
9
|
+
src/i2v_ai.egg-info/dependency_links.txt
|
|
10
|
+
src/i2v_ai.egg-info/top_level.txt
|
|
11
|
+
tests/test_client.py
|
|
12
|
+
tests/test_webhook.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
i2v
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Tests for the i2v.ai Python client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import threading
|
|
9
|
+
import unittest
|
|
10
|
+
import urllib.parse
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
16
|
+
|
|
17
|
+
from i2v import ( # noqa: E402
|
|
18
|
+
I2VClient,
|
|
19
|
+
I2VHttpError,
|
|
20
|
+
I2VSubmissionUnknownError,
|
|
21
|
+
I2VWaitTimeoutError,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Server:
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
self.routes = {}
|
|
28
|
+
self.requests = []
|
|
29
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
|
|
30
|
+
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
|
31
|
+
|
|
32
|
+
def __enter__(self):
|
|
33
|
+
self.thread.start()
|
|
34
|
+
return self
|
|
35
|
+
|
|
36
|
+
def __exit__(self, *exc):
|
|
37
|
+
self.server.shutdown()
|
|
38
|
+
self.server.server_close()
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def base_url(self) -> str:
|
|
42
|
+
host, port = self.server.server_address[:2]
|
|
43
|
+
return f"http://{host}:{port}"
|
|
44
|
+
|
|
45
|
+
def _handler(self):
|
|
46
|
+
outer = self
|
|
47
|
+
|
|
48
|
+
class Handler(BaseHTTPRequestHandler):
|
|
49
|
+
def log_message(self, *args): # silence test output
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
def _handle(self):
|
|
53
|
+
parsed = urllib.parse.urlsplit(self.path)
|
|
54
|
+
length = int(self.headers.get("content-length") or 0)
|
|
55
|
+
body = self.rfile.read(length) if length else b""
|
|
56
|
+
outer.requests.append(
|
|
57
|
+
{
|
|
58
|
+
"method": self.command,
|
|
59
|
+
"path": parsed.path,
|
|
60
|
+
"query": urllib.parse.parse_qs(parsed.query),
|
|
61
|
+
"headers": {k.lower(): v for k, v in self.headers.items()},
|
|
62
|
+
"body": body,
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
route = outer.routes.get((self.command, parsed.path))
|
|
66
|
+
if route is None:
|
|
67
|
+
self.send_response(404)
|
|
68
|
+
self.end_headers()
|
|
69
|
+
return
|
|
70
|
+
status, payload = route
|
|
71
|
+
raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
|
|
72
|
+
self.send_response(status)
|
|
73
|
+
self.send_header("Content-Type", "application/json")
|
|
74
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
75
|
+
self.end_headers()
|
|
76
|
+
self.wfile.write(raw)
|
|
77
|
+
|
|
78
|
+
do_GET = _handle
|
|
79
|
+
do_POST = _handle
|
|
80
|
+
do_PUT = _handle
|
|
81
|
+
|
|
82
|
+
return Handler
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ClientTests(unittest.TestCase):
|
|
86
|
+
def test_list_models_is_public(self):
|
|
87
|
+
with _Server() as server:
|
|
88
|
+
server.routes[("GET", "/api/v1/generation-models")] = (
|
|
89
|
+
200,
|
|
90
|
+
{"data": [{"id": "gpt-image-2", "mediaType": "image"}]},
|
|
91
|
+
)
|
|
92
|
+
client = I2VClient(base_url=server.base_url)
|
|
93
|
+
result = client.list_models()
|
|
94
|
+
self.assertEqual(result.data["data"][0]["id"], "gpt-image-2")
|
|
95
|
+
self.assertNotIn("authorization", server.requests[0]["headers"])
|
|
96
|
+
|
|
97
|
+
def test_quote_sends_key_and_inputs(self):
|
|
98
|
+
with _Server() as server:
|
|
99
|
+
server.routes[("POST", "/api/v1/jobs/quote")] = (
|
|
100
|
+
200,
|
|
101
|
+
{"maximum": {"currency": "USD", "amount": "0.07000000"}, "expectedRevision": 1},
|
|
102
|
+
)
|
|
103
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
104
|
+
quote = client.quote("gpt-image-2", {"prompt": "a mug"})
|
|
105
|
+
self.assertEqual(quote.data["expectedRevision"], 1)
|
|
106
|
+
sent = server.requests[0]
|
|
107
|
+
self.assertEqual(sent["headers"]["authorization"], "Bearer key-123")
|
|
108
|
+
self.assertEqual(json.loads(sent["body"]), {"model": "gpt-image-2", "inputs": {"prompt": "a mug"}})
|
|
109
|
+
|
|
110
|
+
def test_create_task_pending_conflict_is_unknown(self):
|
|
111
|
+
with _Server() as server:
|
|
112
|
+
server.routes[("POST", "/api/v1/jobs/createTask")] = (
|
|
113
|
+
409,
|
|
114
|
+
{"reason": "submission_pending", "error": {"code": "submission_pending"}},
|
|
115
|
+
)
|
|
116
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
117
|
+
with self.assertRaises(I2VSubmissionUnknownError) as ctx:
|
|
118
|
+
client.create_task(
|
|
119
|
+
"gpt-image-2",
|
|
120
|
+
{"prompt": "a mug"},
|
|
121
|
+
max_cost_usd="0.2",
|
|
122
|
+
expected_revision=1,
|
|
123
|
+
idempotency_key="op-1",
|
|
124
|
+
)
|
|
125
|
+
self.assertEqual(ctx.exception.idempotency_key, "op-1")
|
|
126
|
+
self.assertEqual(ctx.exception.cause.status, 409)
|
|
127
|
+
self.assertEqual(ctx.exception.cause.reason, "submission_pending")
|
|
128
|
+
|
|
129
|
+
def test_create_task_server_error_is_unknown(self):
|
|
130
|
+
with _Server() as server:
|
|
131
|
+
server.routes[("POST", "/api/v1/jobs/createTask")] = (503, {"error": "unavailable"})
|
|
132
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
133
|
+
with self.assertRaises(I2VSubmissionUnknownError) as ctx:
|
|
134
|
+
client.create_task(
|
|
135
|
+
"gpt-image-2",
|
|
136
|
+
{"prompt": "a mug"},
|
|
137
|
+
max_cost_usd="0.2",
|
|
138
|
+
expected_revision=1,
|
|
139
|
+
idempotency_key="op-2",
|
|
140
|
+
)
|
|
141
|
+
self.assertEqual(ctx.exception.idempotency_key, "op-2")
|
|
142
|
+
|
|
143
|
+
def test_create_task_client_error_raises(self):
|
|
144
|
+
with _Server() as server:
|
|
145
|
+
server.routes[("POST", "/api/v1/jobs/createTask")] = (400, {"error": "invalid_params"})
|
|
146
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
147
|
+
with self.assertRaises(I2VHttpError):
|
|
148
|
+
client.create_task(
|
|
149
|
+
"gpt-image-2",
|
|
150
|
+
{"prompt": "a mug"},
|
|
151
|
+
max_cost_usd="0.2",
|
|
152
|
+
expected_revision=1,
|
|
153
|
+
idempotency_key="op-3",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def test_create_task_validates_inputs(self):
|
|
157
|
+
client = I2VClient(api_key="key-123")
|
|
158
|
+
with self.assertRaises(TypeError):
|
|
159
|
+
client.create_task("m", {}, max_cost_usd="1", expected_revision=0, idempotency_key="bad key")
|
|
160
|
+
with self.assertRaises(TypeError):
|
|
161
|
+
client.create_task("m", {}, max_cost_usd="1.123456789", expected_revision=0, idempotency_key="ok")
|
|
162
|
+
with self.assertRaises(TypeError):
|
|
163
|
+
client.create_task("m", {}, max_cost_usd="1", expected_revision=-1, idempotency_key="ok")
|
|
164
|
+
|
|
165
|
+
def test_get_task_builds_query(self):
|
|
166
|
+
with _Server() as server:
|
|
167
|
+
server.routes[("GET", "/api/v1/jobs/recordInfo")] = (200, {"status": "success"})
|
|
168
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
169
|
+
result = client.get_task("task-9")
|
|
170
|
+
self.assertEqual(result.data["status"], "success")
|
|
171
|
+
self.assertEqual(server.requests[0]["query"]["taskId"], ["task-9"])
|
|
172
|
+
|
|
173
|
+
def test_wait_for_task_returns_terminal_state(self):
|
|
174
|
+
with _Server() as server:
|
|
175
|
+
server.routes[("GET", "/api/v1/jobs/recordInfo")] = (200, {"status": "success"})
|
|
176
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
177
|
+
result = client.wait_for_task("task-1", timeout=5)
|
|
178
|
+
self.assertEqual(result.data["status"], "success")
|
|
179
|
+
|
|
180
|
+
def test_wait_for_task_times_out(self):
|
|
181
|
+
with _Server() as server:
|
|
182
|
+
server.routes[("GET", "/api/v1/jobs/recordInfo")] = (200, {"status": "processing"})
|
|
183
|
+
client = I2VClient(api_key="key-123", base_url=server.base_url)
|
|
184
|
+
with self.assertRaises(I2VWaitTimeoutError):
|
|
185
|
+
client.wait_for_task("task-2", timeout=0.4, poll_interval=0.1)
|
|
186
|
+
|
|
187
|
+
def test_upload_asset_flow(self):
|
|
188
|
+
with _Server() as storage, _Server() as api:
|
|
189
|
+
api.routes[("POST", "/api/v1/assets")] = (
|
|
190
|
+
200,
|
|
191
|
+
{
|
|
192
|
+
"assetId": "asset-1",
|
|
193
|
+
"uploadUrl": storage.base_url + "/put/asset-1",
|
|
194
|
+
"contentType": "image/png",
|
|
195
|
+
},
|
|
196
|
+
)
|
|
197
|
+
api.routes[("POST", "/api/v1/assets/asset-1/complete")] = (
|
|
198
|
+
200,
|
|
199
|
+
{"assetId": "asset-1", "url": "https://cdn.example/asset-1.png"},
|
|
200
|
+
)
|
|
201
|
+
storage.routes[("PUT", "/put/asset-1")] = (200, b"")
|
|
202
|
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as handle:
|
|
203
|
+
handle.write(b"png-bytes")
|
|
204
|
+
path = handle.name
|
|
205
|
+
try:
|
|
206
|
+
client = I2VClient(api_key="key-123", base_url=api.base_url)
|
|
207
|
+
completed = client.upload_asset(path, content_type="image/png")
|
|
208
|
+
finally:
|
|
209
|
+
os.unlink(path)
|
|
210
|
+
self.assertEqual(completed.data["url"], "https://cdn.example/asset-1.png")
|
|
211
|
+
put = storage.requests[0]
|
|
212
|
+
self.assertEqual(put["body"], b"png-bytes")
|
|
213
|
+
self.assertEqual(put["headers"]["content-type"], "image/png")
|
|
214
|
+
|
|
215
|
+
def test_rejects_insecure_base_url(self):
|
|
216
|
+
with self.assertRaises(TypeError):
|
|
217
|
+
I2VClient(base_url="http://api.i2v.ai")
|
|
218
|
+
with self.assertRaises(TypeError):
|
|
219
|
+
I2VClient(base_url="https://api.i2v.ai/v1")
|
|
220
|
+
|
|
221
|
+
def test_requires_key_for_private_routes(self):
|
|
222
|
+
client = I2VClient()
|
|
223
|
+
with self.assertRaises(TypeError):
|
|
224
|
+
client.get_account()
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
if __name__ == "__main__":
|
|
228
|
+
unittest.main()
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Tests for webhook verification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import unittest
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
13
|
+
|
|
14
|
+
from i2v import verify_webhook # noqa: E402
|
|
15
|
+
|
|
16
|
+
SECRET = b"whsec_test"
|
|
17
|
+
KEY_ID = "key_1"
|
|
18
|
+
EVENT = {"eventId": "evt_1", "type": "task.completed", "data": {"taskId": "task-1"}}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _sign(raw: bytes, timestamp: int, secret: bytes = SECRET) -> str:
|
|
22
|
+
digest = hmac.new(secret, digestmod=hashlib.sha256)
|
|
23
|
+
digest.update(str(timestamp).encode())
|
|
24
|
+
digest.update(b".")
|
|
25
|
+
digest.update(raw)
|
|
26
|
+
return "v1=" + digest.hexdigest()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _headers(raw: bytes, timestamp: int, signature: str | None = None) -> dict:
|
|
30
|
+
return {
|
|
31
|
+
"X-I2V-Event-ID": EVENT["eventId"],
|
|
32
|
+
"X-I2V-Key-ID": KEY_ID,
|
|
33
|
+
"X-I2V-Timestamp": str(timestamp),
|
|
34
|
+
"X-I2V-Signature": signature if signature is not None else _sign(raw, timestamp),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class WebhookTests(unittest.TestCase):
|
|
39
|
+
def setUp(self) -> None:
|
|
40
|
+
self.raw = json.dumps(EVENT).encode()
|
|
41
|
+
self.now = 1_800_000_000_000
|
|
42
|
+
|
|
43
|
+
def test_valid_delivery(self):
|
|
44
|
+
verified = verify_webhook(
|
|
45
|
+
self.raw, _headers(self.raw, self.now // 1000), lambda key: SECRET, now=self.now
|
|
46
|
+
)
|
|
47
|
+
self.assertIsNotNone(verified)
|
|
48
|
+
self.assertEqual(verified["eventId"], "evt_1")
|
|
49
|
+
self.assertEqual(verified["body"]["type"], "task.completed")
|
|
50
|
+
|
|
51
|
+
def test_tampered_body_is_rejected(self):
|
|
52
|
+
headers = _headers(self.raw, self.now // 1000)
|
|
53
|
+
tampered = self.raw.replace(b"task-1", b"task-2")
|
|
54
|
+
self.assertIsNone(verify_webhook(tampered, headers, lambda key: SECRET, now=self.now))
|
|
55
|
+
|
|
56
|
+
def test_stale_timestamp_is_rejected(self):
|
|
57
|
+
old = self.now // 1000 - 3_600
|
|
58
|
+
headers = _headers(self.raw, old)
|
|
59
|
+
self.assertIsNone(verify_webhook(self.raw, headers, lambda key: SECRET, now=self.now))
|
|
60
|
+
|
|
61
|
+
def test_unknown_key_is_rejected(self):
|
|
62
|
+
headers = _headers(self.raw, self.now // 1000)
|
|
63
|
+
self.assertIsNone(verify_webhook(self.raw, headers, lambda key: None, now=self.now))
|
|
64
|
+
|
|
65
|
+
def test_event_id_mismatch_is_rejected(self):
|
|
66
|
+
body = dict(EVENT)
|
|
67
|
+
body["eventId"] = "evt_other"
|
|
68
|
+
raw = json.dumps(body).encode()
|
|
69
|
+
headers = _headers(raw, self.now // 1000)
|
|
70
|
+
self.assertIsNone(verify_webhook(raw, headers, lambda key: SECRET, now=self.now))
|
|
71
|
+
|
|
72
|
+
def test_malformed_headers_are_rejected(self):
|
|
73
|
+
self.assertIsNone(verify_webhook(self.raw, {}, lambda key: SECRET, now=self.now))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
unittest.main()
|