@somewhere-cloud/cli 0.38.153 → 0.38.155
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/CHANGELOG.md +11 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
- package/runtime/DECLARED-DATA-VENDOR.json +5 -5
- package/runtime/PLATFORM-SOURCE.json +1 -1
- package/runtime/SOURCE-LINT-VENDOR.json +2 -2
- package/runtime/declared-data.cjs +37 -19
- package/runtime/source-lint.cjs +1 -1
|
@@ -0,0 +1,1291 @@
|
|
|
1
|
+
# AI and search
|
|
2
|
+
|
|
3
|
+
`sw.ai.chat` calls a model from a function with no provider key. Omit
|
|
4
|
+
`provider` and `model` to use the free default model, which draws only on your
|
|
5
|
+
account's included AI allowance and never on prepaid balance. Managed search
|
|
6
|
+
makes a user's own documents searchable by meaning. The platform extracts the
|
|
7
|
+
text, splits it and indexes it, so there's no embedding code or vector database
|
|
8
|
+
to run.
|
|
9
|
+
|
|
10
|
+
The free default, OpenAI-selected `sw.ai` calls, image generation and moderation use OpenAI. Claude-selected `sw.ai` calls and the free default's Claude backup use Anthropic. A provider-backed call is unavailable in regions where that provider does not operate. It returns `AI_REGION_UNAVAILABLE`, with no retry or charge. [OpenAI supported regions](https://help.openai.com/en/articles/7947663-chatgpt-and-openai-api-supported-countries-and-territories) · [Anthropic supported regions](https://www.anthropic.com/legal/supported-regions)
|
|
11
|
+
|
|
12
|
+
## Call a model
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// api/suggest-title.ts
|
|
16
|
+
export default async function suggestTitle(
|
|
17
|
+
request: Request,
|
|
18
|
+
sw: SomewhereRuntimeContext,
|
|
19
|
+
): Promise<Response> {
|
|
20
|
+
if (request.method !== 'POST') {
|
|
21
|
+
return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const user = await sw.auth.fromRequest(request);
|
|
25
|
+
if (!user) {
|
|
26
|
+
return Response.json({ error: 'Sign in to get a suggestion.' }, { status: 401 });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const input: unknown = await request.json().catch(() => null);
|
|
30
|
+
const text = typeof input === 'object' && input !== null && 'text' in input ? input.text : undefined;
|
|
31
|
+
if (typeof text !== 'string' || !text.trim() || text.length > 4000) {
|
|
32
|
+
return Response.json({ error: 'Send up to 4,000 characters of text.' }, { status: 400 });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Model calls draw on the account's allowance: limit each user before calling one.
|
|
36
|
+
const allowance = await sw.rateLimit.check(`suggest-title:${user.id}`, 20, 3600);
|
|
37
|
+
if (!allowance.allowed) {
|
|
38
|
+
return Response.json({ error: 'Too many suggestions. Try again later.' }, { status: 429 });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const reply = await sw.ai.chat({
|
|
43
|
+
system: 'Reply with one short title for the text. No quotes.',
|
|
44
|
+
messages: [{ role: 'user', content: text }],
|
|
45
|
+
});
|
|
46
|
+
return Response.json({ title: reply.text.trim() });
|
|
47
|
+
} catch (error) {
|
|
48
|
+
const code = error instanceof Error && 'code' in error ? String(error.code) : 'AI_FAILED';
|
|
49
|
+
return Response.json({ error: 'No suggestion right now. Try again later.', code }, { status: 503 });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Deploy, sign in, and POST `{ "text": "…" }` to `/api/suggest-title`. You get
|
|
55
|
+
back `{ "title": "…" }`, the model's suggestion. Read `reply.text` for prose
|
|
56
|
+
and `reply.content` for content blocks.
|
|
57
|
+
|
|
58
|
+
The free default refuses rather than charging, and each refusal has its own
|
|
59
|
+
code:
|
|
60
|
+
|
|
61
|
+
- `RATE_LIMITED`: its per-minute or per-day request limit, shared across the
|
|
62
|
+
account owner's projects.
|
|
63
|
+
- `AI_ALLOWANCE_EXHAUSTED`: the account's included AI allowance is used up for
|
|
64
|
+
the billing period.
|
|
65
|
+
- `AI_SPEND_CAP_REACHED`: the project's monthly AI spend cap, which counts
|
|
66
|
+
allowance-paid calls too.
|
|
67
|
+
|
|
68
|
+
To use a larger or different model, name a `provider` and `model` from
|
|
69
|
+
`ai_catalog`. That paid path bills prepaid balance and counts toward the spend
|
|
70
|
+
cap, unless the call runs on your own provider key. Exact limits: `sw.ai` → `default-model-recommendation` and
|
|
71
|
+
`monthly-ai-spend-cap-per-project`.
|
|
72
|
+
|
|
73
|
+
## Search a user's documents
|
|
74
|
+
|
|
75
|
+
Declare per-user search once in `db/schema.ts`. Without it, managed search is
|
|
76
|
+
refused with `SEARCH_NOT_DECLARED`:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
// db/schema.ts
|
|
80
|
+
import { owner, schema } from 'somewhere/db';
|
|
81
|
+
|
|
82
|
+
export default schema({}, { search: owner() });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Add your tables and file collections to the same call. From a signed-in
|
|
86
|
+
request, `await sw.search.add(path)` indexes one file that the user owns. It
|
|
87
|
+
refuses any other file, and it re-indexes when the file changes. Then search:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// api/search-documents.ts
|
|
91
|
+
export default async function searchDocuments(
|
|
92
|
+
request: Request,
|
|
93
|
+
sw: SomewhereRuntimeContext,
|
|
94
|
+
): Promise<Response> {
|
|
95
|
+
if (request.method !== 'GET') {
|
|
96
|
+
return new Response('Use GET.', { status: 405, headers: { Allow: 'GET' } });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const user = await sw.auth.fromRequest(request);
|
|
100
|
+
if (!user) {
|
|
101
|
+
return Response.json({ error: 'Sign in to search your documents.' }, { status: 401 });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const query = new URL(request.url).searchParams.get('q')?.trim() ?? '';
|
|
105
|
+
if (!query || query.length > 200) {
|
|
106
|
+
return Response.json({ error: 'Search for 1–200 characters.' }, { status: 400 });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The string form searches only the documents this user added.
|
|
110
|
+
const { results } = await sw.search.query(query);
|
|
111
|
+
return Response.json(results.map((hit) => ({ content: hit.content, score: hit.score, source: hit.source })));
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Each hit has a passage, a score, and a `source` naming the file and where in
|
|
116
|
+
it the passage came from.
|
|
117
|
+
|
|
118
|
+
## Which search to use
|
|
119
|
+
|
|
120
|
+
| You want | Use |
|
|
121
|
+
|---|---|
|
|
122
|
+
| A user's own documents, by meaning | Managed search: `search: owner()`, `sw.search.add(path)`, `sw.search.query(text)` (above). Ownership comes from the session. |
|
|
123
|
+
| App content you compose, such as FAQs or products, by meaning | A named index: `sw.search.upsert({ index, items })` and `sw.search.query({ index, query })`. A named index is shared across the project, so your function decides what each caller may see. |
|
|
124
|
+
| Rows whose column contains some text | `sw.db.from(table, { where: { title: { contains: q } } })` in a function (**Data**) |
|
|
125
|
+
| Your project's source and text files, while developing | `sw.fs.dev.search`, developer `run_code` only, not in deployed functions |
|
|
126
|
+
|
|
127
|
+
## More on AI and search
|
|
128
|
+
|
|
129
|
+
| Need | Where |
|
|
130
|
+
|---|---|
|
|
131
|
+
| A complete AI feature: model choice, failures and the page | `recipe-ai-features` |
|
|
132
|
+
| Free default limits, explicit models, provider keys | `sw.ai` → `default-model-recommendation`, `provider-credentials-optional-byok` |
|
|
133
|
+
| Monthly AI spend cap per project | `sw.ai` → `monthly-ai-spend-cap-per-project` |
|
|
134
|
+
| Chat options, cost on the result, errors | `sw.ai` → `swaichatoptions`, `cost-on-the-result-settled-or-pending-openai-and-anthropic-completions`, `error-codes` |
|
|
135
|
+
| Conversation history and compaction | `sw.ai` → `conversation-history-all-providers`, `compaction-preserve-context-across-overflow` |
|
|
136
|
+
| Labels, routing and scores with typed answers | `sw.ai` → `typed-decisions` |
|
|
137
|
+
| Structured output | `sw.ai` → `structured-output-responseschema` |
|
|
138
|
+
| Images, speech, moderation | `sw.ai` → `image-generation-models`, `text-to-speech`, `content-moderation` |
|
|
139
|
+
| Managed search and named indexes | `search` → `managed-file-search-point-it-at-a-file-inside-functions`, `from-inside-a-function-swsearch` |
|
|
140
|
+
| Multi-step model work with tools | **Agents** (`sw.agent`) |
|
|
141
|
+
|
|
142
|
+
## Default model recommendation
|
|
143
|
+
|
|
144
|
+
Omit both `provider` and `model` to start with free
|
|
145
|
+
`gpt-6-luna`. No customer provider key or prepaid balance is required. Calls use the account's
|
|
146
|
+
included AI allowance and are also subject to its project spend cap.
|
|
147
|
+
An exhausted included allowance returns `AI_ALLOWANCE_EXHAUSTED`; the
|
|
148
|
+
default path never silently spends prepaid balance. The request limits are
|
|
149
|
+
10 requests/minute and 200/day per project owner, across their projects,
|
|
150
|
+
on every plan. Each call accepts at most 8,192 estimated input tokens
|
|
151
|
+
(including system text, tools and retained history) and 1,024 output tokens.
|
|
152
|
+
|
|
153
|
+
The free path uses standard service with reasoning disabled, a 20-second
|
|
154
|
+
provider deadline including the response body, and no paid fallback.
|
|
155
|
+
A limit returns a structured error; it never silently charges your balance.
|
|
156
|
+
Use `r.text` for text, `r.content` for content blocks, and
|
|
157
|
+
`r.parsed` when requesting `response_schema`.
|
|
158
|
+
|
|
159
|
+
For larger requests, choose an explicit kept model from `ai_catalog`.
|
|
160
|
+
Explicit `model: 'gpt-6-luna'` selects the paid path for that model; a provider
|
|
161
|
+
whose earlier default was removed requires an explicit model and returns 400
|
|
162
|
+
when it is omitted. A named retired ID returns 410. The free default uses
|
|
163
|
+
platform credentials even when the project has a managed key.
|
|
164
|
+
|
|
165
|
+
`ai_catalog` (`GET /v1/ai/catalog`) reports `free_complete_default.limits`,
|
|
166
|
+
including the owner-wide 10/minute and 200/day counters shared with moderation.
|
|
167
|
+
|
|
168
|
+
## Provider credentials (optional BYOK)
|
|
169
|
+
|
|
170
|
+
### Use any model with your own key
|
|
171
|
+
|
|
172
|
+
For OpenAI and Anthropic completions, save a provider key for the project:
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
# Replace my-app with your project slug or ID.
|
|
176
|
+
somewhere ai keys set openai --project my-app
|
|
177
|
+
somewhere ai keys set anthropic --project my-app
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Each command asks for the key without displaying it; `--stdin` reads it from a
|
|
181
|
+
pipe. A developer or project editor can add or replace the key. Keys are encrypted,
|
|
182
|
+
write-only, and never returned to an agent or exposed through `sw.env`.
|
|
183
|
+
`somewhere ai keys --project <project>` lists configured providers;
|
|
184
|
+
`somewhere ai keys remove openai --project <project>` removes a managed key.
|
|
185
|
+
|
|
186
|
+
Name the provider or model explicitly when calling `sw.ai.chat`. Models removed
|
|
187
|
+
from platform funding still reach OpenAI or Anthropic using your project's key.
|
|
188
|
+
The provider bills your account. These completions take no platform AI hold,
|
|
189
|
+
debit no managed-AI balance or included allowance, and their usage rows have
|
|
190
|
+
`external_billing: 1`. Limits on your own key count steps and tokens, not
|
|
191
|
+
money: the project's AI spend cap and `sw.agent`'s `maxSpendCents` do not
|
|
192
|
+
apply, so bound a run with `maxSteps` and `maxTokens`. Ordinary function and platform usage still applies.
|
|
193
|
+
The completion response does not have an `external_billing` field.
|
|
194
|
+
|
|
195
|
+
A project that saved a key must name the model (or provider) in each
|
|
196
|
+
completion: a call naming neither is refused with `AI_MODEL_REQUIRED` rather
|
|
197
|
+
than running on the free default without your key. The paid-AI kill switch, project access checks and
|
|
198
|
+
completion input contract still apply. A key does not add an unsupported API
|
|
199
|
+
feature or grant access to models your provider account cannot use. Other AI
|
|
200
|
+
features, including images, embeddings and speech, do not use managed completion
|
|
201
|
+
keys. The next completion uses a changed key without a redeploy.
|
|
202
|
+
|
|
203
|
+
The API also accepts a key with a developer credential at
|
|
204
|
+
`POST /v1/ai/provider-keys` (`project_id`, `provider`, `key`). Its GET lists only
|
|
205
|
+
provider names and update times; DELETE removes one. Never paste a key into an
|
|
206
|
+
agent conversation or put a developer credential in browser code.
|
|
207
|
+
|
|
208
|
+
#### Other providers and APIs
|
|
209
|
+
|
|
210
|
+
For any other provider, save its key as a **project secret**, then call its API
|
|
211
|
+
from a server function. This also fits provider features outside managed
|
|
212
|
+
completions. The provider bills you directly; there is no managed AI charge for
|
|
213
|
+
that fetch, while ordinary function and outbound usage still applies.
|
|
214
|
+
|
|
215
|
+
An agent without a terminal can start secret entry with
|
|
216
|
+
`env_request({ project_id: "<project>", key: "DEEPSEEK_API_KEY", purpose: "Call my model provider" })`.
|
|
217
|
+
The returned link lets a signed-in project editor enter the value privately.
|
|
218
|
+
`handoff_status({ request })` confirms it was saved without returning the value.
|
|
219
|
+
That stores `sw.env.DEEPSEEK_API_KEY`; it does **not** configure a managed
|
|
220
|
+
OpenAI/Anthropic completion key. Use the CLI commands above for that.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
// api/answer.ts — the app uses its existing sign-in flow.
|
|
224
|
+
export default sw.endpoint({
|
|
225
|
+
auth: 'required',
|
|
226
|
+
body: { prompt: 'string' },
|
|
227
|
+
handler: async ({ body }, sw) => {
|
|
228
|
+
const key = sw.env.DEEPSEEK_API_KEY;
|
|
229
|
+
if (!key) return Response.json({ error: 'Provider key is missing.' }, { status: 503 });
|
|
230
|
+
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
231
|
+
method: 'POST',
|
|
232
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
|
|
233
|
+
body: JSON.stringify({
|
|
234
|
+
model: 'deepseek-v4-pro', thinking: { type: 'disabled' }, max_tokens: 256,
|
|
235
|
+
messages: [{ role: 'user', content: body.prompt }],
|
|
236
|
+
}),
|
|
237
|
+
});
|
|
238
|
+
if (!response.ok) return Response.json({ error: 'Provider request failed.' }, { status: 502 });
|
|
239
|
+
const data = await response.json() as { choices?: { message?: { content?: string } }[] };
|
|
240
|
+
return { text: data.choices?.[0]?.message?.content ?? '' };
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
This example uses DeepSeek's [chat API](https://api-docs.deepseek.com/) and
|
|
246
|
+
[thinking toggle](https://api-docs.deepseek.com/guides/thinking_mode/).
|
|
247
|
+
Keep keys in server code. For an embedding model you already use, keep stored
|
|
248
|
+
and query vectors in the same model's space; changing models requires recreating
|
|
249
|
+
both. Adding a managed completion key does not enable managed embedding BYOK.
|
|
250
|
+
|
|
251
|
+
## Monthly AI spend cap (per project)
|
|
252
|
+
|
|
253
|
+
Each project has a monthly AI spend cap. Its size comes from your plan
|
|
254
|
+
(`ai_spend_cap_cents` in `GET /v1/pricing`; a plan with `null` there
|
|
255
|
+
has no cap), and it counts each project on its own, per calendar month
|
|
256
|
+
(UTC). It counts every AI call the platform bills for that project —
|
|
257
|
+
chat, embeddings, speech, transcription, images — including calls paid
|
|
258
|
+
from the included allowance. Calls on your own provider credential
|
|
259
|
+
(ledger rows with `external_billing: true`) are not counted.
|
|
260
|
+
|
|
261
|
+
- **80%:** the project owner is told once per month: an email, a warning
|
|
262
|
+
line in the project's logs, and a warning in every deploy response.
|
|
263
|
+
- **100%:** every AI call from that project answers HTTP 429
|
|
264
|
+
`AI_SPEND_CAP_REACHED` until the month turns or the owner raises the
|
|
265
|
+
cap. The rest of the app keeps working. The `message` is neutral because
|
|
266
|
+
your visitors can see it; `data` carries `cap_cents`, `cap_source`,
|
|
267
|
+
`spent_cents`, `window`, `window_start`, `resets_at` and `override`.
|
|
268
|
+
The first refusal of the month is recorded once in the project's errors
|
|
269
|
+
and emailed to the owner — not once per request.
|
|
270
|
+
- **Override (owner only):** `PATCH /v1/projects/{id}` (MCP
|
|
271
|
+
`project_update`) with `{ "ai_spend_cap_cents": 5000 }` sets this
|
|
272
|
+
project's cap to $50; `null` turns the cap off for the project;
|
|
273
|
+
`"plan"` goes back to the plan's cap. Collaborators are refused with 403.
|
|
274
|
+
Every change is recorded (who, when, old → new) and shown, with this
|
|
275
|
+
month's spend, in `project_get` → `ai_spend_cap`.
|
|
276
|
+
- **Your prepaid balance is still the outer limit.** A raised or disabled
|
|
277
|
+
cap never spends money the balance does not have; when both are
|
|
278
|
+
exhausted the balance refusal (`INSUFFICIENT_BALANCE`) is the answer.
|
|
279
|
+
|
|
280
|
+
The cap is per project, not per visitor: to stop one visitor using it up,
|
|
281
|
+
add `rateLimit` to the endpoint (`docs({ topic: 'sw.endpoint' })`) or use
|
|
282
|
+
`sw.rateLimit`.
|
|
283
|
+
|
|
284
|
+
## sw.ai.chat(options)
|
|
285
|
+
|
|
286
|
+
Return shape contract: `result.content` is always the normalized
|
|
287
|
+
content-block array (text blocks and, when supported, tool_use blocks).
|
|
288
|
+
`result.text` is the flattened text convenience for callers that only need
|
|
289
|
+
prose. Do not treat `content` as a string.
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
// api/_lib/ai-models.ts — server-side helpers. Call them from a handler that has
|
|
293
|
+
// already authorized the caller and accepted the text; paid providers bill this project.
|
|
294
|
+
|
|
295
|
+
// Free default — no activation, no user billing. Rate-limited and capped.
|
|
296
|
+
export async function haiku(sw: SomewhereRuntimeContext): Promise<string> {
|
|
297
|
+
const result = await sw.ai.chat({
|
|
298
|
+
messages: [{ role: 'user', content: 'Write a haiku' }],
|
|
299
|
+
});
|
|
300
|
+
// result.content is the normalized content-block array (text + tool_use
|
|
301
|
+
// blocks). result.text is a flattened text convenience.
|
|
302
|
+
return result.text;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Paid Sonnet for user-visible quality.
|
|
306
|
+
export async function haikuWithSonnet(sw: SomewhereRuntimeContext): Promise<SomewhereAiChatResult> {
|
|
307
|
+
const sonnet = await sw.ai.chat({
|
|
308
|
+
provider: 'anthropic',
|
|
309
|
+
model: 'claude-sonnet-5-5',
|
|
310
|
+
messages: [{ role: 'user', content: 'Write a haiku' }],
|
|
311
|
+
});
|
|
312
|
+
// sonnet.stop_reason is 'end_turn' | 'tool_use' | 'max_tokens' | ...
|
|
313
|
+
return sonnet;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Paid model — same activation gate, billed per token at the rate shown
|
|
317
|
+
// in /v1/pricing. Call ai_catalog for the live model list and categories.
|
|
318
|
+
export async function explainWithGpt(sw: SomewhereRuntimeContext): Promise<string> {
|
|
319
|
+
const gptResult = await sw.ai.chat({
|
|
320
|
+
provider: 'openai',
|
|
321
|
+
model: 'gpt-6-luna',
|
|
322
|
+
messages: [{ role: 'user', content: 'Explain quicksort in two sentences.' }],
|
|
323
|
+
max_tokens: 256,
|
|
324
|
+
});
|
|
325
|
+
return gptResult.text;
|
|
326
|
+
}
|
|
327
|
+
// conversation_id works on every provider — pass it and the platform
|
|
328
|
+
// replays prior turns from the per-project database. stream is the only
|
|
329
|
+
// field still gated to anthropic.
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
## Read an image or PDF
|
|
333
|
+
|
|
334
|
+
Use `provider: 'anthropic'` with an image-capable model from `ai_catalog`.
|
|
335
|
+
Put a native `image` or `document` block in the user's message alongside
|
|
336
|
+
the text instruction. `SomewhereAiImageInputBlock` names the supported
|
|
337
|
+
JPEG, PNG, GIF and WebP formats; `SomewhereAiDocumentInputBlock` names PDFs.
|
|
338
|
+
Both take `source: { type: 'base64', media_type, data }`, where `data`
|
|
339
|
+
is the file's bytes encoded as base64, without a data-URL prefix.
|
|
340
|
+
|
|
341
|
+
Keep uploaded receipts in an owner-scoped file collection. Require the
|
|
342
|
+
signed-in user before reading the file with `sw.fs.read`; that read keeps
|
|
343
|
+
the user's file scope. Send the bytes directly to the model, request
|
|
344
|
+
`response_schema`, and let the user review the extracted values before
|
|
345
|
+
saving them to an owner-scoped table. Make extraction a one-shot call:
|
|
346
|
+
omit `conversation_id` so the file is not saved into chat history.
|
|
347
|
+
|
|
348
|
+
All completions size their hold from the prepared system, messages and tools
|
|
349
|
+
at the serving model's rates, with a 4,096-token input margin and the output
|
|
350
|
+
budget. Ordinary text uses a conservative local UTF-8 byte ceiling, with no
|
|
351
|
+
provider count request. Only when an ordinary Anthropic text hold is refused
|
|
352
|
+
for insufficient balance or eligible allowance, the platform makes one free
|
|
353
|
+
exact count with the serving model and key and tries admission once more.
|
|
354
|
+
Count failure preserves the original refusal. The local bound sizes the hold only;
|
|
355
|
+
reported usage and the existing missing-usage billing policy determine the charge. Media and superseded Anthropic
|
|
356
|
+
paths retain their existing prepared-input count before admission.
|
|
357
|
+
Input/context or requested-output overflow returns `AI_INPUT_TOO_LARGE` before
|
|
358
|
+
reserving money. Prices and included allowance values are unchanged.
|
|
359
|
+
|
|
360
|
+
The platform counts attachment input before reserving the completion's
|
|
361
|
+
cost. A failed count stops the call before any paid generation. An oversized
|
|
362
|
+
request returns `AI_INPUT_TOO_LARGE` with its limit; reduce the image size
|
|
363
|
+
or send fewer pages. URL sources, file-reference sources and unsupported
|
|
364
|
+
formats return `AI_INPUT_UNSUPPORTED`: read the file and send its bytes
|
|
365
|
+
inline. Other providers currently reject image and document input.
|
|
366
|
+
|
|
367
|
+
## Flex service tier (~50% discount)
|
|
368
|
+
|
|
369
|
+
The flex service tier serves your request from spare capacity. Trade-offs:
|
|
370
|
+
|
|
371
|
+
• Cost: ~half the standard per-token rate (see /v1/pricing).
|
|
372
|
+
• Latency: noticeably slower than standard.
|
|
373
|
+
• Reliability: may return 429 resource_unavailable when capacity is tight.
|
|
374
|
+
|
|
375
|
+
Good fit: cron jobs, queue workers, batch enrichment, summarization,
|
|
376
|
+
nightly reports — anything where a 2–5s delay or a retry is fine.
|
|
377
|
+
Bad fit: live chat UX, anything a human is waiting on.
|
|
378
|
+
|
|
379
|
+
Opt in by passing service_tier: 'flex'. Default is 'standard'. The
|
|
380
|
+
field is only valid on provider: 'openai' — sending it on anthropic /
|
|
381
|
+
other providers returns a VALIDATION_ERROR.
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
// api/_lib/ai-flex.ts — for cron jobs, queue workers and batch work nobody waits on.
|
|
385
|
+
// Callers pass messages their handler has already authorized.
|
|
386
|
+
export async function summarizeOnFlex(
|
|
387
|
+
sw: SomewhereRuntimeContext,
|
|
388
|
+
messages: readonly SomewhereAiMessage[],
|
|
389
|
+
): Promise<SomewhereAiChatResult> {
|
|
390
|
+
const flexResult = await sw.ai.chat({
|
|
391
|
+
provider: 'openai',
|
|
392
|
+
model: 'gpt-6-luna',
|
|
393
|
+
service_tier: 'flex',
|
|
394
|
+
messages,
|
|
395
|
+
max_tokens: 512,
|
|
396
|
+
});
|
|
397
|
+
// flexResult.service_tier and flexResult.model report what the provider says
|
|
398
|
+
// it served: 'flex', or 'standard' (also after the platform retried a flex
|
|
399
|
+
// capacity refusal on standard). When the provider response carries no
|
|
400
|
+
// served tier or model the field is null and the call's cost is pending
|
|
401
|
+
// (see "Cost on the result"). Cost is priced from the served tier when it is known.
|
|
402
|
+
return flexResult;
|
|
403
|
+
}
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
When the provider refuses a flex request with its explicit flex-capacity
|
|
407
|
+
signal, the platform retries it once on standard. The result reports the
|
|
408
|
+
served tier when the provider returns it. Any other failure reaches your code as a
|
|
409
|
+
thrown error. A 429 surfaces as `UPSTREAM_RATE_LIMITED` with a retry hint;
|
|
410
|
+
that code also covers ordinary rate limits and quota, so it does not by itself
|
|
411
|
+
mean flex capacity ran out.
|
|
412
|
+
|
|
413
|
+
Per-model token rates are not hardcoded here — call `ai_catalog` (or
|
|
414
|
+
`GET /v1/pricing`) for the live per-model input/output rates and which
|
|
415
|
+
models your tier can use. Flex calls run at roughly half the standard rate.
|
|
416
|
+
|
|
417
|
+
To know which tier a call actually ran on, read `result.service_tier`
|
|
418
|
+
on the response.
|
|
419
|
+
|
|
420
|
+
## Cost on the result: settled or pending (OpenAI and Anthropic completions)
|
|
421
|
+
|
|
422
|
+
This contract applies to `provider: 'openai'` and `provider: 'anthropic'`
|
|
423
|
+
completions; other AI features keep their existing
|
|
424
|
+
all-in `cost` shape and are not migrated. Every such completion carries a
|
|
425
|
+
`cost` object. When the platform has settled the
|
|
426
|
+
call, `cost.total_cents` is the all-in amount taken from your balance and
|
|
427
|
+
`cost.total` is the same amount as a dollar string. When the platform has
|
|
428
|
+
not yet been able to price the call — the provider response did not carry a
|
|
429
|
+
usable served model, tier, or token counts, or the accounting record could
|
|
430
|
+
not be completed — the result is still delivered and `cost` is
|
|
431
|
+
`{ status: 'pending', total_cents: null, total: null }`: null means
|
|
432
|
+
unknown, never zero and never an estimate. `model`, `service_tier` and
|
|
433
|
+
the `usage` token counts are null on that result when the provider did
|
|
434
|
+
not report them. The platform reconciles pending accounting itself; you do
|
|
435
|
+
not need to retry the call or replay the model. Your balance may already
|
|
436
|
+
reflect the call while its cost reads pending, and it is corrected when the
|
|
437
|
+
accounting completes. This describes cost reporting only; model
|
|
438
|
+
availability and catalog coverage are separate.
|
|
439
|
+
|
|
440
|
+
**Direct Anthropic completions.** `provider: 'anthropic'` calls go
|
|
441
|
+
straight to the provider, one accounting record per model invocation. The
|
|
442
|
+
platform does not substitute another provider behind a Claude call: there is
|
|
443
|
+
no automatic fallback, `fallback_used` is always false and
|
|
444
|
+
`fallback_provider` null. Requests run on the standard service tier. A
|
|
445
|
+
project-owned provider key keeps your exact model selection and takes no
|
|
446
|
+
platform debit. When the provider refuses admission with a documented
|
|
447
|
+
refusal (HTTP 400, 401, 402, 403, 404, 413 or 429) the balance hold is
|
|
448
|
+
released automatically; a native 400 returns `VALIDATION_ERROR`, or
|
|
449
|
+
`CONV_HISTORY_REJECTED` when a conversation is involved, and the other
|
|
450
|
+
refusals surface as `UPSTREAM_AUTH_FAILED`, `UPSTREAM_BILLING`,
|
|
451
|
+
`UPSTREAM_RATE_LIMITED` or `UPSTREAM_ERROR`. A provider 5xx returns
|
|
452
|
+
`UPSTREAM_DOWN`, a deadline `AI_UPSTREAM_TIMEOUT`, and those, transport
|
|
453
|
+
failures and malformed responses keep the accounting record open and
|
|
454
|
+
reconcile with `retry: false` rather than being assumed unbilled. An empty
|
|
455
|
+
paid response settles the usage it did consume and then returns
|
|
456
|
+
`MODEL_EMPTY_RESPONSE` carrying the `cost` object (pending when unknown).
|
|
457
|
+
A streamed call carries the same `cost` object on its final
|
|
458
|
+
`message_delta` event. A tool call the model left incomplete — missing id
|
|
459
|
+
or name, non-object input, or no `tool_use` stop — is never returned as
|
|
460
|
+
executable; the text and the accounting are kept.
|
|
461
|
+
|
|
462
|
+
**Current Claude models on provider: 'anthropic'.** `claude-opus-5` and
|
|
463
|
+
`claude-sonnet-5` are served with the provider's native reasoning on:
|
|
464
|
+
each carries a 1,000,000-token context window and a 128,000-token output
|
|
465
|
+
cap, and the reasoning the model emits is part of the output you are billed
|
|
466
|
+
for, counted once. A streamed call carries the thinking, signature and
|
|
467
|
+
redacted blocks in native order alongside the text, and a following turn in
|
|
468
|
+
the same conversation replays them unchanged with the matching tool result.
|
|
469
|
+
Structured output (`response_schema`) works on both.
|
|
470
|
+
Pass `effort` (also read from `output_config.effort`) to set how hard a
|
|
471
|
+
reasoning model thinks; lower is faster and cheaper. Left out, the model's
|
|
472
|
+
default applies. A value the model does not take is refused with
|
|
473
|
+
`VALIDATION_ERROR` before anything is sent or charged; it is never ignored.
|
|
474
|
+
|
|
475
|
+
| Model | `effort` values | With `tools` or `response_schema` |
|
|
476
|
+
|---|---|---|
|
|
477
|
+
| Claude models | `low`, `medium`, `high`, `xhigh`, `max`. `claude-sonnet-5-5` accepts `low` through `high` | Honoured with supported tool choices |
|
|
478
|
+
| `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6.1-sol` | `low`, `medium`, `high`, `xhigh`, `max` | Tools and `response_schema` are unavailable |
|
|
479
|
+
| `gpt-6.1-terra` | `none`, `low`, `medium`, `high`, `xhigh`, `max` | Tools and `response_schema` are unavailable |
|
|
480
|
+
| `gpt-6-luna` and other OpenAI chat models | `low`, `medium`, `high` | Refused: these models run tools without extended reasoning. Leave `effort` out, or use a Claude model |
|
|
481
|
+
|
|
482
|
+
The free default (provider and model left out) runs with reasoning off, so
|
|
483
|
+
`effort` there is refused: name a model to set it. `sw.agent` passes
|
|
484
|
+
`effort` to every step.
|
|
485
|
+
|
|
486
|
+
`claude-haiku-5-5` is the fast, low-cost Claude model, with the provider's
|
|
487
|
+
adaptive reasoning on. It takes prompts up to 100,000 tokens: a larger prompt is
|
|
488
|
+
refused with `AI_INPUT_TOO_LARGE` before anything is sent or charged (use
|
|
489
|
+
`claude-sonnet-5-5` for long prompts). When the provider reports it
|
|
490
|
+
served the request from a US-region inference path, the regional rate
|
|
491
|
+
applies (1.1× across all token classes); the platform never overrides your
|
|
492
|
+
workspace geography. Prompt caching is billed at the provider's read and
|
|
493
|
+
write classes when the response reports them.
|
|
494
|
+
|
|
495
|
+
GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol and GPT-6.1 Terra each have a
|
|
496
|
+
1,050,000-token context window, a 922,000-token input limit and a
|
|
497
|
+
128,000-token output limit. Calls use Standard by default. GPT-6.1 Sol and
|
|
498
|
+
GPT-6.1 Terra also accept `service_tier: "flex"`. OpenAI completions return
|
|
499
|
+
a complete response. For `stream: true`, use a Claude model.
|
|
500
|
+
|
|
501
|
+
Managed GPT requests must also fit a 922,000-byte limit on the
|
|
502
|
+
serialized UTF-8 provider request, including messages and request fields.
|
|
503
|
+
OpenAI measures its context in tokens. A request can reach the byte limit
|
|
504
|
+
with fewer tokens than OpenAI permits.
|
|
505
|
+
|
|
506
|
+
A Claude classifier refusal returns `stop_reason: "refusal"`. A free
|
|
507
|
+
refusal before output settles at zero. Billable refusal categories and
|
|
508
|
+
output already generated before a refusal are charged at the model's
|
|
509
|
+
rates. Discard partial output if a stream ends with a refusal.
|
|
510
|
+
|
|
511
|
+
Claude Fable 5.2 has a 1,000,000-token context window and supports up to
|
|
512
|
+
128,000 output tokens. Its adaptive thinking is always on, with `high`
|
|
513
|
+
as the default effort. It accepts automatic or disabled tool choice.
|
|
514
|
+
Forced tool choice, `response_schema`, assistant prefill and sampling
|
|
515
|
+
controls are unavailable. Pass your own message history instead of
|
|
516
|
+
`conversation_id`. When replaying a signed thinking block, preserve the system
|
|
517
|
+
prompt, tool definitions and earlier messages. Anthropic requires
|
|
518
|
+
30-day data retention for this model.
|
|
519
|
+
|
|
520
|
+
The provider counts the prepared Fable request before a completion hold.
|
|
521
|
+
The input token count plus the requested output limit must fit its context
|
|
522
|
+
window. The separate managed request size limit is 16 MiB.
|
|
523
|
+
|
|
524
|
+
Use a model that supports `response_schema` for managed structured output.
|
|
525
|
+
Claude requests with native `output_config.format` are refused.
|
|
526
|
+
|
|
527
|
+
Read `ai_models` in `GET /v1/pricing` for text-model prices and
|
|
528
|
+
`GET /v1/ai/catalog` for the full AI catalog. The deadline for a single call
|
|
529
|
+
is 120 seconds. A large output can time out into the pending-cost state
|
|
530
|
+
described above.
|
|
531
|
+
|
|
532
|
+
**Tool use (anthropic and openai).** Pass tool definitions in the standard
|
|
533
|
+
tool-use shape via `tools`; the platform translates them to the provider's
|
|
534
|
+
native format. tool_use blocks come back in `result.content` the same way for
|
|
535
|
+
either provider, and `stop_reason` is normalized to `'tool_use'`. Run each call
|
|
536
|
+
yourself, then continue the loop by appending the assistant message and a user
|
|
537
|
+
message with `tool_result` blocks carrying each call's `id`.
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
// api/_lib/todo-search.ts — the calling handler has authorized the request;
|
|
541
|
+
// the model only asks for the search, your code decides whether to run it.
|
|
542
|
+
export async function requestTodoSearch(
|
|
543
|
+
sw: SomewhereRuntimeContext,
|
|
544
|
+
): Promise<{ id: string; query: string }[]> {
|
|
545
|
+
const r = await sw.ai.chat({
|
|
546
|
+
provider: 'anthropic', // or 'openai' — same tool definition shape
|
|
547
|
+
model: 'claude-sonnet-5-5',
|
|
548
|
+
messages: [{ role: 'user', content: 'Find files containing TODO.' }],
|
|
549
|
+
tools: [{
|
|
550
|
+
name: 'fs_search',
|
|
551
|
+
description: 'Search files for a literal substring.',
|
|
552
|
+
input_schema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
|
|
553
|
+
}],
|
|
554
|
+
});
|
|
555
|
+
if (r.stop_reason !== 'tool_use') return [];
|
|
556
|
+
const calls: { id: string; query: string }[] = [];
|
|
557
|
+
for (const block of r.content) {
|
|
558
|
+
const query = block.input?.query;
|
|
559
|
+
if (block.type === 'tool_use' && block.name === 'fs_search' && typeof block.id === 'string' && typeof query === 'string') {
|
|
560
|
+
calls.push({ id: block.id, query }); // keep the id: your tool_result must echo it
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return calls;
|
|
564
|
+
}
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
**Streaming — provider 'anthropic' only.**
|
|
568
|
+
|
|
569
|
+
```ts
|
|
570
|
+
// api/chat-stream.ts
|
|
571
|
+
export default async function chatStream(
|
|
572
|
+
request: Request,
|
|
573
|
+
sw: SomewhereRuntimeContext,
|
|
574
|
+
): Promise<Response> {
|
|
575
|
+
if (request.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
576
|
+
const user = await sw.auth.requireUser(request); // 401 when not signed in
|
|
577
|
+
const input: unknown = await request.json().catch(() => null);
|
|
578
|
+
const message = typeof input === 'object' && input !== null && 'message' in input ? input.message : undefined;
|
|
579
|
+
if (typeof message !== 'string' || !message.trim() || message.length > 4000) {
|
|
580
|
+
return Response.json({ error: 'Send a message of 1–4,000 characters.' }, { status: 400 });
|
|
581
|
+
}
|
|
582
|
+
const allowance = await sw.rateLimit.check(`chat-stream:${user.id}`, 20, 3600);
|
|
583
|
+
if (!allowance.allowed) {
|
|
584
|
+
return Response.json({ error: 'Too many messages. Try again later.' }, { status: 429 });
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const stream = await sw.ai.chat({
|
|
588
|
+
provider: 'anthropic',
|
|
589
|
+
model: 'claude-sonnet-5-5',
|
|
590
|
+
messages: [{ role: 'user', content: message }],
|
|
591
|
+
stream: true,
|
|
592
|
+
max_tokens: 1024,
|
|
593
|
+
});
|
|
594
|
+
return new Response(stream, { headers: { 'Content-Type': 'text/event-stream' } });
|
|
595
|
+
}
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
What comes back is an SSE body in the Anthropic event shape:
|
|
599
|
+
message_start, content_block_start / content_block_delta /
|
|
600
|
+
content_block_stop, message_delta (cumulative output_tokens),
|
|
601
|
+
message_stop. Today the answer is generated first and then sent as one
|
|
602
|
+
complete SSE payload, so the frames arrive together rather than token by
|
|
603
|
+
token — parse it as a stream, but don't build a UI that depends on
|
|
604
|
+
incremental arrival yet.
|
|
605
|
+
|
|
606
|
+
On every other provider stream is NOT honoured. openai and the free default (gpt-6-luna, what you get when you omit
|
|
607
|
+
provider/model) reject it with VALIDATION_ERROR "stream=true is not supported
|
|
608
|
+
on the <provider> provider yet." Uncaught in a handler that surfaces as a 500,
|
|
609
|
+
so select a supported provider before setting the flag.
|
|
610
|
+
|
|
611
|
+
stream: true is also mutually exclusive with conversation_id and with
|
|
612
|
+
response_schema (both VALIDATION_ERROR).
|
|
613
|
+
|
|
614
|
+
## Conversation history (all providers)
|
|
615
|
+
|
|
616
|
+
Pass conversation_id and the platform stores+replays the chat for you.
|
|
617
|
+
Prior turns are loaded from this project's database, prepended to your
|
|
618
|
+
messages, and sent to the model. After the response, your new user
|
|
619
|
+
message(s) and the assistant reply are saved under the same id. Next
|
|
620
|
+
call: send only the new user turn.
|
|
621
|
+
|
|
622
|
+
In app functions, sw.ai.chat derives the verified request user when one is
|
|
623
|
+
available; the scoped AI view below also supports session-owned conversations.
|
|
624
|
+
Through MCP, ai_complete requires subject_type and subject_id whenever you
|
|
625
|
+
supply conversation_id. Use the same pair to list, read, delete, or fork that
|
|
626
|
+
conversation. A conversation id alone does not identify its owner.
|
|
627
|
+
|
|
628
|
+
Works on Anthropic and OpenAI. You can
|
|
629
|
+
even mix providers under the same conversation_id; whichever model you
|
|
630
|
+
call next sees the retained history. Compaction configuration and billing
|
|
631
|
+
are described below. The only field still pinned to anthropic is stream: `stream: true` produces
|
|
632
|
+
an SSE body only on `provider: 'anthropic'`. openai and the free default reject it with VALIDATION_ERROR.
|
|
633
|
+
Do not label an ordinary JSON result as a text/event-stream Response.
|
|
634
|
+
`stream: true` cannot be combined with conversation_id or response_schema.
|
|
635
|
+
The anthropic stream is generated first and replayed as one complete SSE
|
|
636
|
+
payload today, so the frames arrive together rather than token by token.
|
|
637
|
+
|
|
638
|
+
```ts
|
|
639
|
+
// api/_lib/chat-turn.ts — call it while handling a signed-in request:
|
|
640
|
+
// sw.ai.chat files the conversation under that verified user.
|
|
641
|
+
export function askInConversation(
|
|
642
|
+
sw: SomewhereRuntimeContext,
|
|
643
|
+
conversationId: string, // any id up to 128 chars (uuid or your own scheme)
|
|
644
|
+
question: string,
|
|
645
|
+
): Promise<SomewhereAiChatResult> {
|
|
646
|
+
return sw.ai.chat({
|
|
647
|
+
provider: 'anthropic',
|
|
648
|
+
model: 'claude-sonnet-5-5',
|
|
649
|
+
conversation_id: conversationId,
|
|
650
|
+
messages: [{ role: 'user', content: question }],
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
// First call: askInConversation(sw, 'c_abc123', "What's the capital of France?")
|
|
654
|
+
// → { content: [...], text: 'Paris.', conversation_id: 'c_abc123', ... }
|
|
655
|
+
// Second call: the server loads the prior turn; send only the new one.
|
|
656
|
+
// askInConversation(sw, 'c_abc123', 'And of Spain?')
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
If the combined input would exceed the model's 200K context window, the
|
|
660
|
+
oldest history messages are dropped automatically — the response carries
|
|
661
|
+
conversation_truncated: true. If the conversation_id doesn't exist, it's
|
|
662
|
+
created on first save.
|
|
663
|
+
|
|
664
|
+
## History caps (per call)
|
|
665
|
+
|
|
666
|
+
Trim what's loaded with two optional fields. Oldest user/assistant
|
|
667
|
+
messages drop first; the new turn in messages and your system prompt
|
|
668
|
+
are never dropped. The smaller cap wins.
|
|
669
|
+
|
|
670
|
+
```ts
|
|
671
|
+
// api/_lib/chat-turn-capped.ts — same signed-in precondition as chat-turn.ts.
|
|
672
|
+
export function askCapped(
|
|
673
|
+
sw: SomewhereRuntimeContext,
|
|
674
|
+
conversationId: string,
|
|
675
|
+
question: string,
|
|
676
|
+
): Promise<SomewhereAiChatResult> {
|
|
677
|
+
return sw.ai.chat({
|
|
678
|
+
provider: 'anthropic',
|
|
679
|
+
model: 'claude-sonnet-5-5',
|
|
680
|
+
conversation_id: conversationId,
|
|
681
|
+
history_max_messages: 20, // default 50
|
|
682
|
+
history_max_tokens: 4000, // default 32000 (char/4 estimate)
|
|
683
|
+
messages: [{ role: 'user', content: question }],
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
```
|
|
687
|
+
|
|
688
|
+
Use these to keep a long-running chat cheap and predictable. The
|
|
689
|
+
model's 200K window still applies on top.
|
|
690
|
+
|
|
691
|
+
## Compaction (preserve context across overflow)
|
|
692
|
+
|
|
693
|
+
By default, messages that overflow the caps above are omitted from that
|
|
694
|
+
model request. The stored transcript remains intact. Set `compaction:
|
|
695
|
+
'summarize'` to maintain a rolling summary. The object form selects an
|
|
696
|
+
explicit compactor; `provider` defaults to the primary call's provider and
|
|
697
|
+
`model` is required.
|
|
698
|
+
|
|
699
|
+
```ts
|
|
700
|
+
// api/_lib/chat-turn-summarized.ts — same signed-in precondition as chat-turn.ts.
|
|
701
|
+
export function askWithSummary(
|
|
702
|
+
sw: SomewhereRuntimeContext,
|
|
703
|
+
conversationId: string,
|
|
704
|
+
question: string,
|
|
705
|
+
): Promise<SomewhereAiChatResult> {
|
|
706
|
+
return sw.ai.chat({
|
|
707
|
+
provider: 'anthropic',
|
|
708
|
+
model: 'claude-sonnet-5-5',
|
|
709
|
+
conversation_id: conversationId,
|
|
710
|
+
history_max_messages: 10,
|
|
711
|
+
compaction: {
|
|
712
|
+
mode: 'summarize',
|
|
713
|
+
provider: 'openai', // optional; defaults to primary provider
|
|
714
|
+
model: 'gpt-6-luna', // required in object form
|
|
715
|
+
},
|
|
716
|
+
messages: [{ role: 'user', content: question }],
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
The response carries conversation_summarized: true on calls where
|
|
722
|
+
summarization actually ran. The compactor uses the normal provider-key,
|
|
723
|
+
metering, and billing path. If that call fails, the primary call continues
|
|
724
|
+
with request-only truncation. The free/default model path is truncate-only.
|
|
725
|
+
Inspect the rolling summary via ai_conversation_list (pass a
|
|
726
|
+
conversation_id); it shows in the conversation row's summary field.
|
|
727
|
+
|
|
728
|
+
Manage conversations from outside functions via the MCP tools
|
|
729
|
+
ai_conversation_list (pass a conversation_id to fetch one) /
|
|
730
|
+
ai_conversation_delete, or
|
|
731
|
+
the matching REST endpoints (GET /v1/ai/conversations,
|
|
732
|
+
GET /v1/ai/conversations/:id, DELETE /v1/ai/conversations/:id — all take
|
|
733
|
+
?project_id=, subject_type, and subject_id). Use the same subject_type and
|
|
734
|
+
subject_id supplied to ai_complete when the conversation was created.
|
|
735
|
+
For MCP and REST history operations, list first and use the returned record
|
|
736
|
+
id to read, delete, or fork. Keep your original caller-chosen conversation_id
|
|
737
|
+
for subsequent ai_complete turns; it is a different identifier from the stored
|
|
738
|
+
record id. The scoped runtime client handles that translation for you.
|
|
739
|
+
Pass include_summarized=1 on the get endpoint to also see messages already
|
|
740
|
+
folded into the summary.
|
|
741
|
+
|
|
742
|
+
Summarized rows remain stored. Conversation reads exclude them by default;
|
|
743
|
+
pass include_summarized=1 to retrieve the complete retained transcript.
|
|
744
|
+
|
|
745
|
+
Compaction is not supported with stream: true.
|
|
746
|
+
|
|
747
|
+
## System prompt — pass either way
|
|
748
|
+
|
|
749
|
+
You can supply the system prompt as a top-level field OR as an inline
|
|
750
|
+
`role: 'system'` message; the platform normalizes both shapes before
|
|
751
|
+
dispatch, so the same code works on every provider.
|
|
752
|
+
|
|
753
|
+
```ts
|
|
754
|
+
// api/_lib/terse.ts
|
|
755
|
+
// Top-level `system` field
|
|
756
|
+
export async function terseReply(sw: SomewhereRuntimeContext, question: string): Promise<string> {
|
|
757
|
+
const r = await sw.ai.chat({ provider: 'anthropic', system: 'Be terse.', messages: [{ role: 'user', content: question }] });
|
|
758
|
+
return r.text;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// Inline `role: 'system'` message
|
|
762
|
+
export async function terseReplyInline(sw: SomewhereRuntimeContext, question: string): Promise<string> {
|
|
763
|
+
const r = await sw.ai.chat({ provider: 'anthropic', messages: [
|
|
764
|
+
{ role: 'system', content: 'Be terse.' },
|
|
765
|
+
{ role: 'user', content: question },
|
|
766
|
+
] });
|
|
767
|
+
return r.text;
|
|
768
|
+
}
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
Both produce identical behavior — no need to branch on provider.
|
|
772
|
+
|
|
773
|
+
## Multi-chat — letting end users keep a list of conversations
|
|
774
|
+
|
|
775
|
+
Give people a sidebar of their saved conversations. The list contains both
|
|
776
|
+
`client_conversation_id`, the name your app supplied when chatting, and
|
|
777
|
+
`id`, the stored ID used to read, delete or fork a saved conversation.
|
|
778
|
+
Every call below uses the signed-in person's conversations.
|
|
779
|
+
|
|
780
|
+
```typescript
|
|
781
|
+
// api/conversations.ts
|
|
782
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
783
|
+
await sw.auth.requireUser(req);
|
|
784
|
+
const { conversations } = await sw.ai.conversations.list();
|
|
785
|
+
const clientId = new URL(req.url).searchParams.get('conversation');
|
|
786
|
+
if (!clientId) return Response.json({ conversations });
|
|
787
|
+
|
|
788
|
+
const thread = conversations.find(c => c.client_conversation_id === clientId);
|
|
789
|
+
if (!thread) return Response.json({ error: 'Conversation not found.' }, { status: 404 });
|
|
790
|
+
return Response.json(await sw.ai.conversations.get(thread.id));
|
|
791
|
+
}
|
|
792
|
+
```
|
|
793
|
+
|
|
794
|
+
Request `/api/conversations` for the sidebar, or pass its selected
|
|
795
|
+
`client_conversation_id` in the `conversation` query parameter to load
|
|
796
|
+
the transcript. The handler resolves it to the stored ID before reading.
|
|
797
|
+
For a long sidebar, use the list's `limit` option to request more entries.
|
|
798
|
+
|
|
799
|
+
| Action | Call |
|
|
800
|
+
|---|---|
|
|
801
|
+
| Continue a chat | Pass its `client_conversation_id` to `sw.ai.chat` |
|
|
802
|
+
| Start a chat | Give `sw.ai.chat` a new `conversation_id` |
|
|
803
|
+
| Read a transcript | `sw.ai.conversations.get(storedId)` |
|
|
804
|
+
| Delete a saved chat | `sw.ai.conversations.delete(storedId)` |
|
|
805
|
+
| Fork a saved chat | `sw.ai.conversations.fork(storedId, newId, { upToMessageId })` |
|
|
806
|
+
|
|
807
|
+
Wire delete and fork to authenticated write handlers. Omit `upToMessageId`
|
|
808
|
+
to copy the complete saved conversation. See `recipe-ai-agent` for the
|
|
809
|
+
agent loop and conversation controls together.
|
|
810
|
+
|
|
811
|
+
## Error codes
|
|
812
|
+
|
|
813
|
+
Every `sw.ai.*` failure rejects with an `Error` whose `.code` and
|
|
814
|
+
`.status` fields are stable — branch on those instead of regex-matching
|
|
815
|
+
`.message`. The contract:
|
|
816
|
+
|
|
817
|
+
CONV_HISTORY_UNAVAILABLE 503 conversation persistence load failed.
|
|
818
|
+
retry without conversation_id to start
|
|
819
|
+
a fresh thread, or pass a different id.
|
|
820
|
+
(.retryable: true)
|
|
821
|
+
SCHEMA_DRIFT 503 conversation table is missing columns
|
|
822
|
+
the platform expects. Same recovery
|
|
823
|
+
as CONV_HISTORY_UNAVAILABLE — our team
|
|
824
|
+
alerted, no caller action.
|
|
825
|
+
|
|
826
|
+
PAID_API_NOT_ACTIVATED 402 caller needs to enable AI completions
|
|
827
|
+
in the dashboard. .data.activation_url
|
|
828
|
+
carries the link.
|
|
829
|
+
INSUFFICIENT_BALANCE 402 monthly cap or pre-paid balance hit.
|
|
830
|
+
.data has available_dollars +
|
|
831
|
+
required_dollars + load_url.
|
|
832
|
+
AI_SPEND_CAP_EXCEEDED 402 sw.agent crossed opts.maxSpendCents after
|
|
833
|
+
a billed step. .metrics has partial
|
|
834
|
+
accounting.
|
|
835
|
+
|
|
836
|
+
AI_PREPARE_STEP_FAILED 422 prepareStep callback failed.
|
|
837
|
+
AI_STEP_HOOK_FAILED 422 onStepFinish callback failed.
|
|
838
|
+
AI_STOP_CONDITION_FAILED 422 stopWhen callback failed.
|
|
839
|
+
|
|
840
|
+
AI_REQUIRED 401 thrown by sw.auth.requireUser when no
|
|
841
|
+
valid session is on the request.
|
|
842
|
+
|
|
843
|
+
RATE_LIMITED 429 free-tier rate envelope hit or per-IP
|
|
844
|
+
anonymous-create cap. (.retryable: true)
|
|
845
|
+
UPSTREAM_ERROR 502/503 the upstream provider rejected.
|
|
846
|
+
.message is the platform-authored
|
|
847
|
+
friendly string; raw provider details
|
|
848
|
+
are server-side only.
|
|
849
|
+
|
|
850
|
+
VALIDATION_ERROR 400 inputs failed shape/range check.
|
|
851
|
+
PROJECT_NOT_FOUND 404 unknown project or no access.
|
|
852
|
+
NOT_FOUND 404 resource (conversation, etc) missing.
|
|
853
|
+
CONFLICT 409 destination id already exists
|
|
854
|
+
(e.g. conversations.fork to an id
|
|
855
|
+
that's taken).
|
|
856
|
+
INTERNAL_ERROR 500 unexpected platform failure — message
|
|
857
|
+
stays generic, server logs have detail.
|
|
858
|
+
|
|
859
|
+
Database-layer errors that surface through sw.db.* keep their own set
|
|
860
|
+
documented in docs({ topic: 'sw.db' }):
|
|
861
|
+
SCHEMA_ERROR · SYNTAX_ERROR · TABLE_NOT_FOUND · CONSTRAINT_VIOLATION ·
|
|
862
|
+
STATEMENT_TOO_LARGE · DATABASE_VALUE_TOO_LARGE · DATABASE_INPUT_TOO_LARGE ·
|
|
863
|
+
DATABASE_FULL · WRITE_CONFLICT · DB_BUSY · QUERY_TIMEOUT.
|
|
864
|
+
|
|
865
|
+
Anything marked retryable: true is safe to attempt again after a short
|
|
866
|
+
backoff. Everything else is a programming/state error — fix the input
|
|
867
|
+
or wait for the platform team.
|
|
868
|
+
|
|
869
|
+
## Catalog search tool — `sw.ai.catalogTool`
|
|
870
|
+
|
|
871
|
+
Build a search tool with `sw.agent.run` and a structured `sw.db.from`
|
|
872
|
+
query. The query binds search text as a value and applies the table's declared
|
|
873
|
+
access rules. See `docs({ topic: 'recipe-ai-agent' })` for a complete
|
|
874
|
+
example with a schema, sign-in and conversation history.
|
|
875
|
+
|
|
876
|
+
`sw.ai.catalogTool` is not available: a call returns
|
|
877
|
+
`CATALOG_TOOL_RETIRED`. Use the pattern above.
|
|
878
|
+
|
|
879
|
+
## Agent execution
|
|
880
|
+
|
|
881
|
+
`sw.agent` is a separate callable runtime capability, not a method on
|
|
882
|
+
`sw.ai`. It supports inline execution, durable execution, status, and
|
|
883
|
+
cancellation. Read the complete signatures and return shapes in
|
|
884
|
+
`docs({ topic: 'sw.agent' })`.
|
|
885
|
+
|
|
886
|
+
## Per-user memory — `sw.ai.userMemory`
|
|
887
|
+
|
|
888
|
+
Keep preferences and remembered facts for the signed-in person. Every method
|
|
889
|
+
uses the request's verified user; you never pass a user ID.
|
|
890
|
+
|
|
891
|
+
| Method | Result |
|
|
892
|
+
|---|---|
|
|
893
|
+
| `get()` | The stored object, or an empty object on first use |
|
|
894
|
+
| `update(patch)` | Merges top-level keys from a plain object and returns the result |
|
|
895
|
+
| `clear()` | Deletes this user's memory and returns `{ cleared: true }` |
|
|
896
|
+
|
|
897
|
+
For example, `await sw.ai.userMemory.update({ preferred_line: 'Northern' })`
|
|
898
|
+
stores a preference. Read it with `await sw.ai.userMemory.get()` inside that
|
|
899
|
+
user's next request. Call `sw.auth.requireUser(req)` before handling a
|
|
900
|
+
preferences form. Without a signed-in user, memory methods throw
|
|
901
|
+
`AUTH_REQUIRED`.
|
|
902
|
+
|
|
903
|
+
Memory uses the project's database. Updates read and replace the object, so
|
|
904
|
+
serialize overlapping updates for one user to avoid losing a concurrent edit.
|
|
905
|
+
|
|
906
|
+
## Auto-compaction — `sw.ai.userMemory.compact`
|
|
907
|
+
|
|
908
|
+
`compact(schema, options)` turns recent conversation text into structured
|
|
909
|
+
memory. It sends the current memory and transcript to a model, then replaces
|
|
910
|
+
the stored object with the returned object. The schema describes the fields
|
|
911
|
+
you want to remember.
|
|
912
|
+
|
|
913
|
+
Call it inside the signed-in user's request. Pass either a transcript in
|
|
914
|
+
`options.history`, or the stored conversation `id` from
|
|
915
|
+
`sw.ai.conversations.list()` in `options.conversation_id`. The list's
|
|
916
|
+
`client_conversation_id` is the name your app originally passed to chat;
|
|
917
|
+
use the separate `id` for lookup. A missing conversation or empty transcript
|
|
918
|
+
leaves memory unchanged without a model call.
|
|
919
|
+
|
|
920
|
+
Use `windowMessages` to bound the recent messages read from a conversation,
|
|
921
|
+
and `provider`, `model` and `maxTokens` to select the model call.
|
|
922
|
+
Compaction uses an explicit model, including when you omit these options, so
|
|
923
|
+
it is paid through your project's provider credential or the project owner's
|
|
924
|
+
AI balance. The same spend limits as a named-model chat call apply. Run it
|
|
925
|
+
periodically within a user's conversation rather than after every message.
|
|
926
|
+
|
|
927
|
+
## Typed decisions
|
|
928
|
+
|
|
929
|
+
Use `sw.ai.evaluate` when the answer is a label, a probability or a score.
|
|
930
|
+
Ask several questions about the same input in one call. Text chooses Jev;
|
|
931
|
+
embedded images choose Clef-flash. Set `model` to choose explicitly.
|
|
932
|
+
|
|
933
|
+
```ts
|
|
934
|
+
// api/_lib/route-message.ts — call after authentication and a per-user rate-limit check.
|
|
935
|
+
export async function routeMessage(sw: SomewhereRuntimeContext, message: string) {
|
|
936
|
+
const decision = await sw.ai.evaluate({
|
|
937
|
+
state: message,
|
|
938
|
+
questions: {
|
|
939
|
+
team: {
|
|
940
|
+
type: 'choice',
|
|
941
|
+
instructions: 'Choose the team that should handle this message.',
|
|
942
|
+
criteria: { billing: 'Payments and invoices', technical: 'App errors', other: 'Anything else' },
|
|
943
|
+
},
|
|
944
|
+
},
|
|
945
|
+
});
|
|
946
|
+
const team = decision.answers.team.choice;
|
|
947
|
+
const confidence = decision.answers.team.confidence;
|
|
948
|
+
return { team, confidence };
|
|
949
|
+
}
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
`team` is one of the supplied option names. The platform checks every answer
|
|
953
|
+
against the requested question before returning it. Choose thresholds using
|
|
954
|
+
labelled examples from your app; a model's confidence cannot establish that a
|
|
955
|
+
payment, deploy or other action succeeded. Check that action's own result.
|
|
956
|
+
|
|
957
|
+
| Question | Answer |
|
|
958
|
+
|---|---|
|
|
959
|
+
| `noul`: a yes/no question | `noul`, a probability between zero and one |
|
|
960
|
+
| `choice`: named options in `criteria` | `choice`, per-option `probabilities`, and `confidence` |
|
|
961
|
+
| `score`: an ordered array in `criteria` | `score`, the probability-weighted index (which can be fractional), plus `legend`, `probabilities`, and `confidence` |
|
|
962
|
+
|
|
963
|
+
Prices per million input tokens are $0.0483 for Jev and
|
|
964
|
+
$0.1035 for Clef-flash, including markup. Output is free;
|
|
965
|
+
image tokens count as input. `ai_catalog` lists the current models and rates.
|
|
966
|
+
Jev uses the account's included AI allowance first, including on Free, then
|
|
967
|
+
prepaid funds for the remainder. One call has one total charge. Keep paid AI
|
|
968
|
+
enabled for the account and limit callers in your function. Jev also has a
|
|
969
|
+
project request cap (120 per 60-second window by default). A refused request
|
|
970
|
+
returns 429 with `Retry-After` before reserving credit; an unavailable request
|
|
971
|
+
limiter returns 503 without sending the request. A provider rate refusal also
|
|
972
|
+
returns 429 with a bounded retry delay; the platform does not retry it.
|
|
973
|
+
An uncertain provider outcome retains the reservation for review and returns
|
|
974
|
+
`retry: false`; do not automatically repeat that paid request.
|
|
975
|
+
|
|
976
|
+
For images, pass `images: [dataUrl]` using embedded PNG, JPEG or WebP data;
|
|
977
|
+
remote URLs are refused. An explicit `model: 'jev'` with images is refused
|
|
978
|
+
because Jev reads text only. The result names `model`, `provider_model`
|
|
979
|
+
and `routed_by`. There is no `mode` option or silent model fallback.
|
|
980
|
+
Keep inputs focused: the input-size estimate is approximate and the model may
|
|
981
|
+
truncate long input.
|
|
982
|
+
|
|
983
|
+
Read `usage.input_tokens` for measured usage and `cost.status` before using
|
|
984
|
+
the price. `pending` means accounting needs reconciliation and the amounts
|
|
985
|
+
are null; the answer is still available. If an error says not to repeat the
|
|
986
|
+
paid request, show that outcome and stop automatic retries.
|
|
987
|
+
|
|
988
|
+
## Structured output — `response_schema`
|
|
989
|
+
|
|
990
|
+
Pass a JSON Schema object as `response_schema` to get a validated, parsed
|
|
991
|
+
response from the free default model. To choose a different model, use one
|
|
992
|
+
that supports forced tool choice. Use `response_schema` on its own, without
|
|
993
|
+
`tools` or `stream`.
|
|
994
|
+
|
|
995
|
+
```ts
|
|
996
|
+
// api/_lib/extract-order.ts — text is input your handler already accepted.
|
|
997
|
+
export interface Order { order_id: string; customer: string; amount: number }
|
|
998
|
+
|
|
999
|
+
export async function extractOrder(sw: SomewhereRuntimeContext, text: string): Promise<Order | null> {
|
|
1000
|
+
const r = await sw.ai.chat({
|
|
1001
|
+
messages: [{ role: 'user', content: `Extract order: ${text}` }],
|
|
1002
|
+
max_tokens: 128,
|
|
1003
|
+
response_schema: {
|
|
1004
|
+
type: 'object',
|
|
1005
|
+
properties: {
|
|
1006
|
+
order_id: { type: 'string' },
|
|
1007
|
+
customer: { type: 'string' },
|
|
1008
|
+
amount: { type: 'number' },
|
|
1009
|
+
},
|
|
1010
|
+
required: ['order_id', 'customer', 'amount'],
|
|
1011
|
+
},
|
|
1012
|
+
});
|
|
1013
|
+
const p = r.parsed;
|
|
1014
|
+
if (!p || typeof p.order_id !== 'string' || typeof p.customer !== 'string' || typeof p.amount !== 'number') {
|
|
1015
|
+
console.warn('parse failed:', r.parse_error);
|
|
1016
|
+
return null;
|
|
1017
|
+
}
|
|
1018
|
+
return { order_id: p.order_id, customer: p.customer, amount: p.amount };
|
|
1019
|
+
}
|
|
1020
|
+
```
|
|
1021
|
+
|
|
1022
|
+
The response gains two fields: `parsed` (the validated object, or null
|
|
1023
|
+
on failure) and `parse_error` (null on success, otherwise a short reason
|
|
1024
|
+
string). The free default makes one request and reports parse failure
|
|
1025
|
+
without a repair call. Other supported paths may retry once before giving up — no exceptions are thrown so your handler can branch. On
|
|
1026
|
+
`provider: 'anthropic'` that retry is one separate model invocation with
|
|
1027
|
+
its own balance reservation, started only after the first call's cost has
|
|
1028
|
+
settled: if the first cost is pending there is no retry; if the balance
|
|
1029
|
+
cannot cover the retry you get the original content with `parse_error`
|
|
1030
|
+
set; if the retry's outcome is ambiguous you get the original content with
|
|
1031
|
+
`cost` pending; a successful retry reports both invocations' bills added
|
|
1032
|
+
together, with no second markup.
|
|
1033
|
+
|
|
1034
|
+
## Free chat
|
|
1035
|
+
|
|
1036
|
+
Default pick — omit both provider/model and the platform serves
|
|
1037
|
+
`gpt-6-luna` from the account's included managed-AI allowance, which renews
|
|
1038
|
+
each month on Free and each billing period on paid plans. Every plan also has the
|
|
1039
|
+
same owner-level request envelope: 10 requests/minute, 200/day, 8,192 estimated
|
|
1040
|
+
input tokens including system/tools/history, and 1,024 output tokens per call.
|
|
1041
|
+
No prepaid fallback or automatic paid repair request. Set `max_tokens` to
|
|
1042
|
+
1,024 or less.
|
|
1043
|
+
|
|
1044
|
+
If `gpt-6-luna` is unavailable (a timeout, an outage or a capacity refusal),
|
|
1045
|
+
the same request is answered once by Claude Haiku 4.5 under the same free
|
|
1046
|
+
limits and allowance. The result then has `model` set to the Haiku model,
|
|
1047
|
+
`provider: 'anthropic'` and `fallback_used: true`. Otherwise they read
|
|
1048
|
+
`gpt-6-luna`, `'openai'` and `false`.
|
|
1049
|
+
|
|
1050
|
+
Explicit platform-funded text choices are Claude Opus 5.5, Sonnet 5.5,
|
|
1051
|
+
Haiku 4.5 and Luna. `ai_catalog` gives current IDs and rates. Named retired
|
|
1052
|
+
text IDs return 410 `MODEL_RETIRED`; a provider-only request whose former
|
|
1053
|
+
default was removed returns 400 and names a model to select explicitly.
|
|
1054
|
+
Neither refusal makes an inference call or takes an AI hold.
|
|
1055
|
+
|
|
1056
|
+
## Other AI surfaces — also on sw.ai
|
|
1057
|
+
|
|
1058
|
+
Embeddings, transcription, text-to-speech, and image generation are
|
|
1059
|
+
first-class on sw.ai inside a deployed function.
|
|
1060
|
+
No API key, no fetch, no project_id juggling — same pattern as
|
|
1061
|
+
sw.ai.chat.
|
|
1062
|
+
|
|
1063
|
+
```ts
|
|
1064
|
+
// api/_lib/ai-surfaces.ts — server helpers. The calling handler has authorized
|
|
1065
|
+
// the request and accepted every input; paid models bill this project. The
|
|
1066
|
+
// model selects the provider (a provider field is accepted and ignored).
|
|
1067
|
+
|
|
1068
|
+
// Embeddings — workers-ai (free tier eligible)
|
|
1069
|
+
export async function embedFree(sw: SomewhereRuntimeContext, texts: readonly string[]): Promise<number[][]> {
|
|
1070
|
+
const r = await sw.ai.embeddings({ model: '@cf/baai/bge-base-en-v1.5', text: texts });
|
|
1071
|
+
// r.embeddings = [[...], [...]], r.dimensions = 768
|
|
1072
|
+
return r.embeddings;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// Transcribe — pass base64 audio or a public audio_url.
|
|
1076
|
+
// The result also includes words: { word, start, end }[], with times in seconds.
|
|
1077
|
+
// On the default model, language and prompt supply a language and vocabulary hint.
|
|
1078
|
+
// Example: { audio_url: audioUrl, language: 'en', prompt: 'Somewhere, Kubernetes' }.
|
|
1079
|
+
// The classic Whisper models reject hints before charging for transcription.
|
|
1080
|
+
export async function transcribeClip(sw: SomewhereRuntimeContext, audioUrl: string): Promise<{ text: string; seconds: number }> {
|
|
1081
|
+
const t = await sw.ai.transcribe({ audio_url: audioUrl });
|
|
1082
|
+
return { text: t.text, seconds: t.duration_seconds };
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// Generate an image — returns a raw Response unless you set storage.
|
|
1086
|
+
// Return it from your handler to stream the PNG straight to the browser.
|
|
1087
|
+
export function draftImage(sw: SomewhereRuntimeContext, prompt: string): Promise<Response> {
|
|
1088
|
+
return sw.ai.generateImage({ model: 'gpt-image-2.5-flare', prompt });
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// Final asset, legible text or a transparent PNG: GPT Image, stored in files
|
|
1092
|
+
export async function planeIcon(sw: SomewhereRuntimeContext): Promise<SomewhereAiGenerateImageStored> {
|
|
1093
|
+
const stored = await sw.ai.generateImage({
|
|
1094
|
+
model: 'gpt-image-2.5-flare',
|
|
1095
|
+
prompt: 'Flat app icon of a paper plane, no text',
|
|
1096
|
+
background: 'transparent',
|
|
1097
|
+
storage: '/icons/plane.png',
|
|
1098
|
+
});
|
|
1099
|
+
// stored = { storage_path, size_bytes, content_type, quality, background, ... }
|
|
1100
|
+
return stored;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// Browse the live model catalog
|
|
1104
|
+
export function listModels(sw: SomewhereRuntimeContext): Promise<SomewhereAiCatalog> {
|
|
1105
|
+
return sw.ai.catalog();
|
|
1106
|
+
}
|
|
1107
|
+
```
|
|
1108
|
+
|
|
1109
|
+
## Image generation models
|
|
1110
|
+
|
|
1111
|
+
Pass `model: 'gpt-image-2.5-flare'` explicitly. Omitting a model returns 400
|
|
1112
|
+
`VALIDATION_ERROR`, before any hold or provider call. Naming a retired image
|
|
1113
|
+
ID returns 410 `MODEL_RETIRED`; no request is silently moved to GPT Image.
|
|
1114
|
+
|
|
1115
|
+
`quality` is 'low', 'medium' (default), or 'high'. `background` is 'auto'
|
|
1116
|
+
(default), 'opaque', or 'transparent' (PNG with alpha). Width/height choose
|
|
1117
|
+
1536×1024 for a wider image, 1024×1536 for a taller image, otherwise
|
|
1118
|
+
1024×1024. The call reserves the calculator hold and bills reported image and
|
|
1119
|
+
prompt token usage at the catalog rates, capped at that hold. Missing usage
|
|
1120
|
+
uses the existing calculator estimate.
|
|
1121
|
+
|
|
1122
|
+
Failed GPT Image calls return the reserved balance. If that return cannot be
|
|
1123
|
+
confirmed, the response includes `settlement: 'unconfirmed'`; check the
|
|
1124
|
+
balance before trying again. For a stored GPT Image, the platform checks the
|
|
1125
|
+
destination and storage allowance before generation. Every stored image's
|
|
1126
|
+
actual size is checked before saving.
|
|
1127
|
+
- Bring your own image provider for anything else: store the vendor's key
|
|
1128
|
+
as a project secret (sw.env) and call the vendor's API from your function
|
|
1129
|
+
with fetch. There is no managed AI charge on that path — the vendor bills
|
|
1130
|
+
you directly; your function's ordinary platform usage still applies. A
|
|
1131
|
+
request for any other managed image model is refused with a message naming
|
|
1132
|
+
gpt-image-2.5-flare.
|
|
1133
|
+
|
|
1134
|
+
## Background removal
|
|
1135
|
+
|
|
1136
|
+
Background removal is not offered as a managed capability. A call to
|
|
1137
|
+
POST /v1/ai/remove-background (or sw.ai.removeBackground) is refused with a
|
|
1138
|
+
typed error; nothing is charged. To remove backgrounds, bring your own
|
|
1139
|
+
provider: store its key as a project secret and call it from your function.
|
|
1140
|
+
A generative image model is not a substitute for background removal, so the
|
|
1141
|
+
platform does not silently swap one in.
|
|
1142
|
+
|
|
1143
|
+
## Text-to-speech
|
|
1144
|
+
|
|
1145
|
+
- inworld-tts-2-flash — the free DEFAULT voice, used when `model` is omitted.
|
|
1146
|
+
166 English voices by name (default Ashley; see ai_catalog). A Kokoro voice
|
|
1147
|
+
id (af_*, am_*, bf_*, bm_*) maps to a similar voice. Up to 2,000 chars per
|
|
1148
|
+
call. `word_timings: true` returns JSON
|
|
1149
|
+
`{ audio_base64, content_type, model, words: [{ word, start, end }] }`
|
|
1150
|
+
(seconds) instead of raw audio; with `storage`, `words` joins the envelope.
|
|
1151
|
+
- hexgrad/Kokoro-82M — free. 28 English voices (American + British) by id,
|
|
1152
|
+
default af_bella. Up to 8,000 chars per call.
|
|
1153
|
+
- ResembleAI/chatterbox-turbo — free. One built-in voice (omit `voice`).
|
|
1154
|
+
Up to 8,000 chars per call.
|
|
1155
|
+
- The free voices share fair-use limits (per-minute, per-day, and
|
|
1156
|
+
monthly-character); exceeding one returns 429 RATE_LIMITED with
|
|
1157
|
+
retry_after_ms, reset_at, and the applicable limit/remaining.
|
|
1158
|
+
- grok-tts — premium voice (pricing at /v1/pricing).
|
|
1159
|
+
Voice options (voice param): eve, ara, rex, sal, leo. `lang`
|
|
1160
|
+
defaults to 'en'. Max 15,000 chars per call.
|
|
1161
|
+
|
|
1162
|
+
A per-request character overflow returns 400. When the provider is not serving
|
|
1163
|
+
the selected voice right now (it refuses, answers 5xx, drops the connection, or
|
|
1164
|
+
gives no answer within 8 seconds for a short line, longer for long text), the
|
|
1165
|
+
call returns 503 VOICE_UNAVAILABLE with `retry: true` and `retry_after_ms`.
|
|
1166
|
+
While the platform's hourly check of the default voice is also failing, it says
|
|
1167
|
+
so and returns `retry: false`: retrying will not help until the provider
|
|
1168
|
+
recovers. Any other provider failure returns 503 UPSTREAM_DOWN with retry
|
|
1169
|
+
guidance. There is no silent model substitution.
|
|
1170
|
+
|
|
1171
|
+
```ts
|
|
1172
|
+
// api/_lib/speech.ts — grok-tts is billed; call these from a handler that has
|
|
1173
|
+
// signed in the user and accepted the text.
|
|
1174
|
+
|
|
1175
|
+
// Stream the audio straight to the browser: return this Response from the handler.
|
|
1176
|
+
export function speak(sw: SomewhereRuntimeContext, text: string): Promise<Response> {
|
|
1177
|
+
return sw.ai.tts({ model: 'grok-tts', voice: 'eve', text }); // Content-Type is the audio MIME
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// Or save to file storage and return its path
|
|
1181
|
+
export async function saveGreeting(sw: SomewhereRuntimeContext): Promise<string> {
|
|
1182
|
+
const stored = await sw.ai.tts({ model: 'grok-tts', voice: 'eve', text: 'Hello world.', storage: '/audio/greeting.mp3' });
|
|
1183
|
+
// stored = { storage_path, size_bytes, content_type, ... }
|
|
1184
|
+
return stored.storage_path;
|
|
1185
|
+
}
|
|
1186
|
+
```
|
|
1187
|
+
|
|
1188
|
+
## Content moderation
|
|
1189
|
+
|
|
1190
|
+
sw.ai.moderate(text) classifies text against a safety taxonomy
|
|
1191
|
+
(violence, sexual content, hate, self-harm, illegal advice, etc.). Free —
|
|
1192
|
+
it uses the platform's content-safety model and consumes no AI allowance.
|
|
1193
|
+
There is no fallback: when moderation is unavailable the call throws, nothing
|
|
1194
|
+
else ran and nothing was charged. Treat that as "not checked", never as
|
|
1195
|
+
"clean".
|
|
1196
|
+
|
|
1197
|
+
```ts
|
|
1198
|
+
// api/_lib/moderation.ts — returns a 422 response for flagged text, or null
|
|
1199
|
+
// when it may proceed. A thrown error means the text was not checked.
|
|
1200
|
+
export async function blockFlagged(sw: SomewhereRuntimeContext, userMessage: string): Promise<Response | null> {
|
|
1201
|
+
const result = await sw.ai.moderate(userMessage);
|
|
1202
|
+
// { flagged, categories: [names of the flagged categories],
|
|
1203
|
+
// scores: { <category>: <score> }, model: 'content-safety', provider: 'somewhere' }
|
|
1204
|
+
if (result.flagged) return Response.json({ error: 'Message blocked' }, { status: 422 });
|
|
1205
|
+
return null;
|
|
1206
|
+
}
|
|
1207
|
+
```
|
|
1208
|
+
|
|
1209
|
+
`categories` lists only the categories that were flagged; `scores` has a
|
|
1210
|
+
score for every category the model reports.
|
|
1211
|
+
|
|
1212
|
+
Max input: 50,000 chars. Subject to the free-tier AI rate limits above.
|
|
1213
|
+
|
|
1214
|
+
## Catalog discovery
|
|
1215
|
+
|
|
1216
|
+
sw.ai.catalog() (or the ai_catalog MCP tool / GET /v1/ai/catalog
|
|
1217
|
+
externally) returns every model the platform exposes — provider, family
|
|
1218
|
+
(chat / embeddings / tts / image), pricing, and
|
|
1219
|
+
default + max steps. Paid-model rates are in /v1/pricing.
|
|
1220
|
+
Use it to render a picker or audit costs without hard-coding model lists.
|
|
1221
|
+
|
|
1222
|
+
Use sw.ai.* inside any deployed function — the platform binding handles
|
|
1223
|
+
auth and project scoping. The smt_ developer key is only for external
|
|
1224
|
+
clients (CI/CD, server-to-server jobs, webhooks).
|
|
1225
|
+
|
|
1226
|
+
## Error envelope (typed catalogue)
|
|
1227
|
+
|
|
1228
|
+
HTTP AI endpoints return JSON error bodies. For example, a request missing
|
|
1229
|
+
its project ID returns HTTP 400 (the recovery hint is omitted here):
|
|
1230
|
+
|
|
1231
|
+
```json
|
|
1232
|
+
{
|
|
1233
|
+
"ok": false,
|
|
1234
|
+
"error": "VALIDATION_ERROR",
|
|
1235
|
+
"message": "project_id is required."
|
|
1236
|
+
}
|
|
1237
|
+
```
|
|
1238
|
+
|
|
1239
|
+
Inside a function, `sw.ai.chat` throws an `Error` with `code` and
|
|
1240
|
+
`status`, plus `retry` and `retry_after_ms` when the response supplies
|
|
1241
|
+
them. Handle the error code and follow its recovery guidance below.
|
|
1242
|
+
|
|
1243
|
+
## Model lifecycle
|
|
1244
|
+
|
|
1245
|
+
The AI catalog reports `state`, `servedBy`, `retiresOn` (UTC) and `alternatives`.
|
|
1246
|
+
A superseded text ID is served by its catalog successor at the successor's
|
|
1247
|
+
price; the response adds `requested_model`, while `model` names the model that
|
|
1248
|
+
answered. Usage-list records also include `requested_model` (null for older
|
|
1249
|
+
records). Older Opus IDs resolve to Opus 5.5; older Sonnet IDs resolve to
|
|
1250
|
+
Sonnet 5.5. These same-tier successor rates are lower or equal across all
|
|
1251
|
+
implemented rate classes. Removed families return 410 instead of forwarding
|
|
1252
|
+
to a different family.
|
|
1253
|
+
|
|
1254
|
+
Unsupported successor capabilities return `MODEL_CAPABILITY_UNSUPPORTED`
|
|
1255
|
+
before a provider call or reservation, naming what to change. This includes
|
|
1256
|
+
forced tool choice, `response_schema`, assistant prefill and sampling controls
|
|
1257
|
+
on Sonnet 5.5. A current entry with a retirement date works until that UTC date; on that date
|
|
1258
|
+
it becomes `retired` and returns `MODEL_RETIRED` before any reservation or
|
|
1259
|
+
charge. Choose a listed alternative explicitly. Embedding IDs are never
|
|
1260
|
+
silently upgraded: recreate existing vectors when choosing a new model.
|
|
1261
|
+
|
|
1262
|
+
### Version upgrades, project keys and boundary behavior
|
|
1263
|
+
|
|
1264
|
+
These mappings apply even when the project supplies its own provider key.
|
|
1265
|
+
The successor is selected before key lookup and the provider bills that key;
|
|
1266
|
+
platform holds and charges are skipped, and usage is marked externally billed.
|
|
1267
|
+
If a provider account cannot access the successor, its access must be resolved;
|
|
1268
|
+
A platform-funded retirement is different: a managed OpenAI or Anthropic
|
|
1269
|
+
key retains that provider's existing completion path. See the own-key guide above.
|
|
1270
|
+
Unrecognized provider-specific model strings retain the existing BYOK policy;
|
|
1271
|
+
matching recognized lifecycle IDs is exact after trimming, not case-insensitive.
|
|
1272
|
+
|
|
1273
|
+
The three availability states are `current`, `superseded` and `retired`.
|
|
1274
|
+
Before a retirement deadline the state stays `current`; `retiresOn`, alternatives
|
|
1275
|
+
and a retiring-on notice describe its scheduled refusal. The platform boundary
|
|
1276
|
+
is inclusive at **2026-11-20T00:00:00Z**. The provider announced a date, not a
|
|
1277
|
+
verified timezone. Admission uses the platform UTC clock; a request admitted
|
|
1278
|
+
just before the boundary may finish after it.
|
|
1279
|
+
|
|
1280
|
+
An upgraded response's `model` is the **serving** model. Code that checked
|
|
1281
|
+
`model === requestedId` must use `requested_model` to identify an upgraded
|
|
1282
|
+
request instead. This also applies to buffered streaming's message-start data.
|
|
1283
|
+
Catalog `servedBy` announces the successor before a call.
|
|
1284
|
+
|
|
1285
|
+
For Sonnet 5.5, the hold counts the actual prepared messages, system prompt and
|
|
1286
|
+
tools against the serving model before inference, rather than treating a history
|
|
1287
|
+
budget as total input. The serving context/output limits still apply. If an
|
|
1288
|
+
actual bill exceeds the admitted hold, no excess debit is made: the hold stays
|
|
1289
|
+
for review, response cost is pending, and usage records known provider cost and
|
|
1290
|
+
both IDs with zero customer bill until authorized settlement. A later settlement
|
|
1291
|
+
updates that usage's bill and daily cost once, without counting another call.
|