# Apply patch

Let a model propose changes to your files as diffs, checked before they reach your code.

1. [What it does](#1-what-it-does).
2. [Name it in `tools`](#2-name-it-in-tools).
3. [Apply the patch and report back](#3-apply-the-patch-and-report-back).
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).

## 1. What it does

The model decides that a file must be created, changed or deleted, and writes a diff. OpenDunes checks the diff's syntax: a malformed diff goes back to the model to correct, before you see it. A valid diff reaches you, and your code applies it. Nothing is written to any file on OpenDunes' side.

| | |
|---|---|
| Type | `opendunes:apply_patch` |
| Route | `/v1/responses` |
| A step | one proposed diff |
| Steps | at most 30 a request |
| Bills on | tokens only |

The helper works on `/v1/responses` and nowhere else. On `/v1/chat/completions` and `/v1/messages`, a request that names it is refused with a `400` and nothing runs.

## 2. Name it in `tools`

Souk Bot renames a function in a shop's code. The sample sends the request, then prints the patch the model proposes and the charge. The patch is yours to apply.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/responses"
MODEL = "anthropic/claude-sonnet-4.5"
PROMPT = "Rename the function calcTotal to computeTotal in src/cart.js."

body = {
    "model": MODEL,
    "input": PROMPT,
    "tools": [{"type": "opendunes:apply_patch"}],
}
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)

for item in answer["output"]:
    if item["type"] == "apply_patch_call":
        print(item["call_id"])
        print(item["operation"])
print(answer["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/responses";
const MODEL = "anthropic/claude-sonnet-4.5";
const PROMPT = "Rename the function calcTotal to computeTotal in src/cart.js.";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    input: PROMPT,
    tools: [{ type: "opendunes:apply_patch" }],
  }),
});
const answer = await response.json();

for (const item of answer.output) {
  if (item.type === "apply_patch_call") {
    console.log(item.call_id);
    console.log(item.operation);
  }
}
console.log(answer.usage.cost);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/responses"
	model   = "anthropic/claude-sonnet-4.5"
	prompt  = "Rename the function calcTotal to computeTotal in src/cart.js."
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	body, err := json.Marshal(map[string]any{
		"model": model,
		"input": prompt,
		"tools": []map[string]string{
			{"type": "opendunes:apply_patch"},
		},
	})
	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 {
		Output []struct {
			Type      string          `json:"type"`
			CallID    string          `json:"call_id"`
			Operation json.RawMessage `json:"operation"`
		} `json:"output"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	for _, item := range answer.Output {
		if item.Type == "apply_patch_call" {
			fmt.Println(item.CallID)
			fmt.Println(string(item.Operation))
		}
	}
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/responses"
MODEL="anthropic/claude-sonnet-4.5"
PROMPT="Rename the function calcTotal to computeTotal in src/cart.js."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "input": "'"$PROMPT"'",
    "tools": [
      {
        "type": "opendunes:apply_patch"
      }
    ]
  }'
```

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

## 3. Apply the patch and report back

A valid diff arrives as an `apply_patch_call` item in `output`. Its `operation` is one of `create_file`, `update_file` or `delete_file`, and it carries the diff.

1. Your code reads each `apply_patch_call` item.
2. Your code applies the change to your files, or refuses it.
3. Your code sends the outcome back on the next turn as an `apply_patch_call_output` item in `input`.

```json
{
  "type": "apply_patch_call_output",
  "call_id": "call_abc123",
  "status": "completed",
  "output": "src/cart.js updated"
}
```

| Field | Holds |
|---|---|
| `call_id` | the `call_id` of the `apply_patch_call` it answers |
| `status` | `completed` or `failed` |
| `output` | optional: what happened, in words |

The model reads the outcome and goes on: another file, a correction after a `failed`, or its answer.

Put this in the helper's `parameters` to change how the diff is checked.

| Parameter | Does |
|---|---|
| `engine` | `auto`, the default, streams the diff as the model writes it where the model's provider does so and checks it whole otherwise; `native` asks for the streamed diff |

## 4. Read what it bills on

No charge beyond the model's tokens. The diff the model writes is output, and the file text it reads is input. `usage.cost` carries the whole of it.

Before the model starts, OpenDunes holds money from your wallet for the words and the answer. A proposed diff costs no money of its own, so the hold sets no step limit lower than yours: a request runs at most 30 steps, or the `max_tool_calls` you name. The helper runs no other model and no sandbox, so it has no spend cap.

<div class="dont">
<p>Don't apply a diff without reading its path. The model proposes, and your code decides what is written.</p>
</div>

<div class="do">
<p>Send back a <code>failed</code> outcome with a reason when you refuse a change, so the model corrects itself instead of repeating it.</p>
</div>
