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

# Cancel Async Chat Stream

POST /v1/messages/async/{message_id}/cancel
Content-Type: application/json

Cancel an active asynchronous chat stream.

This endpoint gracefully cancels an ongoing chat completion stream by:
1. Setting the cancellation token to stop the event generation loop
2. Cancelling the underlying asyncio task
3. Updating the stream status to 'cancelled'

Notes:
* Cancellation is irreversible - stream cannot be resumed
* Any active SSE connections will receive a final event and close
* Stream status will be updated to reflect cancellation
* Use DELETE endpoint to remove cancelled streams from storage

Reference: https://docs.privategpt.dev/api-reference/async-messages/cancel-stream-v-1-messages-async-message-id-cancel-post

## Request

### Path parameters

- `message_id` (string, required) — Message ID of the asynchronous chat stream to cancel.

## Response

### 200

Stream cancelled successfully

- `message` (string, required) — Confirmation message for successful stream cancellation
- `message_id` (string, required) — Unique identifier of the cancelled stream

## Errors

### 401 Unauthorized Error

Unauthorized

- `any`

### 404 Not Found Error

Stream not found

- `detail` (OpenApiValidationErrorResponseDetail, required) — Error detail — a string message or a list of validation error objects.

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional) — detail field.

## Types

### OpenApiValidationErrorResponseDetail

Error detail — a string message or a list of validation error objects.

### ValidationError

ValidationError schema.

- `loc` (list of ValidationErrorLocItems, required) — loc field.
- `msg` (string, required) — msg field.
- `type` (string, required) — type field.
- `input` (any, optional) — input field.
- `ctx` (ValidationErrorCtx, optional) — ctx field.

### ValidationErrorLocItems

### ValidationErrorCtx

ctx field.

## Examples

### Stream cancelled successfully

**Request**

```json
{}
```

**Response**

```json
{
  "message": "Stream cancelled successfully",
  "message_id": "msg_async_12345"
}
```

**SDK Code**

```python Stream cancelled successfully
import requests

url = "https://api.example.com/v1/messages/async/message_id/cancel"

payload = {}
headers = {"Content-Type": "application/json"}

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

print(response.json())
```

```javascript Stream cancelled successfully
const url = 'https://api.example.com/v1/messages/async/message_id/cancel';
const options = {method: 'POST', headers: {'Content-Type': 'application/json'}, body: '{}'};

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

```go Stream cancelled successfully
package main

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

func main() {

	url := "https://api.example.com/v1/messages/async/message_id/cancel"

	payload := strings.NewReader("{}")

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

	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 Stream cancelled successfully
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/messages/async/message_id/cancel")

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

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{}"

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

```java Stream cancelled successfully
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/messages/async/message_id/cancel")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/messages/async/message_id/cancel', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Stream cancelled successfully
using RestSharp;

var client = new RestClient("https://api.example.com/v1/messages/async/message_id/cancel");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Stream cancelled successfully
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/messages/async/message_id/cancel")! 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()
```

### Stream cancelled with cleanup

**Request**

```json
{}
```

**Response**

```json
{
  "message": "Stream cancelled successfully",
  "message_id": "msg_async_long_running"
}
```

**SDK Code**

```python Stream cancelled with cleanup
import requests

url = "https://api.example.com/v1/messages/async/message_id/cancel"

payload = {}
headers = {"Content-Type": "application/json"}

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

print(response.json())
```

```javascript Stream cancelled with cleanup
const url = 'https://api.example.com/v1/messages/async/message_id/cancel';
const options = {method: 'POST', headers: {'Content-Type': 'application/json'}, body: '{}'};

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

```go Stream cancelled with cleanup
package main

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

func main() {

	url := "https://api.example.com/v1/messages/async/message_id/cancel"

	payload := strings.NewReader("{}")

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

	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 Stream cancelled with cleanup
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/messages/async/message_id/cancel")

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

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{}"

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

```java Stream cancelled with cleanup
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/messages/async/message_id/cancel")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php Stream cancelled with cleanup
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/messages/async/message_id/cancel', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Stream cancelled with cleanup
using RestSharp;

var client = new RestClient("https://api.example.com/v1/messages/async/message_id/cancel");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Stream cancelled with cleanup
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/messages/async/message_id/cancel")! 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()
```