> ## 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.

# Debugging Requests

> Inspect the transformed request body OpenRouter sends to the upstream provider

OpenRouter provides a `debug` option that allows you to inspect the exact request body that was sent to the upstream provider. This works with both the Chat Completions API (`/api/v1/chat/completions`) and the Responses API (`/api/v1/responses`). Useful for understanding how OpenRouter transforms your request parameters for different providers.

## Debug option shape

The debug option is an object with the following shape:

```typescript lines theme={null}
type DebugOptions = {
  echo_upstream_body?: boolean; // If true, returns the transformed request body sent to the provider
};
```

## Usage

To enable debug output, include the `debug` parameter in your request:

### Chat Completions

```typescript title="TypeScript" expandable lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'anthropic/claude-haiku-5.5',
    stream: true, // Debug only works with streaming
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'Hello!' },
    ],
    debug: {
      echo_upstream_body: true,
    },
  }),
});

const text = await response.text();

for (const line of text.split('\n')) {
  if (!line.startsWith('data: ')) continue;

  const data = line.slice(6);
  if (data === '[DONE]') break;

  const parsed = JSON.parse(data);

  if (parsed.debug?.echo_upstream_body) {
    console.log('\nDebug:', JSON.stringify(parsed.debug.echo_upstream_body, null, 2));
  }

  process.stdout.write(parsed.choices?.[0]?.delta?.content ?? '');
}
```

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

response = requests.post(
  url="https://openrouter.ai/api/v1/chat/completions",
  headers={
    "Authorization": "Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  data=json.dumps({
    "model": "anthropic/claude-haiku-5.5",
    "stream": True,
    "messages": [
      { "role": "system", "content": "You are a helpful assistant." },
      { "role": "user", "content": "Hello!" }
    ],
    "debug": {
      "echo_upstream_body": True
    }
  }),
  stream=True
)

for line in response.iter_lines():
  if line:
    text = line.decode('utf-8')
    if 'echo_upstream_body' in text:
      print(text)
```

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

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

type chunk struct {
	Error json.RawMessage `json:"error"`
	Debug struct {
		EchoUpstreamBody json.RawMessage `json:"echo_upstream_body"`
	} `json:"debug"`
	Choices []struct {
		Delta struct {
			Content string `json:"content"`
		} `json:"delta"`
	} `json:"choices"`
}

func main() {
	body := []byte(`{
		"model": "anthropic/claude-haiku-5.5",
		"stream": true,
		"messages": [
			{"role": "system", "content": "You are a helpful assistant."},
			{"role": "user", "content": "Hello!"}
		],
		"debug": {"echo_upstream_body": true}
	}`) // Debug only works with streaming
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	text, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	// A rejected request returns plain JSON, not an event stream
	if res.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("%s: %s", res.Status, text))
	}

	for _, line := range strings.Split(string(text), "\n") {
		if !strings.HasPrefix(line, "data: ") {
			continue
		}

		data := strings.TrimSpace(line[6:])
		if data == "[DONE]" {
			break
		}

		var parsed chunk
		if err := json.Unmarshal([]byte(data), &parsed); err != nil {
			panic(err)
		}

		// A failure after the stream starts arrives as a chunk with an error field
		if len(parsed.Error) > 0 && string(parsed.Error) != "null" {
			panic(fmt.Sprintf("stream error: %s", parsed.Error))
		}

		if raw := parsed.Debug.EchoUpstreamBody; len(raw) > 0 && string(raw) != "null" {
			var out bytes.Buffer
			json.Indent(&out, raw, "", "  ")
			fmt.Println("\nDebug:", out.String())
		}

		if len(parsed.Choices) > 0 {
			fmt.Print(parsed.Choices[0].Delta.Content)
		}
	}
}

```

```bash title="cURL" lines theme={null}
while IFS= read -r line; do
  [[ $line == "data: "* ]] || continue
  data=${line#data: }
  [[ $data == "[DONE]" ]] && break

  if jq -e '.debug.echo_upstream_body' <<< "$data" > /dev/null; then
    printf '\nDebug: '
    jq '.debug.echo_upstream_body' <<< "$data"
  fi

  jq -j '.choices[0].delta.content // ""' <<< "$data"
done < <(curl -sN https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-haiku-5.5",
    "stream": true,
    "messages": [
      { "role": "system", "content": "You are a helpful assistant." },
      { "role": "user", "content": "Hello!" }
    ],
    "debug": { "echo_upstream_body": true }
  }') # Debug only works with streaming
echo
```

```bash title="cURL" lines theme={null}
curl -sN https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-haiku-5.5",
    "stream": true,
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
    ],
    "debug": {"echo_upstream_body": true}
  }' |
  sed -n '/^data: \[DONE\]/q; s/^data: //p' |
  jq -j '
    (if .debug.echo_upstream_body then "\nDebug: ", .debug.echo_upstream_body, "\n" else empty end),
    (.choices[0].delta.content // "")'
echo
```

```text title="Output" theme={null}

Debug: {
  "system": [
    {
      "type": "text",
      "text": "You are a helpful assistant."
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "model": "claude-haiku-5-5",
  "stream": true,
  "metadata": {
    "user_id": "<redacted>"
  },
  "max_tokens": 65536,
  "stop_sequences": []
}
Hello! How can I help you today?
```

### Responses API

```typescript title="TypeScript" expandable 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: 'anthropic/claude-haiku-5.5',
    stream: true,
    input: 'Hello!',
    debug: {
      echo_upstream_body: true,
    },
  }),
});

const text = await response.text();

for (const line of text.split('\n')) {
  if (!line.startsWith('data: ')) continue;

  const data = line.slice(6);
  if (data === '[DONE]') break;

  const parsed = JSON.parse(data);

  if (parsed.type === 'response.debug') {
    console.log('\nDebug:', JSON.stringify(parsed.debug, null, 2));
  }
}
```

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

