@palettelab/cli 0.3.65 → 0.3.67
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 +33 -5
- package/backend-sdk/palette_sdk/__init__.py +7 -1
- package/backend-sdk/palette_sdk/manifest.py +7 -0
- package/backend-sdk/palette_sdk/platform_services.py +566 -90
- package/backend-sdk/palette_sdk/plugin_context.py +7 -4
- package/backend-sdk/pyproject.toml +1 -1
- package/lib/cli.js +9 -1
- package/lib/commands/models.js +65 -0
- package/lib/manifest.js +26 -4
- package/package.json +1 -1
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/backend/api/main.py +10 -5
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
package/README.md
CHANGED
|
@@ -324,9 +324,9 @@ Backend SDK features for app-owned data:
|
|
|
324
324
|
- `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
|
|
325
325
|
- `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
|
|
326
326
|
- `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
|
|
327
|
-
- `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.
|
|
328
|
-
- `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, and reports `ctx.llm.models()`
|
|
329
|
-
- `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` handle multi-minute renders, `upload` puts
|
|
327
|
+
- `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 standard-tier model with `model=`; premium models need `platform_services.llm.models` (declared in the manifest the publish review approves), and nothing bypasses the org'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. Spend is metered per organisation and app and refused once the monthly budget is spent.
|
|
328
|
+
- `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, 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.
|
|
329
|
+
- `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 shares one monthly wallet with `ctx.llm`.
|
|
330
330
|
- `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
|
|
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.
|
|
332
332
|
- `ctx.connections` gives the viewer's OS service connections — see `pltt connections`.
|
|
@@ -1010,8 +1010,8 @@ pltt platform disable web
|
|
|
1010
1010
|
|
|
1011
1011
|
| Service | Replaces | `ctx.*` |
|
|
1012
1012
|
|---|---|---|
|
|
1013
|
-
| `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat, streaming, embeddings, image generation |
|
|
1014
|
-
| `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes |
|
|
1013
|
+
| `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat with tool calls, streaming, embeddings, image generation; receipts name the model that ran |
|
|
1014
|
+
| `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes; `upload()` for private inputs |
|
|
1015
1015
|
| `web` | `TAVILY_API_KEY` / `SERPAPI_KEY` | search + SSRF-guarded page reader |
|
|
1016
1016
|
| `storage` | an S3/GCS bucket | per-app, per-org objects with resumable uploads |
|
|
1017
1017
|
| `vector` | a Pinecone/Qdrant account | namespaced vector search |
|
|
@@ -1033,10 +1033,38 @@ Notes:
|
|
|
1033
1033
|
deterministic stubs when it does not. `pltt doctor` prints which mode each
|
|
1034
1034
|
one is in.
|
|
1035
1035
|
|
|
1036
|
+
- Premium models and bigger calls are declared on `llm`'s object form —
|
|
1037
|
+
`{"llm": {"models": ["gpt-6-astra"], "max_output_tokens": 12000, "max_images": 16}}` —
|
|
1038
|
+
in the manifest the publish review approves. `pltt build` / `pltt test` validate it.
|
|
1039
|
+
|
|
1036
1040
|
`pltt platform` is about what the *platform* provides. For app-to-app contracts
|
|
1037
1041
|
see `pltt services`; for third-party accounts the *user* connected see
|
|
1038
1042
|
`pltt connections`.
|
|
1039
1043
|
|
|
1044
|
+
### `pltt models`
|
|
1045
|
+
|
|
1046
|
+
The chat, image, video and audio models your app can use **in your workspace
|
|
1047
|
+
right now**, as `ctx.llm.catalog()` / `ctx.media.catalog()` would report them
|
|
1048
|
+
at runtime. Your `palette-plugin.json` is sent along, so declared premium
|
|
1049
|
+
models and capacity are reflected. Needs `pltt login` (a publish token).
|
|
1050
|
+
|
|
1051
|
+
```bash
|
|
1052
|
+
pltt models # every model: provider, kind, limits, why not
|
|
1053
|
+
pltt models --kind image --available # only the image models you can run
|
|
1054
|
+
pltt models --json --env staging
|
|
1055
|
+
```
|
|
1056
|
+
|
|
1057
|
+
```text
|
|
1058
|
+
ok gpt-6-astra openai chat 12000 out tok, 16 img
|
|
1059
|
+
-- claude-fable-5-1 anthropic chat 4096 out tok, 4 img (not_approved)
|
|
1060
|
+
ok fal-ai/nano-banana/edit fal image image-to-image
|
|
1061
|
+
```
|
|
1062
|
+
|
|
1063
|
+
`reason` values: `unknown_model`, `provider_unconfigured`, `not_approved`
|
|
1064
|
+
(declare it in `platform_services.llm.models`), `billing_disabled`,
|
|
1065
|
+
`org_policy` (SECURE workspace), `budget_exhausted`. The same reason is what a
|
|
1066
|
+
`fallback=False` call raises as `ModelUnavailable`.
|
|
1067
|
+
|
|
1040
1068
|
### `pltt connections`
|
|
1041
1069
|
|
|
1042
1070
|
Use the third-party services the OS already holds — Gmail, Drive, Calendar,
|
|
@@ -16,7 +16,10 @@ from palette_sdk.platform_services import (
|
|
|
16
16
|
LocalRedisService,
|
|
17
17
|
LocalVectorService,
|
|
18
18
|
LocalWebService,
|
|
19
|
+
MediaRateLimited,
|
|
19
20
|
MediaStillRunning,
|
|
21
|
+
MediaSubmitInterrupted,
|
|
22
|
+
ModelUnavailable,
|
|
20
23
|
PlatformServiceUnavailable,
|
|
21
24
|
UnavailablePlatformService,
|
|
22
25
|
)
|
|
@@ -92,7 +95,10 @@ __all__ = [
|
|
|
92
95
|
"LocalRedisService",
|
|
93
96
|
"LocalVectorService",
|
|
94
97
|
"LocalWebService",
|
|
98
|
+
"MediaRateLimited",
|
|
95
99
|
"MediaStillRunning",
|
|
100
|
+
"MediaSubmitInterrupted",
|
|
101
|
+
"ModelUnavailable",
|
|
96
102
|
"PlatformServiceUnavailable",
|
|
97
103
|
"UnavailablePlatformService",
|
|
98
104
|
"OrgRepository",
|
|
@@ -148,4 +154,4 @@ __all__ = [
|
|
|
148
154
|
"LocalStorageService",
|
|
149
155
|
]
|
|
150
156
|
|
|
151
|
-
__version__ = "0.1.
|
|
157
|
+
__version__ = "0.1.16"
|
|
@@ -227,6 +227,13 @@ class ConsumesSpec(BaseModel):
|
|
|
227
227
|
class PlatformServiceSpec(BaseModel):
|
|
228
228
|
required: bool = False
|
|
229
229
|
billing: Literal["org_wallet", "plugin_owner", "platform"] | None = None
|
|
230
|
+
# llm only — premium models (gpt-6-astra, claude-opus-*, claude-fable-*)
|
|
231
|
+
# and the capacity the app needs, declared where the publish review sees
|
|
232
|
+
# them and bounded by the platform. Without them: standard models, 4096
|
|
233
|
+
# output tokens and 4 images per call.
|
|
234
|
+
models: list[str] | None = Field(default=None, max_length=50)
|
|
235
|
+
max_output_tokens: int | None = Field(default=None, ge=0, le=200_000)
|
|
236
|
+
max_images: int | None = Field(default=None, ge=0, le=100)
|
|
230
237
|
|
|
231
238
|
|
|
232
239
|
class McpToolSpec(BaseModel):
|
|
@@ -2,15 +2,112 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import hashlib
|
|
7
|
+
import json
|
|
6
8
|
import math
|
|
9
|
+
import sys
|
|
7
10
|
import time
|
|
11
|
+
import types
|
|
8
12
|
from dataclasses import dataclass, field
|
|
9
13
|
from typing import Any
|
|
10
14
|
|
|
11
15
|
|
|
16
|
+
# ---- errors shared with palette_sdk -----------------------------------------
|
|
17
|
+
# Every app bundle vendors its own palette_sdk and the loader re-imports it per
|
|
18
|
+
# app, so a class defined in a module is a different object in every app: an
|
|
19
|
+
# `except MediaStillRunning` in app code never matched the one raised here.
|
|
20
|
+
# The platform and every SDK copy therefore take their error classes from ONE
|
|
21
|
+
# registry module per process — whoever imports first defines them. Keep this
|
|
22
|
+
# block identical to backend/app/plugins/platform_services.py
|
|
23
|
+
# (backend test_platform_errors_shared pins it). Constructors accept **details so a
|
|
24
|
+
# newer caller never breaks an older definition that won the race.
|
|
25
|
+
_ERRORS_MODULE = "palette_platform_errors"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _shared(cls: type) -> type:
|
|
29
|
+
registry = sys.modules.setdefault(_ERRORS_MODULE, types.ModuleType(_ERRORS_MODULE))
|
|
30
|
+
return registry.__dict__.setdefault(cls.__name__, cls)
|
|
31
|
+
|
|
32
|
+
|
|
12
33
|
class PlatformServiceUnavailable(RuntimeError):
|
|
13
|
-
"""
|
|
34
|
+
"""A ctx.* platform service cannot serve this call: not declared in the
|
|
35
|
+
manifest, not configured on this platform, or over the monthly budget."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, message: str = "", **details: Any):
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.__dict__.update(details)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
PlatformServiceUnavailable = _shared(PlatformServiceUnavailable)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ModelUnavailable(PlatformServiceUnavailable):
|
|
46
|
+
"""ctx.llm will not run `model` and the call asked for no substitute
|
|
47
|
+
(`fallback=False`). `reason`: unknown_model, provider_unconfigured,
|
|
48
|
+
not_approved, billing_disabled, org_policy."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, message: str = "", *, model: str | None = None, reason: str | None = None, **details: Any):
|
|
51
|
+
super().__init__(
|
|
52
|
+
message or f"ctx.llm: model {model!r} is unavailable ({reason})",
|
|
53
|
+
model=model,
|
|
54
|
+
reason=reason,
|
|
55
|
+
**details,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
ModelUnavailable = _shared(ModelUnavailable)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class MediaRateLimited(PlatformServiceUnavailable):
|
|
63
|
+
"""fal kept answering 429 after the platform's own retries. Nothing was
|
|
64
|
+
queued or billed; wait `retry_after` seconds (None = unknown) or move the
|
|
65
|
+
work into ctx.jobs."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, message: str = "", *, model: str | None = None, retry_after: float | None = None, **details: Any):
|
|
68
|
+
super().__init__(
|
|
69
|
+
message or f"ctx.media: fal is rate limiting {model} — retry later",
|
|
70
|
+
model=model,
|
|
71
|
+
retry_after=retry_after,
|
|
72
|
+
**details,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
MediaRateLimited = _shared(MediaRateLimited)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class MediaSubmitInterrupted(RuntimeError):
|
|
80
|
+
"""The submit reached fal but its answer was lost (timeout, dropped
|
|
81
|
+
connection, gateway error). The job MAY exist and MAY be billed, and there
|
|
82
|
+
is no handle to collect it. The platform never resubmits on its own —
|
|
83
|
+
resubmitting is the app's decision, and it can mean paying twice."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, message: str = "", *, model: str | None = None, **details: Any):
|
|
86
|
+
super().__init__(message or f"ctx.media: submitting {model} was interrupted; the job may or may not exist")
|
|
87
|
+
self.model = model
|
|
88
|
+
self.__dict__.update(details)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
MediaSubmitInterrupted = _shared(MediaSubmitInterrupted)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class MediaStillRunning(TimeoutError):
|
|
95
|
+
"""The fal job is still going (or could not be polled right now).
|
|
96
|
+
|
|
97
|
+
`handle` is the durable resume handle — persist it (a DB row, ctx.jobs
|
|
98
|
+
payload, the browser) and collect with `ctx.media.result(handle)`.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, request_id: str = "", model: str = "", **handle: Any):
|
|
102
|
+
super().__init__(
|
|
103
|
+
f"ctx.media: {model} is still running — collect it with ctx.media.result(exc.handle)"
|
|
104
|
+
)
|
|
105
|
+
self.request_id = request_id
|
|
106
|
+
self.model = model
|
|
107
|
+
self.handle = {"request_id": request_id, "model": model, **handle}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
MediaStillRunning = _shared(MediaStillRunning)
|
|
14
111
|
|
|
15
112
|
|
|
16
113
|
class UnavailablePlatformService:
|
|
@@ -377,13 +474,125 @@ class LocalVectorService:
|
|
|
377
474
|
return {"indexes": {name: len(items) for name, items in self._items.items()}}
|
|
378
475
|
|
|
379
476
|
|
|
380
|
-
|
|
381
|
-
|
|
477
|
+
_TOOL_NAME_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-")
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _text_of(content: Any) -> str:
|
|
481
|
+
if isinstance(content, str):
|
|
482
|
+
return content
|
|
483
|
+
if not isinstance(content, list):
|
|
484
|
+
return str(content or "")
|
|
485
|
+
return "".join(
|
|
486
|
+
str(block.get("text") or "")
|
|
487
|
+
for block in content
|
|
488
|
+
if isinstance(block, dict) and block.get("type", "text") in ("text", "output_text")
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _openai_tools(tools: Any) -> list[dict[str, Any]]:
|
|
493
|
+
"""Same tool shapes and checks as hosted ctx.llm, as OpenAI function tools."""
|
|
494
|
+
if not tools:
|
|
495
|
+
return []
|
|
496
|
+
if not isinstance(tools, (list, tuple)) or len(tools) > 128:
|
|
497
|
+
raise ValueError("ctx.llm: tools must be a list of at most 128 function definitions")
|
|
498
|
+
out: list[dict[str, Any]] = []
|
|
499
|
+
for tool in tools:
|
|
500
|
+
if not isinstance(tool, dict) or tool.get("type", "function") != "function":
|
|
501
|
+
raise ValueError("ctx.llm: only function tools are supported ({name, description, parameters})")
|
|
502
|
+
fn = tool["function"] if isinstance(tool.get("function"), dict) else tool
|
|
503
|
+
name = fn.get("name")
|
|
504
|
+
if (
|
|
505
|
+
not isinstance(name, str)
|
|
506
|
+
or not 0 < len(name) <= 64
|
|
507
|
+
or set(name) - _TOOL_NAME_CHARS
|
|
508
|
+
or name in {t["function"]["name"] for t in out}
|
|
509
|
+
):
|
|
510
|
+
raise ValueError(f"ctx.llm: tool names must be unique and match [A-Za-z0-9_-]{{1,64}} (got {name!r})")
|
|
511
|
+
parameters = fn.get("parameters", fn.get("input_schema")) or {"type": "object", "properties": {}}
|
|
512
|
+
if not isinstance(parameters, dict):
|
|
513
|
+
raise ValueError(f"ctx.llm: tool {name!r} parameters must be a JSON-schema object")
|
|
514
|
+
out.append({
|
|
515
|
+
"type": "function",
|
|
516
|
+
"function": {"name": name, "description": str(fn.get("description") or ""), "parameters": parameters},
|
|
517
|
+
})
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _openai_tool_choice(choice: Any, tools: list[dict[str, Any]]) -> Any:
|
|
522
|
+
if choice is None or choice == "auto":
|
|
523
|
+
return None
|
|
524
|
+
if isinstance(choice, dict):
|
|
525
|
+
choice = (choice.get("function") or {}).get("name") or choice.get("name")
|
|
526
|
+
if choice in ("required", "any"):
|
|
527
|
+
return "required"
|
|
528
|
+
if choice == "none":
|
|
529
|
+
return "none"
|
|
530
|
+
if not isinstance(choice, str) or choice not in {t["function"]["name"] for t in tools}:
|
|
531
|
+
raise ValueError("ctx.llm: tool_choice must be 'auto', 'none', 'required' or the name of a passed tool")
|
|
532
|
+
return {"type": "function", "function": {"name": choice}}
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _openai_messages(messages: list[dict[str, Any]], system: str | None) -> list[dict[str, Any]]:
|
|
536
|
+
"""The hosted ctx.llm history format, spoken as chat-completions."""
|
|
537
|
+
systems = [system] if system else []
|
|
538
|
+
out: list[dict[str, Any]] = []
|
|
539
|
+
for message in messages or []:
|
|
540
|
+
if not isinstance(message, dict):
|
|
541
|
+
raise ValueError("ctx.llm: every message must be a dict with a role")
|
|
542
|
+
role = str(message.get("role") or "user")
|
|
543
|
+
content = message.get("content")
|
|
544
|
+
if role in ("system", "developer"):
|
|
545
|
+
systems.append(_text_of(content))
|
|
546
|
+
elif role == "assistant":
|
|
547
|
+
entry: dict[str, Any] = {"role": "assistant", "content": _text_of(content) or None}
|
|
548
|
+
calls = []
|
|
549
|
+
for call in message.get("tool_calls") or []:
|
|
550
|
+
fn = call["function"] if isinstance(call.get("function"), dict) else call
|
|
551
|
+
args = fn.get("arguments", fn.get("args")) or {}
|
|
552
|
+
calls.append({
|
|
553
|
+
"id": str(call.get("id") or ""),
|
|
554
|
+
"type": "function",
|
|
555
|
+
"function": {"name": str(fn.get("name") or ""), "arguments": args if isinstance(args, str) else json.dumps(args)},
|
|
556
|
+
})
|
|
557
|
+
if calls:
|
|
558
|
+
entry["tool_calls"] = calls
|
|
559
|
+
out.append(entry)
|
|
560
|
+
elif role == "tool":
|
|
561
|
+
if not message.get("tool_call_id"):
|
|
562
|
+
raise ValueError("ctx.llm: a role=tool message needs the tool_call_id it answers")
|
|
563
|
+
out.append({
|
|
564
|
+
"role": "tool",
|
|
565
|
+
"tool_call_id": str(message["tool_call_id"]),
|
|
566
|
+
"content": content if isinstance(content, str) else json.dumps(content, default=str),
|
|
567
|
+
})
|
|
568
|
+
else:
|
|
569
|
+
out.append({"role": "user", "content": content if isinstance(content, list) else str(content or "")})
|
|
570
|
+
if systems:
|
|
571
|
+
out.insert(0, {"role": "system", "content": "\n\n".join(text for text in systems if text)})
|
|
572
|
+
return out
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _stop_reason(raw: Any, has_calls: bool) -> str:
|
|
576
|
+
key = str(raw or "").lower()
|
|
577
|
+
if key in ("length", "max_tokens", "max_output_tokens"):
|
|
578
|
+
return "length"
|
|
579
|
+
if key in ("content_filter", "refusal", "safety"):
|
|
580
|
+
return "content_filter"
|
|
581
|
+
if has_calls or key in ("tool_calls", "function_call", "tool_use"):
|
|
582
|
+
return "tool_calls"
|
|
583
|
+
return "stop"
|
|
584
|
+
|
|
382
585
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
586
|
+
class LocalLLMService:
|
|
587
|
+
"""`ctx.llm` for pltt dev — the hosted call shapes and receipt keys.
|
|
588
|
+
|
|
589
|
+
Hosted, this is the platform's catalog on its keys, under an org spend cap.
|
|
590
|
+
Locally there is no platform: OpenAI models run on the developer's own
|
|
591
|
+
`OPENAI_API_KEY` when the dev env supplies one; without a key every call
|
|
592
|
+
returns a deterministic stub, so the app's code path still runs with zero
|
|
593
|
+
setup. Claude and Gemini ids run hosted only (`pltt dev --sandbox`): here
|
|
594
|
+
they are `provider_unconfigured` — a ModelUnavailable with fallback=False,
|
|
595
|
+
the dev model plus an honest receipt otherwise.
|
|
387
596
|
"""
|
|
388
597
|
|
|
389
598
|
def __init__(self, api_key: str | None = None, model: str = "gpt-5.4-mini"):
|
|
@@ -394,21 +603,106 @@ class LocalLLMService:
|
|
|
394
603
|
def live(self) -> bool:
|
|
395
604
|
return bool(self.api_key)
|
|
396
605
|
|
|
606
|
+
def _pick(self, requested: str | None, fallback: bool) -> tuple[str, str | None]:
|
|
607
|
+
if not requested or (self.live and requested.startswith(("gpt-", "o1", "o3", "o4"))):
|
|
608
|
+
return requested or self.model, None
|
|
609
|
+
if not fallback:
|
|
610
|
+
raise ModelUnavailable(
|
|
611
|
+
f"ctx.llm: {requested!r} is unavailable under pltt dev — only OpenAI ids run, on an "
|
|
612
|
+
"OPENAI_API_KEY in .env.local; use pltt dev --sandbox for the platform catalog",
|
|
613
|
+
model=requested,
|
|
614
|
+
reason="provider_unconfigured",
|
|
615
|
+
)
|
|
616
|
+
return self.model, "provider_unconfigured"
|
|
617
|
+
|
|
397
618
|
@staticmethod
|
|
398
619
|
def _last_user(messages: list[dict[str, Any]]) -> str:
|
|
399
620
|
for message in reversed(messages or []):
|
|
400
621
|
if str(message.get("role") or "user") == "user":
|
|
401
|
-
return
|
|
622
|
+
return _text_of(message.get("content"))
|
|
402
623
|
return ""
|
|
403
624
|
|
|
404
|
-
def
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
625
|
+
def _receipt(
|
|
626
|
+
self,
|
|
627
|
+
*,
|
|
628
|
+
text: str,
|
|
629
|
+
calls: list[dict[str, Any]],
|
|
630
|
+
broken: list[dict[str, Any]],
|
|
631
|
+
finish: Any,
|
|
632
|
+
model: str,
|
|
633
|
+
provider: str,
|
|
634
|
+
requested: str | None,
|
|
635
|
+
reason: str | None,
|
|
636
|
+
usage: dict[str, int],
|
|
637
|
+
max_tokens: int,
|
|
638
|
+
) -> dict[str, Any]:
|
|
639
|
+
stop = _stop_reason(finish, bool(calls or broken))
|
|
640
|
+
message: dict[str, Any] = {"role": "assistant", "content": text}
|
|
641
|
+
if calls:
|
|
642
|
+
message["tool_calls"] = calls
|
|
643
|
+
out = {
|
|
644
|
+
"text": text,
|
|
645
|
+
"model": model,
|
|
646
|
+
"provider": provider,
|
|
647
|
+
"provider_model": model,
|
|
648
|
+
"requested_model": requested,
|
|
649
|
+
"fallback_used": reason is not None,
|
|
650
|
+
"fallback_reason": reason,
|
|
651
|
+
"attempts": [],
|
|
652
|
+
"stop_reason": stop,
|
|
653
|
+
"provider_stop_reason": finish,
|
|
654
|
+
"truncated": stop == "length",
|
|
655
|
+
"tool_calls": calls,
|
|
656
|
+
"message": message,
|
|
657
|
+
"max_tokens": max_tokens,
|
|
658
|
+
"input_tokens": usage.get("input_tokens", 0),
|
|
659
|
+
"output_tokens": usage.get("output_tokens", 0),
|
|
660
|
+
"usage": {"cached_input_tokens": 0, "reasoning_tokens": 0, **usage},
|
|
661
|
+
"cost_usd": None,
|
|
662
|
+
}
|
|
663
|
+
if broken:
|
|
664
|
+
out["invalid_tool_calls"] = broken
|
|
665
|
+
return out
|
|
666
|
+
|
|
667
|
+
def _stub(self, messages, requested: str | None, max_tokens: int) -> dict[str, Any]:
|
|
668
|
+
return self._receipt(
|
|
669
|
+
text=f"[pltt dev: no LLM key] {self._last_user(messages)}",
|
|
670
|
+
calls=[],
|
|
671
|
+
broken=[],
|
|
672
|
+
finish="stop",
|
|
673
|
+
model="pltt-dev-stub",
|
|
674
|
+
provider="pltt-dev",
|
|
675
|
+
requested=requested,
|
|
676
|
+
reason="provider_unconfigured" if requested else None,
|
|
677
|
+
usage={"input_tokens": 0, "output_tokens": 0},
|
|
678
|
+
max_tokens=max_tokens,
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
def _request(self, messages, system, model, max_tokens, tools, tool_choice, kwargs) -> dict[str, Any]:
|
|
682
|
+
specs = _openai_tools(tools)
|
|
683
|
+
body: dict[str, Any] = {
|
|
684
|
+
"model": model,
|
|
685
|
+
"messages": _openai_messages(messages, system),
|
|
686
|
+
"max_completion_tokens": max_tokens,
|
|
687
|
+
**kwargs,
|
|
411
688
|
}
|
|
689
|
+
if specs:
|
|
690
|
+
body["tools"] = specs
|
|
691
|
+
choice = _openai_tool_choice(tool_choice, specs)
|
|
692
|
+
if choice is not None:
|
|
693
|
+
body["tool_choice"] = choice
|
|
694
|
+
return body
|
|
695
|
+
|
|
696
|
+
@staticmethod
|
|
697
|
+
def _calls(raw_calls: list[tuple[str, str, str]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
698
|
+
calls, broken = [], []
|
|
699
|
+
for call_id, name, arguments in raw_calls:
|
|
700
|
+
try:
|
|
701
|
+
args = json.loads(arguments) if arguments.strip() else {}
|
|
702
|
+
calls.append({"id": call_id, "name": name, "arguments": args if isinstance(args, dict) else {"value": args}})
|
|
703
|
+
except ValueError as exc:
|
|
704
|
+
broken.append({"id": call_id, "name": name, "raw_arguments": arguments, "error": str(exc)})
|
|
705
|
+
return calls, broken
|
|
412
706
|
|
|
413
707
|
async def chat(
|
|
414
708
|
self,
|
|
@@ -418,47 +712,105 @@ class LocalLLMService:
|
|
|
418
712
|
system: str | None = None,
|
|
419
713
|
max_tokens: int = 1024,
|
|
420
714
|
temperature: float = 0.2,
|
|
715
|
+
tools: list[dict[str, Any]] | None = None,
|
|
716
|
+
tool_choice: Any = None,
|
|
717
|
+
fallback: bool = True,
|
|
421
718
|
**kwargs: Any,
|
|
422
719
|
) -> dict[str, Any]:
|
|
720
|
+
requested = (model or "").strip() or None
|
|
721
|
+
# Same checks as hosted, stubbed or not: bad tools / tool_choice are a
|
|
722
|
+
# ValueError and fallback=False refuses what pltt dev cannot run.
|
|
723
|
+
specs = _openai_tools(tools)
|
|
724
|
+
if specs:
|
|
725
|
+
_openai_tool_choice(tool_choice, specs)
|
|
726
|
+
used, reason = self._pick(requested, fallback)
|
|
423
727
|
if not self.live:
|
|
424
|
-
return self._stub(messages)
|
|
728
|
+
return self._stub(messages, requested, max_tokens)
|
|
425
729
|
from openai import AsyncOpenAI
|
|
426
730
|
|
|
427
|
-
payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
|
|
428
731
|
reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
|
|
429
|
-
|
|
732
|
+
**self._request(messages, system, used, max_tokens, tools, tool_choice, kwargs)
|
|
430
733
|
)
|
|
734
|
+
choice = reply.choices[0]
|
|
735
|
+
calls, broken = self._calls([
|
|
736
|
+
(call.id, call.function.name, call.function.arguments or "")
|
|
737
|
+
for call in (choice.message.tool_calls or [])
|
|
738
|
+
])
|
|
431
739
|
usage = reply.usage
|
|
432
|
-
return
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
740
|
+
return self._receipt(
|
|
741
|
+
text=choice.message.content or "",
|
|
742
|
+
calls=calls,
|
|
743
|
+
broken=broken,
|
|
744
|
+
finish=choice.finish_reason,
|
|
745
|
+
model=used,
|
|
746
|
+
provider="openai",
|
|
747
|
+
requested=requested,
|
|
748
|
+
reason=reason,
|
|
749
|
+
usage={
|
|
750
|
+
"input_tokens": getattr(usage, "prompt_tokens", 0) or 0,
|
|
751
|
+
"output_tokens": getattr(usage, "completion_tokens", 0) or 0,
|
|
752
|
+
},
|
|
753
|
+
max_tokens=max_tokens,
|
|
754
|
+
)
|
|
439
755
|
|
|
440
|
-
async def stream(
|
|
756
|
+
async def stream(
|
|
757
|
+
self,
|
|
758
|
+
messages: list[dict[str, Any]],
|
|
759
|
+
*,
|
|
760
|
+
model: str | None = None,
|
|
761
|
+
system: str | None = None,
|
|
762
|
+
max_tokens: int = 1024,
|
|
763
|
+
temperature: float = 0.2,
|
|
764
|
+
tools: list[dict[str, Any]] | None = None,
|
|
765
|
+
tool_choice: Any = None,
|
|
766
|
+
fallback: bool = True,
|
|
767
|
+
events: bool = False,
|
|
768
|
+
**kwargs: Any,
|
|
769
|
+
):
|
|
770
|
+
requested = (model or "").strip() or None
|
|
771
|
+
specs = _openai_tools(tools)
|
|
772
|
+
if specs:
|
|
773
|
+
_openai_tool_choice(tool_choice, specs)
|
|
774
|
+
used, reason = self._pick(requested, fallback)
|
|
441
775
|
if not self.live:
|
|
442
|
-
|
|
776
|
+
stub = self._stub(messages, requested, max_tokens)
|
|
777
|
+
yield {"type": "text", "text": stub["text"]} if events else stub["text"]
|
|
778
|
+
if events:
|
|
779
|
+
yield {"type": "done", **stub}
|
|
443
780
|
return
|
|
444
781
|
from openai import AsyncOpenAI
|
|
445
782
|
|
|
446
|
-
|
|
447
|
-
payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
|
|
448
|
-
passthrough = {
|
|
449
|
-
k: v for k, v in kwargs.items() if k not in ("model", "system", "max_tokens", "temperature")
|
|
450
|
-
}
|
|
783
|
+
body = self._request(messages, system, used, max_tokens, tools, tool_choice, kwargs)
|
|
451
784
|
stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
|
|
452
|
-
|
|
453
|
-
messages=payload,
|
|
454
|
-
max_completion_tokens=kwargs.get("max_tokens", 1024),
|
|
455
|
-
stream=True,
|
|
456
|
-
**passthrough,
|
|
785
|
+
**body, stream=True, stream_options={"include_usage": True}
|
|
457
786
|
)
|
|
787
|
+
text: list[str] = []
|
|
788
|
+
pending: dict[int, list[str]] = {}
|
|
789
|
+
finish = None
|
|
790
|
+
usage = {"input_tokens": 0, "output_tokens": 0}
|
|
458
791
|
async for chunk in stream:
|
|
459
|
-
|
|
792
|
+
if chunk.usage:
|
|
793
|
+
usage = {"input_tokens": chunk.usage.prompt_tokens or 0, "output_tokens": chunk.usage.completion_tokens or 0}
|
|
794
|
+
if not chunk.choices:
|
|
795
|
+
continue
|
|
796
|
+
choice = chunk.choices[0]
|
|
797
|
+
finish = choice.finish_reason or finish
|
|
798
|
+
delta = choice.delta
|
|
460
799
|
if delta and delta.content:
|
|
461
|
-
|
|
800
|
+
text.append(delta.content)
|
|
801
|
+
yield {"type": "text", "text": delta.content} if events else delta.content
|
|
802
|
+
for call in (delta.tool_calls if delta else None) or []:
|
|
803
|
+
slot = pending.setdefault(call.index, ["", "", ""])
|
|
804
|
+
slot[0] = call.id or slot[0]
|
|
805
|
+
if call.function:
|
|
806
|
+
slot[1] = call.function.name or slot[1]
|
|
807
|
+
slot[2] += call.function.arguments or ""
|
|
808
|
+
if events:
|
|
809
|
+
calls, broken = self._calls([tuple(pending[index]) for index in sorted(pending)])
|
|
810
|
+
yield {"type": "done", **self._receipt(
|
|
811
|
+
text="".join(text), calls=calls, broken=broken, finish=finish, model=used, provider="openai",
|
|
812
|
+
requested=requested, reason=reason, usage=usage, max_tokens=max_tokens,
|
|
813
|
+
)}
|
|
462
814
|
|
|
463
815
|
async def embed(self, texts: list[str]) -> list[list[float]]:
|
|
464
816
|
if not self.live:
|
|
@@ -475,6 +827,22 @@ class LocalLLMService:
|
|
|
475
827
|
async def image(self, prompt: str, *, aspect_ratio: str = "1:1", **kwargs: Any) -> tuple[bytes, str]:
|
|
476
828
|
raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
|
|
477
829
|
|
|
830
|
+
async def catalog(self) -> list[dict[str, Any]]:
|
|
831
|
+
"""Hosted, every model on the platform with limits and availability
|
|
832
|
+
reasons. Locally only the dev model is known."""
|
|
833
|
+
return [{
|
|
834
|
+
"id": self.model,
|
|
835
|
+
"name": self.model,
|
|
836
|
+
"provider": "openai",
|
|
837
|
+
"kind": "chat",
|
|
838
|
+
"capabilities": ["chat", "streaming", "tools", "vision"],
|
|
839
|
+
"limits": {"max_output_tokens": None, "max_input_tokens": None, "max_images": None},
|
|
840
|
+
"tier": "standard",
|
|
841
|
+
"available": self.live,
|
|
842
|
+
"reason": None if self.live else "provider_unconfigured",
|
|
843
|
+
"default": True,
|
|
844
|
+
}]
|
|
845
|
+
|
|
478
846
|
async def models(self) -> list[str]:
|
|
479
847
|
"""Hosted, this is the list the platform will honour in `model=`.
|
|
480
848
|
Locally there is no catalog, so it reports the dev model only."""
|
|
@@ -521,23 +889,6 @@ _STUB_PNG = (
|
|
|
521
889
|
)
|
|
522
890
|
|
|
523
891
|
|
|
524
|
-
class MediaStillRunning(TimeoutError):
|
|
525
|
-
"""`ctx.media.run` gave up waiting; the fal job is still going.
|
|
526
|
-
|
|
527
|
-
Carries what is needed to collect it later, so a request handler can hand
|
|
528
|
-
the id to `ctx.jobs` (or return it to the browser) instead of holding a
|
|
529
|
-
connection open for a four-minute render.
|
|
530
|
-
"""
|
|
531
|
-
|
|
532
|
-
def __init__(self, request_id: str, model: str):
|
|
533
|
-
super().__init__(
|
|
534
|
-
f"ctx.media: {model} is still running — collect it with "
|
|
535
|
-
f"ctx.media.result({request_id!r}, model={model!r})"
|
|
536
|
-
)
|
|
537
|
-
self.request_id = request_id
|
|
538
|
-
self.model = model
|
|
539
|
-
|
|
540
|
-
|
|
541
892
|
class LocalMediaService:
|
|
542
893
|
"""`ctx.media` for pltt dev — the same fal.ai surface as hosted.
|
|
543
894
|
|
|
@@ -548,18 +899,25 @@ class LocalMediaService:
|
|
|
548
899
|
"""
|
|
549
900
|
|
|
550
901
|
QUEUE_BASE = "https://queue.fal.run"
|
|
551
|
-
|
|
902
|
+
# fal's own upload flow (fal-client "fal_v3"): trade the key for a CDN
|
|
903
|
+
# token, then POST the bytes. storage.fal.ai no longer resolves.
|
|
904
|
+
CDN_TOKEN_URL = "https://rest.fal.ai/storage/auth/token?storage_type=fal-cdn-v3"
|
|
905
|
+
CDN_UPLOAD_URL = "https://v3.fal.media/files/upload"
|
|
552
906
|
POLL_INTERVAL_S = 3.0
|
|
907
|
+
SUBMIT_ATTEMPTS = 3
|
|
908
|
+
RETRY_BASE_S = 1.0
|
|
553
909
|
DEFAULT_MODELS = {
|
|
554
910
|
"image": "fal-ai/flux/dev",
|
|
555
911
|
"video": "fal-ai/kling-video/v3/standard/text-to-video",
|
|
556
912
|
"speech": "fal-ai/elevenlabs/tts/turbo-v2.5",
|
|
557
913
|
"transcribe": "fal-ai/whisper",
|
|
558
914
|
}
|
|
915
|
+
_DEFAULT_KINDS = {"image": "image", "video": "video", "speech": "audio", "transcribe": "audio"}
|
|
559
916
|
|
|
560
917
|
def __init__(self, api_key: str | None = None, storage: Any = None):
|
|
561
918
|
self.api_key = api_key or ""
|
|
562
919
|
self._storage = storage
|
|
920
|
+
self._cdn_token: dict[str, Any] | None = None
|
|
563
921
|
|
|
564
922
|
@property
|
|
565
923
|
def live(self) -> bool:
|
|
@@ -577,6 +935,13 @@ class LocalMediaService:
|
|
|
577
935
|
root = f"{self.QUEUE_BASE}/{base}/requests/{request_id}"
|
|
578
936
|
return f"{root}/status", root, f"{root}/cancel"
|
|
579
937
|
|
|
938
|
+
@staticmethod
|
|
939
|
+
def _ref(request: Any, model: str | None) -> tuple[str, str]:
|
|
940
|
+
"""(request_id, model) from a submit() handle or a bare request id."""
|
|
941
|
+
if isinstance(request, dict):
|
|
942
|
+
return str(request.get("request_id") or ""), str(model or request.get("model") or "")
|
|
943
|
+
return str(request or ""), str(model or "")
|
|
944
|
+
|
|
580
945
|
@staticmethod
|
|
581
946
|
def _fal_host_ok(url: str) -> bool:
|
|
582
947
|
"""A url fetched with the FAL_KEY attached must be on fal's domains.
|
|
@@ -611,53 +976,87 @@ class LocalMediaService:
|
|
|
611
976
|
}
|
|
612
977
|
|
|
613
978
|
async def submit(self, model: str, payload: dict[str, Any] | None = None, **fields: Any) -> dict[str, Any]:
|
|
979
|
+
"""Queue a job; returns the durable handle {request_id, model,
|
|
980
|
+
status_url, response_url, cancel_url}. A 429 is retried with backoff,
|
|
981
|
+
then MediaRateLimited; a lost answer is MediaSubmitInterrupted."""
|
|
614
982
|
body = self._merge(payload, fields)
|
|
615
983
|
if not self.live:
|
|
616
|
-
return {
|
|
984
|
+
return {
|
|
985
|
+
"request_id": "pltt-dev-stub", "model": model, "status_url": "", "response_url": "",
|
|
986
|
+
"cancel_url": "", "request": body,
|
|
987
|
+
}
|
|
617
988
|
import httpx
|
|
618
989
|
|
|
619
990
|
async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
|
|
620
|
-
|
|
991
|
+
for attempt in range(1, self.SUBMIT_ATTEMPTS + 1):
|
|
992
|
+
try:
|
|
993
|
+
response = await client.post(f"{self.QUEUE_BASE}/{str(model).strip('/')}", json=body)
|
|
994
|
+
except (httpx.ConnectError, httpx.ConnectTimeout):
|
|
995
|
+
if attempt == self.SUBMIT_ATTEMPTS:
|
|
996
|
+
raise
|
|
997
|
+
await asyncio.sleep(self.RETRY_BASE_S * attempt)
|
|
998
|
+
continue
|
|
999
|
+
except httpx.TransportError as exc:
|
|
1000
|
+
raise MediaSubmitInterrupted(model=model) from exc
|
|
1001
|
+
if response.status_code in (502, 504):
|
|
1002
|
+
raise MediaSubmitInterrupted(model=model, status_code=response.status_code)
|
|
1003
|
+
if response.status_code != 429:
|
|
1004
|
+
break
|
|
1005
|
+
if attempt == self.SUBMIT_ATTEMPTS:
|
|
1006
|
+
retry = str(response.headers.get("retry-after") or "")
|
|
1007
|
+
raise MediaRateLimited(
|
|
1008
|
+
model=model, retry_after=float(retry) if retry.replace(".", "", 1).isdigit() else None
|
|
1009
|
+
)
|
|
1010
|
+
await asyncio.sleep(self.RETRY_BASE_S * attempt)
|
|
621
1011
|
response.raise_for_status()
|
|
622
1012
|
task = response.json() or {}
|
|
623
1013
|
request_id = str(task.get("request_id") or "")
|
|
624
|
-
rebuilt_status, rebuilt_response,
|
|
1014
|
+
rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
|
|
625
1015
|
provider_status = str(task.get("status_url") or "")
|
|
626
1016
|
provider_response = str(task.get("response_url") or "")
|
|
1017
|
+
provider_cancel = str(task.get("cancel_url") or "")
|
|
627
1018
|
return {
|
|
628
1019
|
"request_id": request_id,
|
|
629
1020
|
"model": model,
|
|
630
1021
|
"status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
|
|
631
1022
|
"response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
|
|
1023
|
+
"cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
|
|
632
1024
|
}
|
|
633
1025
|
|
|
634
|
-
async def status(self,
|
|
1026
|
+
async def status(self, request: Any, *, model: str | None = None, **params: Any) -> dict[str, Any]:
|
|
635
1027
|
if not self.live:
|
|
636
1028
|
return {"status": "COMPLETED", "pltt_dev_stub": True}
|
|
637
1029
|
import httpx
|
|
638
1030
|
|
|
1031
|
+
request_id, model = self._ref(request, model)
|
|
639
1032
|
status_url, _response, _cancel = self._queue_urls(model, request_id)
|
|
640
1033
|
async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
|
|
641
1034
|
response = await client.get(status_url, params=params or None)
|
|
642
1035
|
response.raise_for_status()
|
|
643
1036
|
return response.json() or {}
|
|
644
1037
|
|
|
645
|
-
async def result(self,
|
|
1038
|
+
async def result(self, request: Any, *, model: str | None = None) -> dict[str, Any]:
|
|
1039
|
+
"""The finished output; an unfinished job raises MediaStillRunning."""
|
|
1040
|
+
request_id, model = self._ref(request, model)
|
|
646
1041
|
if not self.live:
|
|
647
1042
|
return self._stub(model, {})
|
|
648
1043
|
import httpx
|
|
649
1044
|
|
|
1045
|
+
state = await self.status(request_id, model=model)
|
|
1046
|
+
if str(state.get("status") or "").upper() in ("IN_QUEUE", "IN_PROGRESS"):
|
|
1047
|
+
raise MediaStillRunning(request_id, model)
|
|
650
1048
|
_status, response_url, _cancel = self._queue_urls(model, request_id)
|
|
651
1049
|
async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
|
|
652
1050
|
response = await client.get(response_url)
|
|
653
1051
|
response.raise_for_status()
|
|
654
1052
|
return response.json() or {}
|
|
655
1053
|
|
|
656
|
-
async def cancel(self,
|
|
1054
|
+
async def cancel(self, request: Any, *, model: str | None = None) -> dict[str, Any]:
|
|
657
1055
|
if not self.live:
|
|
658
1056
|
return {"cancelled": True, "pltt_dev_stub": True}
|
|
659
1057
|
import httpx
|
|
660
1058
|
|
|
1059
|
+
request_id, model = self._ref(request, model)
|
|
661
1060
|
_status, _response, cancel_url = self._queue_urls(model, request_id)
|
|
662
1061
|
async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
|
|
663
1062
|
response = await client.put(cancel_url)
|
|
@@ -676,19 +1075,23 @@ class LocalMediaService:
|
|
|
676
1075
|
body = self._merge(payload, fields)
|
|
677
1076
|
if not self.live:
|
|
678
1077
|
return self._stub(model, body)
|
|
679
|
-
import asyncio
|
|
680
|
-
|
|
681
1078
|
import httpx
|
|
682
1079
|
|
|
683
1080
|
job = await self.submit(model, body)
|
|
1081
|
+
handle = {key: value for key, value in job.items() if key not in ("request_id", "model")}
|
|
684
1082
|
deadline = time.monotonic() + float(timeout if timeout is not None else 600.0)
|
|
685
1083
|
interval = float(poll_interval or self.POLL_INTERVAL_S)
|
|
686
1084
|
last = None
|
|
687
1085
|
async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
|
|
688
1086
|
while True:
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
1087
|
+
try:
|
|
1088
|
+
probe = await client.get(job["status_url"])
|
|
1089
|
+
probe.raise_for_status()
|
|
1090
|
+
body_state = probe.json() or {}
|
|
1091
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
1092
|
+
# Queued and paid for: hand back the handle, never lose it.
|
|
1093
|
+
raise MediaStillRunning(job["request_id"], model, **handle) from exc
|
|
1094
|
+
state = str(body_state.get("status") or "").upper()
|
|
692
1095
|
if state != last:
|
|
693
1096
|
last = state
|
|
694
1097
|
if on_status is not None:
|
|
@@ -698,9 +1101,9 @@ class LocalMediaService:
|
|
|
698
1101
|
if state == "COMPLETED":
|
|
699
1102
|
break
|
|
700
1103
|
if state in ("FAILED", "ERROR", "CANCELLED"):
|
|
701
|
-
raise RuntimeError(f"ctx.media: {model} {state.lower()} ({str(
|
|
1104
|
+
raise RuntimeError(f"ctx.media: {model} {state.lower()} ({str(body_state)[:300]})")
|
|
702
1105
|
if time.monotonic() > deadline:
|
|
703
|
-
raise MediaStillRunning(job["request_id"], model)
|
|
1106
|
+
raise MediaStillRunning(job["request_id"], model, **handle)
|
|
704
1107
|
await asyncio.sleep(interval)
|
|
705
1108
|
final = await client.get(job["response_url"])
|
|
706
1109
|
final.raise_for_status()
|
|
@@ -718,37 +1121,76 @@ class LocalMediaService:
|
|
|
718
1121
|
async def transcribe(self, audio_url: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
|
|
719
1122
|
return await self.run(model or self.DEFAULT_MODELS["transcribe"], {"audio_url": audio_url, **payload})
|
|
720
1123
|
|
|
1124
|
+
async def _source_bytes(self, source: Any) -> tuple[bytes, str | None]:
|
|
1125
|
+
"""bytes | data: URL | file:// URL inside local ctx.storage | https URL."""
|
|
1126
|
+
import base64
|
|
1127
|
+
from pathlib import Path
|
|
1128
|
+
from urllib.parse import unquote, unquote_to_bytes, urlparse
|
|
1129
|
+
|
|
1130
|
+
if isinstance(source, (bytes, bytearray, memoryview)):
|
|
1131
|
+
return bytes(source), None
|
|
1132
|
+
if not isinstance(source, str) or not source.strip():
|
|
1133
|
+
raise ValueError("ctx.media.upload: pass bytes, a data: URL, an https URL or a ctx.storage file URL")
|
|
1134
|
+
if source.startswith("data:"):
|
|
1135
|
+
header, _, encoded = source.partition(",")
|
|
1136
|
+
data = base64.b64decode(encoded) if ";base64" in header else unquote_to_bytes(encoded)
|
|
1137
|
+
return data, header[5:].split(";")[0] or None
|
|
1138
|
+
if source.startswith("file:"):
|
|
1139
|
+
# pltt dev's ctx.storage hands out file:// URLs; like hosted, only
|
|
1140
|
+
# this app's own storage is readable through upload().
|
|
1141
|
+
storage = self._storage
|
|
1142
|
+
root = getattr(storage, "root", None)
|
|
1143
|
+
target = Path(unquote(urlparse(source).path)).resolve()
|
|
1144
|
+
if root is None or not target.is_relative_to((Path(root) / storage._prefix()).resolve()):
|
|
1145
|
+
raise ValueError("ctx.media.upload: only this app's own ctx.storage files can be read by URL")
|
|
1146
|
+
return target.read_bytes(), None
|
|
1147
|
+
import httpx
|
|
1148
|
+
|
|
1149
|
+
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
|
|
1150
|
+
fetched = await client.get(source)
|
|
1151
|
+
fetched.raise_for_status()
|
|
1152
|
+
return fetched.content, (fetched.headers.get("content-type") or "").split(";")[0].strip() or None
|
|
1153
|
+
|
|
721
1154
|
async def upload(
|
|
722
1155
|
self,
|
|
723
1156
|
source: bytes | str,
|
|
724
1157
|
*,
|
|
725
|
-
filename: str =
|
|
726
|
-
content_type: str =
|
|
1158
|
+
filename: str | None = None,
|
|
1159
|
+
content_type: str | None = None,
|
|
727
1160
|
) -> str:
|
|
728
1161
|
if not self.live:
|
|
729
1162
|
return _STUB_PNG
|
|
730
1163
|
import httpx
|
|
1164
|
+
import mimetypes
|
|
1165
|
+
from urllib.parse import urlparse
|
|
731
1166
|
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
else:
|
|
739
|
-
content = bytes(source)
|
|
1167
|
+
content, detected = await self._source_bytes(source)
|
|
1168
|
+
mime = content_type or detected or _sniff_mime(content) or "application/octet-stream"
|
|
1169
|
+
name = filename
|
|
1170
|
+
if not name and isinstance(source, str) and not source.startswith("data:"):
|
|
1171
|
+
name = urlparse(source).path.rsplit("/", 1)[-1]
|
|
1172
|
+
name = name or f"upload{mimetypes.guess_extension(mime) or '.bin'}"
|
|
740
1173
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
|
741
|
-
|
|
742
|
-
self.
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
1174
|
+
for refresh in (False, True):
|
|
1175
|
+
if refresh or not self._cdn_token or self._cdn_token["expires"] < time.time() + 300:
|
|
1176
|
+
minted = await client.post(
|
|
1177
|
+
self.CDN_TOKEN_URL, headers={**self._headers(), "Accept": "application/json"}, json={}
|
|
1178
|
+
)
|
|
1179
|
+
minted.raise_for_status()
|
|
1180
|
+
data = minted.json() or {}
|
|
1181
|
+
self._cdn_token = {"auth": f"{data['token_type']} {data['token']}", "expires": time.time() + 3600}
|
|
1182
|
+
response = await client.post(
|
|
1183
|
+
self.CDN_UPLOAD_URL,
|
|
1184
|
+
content=content,
|
|
1185
|
+
headers={"Authorization": self._cdn_token["auth"], "Content-Type": mime, "X-Fal-File-Name": name},
|
|
1186
|
+
)
|
|
1187
|
+
if response.status_code != 401:
|
|
1188
|
+
break
|
|
746
1189
|
response.raise_for_status()
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
return str(url)
|
|
1190
|
+
url = str((response.json() or {}).get("access_url") or "")
|
|
1191
|
+
if not url.startswith("https://"):
|
|
1192
|
+
raise RuntimeError(f"ctx.media: fal upload returned no URL ({response.text[:200]})")
|
|
1193
|
+
return url
|
|
752
1194
|
|
|
753
1195
|
async def save(self, url: str, *, filename: str | None = None, key: str | None = None) -> dict[str, Any]:
|
|
754
1196
|
if self._storage is None or isinstance(self._storage, UnavailablePlatformService):
|
|
@@ -772,6 +1214,40 @@ class LocalMediaService:
|
|
|
772
1214
|
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";")[0].strip()
|
|
773
1215
|
return await self._storage.upload_file(name, content, content_type, key=key)
|
|
774
1216
|
|
|
1217
|
+
async def catalog(self, kind: str | None = None) -> list[dict[str, Any]]:
|
|
1218
|
+
"""Hosted, the platform's priced fal models with limits and reasons.
|
|
1219
|
+
Locally, the sugar defaults — `run()` still takes any fal id."""
|
|
1220
|
+
rows = []
|
|
1221
|
+
for sugar, model in sorted(self.DEFAULT_MODELS.items()):
|
|
1222
|
+
row_kind = self._DEFAULT_KINDS[sugar]
|
|
1223
|
+
if kind and row_kind != kind:
|
|
1224
|
+
continue
|
|
1225
|
+
rows.append({
|
|
1226
|
+
"id": model,
|
|
1227
|
+
"name": model,
|
|
1228
|
+
"provider": "fal",
|
|
1229
|
+
"kind": row_kind,
|
|
1230
|
+
"operations": [{"image": "text-to-image", "video": "text-to-video", "speech": "text-to-speech", "transcribe": "speech-to-text"}[sugar]],
|
|
1231
|
+
"limits": {"unit": "request", "max_units": None, "max_upload_bytes": 100 * 1024 * 1024},
|
|
1232
|
+
"available": self.live,
|
|
1233
|
+
"reason": None if self.live else "provider_unconfigured",
|
|
1234
|
+
"default_for": [sugar],
|
|
1235
|
+
})
|
|
1236
|
+
return rows
|
|
1237
|
+
|
|
775
1238
|
async def spend(self) -> dict[str, Any]:
|
|
776
1239
|
"""Hosted, the org's monthly wallet. Locally the developer's own key pays."""
|
|
777
1240
|
return {"spent_usd": 0.0, "cap_usd": None, "remaining_usd": None}
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
def _sniff_mime(content: bytes) -> str | None:
|
|
1244
|
+
"""fal models read the stored Content-Type; application/octet-stream is not an image."""
|
|
1245
|
+
if content.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
1246
|
+
return "image/png"
|
|
1247
|
+
if content.startswith(b"\xff\xd8\xff"):
|
|
1248
|
+
return "image/jpeg"
|
|
1249
|
+
if content[:4] == b"RIFF" and content[8:12] == b"WEBP":
|
|
1250
|
+
return "image/webp"
|
|
1251
|
+
if content.startswith((b"GIF87a", b"GIF89a")):
|
|
1252
|
+
return "image/gif"
|
|
1253
|
+
return None
|
|
@@ -55,12 +55,15 @@ class PluginContext:
|
|
|
55
55
|
talk: Post into Talk channels as the app's own agent identity
|
|
56
56
|
tasks: The caller's task board, scoped to the tasks this app created.
|
|
57
57
|
Needs `tasks:read` / `tasks:write` in the manifest.
|
|
58
|
-
llm: Chat / stream / embed / image on the platform's
|
|
59
|
-
the organisation's monthly spend cap
|
|
58
|
+
llm: Chat (with tool calls) / stream / embed / image on the platform's
|
|
59
|
+
model keys, under the organisation's monthly spend cap; replies name
|
|
60
|
+
the model that ran, `fallback=False` refuses substitutes, and
|
|
61
|
+
`catalog()` lists models for a picker. platform_services: ["llm"].
|
|
60
62
|
web: Web search + SSRF-guarded page reader. platform_services: ["web"].
|
|
61
63
|
media: fal.ai — image, video, speech, transcription, or any model fal
|
|
62
|
-
publishes, with the payload passed through untouched
|
|
63
|
-
|
|
64
|
+
publishes, with the payload passed through untouched; `upload()`
|
|
65
|
+
puts private files on fal's CDN, `submit()` returns a durable
|
|
66
|
+
handle. Needs platform_services: ["media"]; no FAL_KEY of its own.
|
|
64
67
|
"""
|
|
65
68
|
db: AsyncSession
|
|
66
69
|
user_id: str
|
package/lib/cli.js
CHANGED
|
@@ -18,6 +18,7 @@ const update = require("./commands/update")
|
|
|
18
18
|
const capabilities = require("./commands/capabilities")
|
|
19
19
|
const connections = require("./commands/connections")
|
|
20
20
|
const platform = require("./commands/platform")
|
|
21
|
+
const models = require("./commands/models")
|
|
21
22
|
|
|
22
23
|
const COMMANDS = {
|
|
23
24
|
init: { run: init, help: "Scaffold a new plugin directory from the template" },
|
|
@@ -69,6 +70,10 @@ const COMMANDS = {
|
|
|
69
70
|
run: platform,
|
|
70
71
|
help: "List / enable the platform services an app borrows through ctx.* (no keys of your own)",
|
|
71
72
|
},
|
|
73
|
+
models: {
|
|
74
|
+
run: models,
|
|
75
|
+
help: "List the chat/image/video/audio models this app can use in your workspace (ids, limits, why not)",
|
|
76
|
+
},
|
|
72
77
|
services: {
|
|
73
78
|
run: services,
|
|
74
79
|
help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
|
|
@@ -93,7 +98,7 @@ function printHelp() {
|
|
|
93
98
|
console.log(` ${name.padEnd(12)} ${help}`)
|
|
94
99
|
}
|
|
95
100
|
console.log("\nGlobal flags:")
|
|
96
|
-
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version, login, dev --sandbox, platform, services, capabilities)")
|
|
101
|
+
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version, login, dev --sandbox, platform, models, services, capabilities)")
|
|
97
102
|
console.log(" -v, --version Show the installed pltt CLI version")
|
|
98
103
|
console.log("\nPublish flags:")
|
|
99
104
|
console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
|
|
@@ -116,6 +121,9 @@ function printHelp() {
|
|
|
116
121
|
console.log(" pltt platform list # llm, media, storage, vector, redis, web")
|
|
117
122
|
console.log(" pltt platform enable llm media # declare them in palette-plugin.json")
|
|
118
123
|
console.log(" pltt platform disable web")
|
|
124
|
+
console.log("\nModels (what ctx.llm / ctx.media will run for this app):")
|
|
125
|
+
console.log(" pltt models # every model, with limits and disabled reasons")
|
|
126
|
+
console.log(" pltt models --kind image --available")
|
|
119
127
|
console.log("\nServices (OS broker):")
|
|
120
128
|
console.log(" pltt services list # show provided services/events in the org")
|
|
121
129
|
console.log(" pltt services add TARGET # add a consumed service/event target")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const { loadManifest } = require("../manifest")
|
|
4
|
+
const { parseFlags, resolveEnvironment } = require("../environments")
|
|
5
|
+
|
|
6
|
+
const KINDS = ["chat", "image", "video", "audio"]
|
|
7
|
+
const USAGE = "usage: pltt models [--kind chat|image|video|audio] [--available] [--json] [--env <name>]"
|
|
8
|
+
|
|
9
|
+
// The platform answers with THIS app's view: the manifest goes along so
|
|
10
|
+
// declared premium models and capacity (platform_services.llm) are reflected.
|
|
11
|
+
async function fetchModels(env, manifest) {
|
|
12
|
+
const url = `${env.url}/api/v1/appstore/platform-models`
|
|
13
|
+
const res = await fetch(url, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: { Authorization: `Bearer ${env.token}`, "Content-Type": "application/json" },
|
|
16
|
+
body: JSON.stringify({ manifest }),
|
|
17
|
+
})
|
|
18
|
+
if (!res.ok) throw new Error(`POST ${url} → ${res.status}: ${await res.text()}`)
|
|
19
|
+
return res.json()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function selectRows(data, { kind, available }) {
|
|
23
|
+
return [...(data.chat || []), ...(data.media || [])].filter(
|
|
24
|
+
(row) => (!kind || row.kind === kind) && (!available || row.available),
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatRow(row) {
|
|
29
|
+
const limits = row.limits || {}
|
|
30
|
+
const detail =
|
|
31
|
+
row.kind === "chat"
|
|
32
|
+
? `${limits.max_output_tokens ?? "?"} out tok, ${limits.max_images ?? "?"} img`
|
|
33
|
+
: (row.operations || []).join(", ")
|
|
34
|
+
const note = row.available ? (row.default || (row.default_for || []).length ? "default" : "") : row.reason
|
|
35
|
+
return ` ${row.available ? "ok" : "--"} ${String(row.id).padEnd(46)} ${String(row.provider).padEnd(9)} ${String(row.kind).padEnd(6)} ${detail}${note ? ` (${note})` : ""}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function run(argv, { cwd, log = console.log } = {}) {
|
|
39
|
+
const kindAt = argv.indexOf("--kind")
|
|
40
|
+
const kind = kindAt >= 0 ? argv[kindAt + 1] : undefined
|
|
41
|
+
if (kindAt >= 0 && !KINDS.includes(kind)) throw new Error(USAGE)
|
|
42
|
+
const manifest = loadManifest(cwd)
|
|
43
|
+
const { flags } = parseFlags(argv)
|
|
44
|
+
const env = resolveEnvironment({ cwd, flags })
|
|
45
|
+
if (!env.url) throw new Error(`environment "${env.name}" has no url — run pltt login --env ${env.name} --url <url> --token <token>`)
|
|
46
|
+
if (!env.token) throw new Error(`no publish token for "${env.name}" — run pltt login or set $${env.token_env}`)
|
|
47
|
+
const data = await fetchModels(env, manifest)
|
|
48
|
+
const rows = selectRows(data, { kind, available: argv.includes("--available") })
|
|
49
|
+
if (argv.includes("--json")) {
|
|
50
|
+
log(JSON.stringify({ app_id: data.app_id, organization_id: data.organization_id, models: rows }, null, 2))
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
log(`Models ${data.app_id} can use in workspace ${data.organization_id} (${env.name}):\n`)
|
|
54
|
+
for (const row of rows) log(formatRow(row))
|
|
55
|
+
const blocked = rows.filter((row) => row.reason === "not_approved").map((row) => row.id)
|
|
56
|
+
if (blocked.length) {
|
|
57
|
+
log(`\n Premium models need a declaration, e.g. platform_services.llm.models: ["${blocked[0]}"]`)
|
|
58
|
+
}
|
|
59
|
+
log("\n Pass an id as ctx.llm.chat(..., model=...) or ctx.media.run(<id>, ...); fallback=False refuses substitutes.")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = run
|
|
63
|
+
module.exports.fetchModels = fetchModels
|
|
64
|
+
module.exports.formatRow = formatRow
|
|
65
|
+
module.exports.selectRows = selectRows
|
package/lib/manifest.js
CHANGED
|
@@ -262,15 +262,15 @@ const PLATFORM_SERVICES = [
|
|
|
262
262
|
{
|
|
263
263
|
name: "llm",
|
|
264
264
|
accessor: "ctx.llm",
|
|
265
|
-
summary: "Chat, streaming, embeddings and
|
|
265
|
+
summary: "Chat with tool calls, streaming, embeddings and images on the platform's model keys; every reply names the model that ran",
|
|
266
266
|
example: 'const r = await ctx.llm.chat([{role: "user", content: "hi"}], {model: "gpt-4o-mini"})',
|
|
267
|
-
python: 'reply = await ctx.llm.chat(
|
|
267
|
+
python: 'reply = await ctx.llm.chat(history, tools=TOOLS, model="claude-opus-5", fallback=False)',
|
|
268
268
|
instead_of: "OPENAI_API_KEY / ANTHROPIC_API_KEY",
|
|
269
269
|
},
|
|
270
270
|
{
|
|
271
271
|
name: "media",
|
|
272
272
|
accessor: "ctx.media",
|
|
273
|
-
summary: "fal.ai — image, video, speech, transcription, or any model fal publishes",
|
|
273
|
+
summary: "fal.ai — image, video, speech, transcription, or any model fal publishes; upload() puts private files on fal's CDN",
|
|
274
274
|
example: 'const out = await ctx.media.run("fal-ai/flux/dev", {prompt: "a red bike"})',
|
|
275
275
|
python: 'out = await ctx.media.image("a red bike", image_size="square_hd")',
|
|
276
276
|
instead_of: "FAL_KEY",
|
|
@@ -324,7 +324,29 @@ function validatePlatformServices(value, errors) {
|
|
|
324
324
|
errors.push(`platform_services.${name} must be an object`)
|
|
325
325
|
continue
|
|
326
326
|
}
|
|
327
|
-
|
|
327
|
+
const allowed = new Set(["required", "billing"])
|
|
328
|
+
if (name === "llm") {
|
|
329
|
+
// Premium models and capacity the app asks ctx.llm for — granted by the
|
|
330
|
+
// publish review, bounded again by the platform at call time.
|
|
331
|
+
for (const key of ["models", "max_output_tokens", "max_images"]) allowed.add(key)
|
|
332
|
+
const models = spec.models
|
|
333
|
+
if (
|
|
334
|
+
models !== undefined &&
|
|
335
|
+
(!Array.isArray(models) ||
|
|
336
|
+
models.length > 50 ||
|
|
337
|
+
new Set(models).size !== models.length ||
|
|
338
|
+
!models.every((m) => typeof m === "string" && m.length > 0 && m.length <= 100))
|
|
339
|
+
) {
|
|
340
|
+
errors.push("platform_services.llm.models must be up to 50 unique model ids")
|
|
341
|
+
}
|
|
342
|
+
for (const [key, ceiling] of [["max_output_tokens", 200000], ["max_images", 100]]) {
|
|
343
|
+
const value = spec[key]
|
|
344
|
+
if (value !== undefined && !(Number.isInteger(value) && value >= 0 && value <= ceiling)) {
|
|
345
|
+
errors.push(`platform_services.llm.${key} must be an integer from 0 to ${ceiling}`)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
unknownKeys(spec, allowed, `platform_services.${name}`, errors)
|
|
328
350
|
requireBoolean(spec, "required", `platform_services.${name}`, errors)
|
|
329
351
|
requireString(spec, "billing", `platform_services.${name}`, errors)
|
|
330
352
|
if (spec.billing !== undefined && !["org_wallet", "plugin_owner", "platform"].includes(spec.billing)) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Database plugin backend — org-scoped notes."""
|
|
2
2
|
|
|
3
|
-
from fastapi import Depends, HTTPException
|
|
4
|
-
from pydantic import BaseModel
|
|
3
|
+
from fastapi import Depends, HTTPException, Query
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
5
|
from palette_sdk import PluginRouter, PluginContext, get_plugin_context, require_permission
|
|
6
6
|
from models import Note
|
|
7
7
|
|
|
@@ -9,12 +9,17 @@ router = PluginRouter(tags=["my-db-plugin"])
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class NoteIn(BaseModel):
|
|
12
|
-
body: str
|
|
12
|
+
body: str = Field(max_length=4000)
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
@router.get("/notes", dependencies=[require_permission("resources:read")])
|
|
16
|
-
async def list_notes(
|
|
17
|
-
|
|
16
|
+
async def list_notes(
|
|
17
|
+
limit: int = Query(50, ge=1, le=500),
|
|
18
|
+
offset: int = Query(0, ge=0),
|
|
19
|
+
ctx: PluginContext = Depends(get_plugin_context),
|
|
20
|
+
) -> list[dict]:
|
|
21
|
+
# One page per request: list() returns 100 rows unless told otherwise.
|
|
22
|
+
rows = await ctx.repo(Note).list(order_by="-id", limit=limit, offset=offset)
|
|
18
23
|
return [{"id": r.id, "body": r.body} for r in rows]
|
|
19
24
|
|
|
20
25
|
|