# Pictures from a preset

Turn a few words into a picture in your house style, with the style kept in a preset.

1. [Save the house style](#1-save-the-house-style).
2. [Ask it for a prompt](#2-ask-it-for-a-prompt).
3. [Draw the picture](#3-draw-the-picture).

Amina runs the Instagram page of Dar Lahlou, a pastry shop in Tlemcen. She types three words, *makrout for Ramadan*. A text model, set up by the preset, writes them out as a full picture prompt in the shop's style, and a picture model draws the poster. The style lives in one place, and every app that calls the preset draws in it.

## 1. Save the house style

A [preset](/docs/presets) keeps a request's settings under a name: here, the text model and a system prompt that holds the house style. The body is the one you would send to [Chat](/docs/reference/chat-completions), posted to [`POST /v1/presets/{slug}/chat/completions`](/docs/reference/presets) instead.

```json
{
  "model": "anthropic/claude-sonnet-4.5",
  "messages": [
    {
      "role": "system",
      "content": "You write picture prompts for Dar Lahlou, ..."
    }
  ],
  "temperature": 0.7,
  "max_tokens": 300
}
```

| The preset keeps | Here |
|---|---|
| `model` | the text model that writes the prompt |
| the first `system` message | the house style: the plate, the table, the light, the colours |
| `temperature` | room to vary the scene from one poster to the next |
| `max_tokens` | a ceiling on the prompt's length |

The slug here is `poster-writer`. Saving runs no model and costs nothing.

## 2. Ask it for a prompt

Name the preset as the model, `@preset/poster-writer`, and send the few words as the user's turn. The answer, in `choices[0].message.content`, is the full picture prompt. The sample saves the style, asks for a prompt, and writes it to `prompt.txt` for step 3.

```python
import json
import os
import urllib.request

key = os.environ["OPENDUNES_API_KEY"]
base_url = "https://opendunes.com/v1"
model = "anthropic/claude-sonnet-4.5"
preset = "poster-writer"

style = (
    "You write picture prompts for Dar Lahlou, a pastry shop in Tlemcen. "
    "Turn the request into one prompt of at most 80 words: the pastry, "
    "the plate, the table, the light, the colours. House style: seen from "
    "above, a green and gold zellige table, soft morning light, no text "
    "in the picture. Answer with the prompt alone."
)
words = "makrout for Ramadan"


def call(path, body):
    request = urllib.request.Request(
        base_url + path,
        data=json.dumps(body).encode(),
        headers={
            "Authorization": "Bearer " + key,
            "Content-Type": "application/json",
        },
    )
    with urllib.request.urlopen(request) as response:
        return json.load(response)


saved = call("/presets/" + preset + "/chat/completions", {
    "model": model,
    "messages": [{"role": "system", "content": style}],
    "temperature": 0.7,
    "max_tokens": 300,
})["data"]
print("version", saved["designated_version"]["version"])

answer = call("/chat/completions", {
    "model": f"@preset/{preset}",
    "messages": [{"role": "user", "content": words}],
})
prompt = answer["choices"][0]["message"]["content"]
with open("prompt.txt", "w") as out:
    out.write(prompt)
print(prompt)
print(answer["usage"]["cost"])
```

```javascript
import { writeFile } from "node:fs/promises";

const key = process.env.OPENDUNES_API_KEY;
const baseURL = "https://opendunes.com/v1";
const model = "anthropic/claude-sonnet-4.5";
const preset = "poster-writer";

const style =
  "You write picture prompts for Dar Lahlou, a pastry shop in Tlemcen. " +
  "Turn the request into one prompt of at most 80 words: the pastry, " +
  "the plate, the table, the light, the colours. House style: seen from " +
  "above, a green and gold zellige table, soft morning light, no text " +
  "in the picture. Answer with the prompt alone.";
const words = "makrout for Ramadan";

async function call(path, body) {
  const response = await fetch(baseURL + path, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${key}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(`${response.status} ${await response.text()}`);
  }
  return response.json();
}

const saved = await call(`/presets/${preset}/chat/completions`, {
  model,
  messages: [{ role: "system", content: style }],
  temperature: 0.7,
  max_tokens: 300,
});
console.log("version", saved.data.designated_version.version);

const answer = await call("/chat/completions", {
  model: `@preset/${preset}`,
  messages: [{ role: "user", content: words }],
});
const prompt = answer.choices[0].message.content;
await writeFile("prompt.txt", prompt);
console.log(prompt);
console.log(answer.usage.cost);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

var key = os.Getenv("OPENDUNES_API_KEY")

const (
	baseURL = "https://opendunes.com/v1"
	model   = "anthropic/claude-sonnet-4.5"
	preset  = "poster-writer"
)

const style = "You write picture prompts for Dar Lahlou, " +
	"a pastry shop in Tlemcen. Turn the request into one prompt " +
	"of at most 80 words: the pastry, the plate, the table, " +
	"the light, the colours. House style: seen from above, " +
	"a green and gold zellige table, soft morning light, " +
	"no text in the picture. Answer with the prompt alone."
const words = "makrout for Ramadan"

type message map[string]string

func call(path string, body any, out any) {
	encoded, err := json.Marshal(body)
	if err != nil {
		panic(err)
	}

	url := baseURL + path
	req, err := http.NewRequest("POST", url, bytes.NewReader(encoded))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+key)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	if res.StatusCode >= 300 {
		text, _ := io.ReadAll(res.Body)
		panic(fmt.Sprintf("%d %s", res.StatusCode, text))
	}
	if err := json.NewDecoder(res.Body).Decode(out); err != nil {
		panic(err)
	}
}

func main() {
	var saved struct {
		Data struct {
			DesignatedVersion struct {
				Version int `json:"version"`
			} `json:"designated_version"`
		} `json:"data"`
	}
	call("/presets/"+preset+"/chat/completions", map[string]any{
		"model":       model,
		"messages":    []message{{"role": "system", "content": style}},
		"temperature": 0.7,
		"max_tokens":  300,
	}, &saved)
	fmt.Println("version", saved.Data.DesignatedVersion.Version)

	var answer struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	call("/chat/completions", map[string]any{
		"model":    fmt.Sprintf("@preset/%s", preset),
		"messages": []message{{"role": "user", "content": words}},
	}, &answer)

	prompt := answer.Choices[0].Message.Content
	if err := os.WriteFile("prompt.txt", []byte(prompt), 0o644); err != nil {
		panic(err)
	}
	fmt.Println(prompt)
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
BASE_URL="https://opendunes.com/v1"
MODEL="anthropic/claude-sonnet-4.5"
PRESET="poster-writer"
PRESET_MODEL="@preset/$PRESET"

STYLE="You write picture prompts for Dar Lahlou, a pastry shop in Tlemcen."
STYLE="$STYLE Turn the request into one prompt of at most 80 words:"
STYLE="$STYLE the pastry, the plate, the table, the light, the colours."
STYLE="$STYLE House style: seen from above, a green and gold zellige table,"
STYLE="$STYLE soft morning light, no text in the picture."
STYLE="$STYLE Answer with the prompt alone."

curl "$BASE_URL/presets/$PRESET/chat/completions" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "system",
        "content": "'"$STYLE"'"
      }
    ],
    "temperature": 0.7,
    "max_tokens": 300
  }'

curl "$BASE_URL/chat/completions" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$PRESET_MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "makrout for Ramadan"
      }
    ]
  }' > answer.json

jq -r '.choices[0].message.content' answer.json | tee prompt.txt
jq '.usage.cost' answer.json
```

Run the save once. After it, any app sends `@preset/poster-writer` and the few words, and nothing else.

<div class="dont">
<p>Don't write the house style into each app that makes pictures. Every change of season then means a deploy of each one.</p>
</div>

<div class="do">
<p>Do keep the style in the preset, and the few words in the app. Save the preset again with the new style, and every app writes in it from its next request.</p>
</div>

## 3. Draw the picture

Send the prompt to [`/v1/images`](/docs/reference/images) with a picture model. The picture comes back in the answer, in base64: decode it and save the file, as the [Pictures](/docs/pictures) guide does. The sample reads `prompt.txt`, draws a 4:5 poster at 2K and writes it to `poster.png` or the type the model returned.

```python
import base64
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/images"
MODEL = "google/gemini-3.1-flash-image"
PROMPT_FILE = "prompt.txt"

with open(PROMPT_FILE) as source:
    prompt = source.read().strip()

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "model": MODEL,
            "prompt": prompt,
            "resolution": "2K",
            "aspect_ratio": "4:5",
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

picture = answer["data"][0]
extension = picture["media_type"].split("/")[1]
with open("poster." + extension, "wb") as out:
    out.write(base64.b64decode(picture["b64_json"]))
print(answer["usage"]["cost"])
```

```javascript
import { readFile, writeFile } from "node:fs/promises";

const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/images";
const MODEL = "google/gemini-3.1-flash-image";
const PROMPT_FILE = "prompt.txt";

const prompt = (await readFile(PROMPT_FILE, "utf8")).trim();

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    prompt,
    resolution: "2K",
    aspect_ratio: "4:5",
  }),
});
const answer = await response.json();

const picture = answer.data[0];
const extension = picture.media_type.split("/")[1];
const bytes = Buffer.from(picture.b64_json, "base64");
await writeFile(`poster.${extension}`, bytes);
console.log(answer.usage.cost);
```

```go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

const (
	address    = "https://opendunes.com/v1/images"
	model      = "google/gemini-3.1-flash-image"
	promptFile = "prompt.txt"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	text, err := os.ReadFile(promptFile)
	if err != nil {
		panic(err)
	}

	body, err := json.Marshal(map[string]any{
		"model":        model,
		"prompt":       strings.TrimSpace(string(text)),
		"resolution":   "2K",
		"aspect_ratio": "4:5",
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Data []struct {
			B64JSON   string `json:"b64_json"`
			MediaType string `json:"media_type"`
		} `json:"data"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}

	picture := answer.Data[0]
	raw, err := base64.StdEncoding.DecodeString(picture.B64JSON)
	if err != nil {
		panic(err)
	}
	extension := strings.TrimPrefix(picture.MediaType, "image/")
	if err := os.WriteFile("poster."+extension, raw, 0o644); err != nil {
		panic(err)
	}
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/images"
MODEL="google/gemini-3.1-flash-image"

jq -n --arg model "$MODEL" --rawfile prompt prompt.txt '{
  model: $model,
  prompt: $prompt,
  resolution: "2K",
  aspect_ratio: "4:5"
}' | curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- > picture.json

EXTENSION=$(jq -r '.data[0].media_type' picture.json | cut -d/ -f2)
jq -r '.data[0].b64_json' picture.json | base64 --decode > "poster.$EXTENSION"
jq '.usage.cost' picture.json
```

| You send | Holds |
|---|---|
| `model` | a picture model's ID, from its page in [Models](/docs/models) |
| `prompt` | the prompt the preset wrote |
| `resolution` | `2K`, one of the sizes this model offers |
| `aspect_ratio` | `4:5`, a portrait frame, one of the shapes this model offers |

<div class="good-to-know">
<p>The model's page lists the sizes and the shapes it makes. A model ignores a field it does not offer.</p>
</div>

## What it cost

Two charges, in DA, from your balance, each read in [`usage.cost`](/docs/balance-and-charges) of its own answer.

| Call | Charged on |
|---|---|
| saving the preset | nothing: it runs no model |
| asking it for a prompt | the text model's tokens, at the rates of the model the preset names |
| drawing the picture | the picture model's meter: each picture, or the tokens it reports, as its page in Models says |

A generation that fails, or answers with no picture, charges nothing. What to do on an error: [Errors and retries](/docs/errors-and-retries).
