> ## Documentation Index
> Fetch the complete documentation index at: https://openrouter.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Apply Patch

> Let models propose file changes via V4A diffs

Beta

> [!NOTE]
>
> **Beta**
>
> Server tools are currently in beta. The API and behavior may change.

> [!WARNING]
>
> **Responses API only**
>
> The apply patch server tool is only available through the [Responses API](https://openrouter.ai/docs/api_reference/responses/overview.md). It is not supported via the Chat Completions API.

> [!NOTE]
>
> **Streaming behavior**
>
> Only OpenAI models stream apply patch results incrementally via `response.apply_patch_call_operation_diff.delta` events. All other models return the complete patch as a single tool output.

The `openrouter:apply_patch` server tool enables models to propose file changes using [V4A diff](https://github.com/openai/codex/blob/main/codex-rs/core/src/patch/v4a.md) patches. This is the building block for coding agents: the model generates a patch describing file creates, updates, or deletes, OpenRouter validates the diff syntax, and your application applies it.

## How It Works

1. You include `{ "type": "openrouter:apply_patch" }` in your `tools` array when calling the Responses API.
2. Based on the conversation, the model decides a file needs to be created, updated, or deleted, and generates a V4A diff patch.
3. OpenRouter validates the patch syntax (correct line prefixes, valid markers, non-empty paths).
4. If validation passes, the tool call is returned to your application as an `apply_patch_call` output item. Your application applies the patch to the filesystem and echoes the result back as `apply_patch_call_output` on the next turn.
5. If validation fails, the error is returned to the model so it can self-correct.

This is a **human-in-the-loop** tool: OpenRouter validates the diff but never applies it. Your application is responsible for executing the file operation.

## Quick Start

```typescript title="TypeScript" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/responses', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-5.1-codex-mini',
    input: 'Create a hello.py file that prints "Hello, world!"',
    tools: [
      { type: 'openrouter:apply_patch' }
    ]
  }),
});

const data = await response.json();
// The response contains an apply_patch_call output item
// with the operation (create_file, update_file, or delete_file)
console.log(data.output);
```

```python title="Python" expandable lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/responses",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  json={
    "model": "openai/gpt-5.1-codex-mini",
    "input": "Create a hello.py file that prints 'Hello, world!'",
    "tools": [
      {"type": "openrouter:apply_patch"}
    ]
  }
)

data = response.json()
# The response contains an apply_patch_call output item
# with the operation (create_file, update_file, or delete_file)
print(data["output"])
```

```bash title="cURL" lines theme={null}
curl https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer <OPENROUTER_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.1-codex-mini",
    "input": "Create a hello.py file that prints \"Hello, world!\"",
    "tools": [
      {"type": "openrouter:apply_patch"}
    ]
  }'
```

```go title="Go" lines theme={null}
package main

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5.1-codex-mini",
		"input": `Create a hello.py file that prints "Hello, world!"`,
		"tools": []map[string]any{
			{"type": "openrouter:apply_patch"},
		},
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

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

	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	if resp.StatusCode != http.StatusOK {
		fmt.Fprintf(os.Stderr, "HTTP %d: %s\n", resp.StatusCode, raw)
		os.Exit(1)
	}

	var data struct {
		Output []map[string]any `json:"output"`
	}
	if err := json.Unmarshal(raw, &data); err != nil {
		panic(err)
	}

	// The output array holds a reasoning item followed by an apply_patch_call
	// item with the operation (create_file, update_file, or delete_file)
	for _, item := range data.Output {
		fmt.Println("output item:", item["type"])
		if item["type"] == "apply_patch_call" {
			op, _ := json.MarshalIndent(item["operation"], "  ", "  ")
			fmt.Println("  status:", item["status"])
			fmt.Println("  operation:", string(op))
		}
	}
}

```

```text title="Output" theme={null}
[
  {
    id: "rs_00c59aa78e15de06016afcc3208a94819584d7aeba43619a9c",
    type: "reasoning",
    status: "completed",
    summary: [],
    encrypted_content: "gAAAAABq_MMg8M-Lx7jGvjE9IpsbaoxNPWl3m_oJ59_RUlwIkE0N3tgh62y0HaQmb6IFhEdp1Q4iusnGWPgqEc8pmJdMuiV0G-qkSW5ftiw2pcCDx9lRQD2lLSmW3VCSdfojAXf9CBkxA7ohGNYP1V0rUrw8Xdb8nGTscYgkJoag30pMz0bnW0TAaSUxzaRpvU6DL0cWh1fmHZyPtH5ho9Ri69fm4xMxTXg4pwnMo3rAg_0VHQ1ZRC7cg8QF45GNV0rXgO17gFYDrL1HABbE2n1BFV-QOxGfTmYS_LhquugYR0INbzDud-Kz5ioc12UtEkJB_ASeV6JekwbUb1nLWPfjIRRK88RQYizPKvcB6EBiVzBLeT2c9RRD79k_as14nXro0GIske16tTIBn7QyhFE0bVyn1088bnPsyMy_RVAKxmQOWTF2USlDrFgXhD5KCUiM_MwWIEa7gsyh0c_HzjWIYBm-ugQwe0pCno9w4sqHDxCpRbWzuox1Ty6qCMhHwJW8BHSQKfVrLKuRQz1Muf_zwbmErXGcb-5n1--fGhS1F7JgeV5lQdGz-hYKVXgHMaPjHOHQiUsz1JN6mmO03dPKvckjiW6995T9fVOEMKvb92Ve9JK1KoSd639zXbJBnmPuB7pNKivlsVTcZaaC83ic743riq001HDM0Ut-LU44qEZG4aBOp3tuLbBQz48NF_FWzkTD-1yjnNNPM8Pb6Q5-jUD9DPXkSzkugwQ8NTZESYoxQkC9Kvbe393raKbor-UFpQneqekDUYKcry2it6_X0l6W6A8v-FldC2OWEd0Aa3pPzCrg5ZaR4Z4htFacff4dREToJQEubZP_WEjpg8RVN19B2jxZ8YvP9ewaYoWqBkMnoCJw28tz9dyldIgFnri9nNRgQaeP6RgRRZaHtK_lhm7jOIQAjxMGvglQ9coFXbGoSs6ifVVkug4uNfB2K-mYYBvu2fqtqGsAewFIgGhdXVQ_7v1IDbc8gRFlXAOifulXKbzHE1Dqr5GoqlY-CXWHujPiHyDeRiqC2h622sUFEioRfsIXgSdh99QnEIcey2x3C-fxLEGwbTEnPKW6tk3OR_HxScjVZGn0haS2lr7mMnAfH9uRGkTt-4TG98cjr0_2cVv9w22v37ArxQdYi_8U70lyrqBSvrdo4DwJksDtsck8erZxsspKEyAUo-4cUOasmH4Z5GyfJEekBX3kVyK_9objXdV9D7OInDE3A7nPrZ6mqOUxLVS8nHPEgYYxNVDMxUJ4BTVFsYwcgd4R16bonSNNM0UI-rZiE2cw0VonCpMRauL7MQgSNmCQc5tYe1LwOG6xf7AYHnfqQb7ngPKIymXEKel76A8Kqh-5JTCQsf0WX7e22X78rEUnBn-LF9PH9YWiRlSSEinIigGgEmReGEleMCPGha4oLCHsdKY-5EApNbRBnFg174pP9fzXTvsA8SeTiw-vo0A25jvRbA4lsHHWG59Fa2fqUAai5DDYWtRi00sj-4NB8Tze33Fy7-bB5JZXtR4FMKRaqsnr_FDiOK9xrPORZqRoixwK1bm2k_UVqpUNIIKrHvVSRV9HqZHrcYB_jrRJuWIAoCAV5UaBTvaJXTlu.eyJlbmRwb2ludF9zbHVnIjoib3BlbmFpL2dwdC01LjEtY29kZXgtbWluaS0yMDI1MTExM3xhenVyZSJ9",
    format: "azure-openai-responses-v1",
  }, {
    type: "apply_patch_call",
    id: "apc_00c59aa78e15de06016afcc320ff4881958804a1ff64faa521",
    status: "completed",
    call_id: "call_bpS3Qpib85gpPKZjOBCMAF2t",
    operation: {
      type: "create_file",
      path: "hello.py",
      diff: "+def main():\n+    print(\"Hello, world!\")\n+\n+\n+if __name__ == \"__main__\":\n+    main()\n",
    },
  }
]
```

## Patch Operations

The tool supports three operation types, each carried as the `operation` field on the `apply_patch_call` output item:

### `create_file`

Creates a new file. Every content line in the diff must start with `+`:

```json lines theme={null}
{
  "type": "apply_patch_call",
  "call_id": "call_abc123",
  "status": "completed",
  "operation": {
    "type": "create_file",
    "path": "/src/hello.py",
    "diff": "+print(\"Hello, world!\")\n"
  }
}
```

### `update_file`

Updates an existing file using a V4A diff with context lines (` ` prefix), additions (`+`), and deletions (`-`):

```json lines theme={null}
{
  "type": "apply_patch_call",
  "call_id": "call_def456",
  "status": "completed",
  "operation": {
    "type": "update_file",
    "path": "/src/main.ts",
    "diff": "@@ function main() {\n-  console.log(\"old\");\n+  console.log(\"new\");\n }"
  }
}
```

### `delete_file`

Deletes a file. No diff is needed, only the file path:

```json lines theme={null}
{
  "type": "apply_patch_call",
  "call_id": "call_ghi789",
  "status": "completed",
  "operation": {
    "type": "delete_file",
    "path": "/src/deprecated.ts"
  }
}
```

## Echoing Results

After your application applies (or rejects) the patch, send the result back on the next turn as an `apply_patch_call_output` input item:

```json lines theme={null}
{
  "model": "openai/gpt-5.1-codex-mini",
  "input": [
    {
      "type": "apply_patch_call_output",
      "call_id": "call_abc123",
      "status": "completed",
      "output": "Applied patch to /src/hello.py"
    }
  ],
  "tools": [
    { "type": "openrouter:apply_patch" }
  ]
}
```

| Field | Type | Description |
| - | - | - |
| `call_id` | string | Must match the `call_id` from the `apply_patch_call` |
| `status` | `"completed"` or `"failed"` | Whether the patch was applied successfully |
| `output` | string (optional) | Human-readable log of what happened |

## Configuration

The apply patch tool accepts an optional `engine` parameter:

```json lines theme={null}
{
  "type": "openrouter:apply_patch",
  "parameters": {
    "engine": "auto"
  }
}
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `engine` | string | `auto` | `auto`: uses native passthrough when the endpoint supports incremental diff streaming, otherwise falls back to OpenRouter's HITL validator. `native`: forces native passthrough (falls back to HITL if unsupported). `openrouter`: always uses the HITL validator, even on endpoints with native support. |

### Engine behavior

To check whether an endpoint runs apply\_patch natively, read `native_tools` on the endpoint object. See [Native Execution](https://openrouter.ai/docs/guides/features/server-tools.md#native-execution).

* **Native passthrough** streams the diff incrementally via `response.apply_patch_call_operation_diff.delta` events, matching OpenAI's streaming format. Currently supported on OpenAI endpoints.
* **HITL (human-in-the-loop)** buffers the complete diff and delivers it as a single atomic `apply_patch_call` output item.

## Pricing

The apply patch tool has no additional cost beyond standard token usage.

## Next Steps

* [Server Tools Overview](https://openrouter.ai/docs/guides/features/server-tools.md). Learn about server tools
* [Web Search](https://openrouter.ai/docs/guides/features/server-tools/web-search.md). Search the web for real-time information
* [Datetime](https://openrouter.ai/docs/guides/features/server-tools/datetime.md). Get the current date and time
* [Tool Calling](https://openrouter.ai/docs/guides/features/tool-calling.md). Learn about user-defined tool calling
