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

# Send one turn to the agentic chat

POST https://api.pyramid-ai.com/api/v2/chat
Content-Type: application/json

Runs the organisation's agents with their skills and tools. Requires the
`api.agentic_chat` feature. The turn runs as the user who created the API key.

Send `messages` to start or continue a chat, or `card_response` to answer the
card of the previous reply. The server keeps the history: for an existing
`chat_id` only the last message of the request is used.

A user message may name `files` uploaded through POST /api/v2/files.
`agent_id` uses one agent from GET /api/v2/agents; without it the router picks.

`stream: false` waits up to 230 seconds and returns the finished turn;
use `stream: true` for long turns. When the agent stops on a card the reply
has `status: awaiting_input` and a `card`. Generated files are listed in
`files`; fetch each with GET /api/v2/files/\{file\_id}.

Reference: https://doc.pyramid-ai.com/api-reference/api-explorer/agentic-chat/send-agentic-chat-turn

## Authentication

- `Authorization` header (bearer token, required) — Pyramid API key (prefix with "Bearer ")

## Servers

- `https://api.pyramid-ai.com` (Production, default)
- `https://api-staging.pyramid-ai.com` (Staging (sandbox): use pai_test_* keys)

## Request

### Body (application/json)

This endpoint expects a ChatRequest.

