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
219## Choose where the bytes land
220
221By default an artifact's bytes are written under
222`artifacts/<runId>/<artifactId>`. Pass `storageKey` to put them in your own
223folder structure instead, which helps when the bucket is shared with the rest of
224your app, or when you want media grouped by the thing it belongs to rather than
225by the run that produced it:
226
227```ts group=generation-bytes
228const storageKeyOptions = withGenerationPersistence(persistence, {
229 storageKey: ({ runId, artifactId, role, name }) =>
230 `products/${role}/${runId}-${artifactId}-${name}`,
231})
232```
233
234Two things worth knowing:
235
236**The resolved key is recorded on the artifact.** Once the path is arbitrary it
237can no longer be recomputed from the record, so it is stored as
238`ArtifactRecord.blobKey` and reads resolve through it. Records written before
239this existed fall back to the default convention, so adding `storageKey` to an
240app with existing artifacts does not orphan them. It does mean the default
241convention can never be changed retroactively.
242
243**Returning a non-unique key overwrites.** Include `artifactId`, or something
244equally unique, unless overwriting is what you want.
245
246This is server-side only, deliberately. A key supplied by the browser would be a
247path-traversal and cross-tenant-write vector.
248
249## Prompt media referenced by URL
250
251What gets stored is the **generated output**. When a provider returns an
252expiring link, the middleware downloads it and keeps the bytes, which is the
253whole point of this page.
254
255Prompt media is different, and it splits by how you sent it:
256
257- **base64** (`source: { type: 'data' }`): stored alongside the output, because
258 the bytes are already in hand.
259- **a URL** (`source: { type: 'url' }`): **not fetched**, and no artifact is
260 recorded for it.
261
262Two reasons a caller-supplied URL is left alone. Downloading it server-side
263would let anyone name an address your server can reach (cloud metadata
264endpoints, `localhost` admin services) and then read the response back through
265the artifact `GET` route. The copy is also redundant: whoever supplied the URL
266already had the media.
267
268If you do need a durable copy of caller-supplied media (a "paste an image URL"
269input box, say), opt in with `allowInputUrl`, which is a predicate rather than a
270flag precisely so the check is not optional:
271
272```ts group=generation-bytes
273const inputUrlOptions = withGenerationPersistence(persistence, {
274 allowInputUrl: ({ url }) => url.hostname.endsWith('.cdn.example.com'),
275})
276```
277
278Every artifact fetch, input or output, is bounded three ways:
279
280- The scheme must be `http:` or `https:`.
281- It is aborted after `artifactFetchTimeoutMs` (default 30s).
282- It is capped at `maxArtifactBytes` (default 1 GiB) as the body drains, or not
283 at all when you pass `false`; see [Nothing is buffered](#nothing-is-buffered).
284
285Input fetches add two more: a loopback / private / link-local host block, and a
286refusal to follow redirects, so a `302` cannot hop somewhere the check never
287saw.
288
289Treat those as a backstop, not the control: a hostname that *resolves* to a
290private address still passes a literal-IP check. Keep `allowInputUrl` narrow,
291and for stronger isolation inject `artifactFetch` to route downloads through an
292egress-restricted proxy that can check the address actually connected to.
293
294## Nothing is buffered
295
296A provider URL is **streamed** into the blob store: the middleware never holds
297the artifact in memory, and `size` on the record is counted as the bytes drain.
298A 2 GB video costs a streaming store (R2, S3, a filesystem) the same memory as
299a 2 KB icon. `memoryPersistence` is the exception, and only because holding the
300bytes in process *is* what it does: it is a dev/test store, not a production
301one.
302
303`maxArtifactBytes` is therefore a bound on **transfer**, not on memory. What it
304buys is a ceiling on what a runaway or hostile origin can make you pull and
305store: `content-length` is advisory, so an origin can declare 1 KB and send
306forever. That is the only reason there is a default at all.
307
308### The body reaches your store untouched when it can
309
310Enforcing the cap during the drain means wrapping the body in a
311`TransformStream` that counts, and a transform's readable side carries **no
312declared length**, which is exactly what workerd's `R2Bucket.put` needs for a
313single-shot upload. So the wrapper is applied only where it is load-bearing:
314
315| The response | What your store gets |
316| ------------------------------------------------------- | ------------------------------------------- |
317| declares a `content-length`, no `content-encoding` | the `fetch` body **untouched**, length intact |
318| chunked, no declared length | the counting wrapper |
319| `content-encoding: gzip` (declared length is compressed) | the counting wrapper |
320
321In the first row nothing is lost by skipping the counter: the declared length
322was already checked against the cap, and HTTP framing holds the origin to it,
323a body cannot exceed a length it declared. That is the common case for a
324provider CDN, so on Cloudflare the default configuration already streams
325straight through:
326
327```ts ignore
328// Inside your BlobStore.put on workerd: nothing buffered, no multipart, no
329// hint needed. (`R2Bucket` comes from @cloudflare/workers-types.)
330const putStraightToR2 = (bucket: R2Bucket, key: string, body: BlobBody) =>
331 bucket.put(key, body)
332```
333
334The other two rows genuinely need the counter, because a chunked reply declares
335nothing, and a compressed one can decode to arbitrarily more than it declared
336(a decompression bomb). For those, `BlobPutOptions.expectedLength` is absent
337too, and a length-strict store falls back to a multipart upload that buffers
338one 8 MiB part at a time, so memory stays flat whatever the artifact's size. The
339`ai-persistence/build-cloudflare-artifact-store` skill ships that recipe.
340
341To drop the ceiling entirely (no counter on any response, no limit on what an
342origin can stream into your bucket) pass `false`:
343
344```ts group=generation-bytes
345const uncappedOptions = withGenerationPersistence(persistence, {
346 maxArtifactBytes: false,
347})
348```
349
350Reach for that when you trust the origins you fetch from and would rather have
351no ceiling than a generous one. Your storage backend's own limits still apply,
352R2, for instance, caps a single-shot upload at 5 GiB and a multipart one at
35310,000 parts. Keep the cap when `allowInputUrl` lets callers name the URL:
354there the origin is by definition not one you control.
355
356## Wire the durable URL through to the client
357
358`artifactUrl` is what makes the stored bytes reachable from the client without
359any extra plumbing. For each persisted ref it returns the app-origin URL that
360serves those bytes (the `GET` route above), and `withGenerationPersistence` does
361two things with it:
362
363- Stamps the URL onto the ref, as `ref.url`.
364- Rewrites the live result's media field to the same URL: `result.images[i].url`
365 for images, `result.url` for a video, `result.audio.url` for audio.
366
367So the live result already points at your origin, not the provider's expiring
368link.
369
370Those durable refs ride along on `result.artifacts`, and they are what a reload
371restores from. In [Generation persistence](./generation-persistence), the
372generation hook rebuilds `result` from the persisted refs on mount, resolving
373each media field to its durable `ref.url`, so the restored result renders the
374same media the live run showed. `result.artifacts` is the whole artifact surface
375on the hook: there are no separate top-level artifact fields to read, live or
376restored.
377
378## Where to go next
379
380- [Generation persistence](./generation-persistence): the run record that
381 survives a reload or a dropped connection, and the `generationRuns` store that
382 byte storage builds on.
383- [Build a generation adapter](./build-your-own-generation-adapter): a
384 custom `ArtifactStore` / `BlobStore` on your own database.