> For the complete documentation index, see [llms.txt](https://docs.flora.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.flora.ai/api/recipes/batch-from-csv.md).

# 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](https://docs.flora.ai/api/recipes/generate-a-grid.md) 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.

{% hint style="info" %}
This script combines three safeguards. Use all three:

* [**Idempotency keys**](https://docs.flora.ai/api/platform/idempotency.md) derived from each row, so a rerun returns the runs it already started instead of paying for new ones.
* **Bounded parallelism**, so you stay under your workspace's rate limit.
* **Exponential backoff** for transient errors.
  {% endhint %}

## 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`.

```ts
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:

```ts
const technique = await client.techniques.retrieve({ techniqueId: SLUG })
const total = technique.run_cost * rows.length
console.log(`Estimated cost: $${total.toFixed(2)} across ${rows.length} rows`)

const usage = await client.workspaces.getUsage({ workspaceId: "ws_abc123" })
if (usage.available_cost < total) throw new Error(`Only $${usage.available_cost} available`)
```

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 retries `429` twice on its own.
* For long video runs, keep concurrency low and the poll interval long, or use [webhooks](https://docs.flora.ai/api/platform/webhooks.md) 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](https://docs.flora.ai/api/platform/idempotency.md): how the `idempotency_key` body field behaves.
* [Errors](https://docs.flora.ai/api/platform/errors.md): what to retry and what to surface.
* [Generate a grid](https://docs.flora.ai/api/recipes/generate-a-grid.md): the single-brief version.
* [Iterate on outputs](https://docs.flora.ai/api/recipes/iterate-on-outputs.md): references from earlier runs.
* Batching from an AI client instead? See [Batch-generate 20 to 500 assets](https://docs.flora.ai/mcp/recipes/batch.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.flora.ai/api/recipes/batch-from-csv.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