- `chat_id` (string, optional) — Continue this chat. Omit to start one.
- `project_id` (string, optional) — Bind a new chat to a project.
- `messages` (list of ChatMessage, optional) — The last message must have role `user`. For an existing `chat_id` the server supplies the earlier turns and only the last message is used.
- `card_response` (CardResponse, optional) — The answer to the card of the previous reply. `tool_call_id` and `card` (the card's `name`) come from that reply.
- `agent_id` (string, optional) — An agent id from GET /api/v2/agents. Absent: the router picks an agent for each turn.
- `knowledge_sources` (ChatRequestKnowledgeSources, optional) — Absent means all on.
- `stream` (boolean, optional, default: false) — `true` returns the event stream instead of the finished turn.
- `include_events` (boolean, optional, default: true) — `false` leaves the raw `events` out of a non-streamed reply.

## Response

### 200

Finished turn (JSON when stream=false, SSE when stream=true)

- `request_id` (string, required) — Server-generated per-request UUID. Also sent as `X-Request-Id` response header. Include in support tickets.
- `success` (any, required)
- `data` (ChatTurn, optional)
- `pagination` (Pagination, optional) — Present only on list endpoints. Top-level (not nested inside `data`).

## Errors

### 400 Bad Request Error

Validation error

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

### 401 Unauthorized Error

Unauthorized

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

### 403 Forbidden Error

The API feature is not enabled for this organization

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

### 404 Not Found Error

Resource not found

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

### 409 Conflict Error

The chat is waiting for a card response

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

### 503 Service Unavailable Error

Agent runtime unavailable, or the turn exceeded the synchronous limit

- `success` (any, required)
- `error` (ApiErrorError, required)
- `request_id` (string, required)

## Types

### ChatMessage

- `role` (enum, required)
  - Allowed values: `user`, `assistant`
- `content` (string, required)
- `files` (list of string, optional) — Files uploaded through POST /api/v2/files, attached to this message. Only on user messages.

### CardResponse

The answer to the card of the previous reply. `tool_call_id` and `card` (the card's `name`) come from that reply.

- `tool_call_id` (string, required)
- `card` (string, required)
- `action` (enum, required) — `confirm` answers a `*_confirm_inputs` card (send `values`); `answer` answers `ask_user` (send `answers`).
  - Allowed values: `confirm`, `answer`
- `values` (list of map from string to any, optional) — Every row of the card's inputs, each with `edited`.
- `units` (any, optional) — Units block of the card, when it has one.
- `answers` (list of CardResponseAnswersItems, optional)
- `comment` (string, optional)

### ChatRequestKnowledgeSources

Absent means all on.

- `org_knowledge` (boolean, optional)
- `open_library` (boolean, optional)

### ChatTurn

- `chat_id` (string, required)
- `status` (enum, required) — `awaiting_input` when the agent stopped on a card.
  - Allowed values: `completed`, `awaiting_input`
- `text` (string, required) — The agent's reply text.
- `card` (Card, required, nullable) — The card the agent stopped on. Answer it with `card_response`.
- `files` (list of GeneratedFile, required) — Files the agent generated in this turn.
- `protocol` (enum, required)
  - Allowed values: `ui-message-stream-v1`
- `events` (list of map from string to any, optional) — Raw events of the turn (text, reasoning, tool activity). Tool inputs and outputs are skill-specific and can change. Absent when `include_events` is false.

### Pagination

Offset-based pagination for list endpoints. Clients compute `has_more` from `offset + data.length < total`. Cursor pagination may be added per-endpoint later if deep-pagination performance becomes a concern.

- `total` (integer, required) — Total item count matching the filters (ignoring limit/offset).
- `offset` (integer, required)
- `limit` (integer, required, default: 50)

### ApiErrorError

- `code` (enum, required)
  - Allowed values: `VALIDATION_ERROR`, `UNAUTHORIZED`, `FORBIDDEN`, `FEATURE_NOT_ENABLED`, `AGENT_NOT_ENABLED`, `QUOTA_EXCEEDED`, `NOT_FOUND`, `CONFLICT`, `IDEMPOTENCY_KEY_REUSED`, `IDEMPOTENCY_IN_PROGRESS`, `UPLOAD_NOT_FOUND`, `UPLOAD_SIZE_MISMATCH`, `RATE_LIMITED`, `INTERNAL_ERROR`
- `message` (string, required) — Human-readable description. May be shown to end users; keep stable across minor changes.
- `docs_url` (string, optional) — Link to the error's documentation section.
- `field` (string, optional) — Only for `VALIDATION_ERROR`. JSONPath-ish reference to the offending field (e.g. `body.project_id`).
- `feature` (string, optional) — Only for `FEATURE_NOT_ENABLED`. The feature key the request required.

### CardResponseAnswersItems

- `questionId` (string, optional)
- `prompt` (string, optional)
- `selected` (list of CardResponseAnswersItemsSelectedItems, optional)

### Card

The card the agent stopped on. Answer it with `card_response`.

- `tool_call_id` (string, required)
- `name` (string, required)
- `input` (any, optional) — The card's content (questions, or inputs to confirm).

### GeneratedFile

- `file_id` (string, required) — Pass to GET /api/v2/files/\{file\_id}.
- `file_name` (string, required)

### CardResponseAnswersItemsSelectedItems

- `id` (string, optional)
- `label` (string, optional)

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "request_id": "string",
  "success": null,
  "data": {
    "chat_id": "string",
    "status": "completed",
    "text": "string",
    "card": {
      "tool_call_id": "string",
      "name": "ask_user",
      "input": null
    },
    "files": [
      {
        "file_id": "string",
        "file_name": "string"
      }
    ],
    "protocol": "ui-message-stream-v1",
    "events": [
      {}
    ]
  },
  "pagination": {
    "total": 127,
    "offset": 0,
    "limit": 50
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.pyramid-ai.com/api/v2/chat"

payload = {}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api.pyramid-ai.com/api/v2/chat';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', '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
package main

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

func main() {

	url := "https://api.pyramid-ai.com/api/v2/chat"

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

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

	req.Header.Add("Authorization", "Bearer <token>")
	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.pyramid-ai.com/api/v2/chat")

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

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

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.pyramid-ai.com/api/v2/chat")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.pyramid-ai.com/api/v2/chat', [
  'body' => '{}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.pyramid-ai.com/api/v2/chat");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.pyramid-ai.com/api/v2/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()
```