> ## Documentation Index
> Fetch the complete documentation index at: https://docs.powabase.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Copilot

> AI-powered workflow builder. Describe what you want in natural language and the copilot generates the workflow graph.

The Copilot API is an AI-assisted workflow builder. Create a copilot session linked to a workflow, describe what you want in natural language, and the copilot generates the workflow graph. Iterate over multiple chat turns to refine it, then save a snapshot to apply the generated graph.

## Common Patterns

Create a copilot session with a workflow\_id, send messages via the chat endpoint (streaming SSE), and save good suggestions with the snapshot endpoint. Each chat message can produce a new version of the workflow graph. The copilot maintains conversation context within a session.

### POST /api/copilot/sessions

Create a copilot session for a workflow.

<RequestExample>
  ```json Request theme={null}
  { "workflow_id": "wf-uuid" }
  ```
</RequestExample>

<CodeGroup>
  ```python Python theme={null}
  requests.post(f"{BASE_URL}/api/copilot/sessions", headers=headers, json={"workflow_id": wf_id})
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions`, { method: "POST", headers, body: JSON.stringify({ workflow_id: wfId }) });
  ```

  ```bash cURL theme={null}
  curl -X POST '{BASE_URL}/api/copilot/sessions' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}" -H "Content-Type: application/json" -d '{"workflow_id": "uuid"}'
  ```
</CodeGroup>

### GET /api/copilot/sessions

Get session by workflow\_id.

<ParamField query="workflow_id" type="string" required>
  Workflow ID
</ParamField>

<CodeGroup>
  ```python Python theme={null}
  requests.get(f"{BASE_URL}/api/copilot/sessions?workflow_id={wf_id}", headers=headers)
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions?workflow_id=${wfId}`, { headers });
  ```

  ```bash cURL theme={null}
  curl '{BASE_URL}/api/copilot/sessions?workflow_id={wf_id}' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}"
  ```
</CodeGroup>

### DELETE /api/copilot/sessions/{id}

Delete a copilot session.

<ParamField path="id" type="string" required>
  Session ID
</ParamField>

<CodeGroup>
  ```python Python theme={null}
  requests.delete(f"{BASE_URL}/api/copilot/sessions/{session_id}", headers=headers)
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions/${sessionId}`, { method: "DELETE", headers });
  ```

  ```bash cURL theme={null}
  curl -X DELETE '{BASE_URL}/api/copilot/sessions/{id}' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}"
  ```
</CodeGroup>

### GET /api/copilot/sessions/{id}/messages

Get copilot conversation history.

<ParamField path="id" type="string" required>
  Session ID
</ParamField>

<CodeGroup>
  ```python Python theme={null}
  requests.get(f"{BASE_URL}/api/copilot/sessions/{session_id}/messages", headers=headers)
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions/${sessionId}/messages`, { headers });
  ```

  ```bash cURL theme={null}
  curl '{BASE_URL}/api/copilot/sessions/{id}/messages' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}"
  ```
</CodeGroup>

### POST /api/copilot/sessions/{id}/messages/{mid}/snapshot

Save the copilot's workflow suggestion as a snapshot.

<ParamField path="id" type="string" required>
  Session ID
</ParamField>

<ParamField path="mid" type="string" required>
  Message ID
</ParamField>

<CodeGroup>
  ```python Python theme={null}
  requests.post(f"{BASE_URL}/api/copilot/sessions/{session_id}/messages/{message_id}/snapshot", headers=headers)
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions/${sessionId}/messages/${messageId}/snapshot`, { method: "POST", headers });
  ```

  ```bash cURL theme={null}
  curl -X POST '{BASE_URL}/api/copilot/sessions/{id}/messages/{mid}/snapshot' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}"
  ```
</CodeGroup>

### POST /api/copilot/sessions/{id}/chat

Send a message and stream the copilot response (SSE). The copilot runs a ReAct loop with access to a fixed set of tools for inspecting and modifying the workflow.

<ParamField path="id" type="string" required>
  Session ID
</ParamField>

<RequestExample>
  ```json Request theme={null}
  {
    "message": "Add a step that sends Slack notifications when the run finishes",
    "workflow_state": { "nodes": [...], "edges": [...] }
  }
  ```
</RequestExample>

| Body field       | Type              | Notes                                                                                                                                                                                       |
| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message`        | string (required) | User message                                                                                                                                                                                |
| `workflow_state` | object            | The current editor state (nodes + edges). The copilot needs this so it can reason against the live in-progress workflow, not just the persisted version. The Studio sends it automatically. |

#### SSE event types

The chat stream emits these events (each as `data: <json>` lines):

