Batch from a CSV
Run a FLORA Technique once per row of a CSV with the TypeScript SDK, using idempotency keys, bounded parallelism and backoff so reruns never double-bill.
The everyday production pattern: read structured input from a CSV (or a database, or another API), run a Technique per row, save each output under the row's key, and handle failures and retries. Use this instead of Generate a grid when each run has different inputs.
What you'll build: a script that reads markets.csv (columns market_code and headline) and writes out/thumbnail_DE.png, out/thumbnail_FR.png and so on.
TypeScript
Install the CSV parser with npm install csv-parse, set the constants at the top to match your Technique (read its inputs with client.techniques.retrieve), and run with npx tsx batch.mts.
import { FloraClient, FloraError } from "@flora-ai/flora"
import { parse } from "csv-parse/sync"
import crypto from "node:crypto"
import fs from "node:fs/promises"
import path from "node:path"
// Match these to your Technique's inputs
const SLUG = "your-technique-slug"
const HEADLINE_INPUT = "headline"
const REFERENCE_INPUTS = ["reference_1", "reference_2"]
const REFERENCES = [
"https://example.com/flora/approved_still_4.png",
"https://example.com/flora/approved_still_7.png",
]
const CONCURRENCY = 4
const POLL_MS = 15_000
const client = new FloraClient()
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
type Row = { market_code: string; headline: string }
type Outcome = { row: Row; url?: string; error?: string }
function keyFor(row: Row): string {
// Same row and headline = same key, so a rerun returns the existing run
const hash = crypto.createHash("sha256").update(row.headline).digest("hex").slice(0, 16)
return `q3-thumb-${row.market_code}-${hash}`
}
async function withRetry<T>(fn: () => Promise<T>, max = 5): Promise<T> {
let lastErr: unknown
for (let attempt = 0; attempt < max; attempt++) {
try {
return await fn()
} catch (err) {
lastErr = err
if (err instanceof FloraError && [400, 401, 402, 403, 404, 409].includes(err.statusCode ?? 0)) {
throw err // the request itself is wrong: don't retry
}
await sleep(Math.min(1000 * 2 ** attempt, 30_000))
}
}
throw lastErr
}
async function processRow(row: Row): Promise<string> {
const run = await withRetry(() =>
client.techniques.runs.create({
techniqueId: SLUG,
inputs: [
{ id: HEADLINE_INPUT, type: "text", value: row.headline },
...REFERENCES.map((url, i) => ({ id: REFERENCE_INPUTS[i], type: "imageUrl" as const, value: url })),
],
mode: "async",
idempotency_key: keyFor(row),
}),
)
let result = await client.techniques.runs.retrieve({ techniqueId: SLUG, runId: run.run_id })
while (result.status === "pending" || result.status === "running") {
await sleep(POLL_MS)
result = await withRetry(() => client.techniques.runs.retrieve({ techniqueId: SLUG, runId: run.run_id }))
}
if (result.status === "failed") throw new Error(`${result.error_code}: ${result.error_message ?? ""}`)
const url = result.outputs?.[0]?.url
if (!url) throw new Error("Run completed without an output")
return url
}
async function parallelMap<T, R>(items: T[], concurrency: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const results: R[] = new Array(items.length)
let next = 0
await Promise.all(
Array.from({ length: concurrency }, async () => {
while (next < items.length) {
const i = next++
results[i] = await fn(items[i])
}
}),
)
return results
}
async function downloadTo(url: string, dest: string) {
const res = await fetch(url)
await fs.writeFile(dest, Buffer.from(await res.arrayBuffer()))
}
// === Main ===
const rows: Row[] = parse(await fs.readFile("./markets.csv", "utf8"), {
columns: true,
skip_empty_lines: true,
})
await fs.mkdir("out", { recursive: true })
const outcomes = await parallelMap(rows, CONCURRENCY, async (row): Promise<Outcome> => {
try {
const url = await processRow(row)
await downloadTo(url, path.join("out", `thumbnail_${row.market_code}.png`))
return { row, url }
} catch (err) {
return { row, error: err instanceof Error ? err.message : String(err) }
}
})
const failures = outcomes.filter((outcome) => outcome.error)
console.log(`Done. ${outcomes.length - failures.length} of ${rows.length} rows written to ./out/`)
if (failures.length > 0) {
await fs.writeFile("out/failures.json", JSON.stringify(failures, null, 2))
console.error(`${failures.length} rows failed; see out/failures.json`)
}A failed row doesn't stop the others; it's recorded in out/failures.json for you to look at.
Check the cost first
Before you start, price the batch and, if your key has billing permission on the workspace, compare it with the balance:
Stop rather than start a batch that will hit 402 insufficient_credits halfway through. available_cost is a snapshot, not a guarantee: other spend can change it.
Resumability
Because every row has a deterministic idempotency key, the script is safe to rerun. Rows it already started return their existing run, finished or not, without a new charge, and the script picks up their outputs. Rows whose create request failed start fresh. Edit a row's headline and its key changes, so that row runs again.
A run that failed keeps its key too, so a rerun returns the same failed run. To retry a failed row, change its key, for example by adding -retry1.
Tuning parallelism
Start with
CONCURRENCY = 4.Each poll is a request against your workspace's rate limit. With four workers polling every 15 seconds, the script makes about 16 requests a minute while it waits.
If you see
429 rate_limited, drop to 2 and let the backoff handle the rest. The SDK also retries429twice on its own.For long video runs, keep concurrency low and the poll interval long, or use webhooks instead of polling.
Schedule it
Run the script from cron or CI. With deterministic keys, a scheduled rerun on an unchanged CSV starts nothing new; only changed rows run.
Related
Idempotency: how the
idempotency_keybody field behaves.Errors: what to retry and what to surface.
Generate a grid: the single-brief version.
Iterate on outputs: references from earlier runs.
Batching from an AI client instead? See Batch-generate 20 to 500 assets.
Last updated
Was this helpful?