@palettelab/cli 0.3.75 → 0.3.76
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.
package/README.md
CHANGED
|
@@ -325,7 +325,7 @@ Backend SDK features for app-owned data:
|
|
|
325
325
|
- `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
|
|
326
326
|
- `ctx.llm` gives chat, streaming, embeddings and image generation on the PLATFORM's own provider keys when `"llm"` is declared — no `OPENAI_API_KEY` secret to ship or rotate. An app picks any model the workspace's own chat offers with `model=` — Palette's own models and the latest Claude, GPT and Gemini models, premium ones included, no declaration — and nothing bypasses the workspace's SECURE policy. `fallback=False` runs exactly the requested model or raises `ModelUnavailable`; every reply reports the model that actually ran. Tool calls (`tools=`, `tool_calls`, `reply["message"]` for the history) are supported. Calls spend the workspace's credits under its plan, seat and member limits, and are refused (the billing `CreditError`) when the workspace could not start a chat turn either.
|
|
327
327
|
- `ctx.llm` also takes generation keywords (`response_format`, `top_p`, `stop`, `seed`, `reasoning_effort`, `top_k`, `thinking`, …) as plain keywords, each sent to the providers that take it (endpoint, credential and transport keywords such as `base_url` or `api_key` raise `ValueError`; any other keyword is ignored with a warning), and reports `ctx.llm.catalog()` (models with limits and unavailable reasons), `ctx.llm.models()` and `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
|
|
328
|
-
- `ctx.media` gives fal.ai on the PLATFORM's key when `"media"` is declared — no `FAL_KEY` secret to ship or rotate. `ctx.media.run(model, payload)` reaches ANY fal model with the payload passed through untouched (so a model fal shipped today needs no SDK release); `image`, `video`, `speech` and `transcribe` are the same call with a default model filled in, `submit`/`status`/`result`/`cancel` handle multi-minute renders through a durable handle (`MediaStillRunning.handle`), `upload` puts bytes, public URLs or the app's own `ctx.storage` files on fal's CDN, `catalog()` lists the fal models it can run, and `save` copies an output into the app's own storage — fal's URLs expire. It spends the workspace's credits like `ctx.llm`.
|
|
328
|
+
- `ctx.media` gives fal.ai on the PLATFORM's key when `"media"` is declared — no `FAL_KEY` secret to ship or rotate. `ctx.media.run(model, payload)` reaches ANY fal model with the payload passed through untouched (so a model fal shipped today needs no SDK release); `image`, `video`, `speech` and `transcribe` are the same call with a default model filled in, `submit`/`status`/`result`/`cancel` handle multi-minute renders through a durable handle (`MediaStillRunning.handle`), `run(model, payload, sync=True)` asks fal's synchronous endpoint for models that answer in a second or two (SAM on a click: no queue, no polls), fal's refusals carry `status_code` (`ValueError` for 4xx, `PlatformServiceUnavailable` for 5xx), `upload` puts bytes, public URLs or the app's own `ctx.storage` files on fal's CDN, `catalog()` lists the fal models it can run, and `save` copies an output into the app's own storage — fal's URLs expire. It spends the workspace's credits like `ctx.llm`.
|
|
329
329
|
- `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared. `ctx.web.fetch(url, render=True)` loads the page in a browser first, for content its scripts build after it loads (a shop page's size table); it takes tens of seconds and `pltt dev` ignores the flag.
|
|
330
330
|
- `ctx.email.send(to, subject, html=..., text=..., cc=..., bcc=..., reply_to=..., from_name=..., attachments=[...], headers=..., tags=...)` sends email through the PLATFORM's email provider when `"email"` is declared — from the platform's sender address under the app's name, so no SendGrid key, SMTP login or verified domain to ship. Attachments are bytes or text with an optional `content_type`, and a `content_id` makes one inline for `<img src="cid:...">`. Up to 50 recipients and 10 MB per message, within a daily recipient allowance per workspace. `pltt dev` sends nothing: each message is checked with the hosted rules and saved to `.palette/dev-outbox/` as an `.eml` file.
|
|
331
331
|
- `pltt platform list` prints every service above with a snippet and its `pltt dev` mode; `pltt platform enable <name>` writes the manifest declaration.
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import functools
|
|
6
7
|
import hashlib
|
|
7
8
|
import json
|
|
8
9
|
import logging
|
|
@@ -1216,6 +1217,45 @@ _STUB_PNG = (
|
|
|
1216
1217
|
)
|
|
1217
1218
|
|
|
1218
1219
|
|
|
1220
|
+
def _hosted_error(exc: Exception) -> Exception | None:
|
|
1221
|
+
"""What hosted ctx.media raises for `exc`, or None to let `exc` go as it is. fal answering an HTTP error status
|
|
1222
|
+
is ValueError (4xx, with up to 300 characters of fal's answer) or PlatformServiceUnavailable (5xx), and both carry
|
|
1223
|
+
`status_code`, which tells "change the request" from "try again later"; an unreachable fal is
|
|
1224
|
+
PlatformServiceUnavailable."""
|
|
1225
|
+
httpx = sys.modules.get("httpx") # only a live call imports it, and only a live call raises its errors
|
|
1226
|
+
if httpx is None:
|
|
1227
|
+
return None
|
|
1228
|
+
if isinstance(exc, httpx.HTTPStatusError):
|
|
1229
|
+
status = exc.response.status_code
|
|
1230
|
+
said = f"ctx.media: fal answered HTTP {status}"
|
|
1231
|
+
if status >= 500:
|
|
1232
|
+
return PlatformServiceUnavailable(said, status_code=status)
|
|
1233
|
+
answer = exc.response.text[:300]
|
|
1234
|
+
refused = ValueError(f"{said}: {answer}" if answer else said)
|
|
1235
|
+
refused.status_code = status
|
|
1236
|
+
return refused
|
|
1237
|
+
if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)):
|
|
1238
|
+
return PlatformServiceUnavailable("ctx.media: fal could not be reached")
|
|
1239
|
+
return None
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def _like_hosted(fn: Any) -> Any:
|
|
1243
|
+
"""A LocalMediaService call that fails the way the hosted one does (_hosted_error), so the app's `except` and
|
|
1244
|
+
its `status_code` checks behave the same under pltt dev."""
|
|
1245
|
+
|
|
1246
|
+
@functools.wraps(fn)
|
|
1247
|
+
async def call(*args: Any, **kwargs: Any) -> Any:
|
|
1248
|
+
try:
|
|
1249
|
+
return await fn(*args, **kwargs)
|
|
1250
|
+
except Exception as exc: # noqa: BLE001 — only fal's HTTP errors are translated
|
|
1251
|
+
hosted = _hosted_error(exc)
|
|
1252
|
+
if hosted is None:
|
|
1253
|
+
raise
|
|
1254
|
+
raise hosted from exc
|
|
1255
|
+
|
|
1256
|
+
return call
|
|
1257
|
+
|
|
1258
|
+
|
|
1219
1259
|
class LocalMediaService:
|
|
1220
1260
|
"""`ctx.media` for pltt dev — the same fal.ai surface as hosted.
|
|
1221
1261
|
|
|
@@ -1226,6 +1266,9 @@ class LocalMediaService:
|
|
|
1226
1266
|
"""
|
|
1227
1267
|
|
|
1228
1268
|
QUEUE_BASE = "https://queue.fal.run"
|
|
1269
|
+
# fal's synchronous endpoint, for run(sync=True): the answer comes back on the request itself.
|
|
1270
|
+
SYNC_BASE = "https://fal.run"
|
|
1271
|
+
SYNC_TIMEOUT_S = 60.0
|
|
1229
1272
|
# fal's own upload flow (fal-client "fal_v3"): trade the key for a CDN
|
|
1230
1273
|
# token, then POST the bytes. storage.fal.ai no longer resolves.
|
|
1231
1274
|
CDN_TOKEN_URL = "https://rest.fal.ai/storage/auth/token?storage_type=fal-cdn-v3"
|
|
@@ -1302,6 +1345,7 @@ class LocalMediaService:
|
|
|
1302
1345
|
"text": f"[pltt dev: no FAL_KEY] {payload.get('prompt') or payload.get('text') or ''}",
|
|
1303
1346
|
}
|
|
1304
1347
|
|
|
1348
|
+
@_like_hosted
|
|
1305
1349
|
async def submit(self, model: str, payload: dict[str, Any] | None = None, **fields: Any) -> dict[str, Any]:
|
|
1306
1350
|
"""Queue a job; returns the durable handle {request_id, model,
|
|
1307
1351
|
status_url, response_url, cancel_url}. A 429 is retried with backoff,
|
|
@@ -1312,12 +1356,30 @@ class LocalMediaService:
|
|
|
1312
1356
|
"request_id": "pltt-dev-stub", "model": model, "status_url": "", "response_url": "",
|
|
1313
1357
|
"cancel_url": "", "request": body,
|
|
1314
1358
|
}
|
|
1359
|
+
task = await self._start(self.QUEUE_BASE, model, body, 60.0)
|
|
1360
|
+
request_id = str(task.get("request_id") or "")
|
|
1361
|
+
rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
|
|
1362
|
+
provider_status = str(task.get("status_url") or "")
|
|
1363
|
+
provider_response = str(task.get("response_url") or "")
|
|
1364
|
+
provider_cancel = str(task.get("cancel_url") or "")
|
|
1365
|
+
return {
|
|
1366
|
+
"request_id": request_id,
|
|
1367
|
+
"model": model,
|
|
1368
|
+
"status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
|
|
1369
|
+
"response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
|
|
1370
|
+
"cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
async def _start(self, base: str, model: str, body: dict[str, Any], timeout: float) -> dict[str, Any]:
|
|
1374
|
+
"""POST work to fal's queue or its synchronous endpoint (`base`), as hosted does: a 429 or a failed connect
|
|
1375
|
+
is retried with backoff, then MediaRateLimited; an answer lost after fal got the request is
|
|
1376
|
+
MediaSubmitInterrupted, never sent again."""
|
|
1315
1377
|
import httpx
|
|
1316
1378
|
|
|
1317
|
-
async with httpx.AsyncClient(timeout=
|
|
1379
|
+
async with httpx.AsyncClient(timeout=timeout, headers=self._headers()) as client:
|
|
1318
1380
|
for attempt in range(1, self.SUBMIT_ATTEMPTS + 1):
|
|
1319
1381
|
try:
|
|
1320
|
-
response = await client.post(f"{
|
|
1382
|
+
response = await client.post(f"{base}/{str(model).strip('/')}", json=body)
|
|
1321
1383
|
except (httpx.ConnectError, httpx.ConnectTimeout):
|
|
1322
1384
|
if attempt == self.SUBMIT_ATTEMPTS:
|
|
1323
1385
|
raise
|
|
@@ -1336,21 +1398,10 @@ class LocalMediaService:
|
|
|
1336
1398
|
)
|
|
1337
1399
|
await asyncio.sleep(self.RETRY_BASE_S * attempt)
|
|
1338
1400
|
response.raise_for_status()
|
|
1339
|
-
|
|
1340
|
-
request_id = str(task.get("request_id") or "")
|
|
1341
|
-
rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
|
|
1342
|
-
provider_status = str(task.get("status_url") or "")
|
|
1343
|
-
provider_response = str(task.get("response_url") or "")
|
|
1344
|
-
provider_cancel = str(task.get("cancel_url") or "")
|
|
1345
|
-
return {
|
|
1346
|
-
"request_id": request_id,
|
|
1347
|
-
"model": model,
|
|
1348
|
-
"status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
|
|
1349
|
-
"response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
|
|
1350
|
-
"cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
|
|
1351
|
-
}
|
|
1401
|
+
return response.json() or {}
|
|
1352
1402
|
|
|
1353
1403
|
# `request_id=` is the keyword these took before SDK 0.1.16; still accepted.
|
|
1404
|
+
@_like_hosted
|
|
1354
1405
|
async def status(
|
|
1355
1406
|
self, request: Any = None, *, model: str | None = None, request_id: str | None = None, **params: Any
|
|
1356
1407
|
) -> dict[str, Any]:
|
|
@@ -1365,6 +1416,7 @@ class LocalMediaService:
|
|
|
1365
1416
|
response.raise_for_status()
|
|
1366
1417
|
return response.json() or {}
|
|
1367
1418
|
|
|
1419
|
+
@_like_hosted
|
|
1368
1420
|
async def result(self, request: Any = None, *, model: str | None = None, request_id: str | None = None) -> dict[str, Any]:
|
|
1369
1421
|
"""The finished output; an unfinished job raises MediaStillRunning."""
|
|
1370
1422
|
request_id, model = self._ref(request or request_id, model)
|
|
@@ -1381,6 +1433,7 @@ class LocalMediaService:
|
|
|
1381
1433
|
response.raise_for_status()
|
|
1382
1434
|
return response.json() or {}
|
|
1383
1435
|
|
|
1436
|
+
@_like_hosted
|
|
1384
1437
|
async def cancel(self, request: Any = None, *, model: str | None = None, request_id: str | None = None) -> dict[str, Any]:
|
|
1385
1438
|
if not self.live:
|
|
1386
1439
|
return {"cancelled": True, "pltt_dev_stub": True}
|
|
@@ -1392,6 +1445,7 @@ class LocalMediaService:
|
|
|
1392
1445
|
response = await client.put(cancel_url)
|
|
1393
1446
|
return {"cancelled": response.status_code < 400, "status_code": response.status_code}
|
|
1394
1447
|
|
|
1448
|
+
@_like_hosted
|
|
1395
1449
|
async def run(
|
|
1396
1450
|
self,
|
|
1397
1451
|
model: str,
|
|
@@ -1400,11 +1454,19 @@ class LocalMediaService:
|
|
|
1400
1454
|
timeout: float | None = None,
|
|
1401
1455
|
poll_interval: float | None = None,
|
|
1402
1456
|
on_status: Any = None,
|
|
1457
|
+
sync: bool = False,
|
|
1403
1458
|
**fields: Any,
|
|
1404
1459
|
) -> dict[str, Any]:
|
|
1460
|
+
"""Submit, poll to completion, return fal's JSON. `sync=True` is one request to fal's synchronous endpoint
|
|
1461
|
+
instead, for models that answer in a second or two (SAM): `timeout` (default 60 s) bounds it, and there is no
|
|
1462
|
+
handle to resume."""
|
|
1405
1463
|
body = self._merge(payload, fields)
|
|
1406
1464
|
if not self.live:
|
|
1407
1465
|
return self._stub(model, body)
|
|
1466
|
+
if sync:
|
|
1467
|
+
return await self._start(
|
|
1468
|
+
self.SYNC_BASE, model, body, float(timeout if timeout is not None else self.SYNC_TIMEOUT_S)
|
|
1469
|
+
)
|
|
1408
1470
|
import httpx
|
|
1409
1471
|
|
|
1410
1472
|
job = await self.submit(model, body)
|
|
@@ -1436,6 +1498,8 @@ class LocalMediaService:
|
|
|
1436
1498
|
raise MediaStillRunning(job["request_id"], model, **handle)
|
|
1437
1499
|
await asyncio.sleep(interval)
|
|
1438
1500
|
final = await client.get(job["response_url"])
|
|
1501
|
+
if final.status_code >= 500: # done and paid for: collect it later, as hosted
|
|
1502
|
+
raise MediaStillRunning(job["request_id"], model, **handle)
|
|
1439
1503
|
final.raise_for_status()
|
|
1440
1504
|
return final.json() or {}
|
|
1441
1505
|
|
|
@@ -1481,6 +1545,7 @@ class LocalMediaService:
|
|
|
1481
1545
|
fetched.raise_for_status()
|
|
1482
1546
|
return fetched.content, (fetched.headers.get("content-type") or "").split(";")[0].strip() or None
|
|
1483
1547
|
|
|
1548
|
+
@_like_hosted
|
|
1484
1549
|
async def upload(
|
|
1485
1550
|
self,
|
|
1486
1551
|
source: bytes | str,
|
|
@@ -1522,6 +1587,7 @@ class LocalMediaService:
|
|
|
1522
1587
|
raise RuntimeError(f"ctx.media: fal upload returned no URL ({response.text[:200]})")
|
|
1523
1588
|
return url
|
|
1524
1589
|
|
|
1590
|
+
@_like_hosted
|
|
1525
1591
|
async def save(self, url: str, *, filename: str | None = None, key: str | None = None) -> dict[str, Any]:
|
|
1526
1592
|
if self._storage is None or isinstance(self._storage, UnavailablePlatformService):
|
|
1527
1593
|
raise PlatformServiceUnavailable(
|
|
@@ -975,6 +975,13 @@ except MediaStillRunning as pending:
|
|
|
975
975
|
job = await ctx.media.submit("fal-ai/kling-video/v3/pro/text-to-video", {"prompt": "…"})
|
|
976
976
|
state = await ctx.media.status(job["request_id"], model=job["model"])
|
|
977
977
|
|
|
978
|
+
# A model that answers in a second or two (SAM on a click): one request to fal's
|
|
979
|
+
# synchronous endpoint, no queue and no polls. timeout defaults to 60 s; no handle.
|
|
980
|
+
mask = await ctx.media.run("fal-ai/sam-3/image", {"image_url": url, "prompt": "shoe"}, sync=True)
|
|
981
|
+
|
|
982
|
+
# fal refusing a call: ValueError (4xx, change the request) or PlatformServiceUnavailable
|
|
983
|
+
# (5xx, try again later), both with .status_code; read it with getattr(exc, "status_code", None).
|
|
984
|
+
|
|
978
985
|
# Web search + reader (HTML tables and PDFs already handled).
|
|
979
986
|
hits = await ctx.web.search("palette os changelog", limit=5)
|
|
980
987
|
text = await ctx.web.fetch("https://example.com/report.pdf")
|