> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://poly-ai.ferndocs.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://poly-ai.ferndocs.com/_mcp/server.

# Create a new debug chat session

POST https://api.us.poly.ai/v1/agents/{agentId}/debug-chat
Content-Type: application/json

Reference: https://poly-ai.ferndocs.com/api-reference/api-reference/data/debug-chat/start

## Authentication

- `X-API-KEY` header (required) — PolyAI API key. Send it in the X-API-KEY header.

## Servers

- `https://api.us.poly.ai` (ProductionUS, default)
- `https://api.eu.poly.ai` (ProductionEU)
- `https://api.uk.poly.ai` (ProductionUK)
- `https://api.studio.poly.ai` (Studio)

## Request

### Path parameters

- `agentId` (string, required)

### Body (application/json)

This endpoint expects a CreateDebugChatBody.

- `clientEnv` (enum, required) — Client environment (sandbox, pre-release, live).
  - Allowed values: `sandbox`, `pre-release`, `live`
- `asrLangCode` (string, optional) — ASR language code (e.g. en-US). Defaults to server config.
- `ttsLangCode` (string, optional) — TTS language code (e.g. en-US). Defaults to server config.
- `conversationId` (string, optional) — Custom conversation ID. Auto-generated if omitted.
- `variantId` (string, optional) — Variant ID to use
- `channel` (string, optional) — Channel type (e.g. chat.polyai)
- `integrationAttributes` (map from string to any, optional) — Custom attributes accessible via conv.integration_attributes in project functions.

## Response

### 201

Successful response

- `conversationId` (string, required)
- `userInput` (string, required)
- `response` (string, required)
- `metadata` (ChatMetadataResponse, required) — Metadata returned with each chat response.
- `conversationEnded` (boolean, required)
- `delayedResponse` (boolean, required)

## Errors

### 400 Bad Request Error

Validation error

- `any`

### 401 Unauthorized Error

Unauthorized – missing or invalid API key

- `any`

### 403 Forbidden Error

Forbidden – insufficient permissions

- `any`

## Types

### ChatMetadataResponse

Metadata returned with each chat response.

- `state` (map from string to any, required) — Dialogue state key/value pairs recorded during the conversation.
- `currentNode` (string, required) — Identifier of the dialogue node the conversation is currently in.
- `nodeTrace` (list of string, required) — Ordered list of dialogue node identifiers traversed to produce this response.
- `metrics` (map from string to DataMetricValue, required) — Custom metrics recorded during the conversation, keyed by metric name.
- `functionEvents` (list of map from string to any, required) — Function-call events emitted while producing this response.
- `handoffDestination` (string, optional) — Destination the conversation was handed off to, if any.
- `retrievedTopics` (list of string, optional) — Knowledge-base topics retrieved while producing this response.
- `retrievedSources` (list of string, optional) — Knowledge-base sources retrieved while producing this response.
- `citedTopic` (string, optional) — Topic cited in the agent response, if any.
- `inFlow` (string, optional) — Identifier of the flow the conversation is currently in.
- `inStep` (string, optional) — Identifier of the step within the flow the conversation is currently in.
- `llmRequests` (list of map from string to any, optional) — LLM requests made while producing this response.
- `asrLangCode` (string, optional) — ASR (speech recognition) language code (e.g. en-US).
- `ttsLangCode` (string, optional) — TTS (speech synthesis) language code (e.g. en-US).

### DataMetricValue

A recorded metric value: a single string or a list of strings when the metric was written more than once.

- string
- list of string

## Examples

**Request**

```json
{
  "clientEnv": "sandbox"
}
```

**Response**

```json
{
  "conversationId": "conv_9f8b7c6d5e4a3b2c1d0e",
  "userInput": "Hello, can you help me with my account?",
  "response": "Of course! What issue are you experiencing with your account?",
  "metadata": {
    "state": {},
    "currentNode": "greeting_node",
    "nodeTrace": [
      "start_node",
      "greeting_node"
    ],
    "metrics": {},
    "functionEvents": [
      null
    ],
    "handoffDestination": "human_agent",
    "retrievedTopics": [
      "account_management"
    ],
    "retrievedSources": [
      "faq_account_issues"
    ],
    "citedTopic": "account_management",
    "inFlow": "account_help_flow",
    "inStep": "initial_greeting",
    "llmRequests": [
      {}
    ],
    "asrLangCode": "en-US",
    "ttsLangCode": "en-US"
  },
  "conversationEnded": false,
  "delayedResponse": false
}
```

**SDK Code**

```python
import requests

url = "https://api.us.poly.ai/v1/agents/agentId/debug-chat"

payload = { "clientEnv": "sandbox" }
headers = {
    "X-API-KEY": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.us.poly.ai/v1/agents/agentId/debug-chat';
const options = {
  method: 'POST',
  headers: {'X-API-KEY': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"clientEnv":"sandbox"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.us.poly.ai/v1/agents/agentId/debug-chat"

	payload := strings.NewReader("{\n  \"clientEnv\": \"sandbox\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-API-KEY", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.us.poly.ai/v1/agents/agentId/debug-chat")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-API-KEY"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"clientEnv\": \"sandbox\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.us.poly.ai/v1/agents/agentId/debug-chat")
  .header("X-API-KEY", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"clientEnv\": \"sandbox\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.us.poly.ai/v1/agents/agentId/debug-chat', [
  'body' => '{
  "clientEnv": "sandbox"
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-API-KEY' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.us.poly.ai/v1/agents/agentId/debug-chat");
var request = new RestRequest(Method.POST);
request.AddHeader("X-API-KEY", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"clientEnv\": \"sandbox\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-API-KEY": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = ["clientEnv": "sandbox"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.us.poly.ai/v1/agents/agentId/debug-chat")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```