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

# Agent

The Agent endpoints let you ask questions over your project's knowledge base. Three options depending on your use case: single query, chat, or batch.

---

## POST /api/v2/agent/query

**Single-shot Q\&A.** Ask one question, get one answer with source citations. Stateless — no conversation history is stored.

**Authentication:** Bearer token required

**Request body:**

| Field             | Type    | Required    | Description                                                                                                                                    |
| ----------------- | ------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `project_id`      | uuid    | Conditional | Required when `search_scope` is `project` (the default); omit for `org` and `open_library`                                                     |
| `query`           | string  | Yes         | The question to ask (max 100,000 characters)                                                                                                   |
| `max_sources`     | integer | No          | Number of sources to return (1–20, default 5)                                                                                                  |
| `search_scope`    | string  | No          | `project` (default), `org` for organization documents, or `open_library` for the Open Library corpus (requires the `api.open_library` feature) |
| `response_format` | string  | No          | `text` (default) or `json` for structured output                                                                                               |
| `response_schema` | object  | No          | JSON schema (required when `response_format` is `json`)                                                                                        |

**Example request:**

```bash
curl -X POST https://api.pyramid-ai.com/api/v2/agent/query \
  -H "Authorization: Bearer pai_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "7f9c8d2a-1b3e-4c5d-8e9f-0a1b2c3d4e5f",
    "query": "What are the fire safety requirements for this project?",
    "max_sources": 5
  }'
```

**Example response** `200 OK`:

```json
{
  "success": true,
  "data": {
    "answer": "Based on Section 3.1 of the Safety Management Plan, the project requires: (1) a documented fire safety plan reviewed quarterly, (2) fire extinguishers inspected monthly on every floor, (3) illuminated emergency exit signage, and (4) quarterly fire drills for all site personnel.",
    "sources": [
      {
        "id": "chunk_8f3a2b1c",
        "title": "Safety-Management-Plan-2026.pdf",
        "relevance": 0.94
      },
      {
        "id": "chunk_2d4e6f8a",
        "title": "HK-Fire-Safety-Code.pdf",
        "relevance": 0.87
      }
    ],
    "model": "gpt-4.1",
    "usage": {
      "prompt_tokens": 1450,
      "completion_tokens": 280,
      "total_tokens": 1730
    }
  },
  "request_id": "..."
}
```

| Field                 | Type   | Description                                       |
| --------------------- | ------ | ------------------------------------------------- |
| `answer`              | string | AI-generated answer grounded in project documents |
| `sources`             | array  | Document chunks referenced in the answer          |
| `sources[].id`        | string | Chunk identifier                                  |
| `sources[].title`     | string | Source document file name                         |
| `sources[].relevance` | number | Semantic similarity score (0 to 1)                |
| `model`               | string | AI model used                                     |
| `usage`               | object | Token consumption for billing                     |

---

## POST /api/v2/chat

**Multi-turn conversation.** Send a message history and get a contextual response. The AI understands follow-up questions based on prior messages.

**Authentication:** Bearer token required

**Request body:**

| Field                | Type    | Required | Description                                                                                                                                                                                                |
| -------------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages`           | array   | Yes      | Conversation history (1–50 messages)                                                                                                                                                                       |
| `messages[].role`    | string  | Yes      | `user`, `assistant`, or `system`                                                                                                                                                                           |
| `messages[].content` | string  | Yes      | Message text                                                                                                                                                                                               |
| `project_id`         | uuid    | No       | Project to search for grounded answers. Omit for `org` and `open_library` scope                                                                                                                            |
| `chat_type`          | string  | No       | Which agent answers: `general`, `project`, or `safety`. Omit to let the API pick the agent automatically (see below)                                                                                       |
| `chat_id`            | uuid    | No       | Provide to continue an existing chat. Omit to start new                                                                                                                                                    |
| `model`              | string  | No       | `chat-model` (default) or `chat-model-reasoning` (slower, more thorough)                                                                                                                                   |
| `stream`             | boolean | No       | `true` for real-time SSE streaming (default `false`)                                                                                                                                                       |
| `search_scope`       | string  | No       | `project`, `org`, or `open_library` for the Open Library corpus (requires the `api.open_library` feature; cannot be combined with `chat_type`). Send it with every request of an Open Library conversation |

### Choosing the agent (`chat_type`)

* `general` / `project` — search your organization's or project's own documents. Always available.
* `safety` — the Safety Assistant, answering from the shared construction-safety corpus (regulations, PPE, site safety practice). Requires the Safety Assistant to be enabled for your organization; if it is not, the request returns `403 AGENT_NOT_ENABLED`. `project_id` is not needed — the safety corpus is organization-independent.
* **Omitted** — the API classifies your message and routes it to the best agent among those enabled for your organization, falling back to `general` (document search) when nothing else fits. Integrations that know which agent they want should set `chat_type` explicitly; end-user chat boxes can omit it.

**Example — asking the Safety Assistant directly:**

```bash
curl -X POST https://api.pyramid-ai.com/api/v2/chat \
  -H "Authorization: Bearer pai_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_type": "safety",
    "messages": [
      {"role": "user", "content": "What precautions are required for excavation works?"}
    ]
  }'
