langchain-treza 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ name: Publish to PyPI
2
+
3
+ # Runs when a GitHub release is published, or by hand from the Actions tab.
4
+ # Uses PyPI Trusted Publishing (OIDC): no API token is stored anywhere.
5
+ on:
6
+ release:
7
+ types: [published]
8
+ workflow_dispatch:
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ jobs:
14
+ test:
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+ - run: pip install -e . pytest langchain-tests
22
+ - run: pytest -q
23
+
24
+ publish:
25
+ needs: test
26
+ runs-on: ubuntu-latest
27
+ if: ${{ github.repository_owner == 'treza-labs' }}
28
+ environment: pypi
29
+ permissions:
30
+ id-token: write
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+ - uses: actions/setup-python@v5
34
+ with:
35
+ python-version: "3.12"
36
+ - run: pip install build
37
+ - run: python -m build
38
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ dist/
6
+ .env
7
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Treza Labs, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-treza
3
+ Version: 0.1.0
4
+ Summary: Treza tools for LangChain: generate AI pictures and videos and run Treza pipelines, with a price cap on every render.
5
+ Project-URL: Homepage, https://www.trezalabs.com
6
+ Project-URL: Repository, https://github.com/treza-labs/langchain-treza
7
+ Project-URL: Issues, https://github.com/treza-labs/langchain-treza/issues
8
+ Author-email: "Treza Labs, Inc." <hello@trezalabs.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai video,image generation,langchain,tools,treza,video generation
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: langchain-core<2,>=0.3.0
17
+ Requires-Dist: requests<3,>=2.31
18
+ Description-Content-Type: text/markdown
19
+
20
+ # langchain-treza
21
+
22
+ [Treza](https://www.trezalabs.com) tools for LangChain and LangGraph. An agent can generate AI pictures and video clips and run your saved Treza pipelines. Treza prices every render first, and a `max_cost_usd` you set stops any render that costs more, with nothing spent.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pip install -U langchain-treza
28
+ ```
29
+
30
+ Create a Treza account at https://www.trezalabs.com, add credits, and make an API key at https://www.trezalabs.com/platform/api-keys with the `pipelines:read`, `pipelines:write` and `pipelines:run` permissions. Then:
31
+
32
+ ```bash
33
+ export TREZA_API_KEY="treza_live_..."
34
+ ```
35
+
36
+ The package is free. Renders are paid from your prepaid Treza credits; there is no subscription.
37
+
38
+ ## Tools
39
+
40
+ | Tool | Name the model sees | What it does | Cost |
41
+ | --- | --- | --- | --- |
42
+ | `TrezaGenerateImage` | `treza_generate_image` | A picture from a prompt, optionally from reference pictures. | Treza credits |
43
+ | `TrezaGenerateVideo` | `treza_generate_video` | A video clip from a prompt, optionally opening or ending on a picture. | Treza credits |
44
+ | `TrezaRunPipeline` | `treza_run_pipeline` | Runs one of your saved Treza pipelines, with new inputs if given. | Treza credits |
45
+ | `TrezaGetRun` | `treza_get_run` | Looks up a render that was still going when its tool stopped waiting. | Free |
46
+ | `TrezaBalance` | `treza_balance` | The credits left on the account. | Free |
47
+
48
+ Each tool returns a JSON string. A finished render looks like this:
49
+
50
+ ```json
51
+ {"url": "https://media.trezalabs.com/...mp4", "status": "success", "finished": true,
52
+ "price_usd": 0.28, "model": "google/veo-3.1-lite", "render_seconds": 56.0,
53
+ "run_id": "...", "pipeline_id": "pipeline_..."}
54
+ ```
55
+
56
+ ## Use one tool
57
+
58
+ ```python
59
+ from langchain_treza import TrezaGenerateVideo
60
+
61
+ tool = TrezaGenerateVideo(max_cost_usd=1.00)
62
+ print(tool.invoke({"prompt": "A red fox trots through fresh snow", "aspect_ratio": "9:16", "duration_sec": 4}))
63
+ ```
64
+
65
+ ## Give the tools to an agent
66
+
67
+ ```python
68
+ from langchain.agents import create_agent
69
+ from langchain_treza import TrezaToolkit
70
+
71
+ tools = TrezaToolkit(max_cost_usd=1.00).get_tools()
72
+ agent = create_agent("anthropic:claude-sonnet-5-5", tools)
73
+ agent.invoke({"messages": [{"role": "user", "content": "Make a 4 second vertical clip of a fox in snow."}]})
74
+ ```
75
+
76
+ `TrezaToolkit(include_pipelines=False)` leaves out `treza_run_pipeline`.
77
+
78
+ ## Spending
79
+
80
+ - `max_cost_usd` is set when you build the tool or toolkit. The model cannot see or change it, and it cannot see the API key.
81
+ - With a cap set, Treza prices the render first. If the price is higher, the tool answers "This render costs $X, over the Max cost of $Y. Nothing was spent." and starts nothing.
82
+ - With no cap (`None`, the default), a render runs at Treza's quoted price as long as the balance covers it. **Set a cap on tools you give to an agent.**
83
+ - A render never starts when the balance does not cover its price.
84
+
85
+ ## Long renders
86
+
87
+ Pictures usually take under a minute and videos one to five minutes. Each tool waits up to `wait_seconds` (300 by default, 600 for pipelines). A render still going after that comes back with `"status": "running"` and its `run_id` and `pipeline_id`, not as an error, and nothing is started twice. `treza_get_run` returns the file once it is done.
88
+
89
+ ## Errors
90
+
91
+ Refusals (over the cap, low balance, a bad key, a render that broke) go back to the model as text, so an agent can react. Pass `handle_tool_error=False` to have them raise `ToolException` instead.
92
+
93
+ ## Network and privacy
94
+
95
+ The tools call Treza's API over HTTPS at `www.trezalabs.com`. They send the prompt and settings with your API key, and store nothing. Privacy policy: https://docs.trezalabs.com/terms-and-privacy/privacy
96
+
97
+ ## Development
98
+
99
+ ```bash
100
+ pip install -e . pytest langchain-tests
101
+ pytest
102
+ ```
103
+
104
+ The tests run against a scripted stand-in for Treza's API and include LangChain's standard tool tests.
105
+
106
+ ## Support
107
+
108
+ Issues: https://github.com/treza-labs/langchain-treza/issues · Email: hello@trezalabs.com
109
+
110
+ MIT licensed.
@@ -0,0 +1,91 @@
1
+ # langchain-treza
2
+
3
+ [Treza](https://www.trezalabs.com) tools for LangChain and LangGraph. An agent can generate AI pictures and video clips and run your saved Treza pipelines. Treza prices every render first, and a `max_cost_usd` you set stops any render that costs more, with nothing spent.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install -U langchain-treza
9
+ ```
10
+
11
+ Create a Treza account at https://www.trezalabs.com, add credits, and make an API key at https://www.trezalabs.com/platform/api-keys with the `pipelines:read`, `pipelines:write` and `pipelines:run` permissions. Then:
12
+
13
+ ```bash
14
+ export TREZA_API_KEY="treza_live_..."
15
+ ```
16
+
17
+ The package is free. Renders are paid from your prepaid Treza credits; there is no subscription.
18
+
19
+ ## Tools
20
+
21
+ | Tool | Name the model sees | What it does | Cost |
22
+ | --- | --- | --- | --- |
23
+ | `TrezaGenerateImage` | `treza_generate_image` | A picture from a prompt, optionally from reference pictures. | Treza credits |
24
+ | `TrezaGenerateVideo` | `treza_generate_video` | A video clip from a prompt, optionally opening or ending on a picture. | Treza credits |
25
+ | `TrezaRunPipeline` | `treza_run_pipeline` | Runs one of your saved Treza pipelines, with new inputs if given. | Treza credits |
26
+ | `TrezaGetRun` | `treza_get_run` | Looks up a render that was still going when its tool stopped waiting. | Free |
27
+ | `TrezaBalance` | `treza_balance` | The credits left on the account. | Free |
28
+
29
+ Each tool returns a JSON string. A finished render looks like this:
30
+
31
+ ```json
32
+ {"url": "https://media.trezalabs.com/...mp4", "status": "success", "finished": true,
33
+ "price_usd": 0.28, "model": "google/veo-3.1-lite", "render_seconds": 56.0,
34
+ "run_id": "...", "pipeline_id": "pipeline_..."}
35
+ ```
36
+
37
+ ## Use one tool
38
+
39
+ ```python
40
+ from langchain_treza import TrezaGenerateVideo
41
+
42
+ tool = TrezaGenerateVideo(max_cost_usd=1.00)
43
+ print(tool.invoke({"prompt": "A red fox trots through fresh snow", "aspect_ratio": "9:16", "duration_sec": 4}))
44
+ ```
45
+
46
+ ## Give the tools to an agent
47
+
48
+ ```python
49
+ from langchain.agents import create_agent
50
+ from langchain_treza import TrezaToolkit
51
+
52
+ tools = TrezaToolkit(max_cost_usd=1.00).get_tools()
53
+ agent = create_agent("anthropic:claude-sonnet-5-5", tools)
54
+ agent.invoke({"messages": [{"role": "user", "content": "Make a 4 second vertical clip of a fox in snow."}]})
55
+ ```
56
+
57
+ `TrezaToolkit(include_pipelines=False)` leaves out `treza_run_pipeline`.
58
+
59
+ ## Spending
60
+
61
+ - `max_cost_usd` is set when you build the tool or toolkit. The model cannot see or change it, and it cannot see the API key.
62
+ - With a cap set, Treza prices the render first. If the price is higher, the tool answers "This render costs $X, over the Max cost of $Y. Nothing was spent." and starts nothing.
63
+ - With no cap (`None`, the default), a render runs at Treza's quoted price as long as the balance covers it. **Set a cap on tools you give to an agent.**
64
+ - A render never starts when the balance does not cover its price.
65
+
66
+ ## Long renders
67
+
68
+ Pictures usually take under a minute and videos one to five minutes. Each tool waits up to `wait_seconds` (300 by default, 600 for pipelines). A render still going after that comes back with `"status": "running"` and its `run_id` and `pipeline_id`, not as an error, and nothing is started twice. `treza_get_run` returns the file once it is done.
69
+
70
+ ## Errors
71
+
72
+ Refusals (over the cap, low balance, a bad key, a render that broke) go back to the model as text, so an agent can react. Pass `handle_tool_error=False` to have them raise `ToolException` instead.
73
+
74
+ ## Network and privacy
75
+
76
+ The tools call Treza's API over HTTPS at `www.trezalabs.com`. They send the prompt and settings with your API key, and store nothing. Privacy policy: https://docs.trezalabs.com/terms-and-privacy/privacy
77
+
78
+ ## Development
79
+
80
+ ```bash
81
+ pip install -e . pytest langchain-tests
82
+ pytest
83
+ ```
84
+
85
+ The tests run against a scripted stand-in for Treza's API and include LangChain's standard tool tests.
86
+
87
+ ## Support
88
+
89
+ Issues: https://github.com/treza-labs/langchain-treza/issues · Email: hello@trezalabs.com
90
+
91
+ MIT licensed.
@@ -0,0 +1,16 @@
1
+ """Treza for LangChain: generate AI pictures and videos and run Treza pipelines from an agent."""
2
+
3
+ from langchain_treza.client import TrezaClient, TrezaError
4
+ from langchain_treza.toolkit import TrezaToolkit
5
+ from langchain_treza.tools import TrezaBalance, TrezaGenerateImage, TrezaGenerateVideo, TrezaGetRun, TrezaRunPipeline
6
+
7
+ __all__ = [
8
+ "TrezaBalance",
9
+ "TrezaClient",
10
+ "TrezaError",
11
+ "TrezaGenerateImage",
12
+ "TrezaGenerateVideo",
13
+ "TrezaGetRun",
14
+ "TrezaRunPipeline",
15
+ "TrezaToolkit",
16
+ ]
@@ -0,0 +1,270 @@
1
+ """A small client for Treza's REST API (POST /api/v1/tools/<name>).
2
+
3
+ Every render follows the same order: ask Treza for a quote, stop if the quote
4
+ is over the Max cost the user set, start the render once at the quoted price,
5
+ then wait for the finished file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import time
12
+ import uuid
13
+ from typing import Any, Callable
14
+
15
+ import requests
16
+
17
+ VERSION = "0.1.0"
18
+ USER_AGENT = f"langchain-treza/{VERSION}"
19
+ TOP_UP_URL = "https://www.trezalabs.com/platform/settings"
20
+ KEYS_PAGE = "https://www.trezalabs.com/platform/api-keys"
21
+ FINISHED = {"success", "error", "partial", "cancelled"}
22
+ STALE_QUOTE_CODES = {"STALE_QUOTE", "QUOTE_MISMATCH", "UNKNOWN_QUOTE"}
23
+
24
+ Data = dict[str, Any]
25
+
26
+
27
+ def base_url() -> str:
28
+ """Treza's API. Tests point it at a mock with TREZA_BASE_URL."""
29
+ return (os.environ.get("TREZA_BASE_URL") or "https://www.trezalabs.com").rstrip("/")
30
+
31
+
32
+ class TrezaError(Exception):
33
+ """A refusal from Treza, worded so a person or a model can act on it."""
34
+
35
+ def __init__(self, message: str, status: int = 0, code: str | None = None, body: Data | None = None):
36
+ super().__init__(message)
37
+ self.status = status
38
+ self.code = code
39
+ self.body = body or {}
40
+
41
+
42
+ def compact(fields: Data) -> Data:
43
+ """Drop empty values, so an optional field left blank gets Treza's default."""
44
+ return {k: v for k, v in fields.items() if v is not None and v != "" and v != []}
45
+
46
+
47
+ def to_number(value: Any) -> float | None:
48
+ if value is None or value == "":
49
+ return None
50
+ try:
51
+ number = float(value)
52
+ except (TypeError, ValueError):
53
+ return None
54
+ return number if number == number and abs(number) != float("inf") else None
55
+
56
+
57
+ def max_cost(value: Any) -> float:
58
+ """The optional price cap on a render: infinity when Max cost is left empty.
59
+
60
+ It used to be required, with a default per tool ($2 for video). That default
61
+ stopped clips people meant to make: 8 seconds of Seedance 2.5 is $2.63.
62
+ """
63
+ number = to_number(value)
64
+ return number if number is not None and number > 0 else float("inf")
65
+
66
+
67
+ def price_limit(cap: float) -> float | None:
68
+ """The cap as Treza's maxPriceUsd, or None (not sent) when there is none."""
69
+ return cap if cap != float("inf") else None
70
+
71
+
72
+ class TrezaClient:
73
+ def __init__(self, api_key: str, session: requests.Session | None = None):
74
+ self.api_key = (api_key or "").strip()
75
+ self.session = session or requests.Session()
76
+
77
+ # ------------------------------------------------------------- requests
78
+
79
+ def request(self, tool: str, args: Data | None = None) -> tuple[bool, int, Data]:
80
+ """Call one tool without raising on a refusal: (ok, HTTP status, body)."""
81
+ response = self.session.post(
82
+ f"{base_url()}/api/v1/tools/{tool}",
83
+ json=compact(args or {}),
84
+ headers={"Authorization": f"Bearer {self.api_key}", "User-Agent": USER_AGENT},
85
+ timeout=(10, 60),
86
+ )
87
+ try:
88
+ body = response.json()
89
+ except ValueError:
90
+ body = {"error": response.text[:300]}
91
+ if not isinstance(body, dict):
92
+ body = {"result": body}
93
+ return response.status_code < 400, response.status_code, body
94
+
95
+ def call(self, tool: str, args: Data | None = None) -> Data:
96
+ ok, status, body = self.request(tool, args)
97
+ if ok:
98
+ return body
99
+ raise refusal(status, body)
100
+
101
+ # ----------------------------------------------------------------- runs
102
+
103
+ def start_quoted(self, max_cost_usd: float, quote: Callable[[], tuple[bool, int, Data]], inputs: Data | None = None) -> Data:
104
+ """Quote, check the cap and the balance, then start the render once."""
105
+ for attempt in range(3):
106
+ ok, status, quoted = quote()
107
+ if not ok:
108
+ if quoted.get("code") == "OVER_BUDGET":
109
+ raise over_budget(to_number(quoted.get("estimatedChargeUsd")), max_cost_usd)
110
+ raise refusal(status, quoted)
111
+ pipeline_id = str(quoted.get("pipelineId"))
112
+ price = to_number(quoted.get("estimatedChargeUsd"))
113
+ if price is None or price > max_cost_usd:
114
+ raise over_budget(price, max_cost_usd)
115
+ if quoted.get("sufficient") is False:
116
+ balance = to_number(quoted.get("balanceUsd")) or 0
117
+ raise TrezaError(
118
+ f"This render costs ${price:.2f} and your Treza balance is ${balance:.2f}. "
119
+ f"Nothing was spent. Add credits at {quoted.get('topUpUrl') or TOP_UP_URL}",
120
+ 402,
121
+ "InsufficientCredits",
122
+ )
123
+ base = compact({"pipelineId": pipeline_id, "inputs": inputs})
124
+ quote_id = quoted.get("quoteId")
125
+ start = {**base, "quoteId": quote_id} if isinstance(quote_id, str) else {**base, "requestId": str(uuid.uuid4())}
126
+ ok, status, run = self.request("run_pipeline", start)
127
+ if ok:
128
+ return {"quoted": quoted, "runId": str(run.get("runId")), "pipelineId": pipeline_id, "priceUsd": price}
129
+ code = run.get("code")
130
+ if attempt < 2 and code in STALE_QUOTE_CODES:
131
+ continue
132
+ if code == "PRICE_CHANGED":
133
+ new_price = to_number(run.get("estimatedChargeUsd"))
134
+ if new_price is None or new_price > max_cost_usd:
135
+ raise over_budget(new_price, max_cost_usd)
136
+ again = self.call("run_pipeline", {**base, "requestId": str(uuid.uuid4())})
137
+ return {"quoted": quoted, "runId": str(again.get("runId")), "pipelineId": pipeline_id, "priceUsd": new_price}
138
+ raise refusal(status, run)
139
+ raise TrezaError("Treza's quote kept changing. Try again.")
140
+
141
+ def wait_for_run(self, pipeline_id: str, run_id: str, wait_seconds: float, on_poll: Callable[[Data], None] | None = None) -> Data:
142
+ """Poll a run until it finishes or the wait is used up. Returns the run as last seen.
143
+
144
+ on_poll is called with each answer. When it raises, the render is
145
+ cancelled in Treza before the error goes on.
146
+ """
147
+ deadline = time.monotonic() + max(0.0, wait_seconds)
148
+ while True:
149
+ run = self.call("get_run", {"pipelineId": pipeline_id, "runId": run_id})
150
+ if run.get("status") != "running":
151
+ return run
152
+ pause = min(max(to_number(run.get("pollAfterSec")) or 3, 2), 10)
153
+ if time.monotonic() + pause >= deadline:
154
+ return run
155
+ slept = 0.0
156
+ try:
157
+ while slept < pause:
158
+ if on_poll:
159
+ on_poll(run)
160
+ time.sleep(min(0.5, pause - slept))
161
+ slept += 0.5
162
+ except BaseException:
163
+ try:
164
+ self.request("cancel_run", {"pipelineId": pipeline_id, "runId": run_id})
165
+ except Exception:
166
+ pass
167
+ raise
168
+
169
+ # -------------------------------------------------------------- uploads
170
+
171
+ def upload(self, data: bytes, content_type: str, name: str) -> str:
172
+ """Put a file in the account's Treza library and return its library URL."""
173
+ target = self.call("create_upload_url", {"contentType": content_type})
174
+ put = self.session.put(str(target.get("uploadUrl")), data=data, headers={"Content-Type": content_type}, timeout=(10, 300))
175
+ if put.status_code >= 400:
176
+ raise TrezaError(f"The upload to Treza was refused (HTTP {put.status_code}). Try again.", put.status_code, "UploadRefused")
177
+ imported = self.call("import_media", {"url": str(target.get("mediaUrl")), "name": name})
178
+ url = imported.get("url")
179
+ if not isinstance(url, str) or not url:
180
+ raise TrezaError("Treza took the upload but did not return its address. Try again.")
181
+ return url
182
+
183
+ def download(self, url: str) -> bytes:
184
+ """Fetch a finished file. Only Treza's own hosts get the API key; media links are public."""
185
+ response = self.session.get(url, headers={"User-Agent": USER_AGENT}, timeout=(10, 300))
186
+ if response.status_code >= 400:
187
+ raise TrezaError(f"The finished file could not be downloaded (HTTP {response.status_code}): {url}", response.status_code, "Download")
188
+ return response.content
189
+
190
+
191
+ # ----------------------------------------------------------------- wording
192
+
193
+
194
+ def refusal(status: int, body: Data) -> TrezaError:
195
+ message = body.get("error") if isinstance(body.get("error"), str) and body.get("error") else f"Treza answered HTTP {status}."
196
+ code = body.get("code") if isinstance(body.get("code"), str) else None
197
+ if status == 401:
198
+ return TrezaError(f"{message} Check your Treza API key ({KEYS_PAGE}).", status, code, body)
199
+ if status == 402:
200
+ return TrezaError(f"{message} Add credits at {body.get('topUpUrl') or TOP_UP_URL}", status, code or "InsufficientCredits", body)
201
+ if status == 429:
202
+ return TrezaError(f"{message} Wait {int(to_number(body.get('retryAfterSec')) or 60)} seconds and try again.", status, code, body)
203
+ return TrezaError(str(message), status, code, body)
204
+
205
+
206
+ def over_budget(price: float | None, max_cost_usd: float) -> TrezaError:
207
+ shown = f"${price:.2f}" if price is not None else "more"
208
+ return TrezaError(
209
+ f"This render costs {shown}, over the Max cost of ${max_cost_usd:.2f}. Nothing was spent. "
210
+ "Raise Max cost, or ask for less (a shorter clip or a cheaper model).",
211
+ 400,
212
+ "OverBudget",
213
+ )
214
+
215
+
216
+ def primary_url(run: Data, key: str | None = None) -> str | None:
217
+ """The finished file: the named output, or else the first URL among the outputs."""
218
+ outputs = run.get("outputs") if isinstance(run.get("outputs"), dict) else {}
219
+ if key and isinstance(outputs.get(key), str):
220
+ return outputs[key]
221
+ for value in outputs.values():
222
+ if isinstance(value, str) and value.startswith(("http://", "https://")):
223
+ return value
224
+ return None
225
+
226
+
227
+ def stopped_message(run: Data) -> str:
228
+ """Why a finished run stopped short, from its notes and the first step that broke."""
229
+ if run.get("status") == "cancelled":
230
+ reason = run.get("cancelReason")
231
+ return f"The render was cancelled{': ' + reason if isinstance(reason, str) and reason else ''}."
232
+ reasons = [run.get("statusNote"), run.get("refusalNote")]
233
+ for node in run.get("nodes") or []:
234
+ if isinstance(node, dict) and isinstance(node.get("error"), str):
235
+ reasons.append(f"{node.get('label') or node.get('type')}: {node['error']}")
236
+ break
237
+ said = " ".join(r for r in reasons if isinstance(r, str) and r)
238
+ return f"The render stopped before it finished. {said}".strip()
239
+
240
+
241
+ def run_item(run: Data, output_key: str | None = None, extra: Data | None = None) -> Data:
242
+ """One render as a flat result: the file first, then status, price and the IDs to look it up."""
243
+ status = str(run.get("status") or "running")
244
+ duration_ms = to_number(run.get("durationMs"))
245
+ return compact(
246
+ {
247
+ "url": primary_url(run, output_key),
248
+ "status": status,
249
+ "finished": status in FINISHED,
250
+ **(extra or {}),
251
+ "render_seconds": round(duration_ms / 1000, 1) if duration_ms is not None else None,
252
+ "outputs": run.get("outputs") if isinstance(run.get("outputs"), dict) and run.get("outputs") else None,
253
+ "run_id": run.get("runId"),
254
+ "pipeline_id": run.get("pipelineId"),
255
+ "started_at": run.get("startedAt"),
256
+ "finished_at": run.get("finishedAt"),
257
+ "status_note": run.get("statusNote") or run.get("refusalNote"),
258
+ }
259
+ )
260
+
261
+
262
+ def finished_or_raise(run: Data) -> None:
263
+ """A render that broke or was cancelled raises, with the reason."""
264
+ if run.get("status") in ("error", "cancelled"):
265
+ raise TrezaError(
266
+ f"{stopped_message(run)} Open the pipeline in Treza to see which step stopped: "
267
+ f"https://www.trezalabs.com/platform/pipelines/{run.get('pipelineId')}",
268
+ 0,
269
+ "RenderCancelled" if run.get("status") == "cancelled" else "RenderStopped",
270
+ )
File without changes
@@ -0,0 +1,42 @@
1
+ """All of Treza's tools with one key and one spending cap."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ from langchain_core.tools import BaseTool, BaseToolkit
8
+ from langchain_core.utils import secret_from_env
9
+ from pydantic import Field, SecretStr
10
+
11
+ from langchain_treza.tools import TrezaBalance, TrezaGenerateImage, TrezaGenerateVideo, TrezaGetRun, TrezaRunPipeline
12
+
13
+
14
+ class TrezaToolkit(BaseToolkit):
15
+ """Treza's tools for an agent: pictures, video clips, saved pipelines, run lookup and balance.
16
+
17
+ Example:
18
+ .. code-block:: python
19
+
20
+ from langchain_treza import TrezaToolkit
21
+
22
+ tools = TrezaToolkit(max_cost_usd=1.0).get_tools()
23
+ """
24
+
25
+ treza_api_key: SecretStr = Field(
26
+ alias="api_key",
27
+ default_factory=secret_from_env(
28
+ "TREZA_API_KEY",
29
+ error_message="Pass api_key or set TREZA_API_KEY. Make a key at https://www.trezalabs.com/platform/api-keys",
30
+ ),
31
+ )
32
+ max_cost_usd: Optional[float] = None
33
+ """The most any one render may cost. None means no cap, so set one for an agent."""
34
+ include_pipelines: bool = True
35
+ """Leave out treza_run_pipeline when the agent should only generate."""
36
+
37
+ def get_tools(self) -> list[BaseTool]:
38
+ shared = {"api_key": self.treza_api_key, "max_cost_usd": self.max_cost_usd}
39
+ tools: list[BaseTool] = [TrezaGenerateImage(**shared), TrezaGenerateVideo(**shared)]
40
+ if self.include_pipelines:
41
+ tools.append(TrezaRunPipeline(**shared))
42
+ return [*tools, TrezaGetRun(**shared), TrezaBalance(**shared)]
@@ -0,0 +1,248 @@
1
+ """Treza tools for LangChain agents and graphs.
2
+
3
+ Each render tool asks Treza for a price, stops when the price is over
4
+ ``max_cost_usd``, starts the render once and waits for the finished file.
5
+ ``max_cost_usd``, the API key and the wait are set when the tool is built, not
6
+ by the model, so an agent cannot raise a spending cap you set.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from typing import Any, Literal, Optional
13
+
14
+ from langchain_core.tools import BaseTool, ToolException
15
+ from langchain_core.utils import secret_from_env
16
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
17
+
18
+ from langchain_treza.client import (
19
+ TOP_UP_URL,
20
+ Data,
21
+ TrezaClient,
22
+ TrezaError,
23
+ compact,
24
+ finished_or_raise,
25
+ max_cost,
26
+ price_limit,
27
+ run_item,
28
+ to_number,
29
+ )
30
+
31
+ ImageShape = Literal["1:1", "16:9", "9:16", "4:5", "3:4", "4:3", "2:3", "3:2"]
32
+ VideoShape = Literal["16:9", "9:16", "1:1"]
33
+
34
+
35
+ class _TrezaTool(BaseTool):
36
+ """What every Treza tool shares: the key, the cap, the wait and how a render is reported."""
37
+
38
+ model_config = ConfigDict(arbitrary_types_allowed=True)
39
+
40
+ treza_api_key: SecretStr = Field(
41
+ alias="api_key",
42
+ default_factory=secret_from_env(
43
+ "TREZA_API_KEY",
44
+ error_message="Pass api_key or set TREZA_API_KEY. Make a key at https://www.trezalabs.com/platform/api-keys",
45
+ ),
46
+ )
47
+ """A Treza API key with the pipelines read, write and run permissions."""
48
+
49
+ max_cost_usd: Optional[float] = None
50
+ """The most one render may cost. Treza prices it first and nothing is spent when it is higher. None means no cap."""
51
+
52
+ wait_seconds: float = 300
53
+ """How long to wait for a render. One still going comes back with status "running" and its IDs."""
54
+
55
+ handle_tool_error: bool = True
56
+ """A refusal (over the cap, low balance, a bad key) goes back to the model as text instead of raising."""
57
+
58
+ client: Optional[Any] = Field(default=None, exclude=True)
59
+ """A ready TrezaClient, for tests."""
60
+
61
+ def _treza(self) -> TrezaClient:
62
+ return self.client or TrezaClient(self.treza_api_key.get_secret_value())
63
+
64
+ def _render(self, started: Data, output_key: Optional[str], extra: Optional[Data] = None) -> str:
65
+ treza = self._treza()
66
+ run = treza.wait_for_run(started["pipelineId"], started["runId"], self.wait_seconds)
67
+ run = {"runId": started["runId"], "pipelineId": started["pipelineId"], **run}
68
+ finished_or_raise(run)
69
+ quoted = started.get("quoted") or {}
70
+ model = quoted.get("model")
71
+ item = run_item(
72
+ run,
73
+ output_key,
74
+ {"price_usd": started.get("priceUsd"), "model": model.get("id") if isinstance(model, dict) else model, **(extra or {})},
75
+ )
76
+ return json.dumps(item)
77
+
78
+ def _guard(self, fn: Any) -> str:
79
+ try:
80
+ return fn()
81
+ except TrezaError as err:
82
+ raise ToolException(str(err)) from err
83
+
84
+
85
+ class GenerateImageInput(BaseModel):
86
+ prompt: str = Field(description="What the picture shows.")
87
+ aspect_ratio: ImageShape = Field(default="1:1", description='The picture\'s shape, for example "16:9" wide or "9:16" tall.')
88
+ reference_image_urls: Optional[list[str]] = Field(
89
+ default=None, description="Links to pictures already in the Treza library to restyle or keep a character from."
90
+ )
91
+ model: Optional[str] = Field(default=None, description="A Treza model ID. Leave out for Treza's default.")
92
+
93
+
94
+ class TrezaGenerateImage(_TrezaTool):
95
+ """Make a picture from a description with Treza."""
96
+
97
+ name: str = "treza_generate_image"
98
+ description: str = (
99
+ "Make a picture from a text description with Treza. Returns JSON with the finished picture's url, "
100
+ "the price in US dollars and the model. Uses the account's prepaid Treza credits."
101
+ )
102
+ args_schema: type[BaseModel] = GenerateImageInput
103
+
104
+ def _run(self, prompt: str, aspect_ratio: str = "1:1", reference_image_urls: Optional[list[str]] = None, model: Optional[str] = None, **_: Any) -> str:
105
+ def go() -> str:
106
+ treza = self._treza()
107
+ cap = max_cost(self.max_cost_usd)
108
+ args = compact(
109
+ {"prompt": prompt, "aspectRatio": aspect_ratio, "model": model, "referenceImageUrls": reference_image_urls, "maxPriceUsd": price_limit(cap)}
110
+ )
111
+ return self._render(treza.start_quoted(cap, lambda: treza.request("make_image", args)), "image")
112
+
113
+ return self._guard(go)
114
+
115
+
116
+ class GenerateVideoInput(BaseModel):
117
+ prompt: str = Field(description="What happens in the clip.")
118
+ aspect_ratio: VideoShape = Field(default="16:9", description='"16:9" wide, "9:16" vertical (Shorts, Reels, TikTok) or "1:1" square.')
119
+ duration_sec: Optional[float] = Field(default=None, ge=1, le=60, description="Clip length in seconds, usually 4 to 10. Defaults to 4.")
120
+ with_audio: Optional[bool] = Field(default=None, description="Generate sound with the video where the model can. Defaults to true.")
121
+ first_frame_url: Optional[str] = Field(default=None, description="Link to a picture in the Treza library that the clip opens on.")
122
+ last_frame_url: Optional[str] = Field(default=None, description="Link to a picture in the Treza library that the clip ends on.")
123
+ model: Optional[str] = Field(default=None, description="A Treza model ID. Leave out for Treza's default.")
124
+
125
+
126
+ class TrezaGenerateVideo(_TrezaTool):
127
+ """Make a video clip from a description with Treza."""
128
+
129
+ name: str = "treza_generate_video"
130
+ description: str = (
131
+ "Make a short video clip from a text description with Treza. Takes one to five minutes. Returns JSON with "
132
+ "the finished clip's url, the price in US dollars and the model, or status \"running\" with a run_id and "
133
+ "pipeline_id to pass to treza_get_run when it is not done in time. Uses the account's prepaid Treza credits."
134
+ )
135
+ args_schema: type[BaseModel] = GenerateVideoInput
136
+
137
+ def _run(
138
+ self,
139
+ prompt: str,
140
+ aspect_ratio: str = "16:9",
141
+ duration_sec: Optional[float] = None,
142
+ with_audio: Optional[bool] = None,
143
+ first_frame_url: Optional[str] = None,
144
+ last_frame_url: Optional[str] = None,
145
+ model: Optional[str] = None,
146
+ **_: Any,
147
+ ) -> str:
148
+ def go() -> str:
149
+ treza = self._treza()
150
+ cap = max_cost(self.max_cost_usd)
151
+ args = compact(
152
+ {
153
+ "prompt": prompt,
154
+ "aspectRatio": aspect_ratio,
155
+ "durationSec": to_number(duration_sec),
156
+ "withAudio": with_audio,
157
+ "firstFrameUrl": first_frame_url,
158
+ "lastFrameUrl": last_frame_url,
159
+ "model": model,
160
+ "maxPriceUsd": price_limit(cap),
161
+ }
162
+ )
163
+ return self._render(treza.start_quoted(cap, lambda: treza.request("make_video", args)), "video")
164
+
165
+ return self._guard(go)
166
+
167
+
168
+ class RunPipelineInput(BaseModel):
169
+ pipeline_id: str = Field(description="The pipeline's ID. It is in the pipeline's address in Treza and starts with pipeline_.")
170
+ inputs: Optional[dict[str, Any]] = Field(
171
+ default=None, description='One entry per input step of the pipeline, for example {"prompt_1": "a lighthouse at dawn"}. Leave out to run it as saved.'
172
+ )
173
+
174
+
175
+ class TrezaRunPipeline(_TrezaTool):
176
+ """Run a pipeline saved in the Treza account."""
177
+
178
+ name: str = "treza_run_pipeline"
179
+ description: str = (
180
+ "Run one of the account's saved Treza pipelines, with new inputs if given. Returns JSON with the url of "
181
+ "what it made, all its outputs and the price, or status \"running\" with IDs for treza_get_run. "
182
+ "Uses the account's prepaid Treza credits."
183
+ )
184
+ args_schema: type[BaseModel] = RunPipelineInput
185
+ wait_seconds: float = 600
186
+
187
+ def _run(self, pipeline_id: str, inputs: Optional[dict[str, Any]] = None, **_: Any) -> str:
188
+ def go() -> str:
189
+ treza = self._treza()
190
+ cap = max_cost(self.max_cost_usd)
191
+ pid = pipeline_id.strip()
192
+ if not pid:
193
+ raise TrezaError("Give the pipeline_id. It is in the pipeline's address in Treza and starts with pipeline_.")
194
+ return self._render(treza.start_quoted(cap, lambda: treza.request("estimate_run_cost", {"pipelineId": pid}), inputs or None), None)
195
+
196
+ return self._guard(go)
197
+
198
+
199
+ class GetRunInput(BaseModel):
200
+ pipeline_id: str = Field(description="The pipeline_id a Treza tool returned.")
201
+ run_id: str = Field(description="The run_id a Treza tool returned.")
202
+
203
+
204
+ class TrezaGetRun(_TrezaTool):
205
+ """Look up a render that was still going when its tool stopped waiting."""
206
+
207
+ name: str = "treza_get_run"
208
+ description: str = (
209
+ "Check a Treza render by its pipeline_id and run_id. Returns JSON with its status and, once finished, "
210
+ "the url of the file. Free."
211
+ )
212
+ args_schema: type[BaseModel] = GetRunInput
213
+
214
+ def _run(self, pipeline_id: str, run_id: str, **_: Any) -> str:
215
+ def go() -> str:
216
+ run = self._treza().call("get_run", {"pipelineId": pipeline_id, "runId": run_id})
217
+ run = {"runId": run_id, "pipelineId": pipeline_id, **run}
218
+ finished_or_raise(run)
219
+ return json.dumps(run_item(run))
220
+
221
+ return self._guard(go)
222
+
223
+
224
+ class BalanceInput(BaseModel):
225
+ pass
226
+
227
+
228
+ class TrezaBalance(_TrezaTool):
229
+ """The credits left on the Treza account."""
230
+
231
+ name: str = "treza_balance"
232
+ description: str = "Get the prepaid credit balance of the Treza account, in US dollars. Free."
233
+ args_schema: type[BaseModel] = BalanceInput
234
+
235
+ def _run(self, **_: Any) -> str:
236
+ def go() -> str:
237
+ balance = self._treza().call("get_credit_balance")
238
+ return json.dumps(
239
+ compact(
240
+ {
241
+ "balance_usd": to_number(balance.get("balanceUsd")),
242
+ "approx_videos_remaining": balance.get("approxVideosRemaining"),
243
+ "top_up_url": balance.get("topUpUrl") or TOP_UP_URL,
244
+ }
245
+ )
246
+ )
247
+
248
+ return self._guard(go)
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-treza"
7
+ version = "0.1.0"
8
+ description = "Treza tools for LangChain: generate AI pictures and videos and run Treza pipelines, with a price cap on every render."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Treza Labs, Inc.", email = "hello@trezalabs.com" }]
14
+ keywords = ["langchain", "treza", "ai video", "image generation", "video generation", "tools"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
19
+ ]
20
+ dependencies = [
21
+ "langchain-core>=0.3.0,<2",
22
+ "requests>=2.31,<3",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://www.trezalabs.com"
27
+ Repository = "https://github.com/treza-labs/langchain-treza"
28
+ Issues = "https://github.com/treza-labs/langchain-treza/issues"
29
+
30
+ [dependency-groups]
31
+ dev = ["pytest>=8", "langchain-tests>=0.3"]
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["langchain_treza"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
File without changes
File without changes
@@ -0,0 +1,26 @@
1
+ """A scripted Treza: answers each tool from a queue and records what was asked."""
2
+
3
+
4
+ class FakeResponse:
5
+ def __init__(self, status, body):
6
+ self.status_code = status
7
+ self._body = body
8
+ self.text = str(body)
9
+
10
+ def json(self):
11
+ return self._body
12
+
13
+
14
+ class FakeTreza:
15
+ def __init__(self, **answers):
16
+ self.answers = {tool: list(replies) for tool, replies in answers.items()}
17
+ self.calls = []
18
+
19
+ def post(self, url, json=None, headers=None, timeout=None):
20
+ tool = url.rsplit("/", 1)[-1]
21
+ self.calls.append((tool, json, headers))
22
+ status, body = self.answers[tool].pop(0)
23
+ return FakeResponse(status, body)
24
+
25
+ def asked(self, tool):
26
+ return [args for name, args, _ in self.calls if name == tool]
@@ -0,0 +1,65 @@
1
+ """LangChain's standard unit tests for tools (langchain-tests)."""
2
+
3
+ from langchain_tests.unit_tests import ToolsUnitTests
4
+
5
+ from langchain_treza import TrezaBalance, TrezaGenerateImage, TrezaGenerateVideo, TrezaGetRun, TrezaRunPipeline
6
+
7
+
8
+ class _Standard(ToolsUnitTests):
9
+ @property
10
+ def tool_constructor_params(self) -> dict:
11
+ return {"api_key": "treza_live_test"}
12
+
13
+ @property
14
+ def init_from_env_params(self):
15
+ return ({"TREZA_API_KEY": "treza_live_test"}, {}, {"treza_api_key": "treza_live_test"})
16
+
17
+
18
+ class TestGenerateImageStandard(_Standard):
19
+ @property
20
+ def tool_constructor(self):
21
+ return TrezaGenerateImage
22
+
23
+ @property
24
+ def tool_invoke_params_example(self) -> dict:
25
+ return {"prompt": "a red kite", "aspect_ratio": "4:5"}
26
+
27
+
28
+ class TestGenerateVideoStandard(_Standard):
29
+ @property
30
+ def tool_constructor(self):
31
+ return TrezaGenerateVideo
32
+
33
+ @property
34
+ def tool_invoke_params_example(self) -> dict:
35
+ return {"prompt": "a fox runs", "aspect_ratio": "9:16", "duration_sec": 4}
36
+
37
+
38
+ class TestRunPipelineStandard(_Standard):
39
+ @property
40
+ def tool_constructor(self):
41
+ return TrezaRunPipeline
42
+
43
+ @property
44
+ def tool_invoke_params_example(self) -> dict:
45
+ return {"pipeline_id": "pipeline_1", "inputs": {"prompt_1": "a lighthouse"}}
46
+
47
+
48
+ class TestGetRunStandard(_Standard):
49
+ @property
50
+ def tool_constructor(self):
51
+ return TrezaGetRun
52
+
53
+ @property
54
+ def tool_invoke_params_example(self) -> dict:
55
+ return {"pipeline_id": "pipeline_1", "run_id": "r1"}
56
+
57
+
58
+ class TestBalanceStandard(_Standard):
59
+ @property
60
+ def tool_constructor(self):
61
+ return TrezaBalance
62
+
63
+ @property
64
+ def tool_invoke_params_example(self) -> dict:
65
+ return {}
@@ -0,0 +1,121 @@
1
+ """The tools against a scripted Treza: quote, cap, start once, wait, report."""
2
+
3
+ import json
4
+
5
+ import pytest
6
+ from langchain_core.tools import ToolException
7
+
8
+ from langchain_treza import TrezaBalance, TrezaGenerateImage, TrezaGenerateVideo, TrezaGetRun, TrezaRunPipeline, TrezaToolkit
9
+ from langchain_treza import client as c
10
+
11
+ from .fakes import FakeTreza
12
+
13
+ QUOTE = {"pipelineId": "pipeline_1", "quoteId": "q1", "estimatedChargeUsd": 0.28, "sufficient": True, "model": {"id": "google/veo-3.1-lite"}}
14
+ DONE = {"status": "success", "outputs": {"video": "https://media.trezalabs.com/v.mp4"}, "durationMs": 56000}
15
+
16
+
17
+ def build(tool, fake, **settings):
18
+ return tool(api_key="treza_live_test", client=c.TrezaClient("treza_live_test", session=fake), **settings)
19
+
20
+
21
+ @pytest.fixture(autouse=True)
22
+ def no_sleep(monkeypatch):
23
+ monkeypatch.setattr(c.time, "sleep", lambda s: None)
24
+
25
+
26
+ def test_video_is_quoted_started_once_and_reported():
27
+ fake = FakeTreza(make_video=[(200, QUOTE)], run_pipeline=[(200, {"runId": "r1"})], get_run=[(200, DONE)])
28
+ out = json.loads(build(TrezaGenerateVideo, fake).invoke({"prompt": "a fox runs", "aspect_ratio": "9:16", "duration_sec": 4}))
29
+ assert out["url"] == "https://media.trezalabs.com/v.mp4"
30
+ assert (out["status"], out["finished"], out["price_usd"], out["model"]) == ("success", True, 0.28, "google/veo-3.1-lite")
31
+ assert (out["run_id"], out["pipeline_id"]) == ("r1", "pipeline_1")
32
+ # No cap set, so none is sent.
33
+ assert fake.asked("make_video") == [{"prompt": "a fox runs", "aspectRatio": "9:16", "durationSec": 4.0}]
34
+ assert fake.asked("run_pipeline") == [{"pipelineId": "pipeline_1", "quoteId": "q1"}]
35
+ assert fake.calls[0][2]["User-Agent"].startswith("langchain-treza/")
36
+
37
+
38
+ def test_over_the_cap_goes_back_to_the_model_and_starts_nothing():
39
+ fake = FakeTreza(make_video=[(200, QUOTE)])
40
+ said = build(TrezaGenerateVideo, fake, max_cost_usd=0.10).invoke({"prompt": "a fox runs"})
41
+ assert "over the Max cost of $0.10" in said and "Nothing was spent" in said
42
+ assert fake.asked("run_pipeline") == []
43
+ assert fake.asked("make_video")[0]["maxPriceUsd"] == 0.10
44
+
45
+
46
+ def test_a_refusal_raises_when_error_handling_is_off():
47
+ fake = FakeTreza(make_video=[(200, QUOTE)])
48
+ with pytest.raises(ToolException):
49
+ build(TrezaGenerateVideo, fake, max_cost_usd=0.10, handle_tool_error=False).invoke({"prompt": "a fox runs"})
50
+
51
+
52
+ def test_the_model_cannot_set_the_cap_or_the_key():
53
+ for tool in (TrezaGenerateImage, TrezaGenerateVideo, TrezaRunPipeline):
54
+ fields = set(tool(api_key="k").args)
55
+ assert not fields & {"max_cost_usd", "api_key", "treza_api_key", "wait_seconds"}, fields
56
+
57
+
58
+ def test_image_passes_references_and_model():
59
+ quote = {**QUOTE, "estimatedChargeUsd": 0, "model": "google/gemini-2.5-flash-image"}
60
+ done = {"status": "success", "outputs": {"image": "https://media.trezalabs.com/i.png"}}
61
+ fake = FakeTreza(make_image=[(200, quote)], run_pipeline=[(200, {"runId": "r1"})], get_run=[(200, done)])
62
+ out = json.loads(
63
+ build(TrezaGenerateImage, fake).invoke(
64
+ {"prompt": "a red kite", "aspect_ratio": "4:5", "reference_image_urls": ["https://media.trezalabs.com/ref.png"]}
65
+ )
66
+ )
67
+ assert out["url"].endswith("i.png") and out["price_usd"] == 0 and out["model"] == "google/gemini-2.5-flash-image"
68
+ assert fake.asked("make_image") == [
69
+ {"prompt": "a red kite", "aspectRatio": "4:5", "referenceImageUrls": ["https://media.trezalabs.com/ref.png"]}
70
+ ]
71
+
72
+
73
+ def test_a_slow_render_comes_back_running_and_get_run_finishes_it():
74
+ fake = FakeTreza(make_video=[(200, QUOTE)], run_pipeline=[(200, {"runId": "r1"})], get_run=[(200, {"status": "running"}), (200, DONE)])
75
+ out = json.loads(build(TrezaGenerateVideo, fake, wait_seconds=0).invoke({"prompt": "a fox runs"}))
76
+ assert out["status"] == "running" and out["finished"] is False and "url" not in out
77
+ later = json.loads(build(TrezaGetRun, fake).invoke({"pipeline_id": out["pipeline_id"], "run_id": out["run_id"]}))
78
+ assert later["url"] == "https://media.trezalabs.com/v.mp4"
79
+
80
+
81
+ def test_pipeline_passes_inputs():
82
+ quote = {"pipelineId": "pipeline_9", "quoteId": "q9", "estimatedChargeUsd": 1.5, "sufficient": True}
83
+ done = {"status": "success", "outputs": {"final": "https://media.trezalabs.com/f.mp4", "note": "ok"}}
84
+ fake = FakeTreza(estimate_run_cost=[(200, quote)], run_pipeline=[(200, {"runId": "r9"})], get_run=[(200, done)])
85
+ out = json.loads(build(TrezaRunPipeline, fake, max_cost_usd=2).invoke({"pipeline_id": " pipeline_9 ", "inputs": {"prompt_1": "a lighthouse"}}))
86
+ assert out["url"] == "https://media.trezalabs.com/f.mp4" and out["outputs"] == done["outputs"] and out["price_usd"] == 1.5
87
+ assert fake.asked("run_pipeline") == [{"pipelineId": "pipeline_9", "inputs": {"prompt_1": "a lighthouse"}, "quoteId": "q9"}]
88
+
89
+
90
+ def test_a_broken_render_says_why():
91
+ fake = FakeTreza(make_video=[(200, QUOTE)], run_pipeline=[(200, {"runId": "r1"})], get_run=[(200, {"status": "error", "statusNote": "The model refused the prompt."})])
92
+ assert "The model refused the prompt." in build(TrezaGenerateVideo, fake).invoke({"prompt": "x"})
93
+
94
+
95
+ def test_balance():
96
+ fake = FakeTreza(get_credit_balance=[(200, {"balanceUsd": 20.76})])
97
+ out = json.loads(build(TrezaBalance, fake).invoke({}))
98
+ assert out["balance_usd"] == 20.76 and out["top_up_url"].startswith("https://www.trezalabs.com/")
99
+
100
+
101
+ def test_a_bad_key_says_what_to_do():
102
+ fake = FakeTreza(get_credit_balance=[(401, {"error": "Invalid API key."})])
103
+ assert "Check your Treza API key" in build(TrezaBalance, fake).invoke({})
104
+
105
+
106
+ def test_key_comes_from_the_environment_and_is_not_printed(monkeypatch):
107
+ monkeypatch.setenv("TREZA_API_KEY", "treza_live_env")
108
+ tool = TrezaGenerateImage()
109
+ assert tool.treza_api_key.get_secret_value() == "treza_live_env"
110
+ assert "treza_live_env" not in repr(tool)
111
+ monkeypatch.delenv("TREZA_API_KEY")
112
+ with pytest.raises(ValueError, match="TREZA_API_KEY"):
113
+ TrezaGenerateImage()
114
+
115
+
116
+ def test_toolkit_shares_the_key_and_the_cap():
117
+ tools = TrezaToolkit(api_key="treza_live_test", max_cost_usd=1.0).get_tools()
118
+ assert [t.name for t in tools] == ["treza_generate_image", "treza_generate_video", "treza_run_pipeline", "treza_get_run", "treza_balance"]
119
+ assert all(t.max_cost_usd == 1.0 and t.treza_api_key.get_secret_value() == "treza_live_test" for t in tools)
120
+ names = [t.name for t in TrezaToolkit(api_key="k", include_pipelines=False).get_tools()]
121
+ assert "treza_run_pipeline" not in names