response = requests.post(
  url="https://openrouter.ai/api/v1/responses",
  headers={
    "Authorization": "Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  data=json.dumps({
    "model": "anthropic/claude-haiku-5.5",
    "stream": True,
    "input": "Hello!",
    "debug": {
      "echo_upstream_body": True
    }
  }),
  stream=True
)

for line in response.iter_lines():
  if line:
    text = line.decode('utf-8')
    if 'response.debug' in text:
      print(text)
```

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

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

type event struct {
	Type  string          `json:"type"`
	Debug json.RawMessage `json:"debug"`
}

func main() {
	body := []byte(`{
		"model": "anthropic/claude-haiku-5.5",
		"stream": true,
		"input": "Hello!",
		"debug": {"echo_upstream_body": true}
	}`)
	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")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	text, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	// A rejected request returns plain JSON, not an event stream
	if res.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("%s: %s", res.Status, text))
	}

	for _, line := range strings.Split(string(text), "\n") {
		if !strings.HasPrefix(line, "data: ") {
			continue
		}

		data := strings.TrimSpace(line[6:])
		if data == "[DONE]" {
			break
		}

		var parsed event
		if err := json.Unmarshal([]byte(data), &parsed); err != nil {
			panic(err)
		}

		// A failure after the stream starts arrives as an error or response.failed event
		if parsed.Type == "error" || parsed.Type == "response.failed" {
			panic(fmt.Sprintf("stream error: %s", data))
		}

		if parsed.Type == "response.debug" {
			var out bytes.Buffer
			json.Indent(&out, parsed.Debug, "", "  ")
			fmt.Println("\nDebug:", out.String())
		}
	}
}

```

```bash title="cURL" lines theme={null}
while IFS= read -r line; do
  [[ $line == "data: "* ]] || continue
  data=${line#data: }
  [[ $data == "[DONE]" ]] && break

  if jq -e '.type == "response.debug"' <<< "$data" > /dev/null; then
    printf '\nDebug: '
    jq '.debug' <<< "$data"
  fi
done < <(curl -sN https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-haiku-5.5",
    "stream": true,
    "input": "Hello!",
    "debug": { "echo_upstream_body": true }
  }')

```

```bash title="cURL" lines theme={null}
curl -sN https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-haiku-5.5",
    "stream": true,
    "input": "Hello!",
    "debug": {"echo_upstream_body": true}
  }' |
  sed -n '/^data: \[DONE\]/q; s/^data: //p' |
  jq -j 'select(.type == "response.debug") | "\nDebug: ", .debug, "\n"'

```

```text title="Output" theme={null}

Debug: {
  "echo_upstream_body": {
    "messages": [
      {
        "role": "user",
        "content": "Hello!"
      }
    ],
    "model": "claude-haiku-5-5",
    "stream": true,
    "metadata": {
      "user_id": "<redacted>"
    },
    "max_tokens": 65536,
    "stop_sequences": []
  }
}
```

## Debug response format

### Chat Completions

When `debug.echo_upstream_body` is set to `true`, OpenRouter sends a debug chunk as the **first chunk** in the streaming response. This chunk has an empty `choices` array and includes a `debug` field with the transformed request body:

```json expandable lines theme={null}
{
  "id": "gen-xxxxx",
  "provider": "Anthropic",
  "model": "anthropic/claude-haiku-5.5",
  "object": "chat.completion.chunk",
  "created": 1234567890,
  "choices": [],
  "debug": {
    "echo_upstream_body": {
      "system": [
        { "type": "text", "text": "You are a helpful assistant." }
      ],
      "messages": [
        { "role": "user", "content": "Hello!" }
      ],
      "model": "claude-haiku-5-5",
      "stream": true,
      "max_tokens": 65536
    }
  }
}
```

### Responses API

On the Responses API, debug data arrives as a `response.debug` SSE event:

```json lines theme={null}
{
  "type": "response.debug",
  "debug": {
    "echo_upstream_body": {
      "model": "claude-haiku-5-5",
      "messages": [
        { "role": "user", "content": "Hello!" }
      ],
      "stream": true,
      "max_tokens": 65536
    }
  },
  "sequence_number": 0
}
```

## Important notes

> [!WARNING]
>
> **Streaming Only**
>
> The debug option **only works with streaming mode** (`stream: true`). Non-streaming requests will ignore the debug parameter.

> [!WARNING]
>
> **Not for Production**
>
> The debug flag should **not be used in production environments**. It is intended for development and debugging purposes only, as it may potentially return sensitive information included in the request that was not intended to be visible elsewhere.

## Use cases

The debug output is particularly useful for:

1. **Understanding Parameter Transformations**: See how OpenRouter maps your parameters to provider-specific formats (e.g., how `max_tokens` is set, how `temperature` is handled).

2. **Verifying Message Formatting**: Check how OpenRouter combines and formats your messages for different providers (e.g., how system messages are concatenated, how user messages are merged).

3. **Checking Applied Defaults**: See what default values OpenRouter applies when parameters are not specified in your request.

4. **Debugging Provider Fallbacks**: When using provider fallbacks, a debug chunk will be sent for **each attempted provider**, allowing you to see which providers were tried and what parameters were sent to each.

## Privacy and redaction

OpenRouter will make a best effort to automatically redact potentially sensitive or noisy data from debug output. Remember that the debug option is not intended for production.

For error response shapes and codes, see [Errors and Debugging](https://openrouter.ai/docs/api_reference/errors-and-debugging.md).