| Event           | Payload                                  | When                                                                                                                                                                    |
| --------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`        | `{ message }`                            | Human-readable status string ("Thinking...", "Modifying workflow\...", etc.) for the UI. Derived from the ReAct step and tool name via the platform's status map.       |
| `tool_call`     | `{ name, arguments }`                    | A copilot tool is about to execute                                                                                                                                      |
| `tool_result`   | `{ name, result }`                       | A copilot tool finished (truncated to readable size)                                                                                                                    |
| `content_delta` | `{ delta }`                              | A token of the copilot's text response                                                                                                                                  |
| `complete`      | `{ message_id, content, workflow_diff }` | Final event. `workflow_diff` is the structured change-set the copilot proposes (added/removed/modified blocks and edges); pass `message_id` to `/snapshot` to apply it. |
| `error`         | `{ error }`                              | The copilot failed mid-run                                                                                                                                              |

#### Copilot tools

The copilot has eight tools, exposed via the ReAct loop:

| Tool                    | Purpose                                                                                                                                                                  |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `modify_workflow`       | Add / update / remove blocks and edges in the in-progress workflow. The `workflow_diff` in the `complete` event is the cumulative effect of all `modify_workflow` calls. |
| `get_block_info`        | Look up the schema for a block type (which config fields, defaults, validation) before constructing it                                                                   |
| `get_db_schema`         | Read the project database's schema (tables, columns, types) so the copilot can build correct SQL for code or general\_api blocks                                         |
| `list_project_assets`   | Enumerate existing agents, KBs, orchestrations, workflows the copilot might want to call                                                                                 |
| `get_asset_details`     | Fetch one asset's full config. For agents, the system prompt is truncated to 1000 chars to fit context                                                                   |
| `execute_public_sql`    | Run a read-only SQL query against the project DB (public schema only) for exploring data before designing a block                                                        |
| `get_workflow_run_logs` | Read past execution logs from this workflow, e.g. for "the last run failed at step X, fix it"                                                                            |
| `manage_project_asset`  | Create / update / delete a project asset (agent, KB, etc.) on the copilot's recommendation. Requires user confirmation in the UI before the change persists.             |

The copilot itself runs as an agent under platform billing. Its model is configurable via `/api/copilot/settings/model` and defaults to `gpt-5.2`, with options including GPT-5.2, GPT-4.1, o3/o4, and Claude Opus/Sonnet/Haiku 4.x. Only function-calling-capable models are allowed.

Runtime limits: 25 ReAct steps max, temperature 0.7, workflow state truncated at 50,000 chars total (block configs over 2,000 chars get `... [truncated]`).

<CodeGroup>
  ```python Python theme={null}
  requests.post(
      f"{BASE_URL}/api/copilot/sessions/{session_id}/chat",
      headers=headers,
      json={"message": "Build a workflow that...", "workflow_state": current_state},
      stream=True,
  )
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/sessions/${sessionId}/chat`, {
    method: "POST", headers,
    body: JSON.stringify({ message: "Build a workflow that...", workflow_state: currentState }),
  });
  ```

  ```bash cURL theme={null}
  curl -N -X POST '{BASE_URL}/api/copilot/sessions/{id}/chat' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}" -H "Content-Type: application/json" -d '{"message": "Build a workflow that..."}'
  ```
</CodeGroup>

### GET /api/copilot/settings/model

Get copilot model configuration.

<CodeGroup>
  ```python Python theme={null}
  requests.get(f"{BASE_URL}/api/copilot/settings/model", headers=headers)
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/settings/model`, { headers });
  ```

  ```bash cURL theme={null}
  curl '{BASE_URL}/api/copilot/settings/model' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}"
  ```
</CodeGroup>

### PUT /api/copilot/settings/model

Set copilot model.

<RequestExample>
  ```json Request theme={null}
  { "model": "gpt-4o" }
  ```
</RequestExample>

<CodeGroup>
  ```python Python theme={null}
  requests.put(f"{BASE_URL}/api/copilot/settings/model", headers=headers, json={"model": "gpt-4o"})
  ```

  ```typescript TypeScript theme={null}
  await fetch(`${BASE_URL}/api/copilot/settings/model`, { method: "PUT", headers, body: JSON.stringify({ model: "gpt-4o" }) });
  ```

  ```bash cURL theme={null}
  curl -X PUT '{BASE_URL}/api/copilot/settings/model' -H "apikey: {API_KEY}" -H "Authorization: Bearer {API_KEY}" -H "Content-Type: application/json" -d '{"model": "gpt-4o"}'
  ```
</CodeGroup>

## Error Responses

Copilot routes return `{"error": "<message>"}`.

| Status | Description                                                                                                                |
| ------ | -------------------------------------------------------------------------------------------------------------------------- |
| 400    | Missing required field (`workflow_id` on POST/GET, `message` on chat, `pre_snapshot` on snapshot, `model` on settings PUT) |
| 400    | Settings PUT: `model` value fails registry validation (must be one of the allowed copilot model options)                   |
| 404    | No workflow or copilot session exists with the given ID                                                                    |
