# Image generation

Let any text model draw a picture in the middle of its answer, and pay on the picture model's meter.

1. [What it does](#1-what-it-does).
2. [Name it in `tools`](#2-name-it-in-tools).
3. [Choose the picture](#3-choose-the-picture).
4. [Read what it bills on](#4-read-what-it-bills-on).

This page is one helper. The list of helpers, and how the charge adds up, sit in [Helpers](/docs/helpers). To draw a picture without a text model in between, call [Picture generation](/docs/reference/images) directly.

## 1. What it does

When the model decides a picture is needed, it writes a prompt. A picture model draws it, and the picture's address goes back to the model, which places it in its answer.

| | |
|---|---|
| Type | `opendunes:image_generation` |
| Routes | `/v1/chat/completions`, `/v1/responses` and `/v1/messages` |
| A step | one picture |
| Steps | at most 30 a request |
| Bills on | the picture model's meter, in DA, beside the text model's tokens |

## 2. Name it in `tools`

Souk Bot draws a logo for a couscous restaurant in Oran. The sample asks for a square picture in the helper's `parameters`, allows two pictures, and prints the answer and the charge.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/chat/completions"
MODEL = "anthropic/claude-sonnet-4.5"
PROMPT = "Draw a logo for a couscous restaurant in Oran."

body = {
    "model": MODEL,
    "messages": [{"role": "user", "content": PROMPT}],
    "tools": [
        {
            "type": "opendunes:image_generation",
            "parameters": {"aspect_ratio": "1:1"},
        }
    ],
    "max_tool_calls": 2,
}
request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(body).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

print(answer["choices"][0]["message"]["content"])
print(answer["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/chat/completions";
const MODEL = "anthropic/claude-sonnet-4.5";
const PROMPT = "Draw a logo for a couscous restaurant in Oran.";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    messages: [{ role: "user", content: PROMPT }],
    tools: [
      {
        type: "opendunes:image_generation",
        parameters: { aspect_ratio: "1:1" },
      },
    ],
    max_tool_calls: 2,
  }),
});
const answer = await response.json();

console.log(answer.choices[0].message.content);
console.log(answer.usage.cost);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/chat/completions"
	model   = "anthropic/claude-sonnet-4.5"
	prompt  = "Draw a logo for a couscous restaurant in Oran."
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	body, err := json.Marshal(map[string]any{
		"model": model,
		"messages": []map[string]string{
			{"role": "user", "content": prompt},
		},
		"tools": []map[string]any{
			{
				"type": "opendunes:image_generation",
				"parameters": map[string]string{
					"aspect_ratio": "1:1",
				},
			},
		},
		"max_tool_calls": 2,
	})
	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 {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.Choices[0].Message.Content)
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
PROMPT="Draw a logo for a couscous restaurant in Oran."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      }
    ],
    "tools": [
      {
        "type": "opendunes:image_generation",
        "parameters": {
          "aspect_ratio": "1:1"
        }
      }
    ],
    "max_tool_calls": 2
  }'
```

The answer is a `200`. Name the helper by its type, `opendunes:image_generation`; any other spelling of the type is a `400`.

## 3. Choose the picture

Put these in the helper's `parameters`. Every one but `model` goes to the picture model as you send it, and which ones it honours depends on the model.

| Parameter | Does |
|---|---|
| `model` | the picture model: any one on `GET /v1/images/models` |
| `size` · `aspect_ratio` | the picture's dimensions, such as `1024x1024`, or its shape, such as `16:9` |
| `quality` | such as `low`, `medium` or `high` |
| `background` | such as `transparent` |
| `output_format` · `output_compression` | `png`, `jpeg` or `webp`, and a compression from 0 to 100 |
| `moderation` | such as `auto` or `low` |

A request that leaves `model` out gets the helper's default picture model. To name another, add `"model": "<lab>/<model>"` to `parameters`.

## 4. Read what it bills on

One charge, in DA, from your balance, the moment the answer ends: the text model's tokens and each picture, on the picture model's own meter. The picture model's page in [Models](/models) gives that meter. `usage.cost` carries the whole of it.

The helper runs another model, so it has a spend cap. Before the model starts, OpenDunes holds money from your wallet for the words and the answer, and writes the cap into the request.

| Your request | The hold |
|---|---|
| names no `stop_server_tools_when` | writes two conditions: the step count, 30 or your `max_tool_calls`, and a `max_cost` equal to half of what the wallet has left after the answer's hold; the helper stops at whichever comes first |
| names `stop_server_tools_when` with a `max_cost` | holds that cap whole; when the wallet cannot pay it, the answer is a `402` that says what the request needs |
| names `stop_server_tools_when` without a `max_cost` | keeps your conditions and adds the cap |

A cap is a condition on the request:

```json
{
  "stop_server_tools_when": [
    { "type": "step_count_is", "step_count": 2 },
    { "type": "max_cost", "max_cost_in_dollars": 0.2 }
  ]
}
```

When the steps or the cap run out, the model answers with what it has gathered.

<div class="dont">
<p>Don't give the helper to a model that has no use for a picture. It decides how often to draw, and every picture is charged.</p>
</div>

<div class="do">
<p>Set <code>max_tool_calls</code> to the number of pictures you want, and pick a picture model whose meter you have read.</p>
</div>