```

**Example request:**

```bash
curl -X POST https://api.pyramid-ai.com/api/v2/chat \
  -H "Authorization: Bearer pai_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "7f9c8d2a-1b3e-4c5d-8e9f-0a1b2c3d4e5f",
    "messages": [
      {"role": "user", "content": "What are the fire safety requirements?"},
      {"role": "assistant", "content": "Based on the Safety Management Plan, the project requires quarterly fire drills, monthly extinguisher inspections, and illuminated exit signage."},
      {"role": "user", "content": "What about for buildings over 30 stories?"}
    ]
  }'
```

**Example response** `200 OK` (when `stream: false`):

```json
{
  "success": true,
  "data": {
    "chat_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "message": {
      "role": "assistant",
      "content": "For buildings over 30 stories, the Fire Safety Code additionally requires..."
    },
    "sources": [
      {
        "id": "chunk_9x8y7z",
        "title": "HK-Fire-Safety-Code.pdf",
        "relevance": 0.91
      }
    ],
    "usage": {
      "prompt_tokens": 2100,
      "completion_tokens": 420,
      "total_tokens": 2520
    }
  },
  "request_id": "..."
}
```

**Streaming:** When `stream: true`, the response is delivered as Server-Sent Events (SSE). See [Streaming & Async](/concepts/streaming) for implementation details.

---

## POST /api/v2/agent/batches

**Create a batch query.** Submit multiple questions to be answered in the background. Ideal for compliance checklists, regulatory questionnaires, or bulk data extraction.

**Authentication:** Bearer token required

**Request body:**

| Field                  | Type   | Required    | Description                                                                                                            |
| ---------------------- | ------ | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
| `project_id`           | uuid   | Conditional | Required when `search_scope` is `project` (the default); omit for `open_library`                                       |
| `name`                 | string | Yes         | Batch name (1–200 characters)                                                                                          |
| `questions`            | array  | Yes         | Array of question objects (1–500)                                                                                      |
| `questions[].query`    | string | Yes         | The question text                                                                                                      |
| `questions[].metadata` | object | No          | Optional metadata to attach to this question                                                                           |
| `question_template`    | string | No          | Template with `{input}` placeholder applied to each question                                                           |
| `search_scope`         | string | No          | `project` (default) or `open_library` to answer from the Open Library corpus (requires the `api.open_library` feature) |

**Example request:**

```bash
curl -X POST https://api.pyramid-ai.com/api/v2/agent/batches \
  -H "Authorization: Bearer pai_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "7f9c8d2a-1b3e-4c5d-8e9f-0a1b2c3d4e5f",
    "name": "Q2 Safety Compliance Checklist",
    "questions": [
      {"query": "Does the project have a documented fire safety plan?"},
      {"query": "Are emergency exits clearly marked on every floor?"},
      {"query": "Is there a monthly fire extinguisher inspection schedule?"}
    ]
  }'
```

**Example response** `201 Created`:

```json
{
  "success": true,
  "data": {
    "id": "b1c2d3e4-f5a6-7890-bcde-f12345678901",
    "name": "Q2 Safety Compliance Checklist",
    "project_id": "7f9c8d2a-1b3e-4c5d-8e9f-0a1b2c3d4e5f",
    "org_id": "iPwoNDP1ribwqCTkvlEyiA6DtGZdYe0k",
    "question_count": 3,
    "trigger_run_id": "run_abc123",
    "created_at": "2026-05-22T10:00:00Z"
  },
  "request_id": "..."
}
```

---

## GET /api/v2/agent/batches

List all batch queries. Supports pagination and filtering by project.

**Authentication:** Bearer token required

**Query parameters:**

| Parameter    | Type    | Default | Description               |
| ------------ | ------- | ------- | ------------------------- |
| `project_id` | uuid    | —       | Filter by project         |
| `limit`      | integer | 50      | Maximum results (max 200) |
| `offset`     | integer | 0       | Results to skip           |

---

## GET /api/v2/agent/batches/\{id}

Get batch details with full results for each question.

**Authentication:** Bearer token required

**Path parameters:**

| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `id`      | uuid | Batch ID    |

**Example response** `200 OK`:

```json
{
  "success": true,
  "data": {
    "id": "b1c2d3e4-f5a6-7890-bcde-f12345678901",
    "name": "Q2 Safety Compliance Checklist",
    "project_id": "7f9c8d2a-1b3e-4c5d-8e9f-0a1b2c3d4e5f",
    "org_id": "iPwoNDP1ribwqCTkvlEyiA6DtGZdYe0k",
    "question_count": 3,
    "trigger_run_id": "run_abc123",
    "created_at": "2026-05-22T10:00:00Z",
    "questions": [
      {
        "id": "q1-uuid",
        "query": "Does the project have a documented fire safety plan?",
        "status": "completed",
        "answer": "Yes, the project includes a Fire Safety Management Plan (ref FSP-2026-01)...",
        "confidence": 0.91,
        "sources": null
      }
    ]
  },
  "request_id": "..."
}
```

---

## GET /api/v2/agent/batches/\{id}/export

Download batch results as a CSV file. Opens in Excel, Google Sheets, etc.

**Authentication:** Bearer token required

**Path parameters:**

| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `id`      | uuid | Batch ID    |

**Response:** `200 OK` with `Content-Type: text/csv`

**CSV columns:**

| Column        | Description                |
| ------------- | -------------------------- |
| `question_id` | Unique question identifier |
| `question`    | The question text          |
| `answer`      | AI-generated answer        |
| `confidence`  | Confidence score (0 to 1)  |
| `sources`     | Source citations           |