> 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/generate-a-grid.md).

# Generate a grid

Run a FLORA Technique several times from one brief with the API, wait for every run, and lay the results out as a 3×3 grid.

The most common FLORA API job: take a brief, run a Technique several times, and get back a set of variants to choose from. A 3×3 grid of nine is the classic shape. Use this recipe for one brief; for many briefs from a spreadsheet, use [Batch from a CSV](https://docs.flora.ai/api/recipes/batch-from-csv.md).

**What you'll build:** a script that starts nine runs of a Technique in parallel and returns their image URLs.

## TypeScript

Save as `grid.mts` and run with `npx tsx grid.mts`. The script fills the Technique's first text input with the brief; if your Technique needs other inputs, add them from `technique.inputs`.

```ts
import { FloraClient } from "@flora-ai/flora"

const client = new FloraClient()
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

async function generateGrid(slug: string, brief: string, count = 9): Promise<string[]> {
  const technique = await client.techniques.retrieve({ techniqueId: slug })
  const textInput = technique.inputs.find((input) => input.type === "text")
  if (!textInput) throw new Error(`${slug} has no text input`)
  console.log(`Estimated cost: $${(technique.run_cost * count).toFixed(2)} for ${count} runs`)

  // Start every run at once
  const runs = await Promise.all(
    Array.from({ length: count }, () =>
      client.techniques.runs.create({
        techniqueId: slug,
        inputs: [{ id: textInput.id, type: "text", value: brief }],
        mode: "async",
      }),
    ),
  )

  return waitForAll(slug, runs.map((run) => run.run_id))
}

async function waitForAll(slug: string, runIds: string[]): Promise<string[]> {
  const pending = new Set(runIds)
  const urls = new Map<string, string[]>()
  // Each poll is one request against the workspace rate limit
  const intervalMs = Math.max(15_000, 2_000 * runIds.length)

  while (pending.size > 0) {
    await sleep(intervalMs)
    for (const runId of [...pending]) {
      const result = await client.techniques.runs.retrieve({ techniqueId: slug, runId })
      if (result.status === "completed") {
        urls.set(runId, (result.outputs ?? []).map((output) => output.url))
        pending.delete(runId)
      } else if (result.status === "failed") {
        console.error(`${runId} failed: ${result.error_code} ${result.error_message ?? ""}`)
        pending.delete(runId)
      }
    }
  }

  return runIds.flatMap((runId) => urls.get(runId) ?? [])
}

const urls = await generateGrid(
  "your-technique-slug",
  "Smart living, simple. Audience 25-40, design-conscious. Warm minimalism, soft shadows. No clip-art, no gradients.",
)
console.log(urls)
```

## CLI

```bash
#!/usr/bin/env bash
set -euo pipefail

SLUG=your-technique-slug
INPUT_ID=prompt   # the text input's id, from: flora techniques retrieve --technique-id "$SLUG"
BRIEF="Smart living, simple. Warm minimalism."
COUNT=9

RUN_IDS=()
for _ in $(seq 1 "$COUNT"); do
  RUN_IDS+=("$(flora techniques:runs create \
    --technique-id "$SLUG" \
    --input "{id: $INPUT_ID, type: text, value: \"$BRIEF\"}" \
    --mode async \
    --transform run_id -r)")
done

for RUN_ID in "${RUN_IDS[@]}"; do
  while true; do
    STATUS=$(flora techniques:runs retrieve --technique-id "$SLUG" --run-id "$RUN_ID" --transform status -r)
    case "$STATUS" in
      completed) flora techniques:runs retrieve --technique-id "$SLUG" --run-id "$RUN_ID" --transform 'outputs.#.url'; break ;;
      failed)    echo "$RUN_ID failed" >&2; break ;;
      *)         sleep 15 ;;
    esac
  done
done
```

## Display the grid

In a React app, render the URLs as a three-column grid:

```tsx
<div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "8px" }}>
  {urls.map((url) => (
    <img key={url} src={url} alt="" loading="lazy" />
  ))}
</div>
```

## Save the grid as files

```ts
import fs from "node:fs/promises"
import path from "node:path"

async function downloadAll(urls: string[], dir: string) {
  await fs.mkdir(dir, { recursive: true })
  await Promise.all(
    urls.map(async (url, i) => {
      const res = await fetch(url)
      const buf = Buffer.from(await res.arrayBuffer())
      await fs.writeFile(path.join(dir, `tile_${i}.png`), buf)
    }),
  )
}

await downloadAll(urls, "./out/q3-grid")
```

## Variations

* **Several outputs per run.** Some Techniques return more than one output per run. Check `technique.outputs` and start fewer runs.
* **Aspect ratio and other settings.** If the Technique exposes an input for them, it's in `technique.inputs`; pass it like any other input.
* **Reference images.** Pass image URLs as `imageUrl` inputs; see [Iterate on outputs](https://docs.flora.ai/api/recipes/iterate-on-outputs.md).

## Tips

* Check the cost before you start: the total is `run_cost × count`, in US dollars.
* Output URLs are long-lived but not permanent. Download anything you need to keep.
* For more than a handful of briefs, use [Batch from a CSV](https://docs.flora.ai/api/recipes/batch-from-csv.md), which adds idempotency keys and backoff.

## Related

* [Iterate on outputs](https://docs.flora.ai/api/recipes/iterate-on-outputs.md): re-run with your favorites as references.
* [Upload an asset](https://docs.flora.ai/api/recipes/upload-an-asset.md): use your own image as an input.
* [Batch from a CSV](https://docs.flora.ai/api/recipes/batch-from-csv.md): many runs from structured input.


---

# 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/generate-a-grid.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.
