Open History to see the last commit
1---
2title: Keep Generated Files (Advanced)
3id: keep-generated-files
4---
5
6Provider URLs for generated media expire. A Sora clip, a batch of images, a long
7audio track: the model hands you a URL that stops working after a while, and
8once it does the output is gone. To keep the output, save the generated bytes to
9your own storage and serve them from your own origin, where they outlive the
10provider's link.
11
12This is a server-side opt-in that layers on **top of** the `generationRuns` store
13[Generation persistence](./generation-persistence) already requires. Byte storage
14adds two more stores, which must be provided together:
15
16- an `artifacts` store: the metadata.
17- a `blobs` store: the bytes.
18
19What each choice gets you:
20
21- **Both provided**: `withGenerationPersistence` writes each generated file's
22 bytes to the blob store, records an `ArtifactRecord`, and attaches durable
23 references to the result and the run record.
24- **Neither provided**: only the run record is kept.
25
26`memoryPersistence()` ships all three stores (`generationRuns`, `artifacts`,
27`blobs`), so it works out of the box. Any backend that implements `ArtifactStore`
28and `BlobStore` (see
29[Build a generation adapter](./build-your-own-generation-adapter))
30works the same way.
31
32## Serve the stored bytes
33
34The bytes land under the blob key `artifacts/<runId>/<artifactId>`. To fetch a
35generated file later (to render it, download it, or hand it to another request),
36add a `GET` route that reads the artifact back with the `retrieveArtifact` /
37`retrieveBlob` helpers and streams it from your own origin:
38
39```ts group=generation-bytes
40// routes/api.generate.image.ts, runs the generation.
41import {
42 generateImage,
43 generationParamsFromRequest,
44 toServerSentEventsResponse,
45} from '@tanstack/ai'
46import { openaiImage } from '@tanstack/ai-openai'
47import {
48 memoryPersistence,
49 retrieveArtifact,
50 retrieveBlob,
51 withGenerationPersistence,
52} from '@tanstack/ai-persistence'
53
54const persistence = memoryPersistence()
55
56export async function POST(request: Request) {
57 const { input, threadId } = await generationParamsFromRequest(
58 'image',
59 request,
60 )
61
62 if (typeof input.prompt !== 'string') {
63 throw new Error('This endpoint accepts text image prompts only.')
64 }
65
66 // Persistence requires the scope these runs are filed under.
67 if (threadId === undefined) {
68 return new Response('`threadId` is required', { status: 400 })
69 }
70
71 const stream = generateImage({
72 adapter: openaiImage('gpt-image-2'),
73 prompt: input.prompt,
74 threadId,
75 stream: true,
76 middleware: [
77 withGenerationPersistence(persistence, {
78 // Stamp the durable serve URL (the artifact route below) onto every
79 // persisted artifact ref, and rewrite the live result's media field to
80 // it. Both the live and the restored result then render from your own
81 // origin instead of the provider's expiring link.
82 artifactUrl: (ref) =>
83 `/api/generate/image/artifact?id=${ref.artifactId}`,
84 }),
85 ],
86 })
87
88 return toServerSentEventsResponse(stream)
89}
90```
91
92The serve route is a **separate** route from the generation endpoint. A `GET` on
93the generation route is already spoken for by
94[Generation persistence](./generation-persistence), which is where a reloading
95client hydrates and where an in-flight run resumes, so the bytes get their own
96path, the one `artifactUrl` stamps above:
97
98```ts group=generation-bytes
99// routes/api.generate.image.artifact.ts, serves stored bytes by id.
100//
101// This is a plain file endpoint: it serves one stored file, it does not resume
102// a run or rebuild a conversation.
103//
104// Security: the id comes from the caller, so this route MUST authorize before
105// it serves. `ArtifactRecord` carries the `threadId` / `runId` the file was
106// generated under. Check that against an identity you derive server-side from
107// the session, never from the query string. Without this check, any caller who
108// learns or guesses an artifact id can read another user's media.
109export async function GET(request: Request) {
110 const artifactId = new URL(request.url).searchParams.get('id')
111 if (!artifactId) return new Response('missing id', { status: 400 })
112
113 const artifact = await retrieveArtifact(persistence, artifactId)
114 if (!artifact) return new Response('not found', { status: 404 })
115
116 // Replace with your session + ownership check, e.g.:
117 // const user = await auth(request)
118 // const owned = user != null && (await db.threadOwnedBy(user.id, artifact.threadId))
119 const owned = true
120 void request
121 // 404, not 403. A distinguishable "exists but forbidden" confirms valid ids.
122 if (!owned) return new Response('not found', { status: 404 })
123
124 const blob = await retrieveBlob(persistence, artifact)
125 if (!blob) return new Response('not found', { status: 404 })
126
127 return new Response(blob.body ?? (await blob.arrayBuffer()), {
128 headers: {
129 'content-type': artifact.mimeType,
130 'content-length': String(artifact.size),
131 },
132 })
133}
134```
135
136### Serve video: honour `Range`
137
138The route above is enough for images. Video is not: seeking a `<video>` is
139built on HTTP range requests, and a source that answers every `Range` with the
140whole file cannot be scrubbed: Safari refuses to play it at all, and every
141other browser downloads the entire clip before it starts. Pass `range` to
142`retrieveBlob` and answer `206`:
143
144```ts group=generation-bytes
145import { parseRangeHeader } from '@tanstack/ai-persistence'
146import type { ArtifactRecord } from '@tanstack/ai-persistence'
147
148// The same route, seek-aware. `parseRangeHeader` resolves the header against
149// the size on the record, including suffix ranges (`bytes=-500` is the LAST
150// 500 bytes) and the unsatisfiable case. `blob.range` then reports the slice
151// actually served, and `artifact.size` the whole file: the two numbers
152// `Content-Range` needs.
153export async function serveArtifactBytes(
154 request: Request,
155 artifact: ArtifactRecord,
156) {
157 const range = parseRangeHeader(request.headers.get('range'), artifact.size)
158 if (range === 'unsatisfiable') {
159 return new Response('range not satisfiable', {
160 status: 416,
161 headers: { 'content-range': `bytes */${artifact.size}` },
162 })
163 }
164
165 const blob = await retrieveBlob(
166 persistence,
167 artifact,
168 range ? { range } : undefined,
169 )
170 if (!blob) return new Response('not found', { status: 404 })
171
172 const body = blob.body ?? (await blob.arrayBuffer())
173 // `accept-ranges` on every response, including the whole-file one: it is how
174 // the player learns it may seek at all.
175 const headers = {
176 'content-type': artifact.mimeType,
177 'accept-ranges': 'bytes',
178 }
179 if (!blob.range) {
180 return new Response(body, {
181 headers: { ...headers, 'content-length': String(artifact.size) },
182 })
183 }
184 const { offset, length } = blob.range
185 return new Response(body, {
186 status: 206,
187 headers: {
188 ...headers,
189 'content-length': String(length),
190 'content-range': `bytes ${offset}-${offset + length - 1}/${artifact.size}`,
191 },
192 })
193}
194```
195
196The client side needs nothing special, which is the point. Given a route that
197answers ranges, the browser drives the rest:
198
199```tsx
200import type { PersistedArtifactRef } from '@tanstack/ai'
201
202export function GeneratedVideo({ artifact }: { artifact: PersistedArtifactRef }) {
203 // `artifact.url` is the app-origin URL `artifactUrl` stamped on the ref.
204 return <video src={artifact.url} controls preload="metadata" />
205}
206```
207
208`preload="metadata"` has the player fetch the header bytes with a range request
209and show the duration and scrubber without pulling the clip down. A store must
210support ranged reads for any of this to work; the
211[conformance testkit](./store-reference#blobstore) asserts it.
212
213`memoryPersistence` keeps everything in process memory, which is right for
214development and tests; point `generationRuns` / `artifacts` / `blobs` at a durable backend
215for production. Control what gets captured with `withGenerationPersistence`'s
216`extractArtifacts` (return your own descriptors) and `nameArtifact` (name each
217file) options.
218
219A custom `extractArtifacts` replaces the built-in rule. If you use a video
220provider with [no public URL](../media/video-generation#videos-with-no-public-url),
221return a descriptor with `bytes: result.body` for the video. If you do not, the
222stream is not stored and `url` is a base64 `data:` URL.
223
224## Choose where the bytes land
225
226By default an artifact's bytes are written under
227`artifacts/<runId>/<artifactId>`. Pass `storageKey` to put them in your own
228folder structure instead, which helps when the bucket is shared with the rest of
229your app, or when you want media grouped by the thing it belongs to rather than
230by the run that produced it:
231
232```ts group=generation-bytes
233const storageKeyOptions = withGenerationPersistence(persistence, {
234 storageKey: ({ runId, artifactId, role, name }) =>
235 `products/${role}/${runId}-${artifactId}-${name}`,
236})
237```
238
239Two things worth knowing:
240
241**The resolved key is recorded on the artifact.** Once the path is arbitrary it
242can no longer be recomputed from the record, so it is stored as
243`ArtifactRecord.blobKey` and reads resolve through it. Records written before
244this existed fall back to the default convention, so adding `storageKey` to an
245app with existing artifacts does not orphan them. It does mean the default
246convention can never be changed retroactively.
247
248**Returning a non-unique key overwrites.** Include `artifactId`, or something
249equally unique, unless overwriting is what you want.
250
251This is server-side only, deliberately. A key supplied by the browser would be a
252path-traversal and cross-tenant-write vector.
253
254## Prompt media referenced by URL
255
256What gets stored is the **generated output**. When a provider returns an
257expiring link, the middleware downloads it and keeps the bytes, which is the
258whole point of this page.
259
260Prompt media is different, and it splits by how you sent it:
261
262- **base64** (`source: { type: 'data' }`): stored alongside the output, because
263 the bytes are already in hand.
264- **a URL** (`source: { type: 'url' }`): **not fetched**, and no artifact is
265 recorded for it.
266
267Two reasons a caller-supplied URL is left alone. Downloading it server-side
268would let anyone name an address your server can reach (cloud metadata
269endpoints, `localhost` admin services) and then read the response back through
270the artifact `GET` route. The copy is also redundant: whoever supplied the URL
271already had the media.
272
273If you do need a durable copy of caller-supplied media (a "paste an image URL"
274input box, say), opt in with `allowInputUrl`, which is a predicate rather than a
275flag precisely so the check is not optional:
276
277```ts group=generation-bytes
278const inputUrlOptions = withGenerationPersistence(persistence, {
279 allowInputUrl: ({ url }) => url.hostname.endsWith('.cdn.example.com'),
280})
281```
282
283Every artifact fetch, input or output, is bounded three ways:
284
285- The scheme must be `http:` or `https:`.
286- It is aborted after `artifactFetchTimeoutMs` (default 30s).
287- It is capped at `maxArtifactBytes` (default 1 GiB) as the body drains, or not
288 at all when you pass `false`; see [Nothing is buffered](#nothing-is-buffered).
289
290Input fetches add two more: a loopback / private / link-local host block, and a
291refusal to follow redirects, so a `302` cannot hop somewhere the check never
292saw.
293
294Treat those as a backstop, not the control: a hostname that *resolves* to a
295private address still passes a literal-IP check. Keep `allowInputUrl` narrow,
296and for stronger isolation inject `artifactFetch` to route downloads through an
297egress-restricted proxy that can check the address actually connected to.
298
299## Nothing is buffered
300
301A provider URL is **streamed** into the blob store: the middleware never holds
302the artifact in memory, and `size` on the record is counted as the bytes drain.
303A 2 GB video costs a streaming store (R2, S3, a filesystem) the same memory as
304a 2 KB icon. `memoryPersistence` is the exception, and only because holding the
305bytes in process *is* what it does: it is a dev/test store, not a production
306one.
307
308`maxArtifactBytes` is therefore a bound on **transfer**, not on memory. What it
309buys is a ceiling on what a runaway or hostile origin can make you pull and
310store: `content-length` is advisory, so an origin can declare 1 KB and send
311forever. That is the only reason there is a default at all.
312
313### A provider stream is stored the same way
314
315Some video providers return the finished video as a stream, with no URL to
316fetch. See [Videos with no public URL](../media/video-generation#videos-with-no-public-url).
317The middleware passes that stream to `BlobStore.put` as it is, so memory stays
318flat here too.
319
320Two differences from a fetched URL:
321
322- **No declared length.** The stream has no `content-length`, and the
323 middleware sends no `BlobPutOptions.expectedLength`. Your store must accept
324 a stream of unknown length. On R2 that means a multipart upload.
325- **No size cap.** `maxArtifactBytes` applies to URL fetches only.
326
327### The body reaches your store untouched when it can
328
329Enforcing the cap during the drain means wrapping the body in a
330`TransformStream` that counts, and a transform's readable side carries **no
331declared length**, which is exactly what workerd's `R2Bucket.put` needs for a
332single-shot upload. So the wrapper is applied only where it is load-bearing:
333
334| The response | What your store gets |
335| ------------------------------------------------------- | ------------------------------------------- |
336| declares a `content-length`, no `content-encoding` | the `fetch` body **untouched**, length intact |
337| chunked, no declared length | the counting wrapper |
338| `content-encoding: gzip` (declared length is compressed) | the counting wrapper |
339
340In the first row nothing is lost by skipping the counter: the declared length
341was already checked against the cap, and HTTP framing holds the origin to it,
342a body cannot exceed a length it declared. That is the common case for a
343provider CDN, so on Cloudflare the default configuration already streams
344straight through:
345
346```ts ignore
347// Inside your BlobStore.put on workerd: nothing buffered, no multipart, no
348// hint needed. (`R2Bucket` comes from @cloudflare/workers-types.)
349const putStraightToR2 = (bucket: R2Bucket, key: string, body: BlobBody) =>
350 bucket.put(key, body)
351```
352
353The other two rows genuinely need the counter, because a chunked reply declares
354nothing, and a compressed one can decode to arbitrarily more than it declared
355(a decompression bomb). For those, `BlobPutOptions.expectedLength` is absent
356too, and a length-strict store falls back to a multipart upload that buffers
357one 8 MiB part at a time, so memory stays flat whatever the artifact's size. The
358`ai-persistence/build-cloudflare-artifact-store` skill ships that recipe.
359
360To drop the ceiling entirely (no counter on any response, no limit on what an
361origin can stream into your bucket) pass `false`:
362
363```ts group=generation-bytes
364const uncappedOptions = withGenerationPersistence(persistence, {
365 maxArtifactBytes: false,
366})
367```
368
369Reach for that when you trust the origins you fetch from and would rather have
370no ceiling than a generous one. Your storage backend's own limits still apply,
371R2, for instance, caps a single-shot upload at 5 GiB and a multipart one at
37210,000 parts. Keep the cap when `allowInputUrl` lets callers name the URL:
373there the origin is by definition not one you control.
374
375## Wire the durable URL through to the client
376
377`artifactUrl` is what makes the stored bytes reachable from the client without
378any extra plumbing. For each persisted ref it returns the app-origin URL that
379serves those bytes (the `GET` route above), and `withGenerationPersistence` does
380two things with it:
381
382- Stamps the URL onto the ref, as `ref.url`.
383- Rewrites the live result's media field to the same URL: `result.images[i].url`
384 for images, `result.url` for a video, `result.audio.url` for audio.
385
386So the live result already points at your origin, not the provider's expiring
387link.
388
389Those durable refs ride along on `result.artifacts`, and they are what a reload
390restores from. In [Generation persistence](./generation-persistence), the
391generation hook rebuilds `result` from the persisted refs on mount, resolving
392each media field to its durable `ref.url`, so the restored result renders the
393same media the live run showed. `result.artifacts` is the whole artifact surface
394on the hook: there are no separate top-level artifact fields to read, live or
395restored.
396
397## Where to go next
398
399- [Generation persistence](./generation-persistence): the run record that
400 survives a reload or a dropped connection, and the `generationRuns` store that
401 byte storage builds on.
402- [Build a generation adapter](./build-your-own-generation-adapter): a
403 custom `ArtifactStore` / `BlobStore` on your own database.