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

> ## Agent Instructions
> Start with /introduction/getting-started. Use the Inference API's Direct Query endpoint (POST /api/inference/query) with the newton-c-2.6 or newton-fusion-1.0 model (text, image, and video reasoning) or the omega-embedding encoder (time-series embeddings). ATAI_API_ENDPOINT is the base URL https://platform.u1.archetypeai.app with no version path; every endpoint path begins with /api. Pages whose descriptions are marked (Archived) document the legacy Lens runtime — do not use them for new projects.

# Connect to Agent

> Open a websocket session with a serving agent

Requires [version 1.1.13](https://docs.archetypeai.app/release-notes/1.1.x.md#v1-1-13) or later of the Archetype platform.

> [!WARNING]
>
> Starting with [version 2.0.1](https://docs.archetypeai.app/release-notes/2.0.x.md#v2-0-1), this endpoint is removed from the platform. Run packages through deployments and sessions instead: deploy a package with [Create Deployment](https://docs.archetypeai.app/api-reference/agents/deployments/create-deployment.md), then open a session on it with [Create Session](https://docs.archetypeai.app/api-reference/agents/sessions/create-session.md). To move existing code, see [Migrating from Bundles and Instances](https://docs.archetypeai.app/core-concepts/agents/migrate-from-bundles.md).

## Overview

This endpoint upgrades the connection to a websocket against an agent that was run with
`mode: serving`. Each text frame the client sends is relayed to the agent and answered with one
frame carrying the agent's answer; what counts as an answer, and when, is the agent's decision.

The agent is checked before the upgrade, so `404`, `409`, and `503` arrive as ordinary HTTP
responses rather than as an accepted socket that closes. Send the bearer token as an
`Authorization` header on the upgrade request.

## Request

**agent\_id** `string` *required*

Serving agent `agt_` id to open a session against.

## Frame protocol

The protocol is JSON text. Every frame the server sends is JSON carrying a `status`, so a client
reads that one field to tell any frame from any other:

* **`connected`** — sent once, when the session opens.
* **`completed`** — the answer to one text frame the client sent. It has the same shape as the
  [Query Agent](https://docs.archetypeai.app/api-reference/agents/instances/query-agent.md) response.
* **`failed`** — a frame the server will not act on (malformed JSON, or a binary frame) is answered
  with a `failed` frame, and the session continues; one bad frame is not a broken session. The same
  frame is sent, and the session then closes, when the agent stops serving or when its state cannot
  be read for long enough to stop vouching for it.

Frames are capped at the same size as an HTTP body; a larger one closes the socket with a reason
rather than a bare disconnect.

### Session-open frame

**status** `string` *required*

Always `connected`.

**agent\_id** `string` *required*

The `agt_` id of the agent the session is bound to.

### Answer frame

**status** `string` *required*

`completed`.

**response** `object` *required*

The agent's answer, passed through as it came back. Its shape belongs to the blueprint's
connectors.

**query\_response\_time\_ms** `number` *required*

Total server-side time, in milliseconds.

### Failure frame

**status** `string` *required*

Always `failed`.

**error** `string` *required*

Why the frame could not be acted on, or why the session is closing.

```python Python theme={"system"}
import json
import os
import websocket

base_url = os.environ["ATAI_API_ENDPOINT"].replace("https://", "wss://", 1)
api_key = os.environ["ATAI_API_KEY"]

socket = websocket.create_connection(
    f"{base_url}/agents/instances/agt_01jc9q8v5nm3ry7t2bkz4dhs6f/connect",
    header={"Authorization": f"Bearer {api_key}"},
)

opened = json.loads(socket.recv())
print(f"{opened['status']}: {opened['agent_id']}")

socket.send(json.dumps({
    "records": [
        {"timestamp": "2026-09-18T11:24:03Z", "vibration": 0.41, "flow": 12.6}
    ]
}))

frame = json.loads(socket.recv())
if frame["status"] == "completed":
    print(frame["response"])
else:
    print(f"Error: {frame['error']}")

socket.close()
```

```json 101 - Session opened theme={"system"}
{
  "status": "connected",
  "agent_id": "agt_01jc9q8v5nm3ry7t2bkz4dhs6f"
}
```

```json 101 - Answer frame theme={"system"}
{
  "status": "completed",
  "response": {
    "predicted_state": "running",
    "p_running": 0.94,
    "p_idle": 0.06
  },
  "query_response_time_ms": 38.4
}
```

```json 101 - Failure frame theme={"system"}
{
  "status": "failed",
  "error": "<reason>"
}
```

```json 404 - No agent with this id theme={"system"}
{
  "errors": [
    {
      "code": "<error_code>",
      "message": "No agent with this id in the caller's org.",
      "suggestion": null,
      "error_uid": "err-xxxxxxxx"
    }
  ]
}
```

```json 409 - Not a running serving agent theme={"system"}
{
  "errors": [
    {
      "code": "<error_code>",
      "message": "The agent was not run in serving mode, or is no longer running.",
      "suggestion": null,
      "error_uid": "err-xxxxxxxx"
    }
  ]
}
```

```json 503 - Node at capacity theme={"system"}
{
  "errors": [
    {
      "code": "node_at_capacity",
      "message": "This node is already holding as many sessions as it will.",
      "suggestion": null,
      "error_uid": "err-xxxxxxxx"
    }
  ]
}
```

## Important Notes

> [!NOTE]
>
> * Start the agent with `mode: serving` on [Run Bundle](https://docs.archetypeai.app/api-reference/agents/bundles/run-bundle.md). A `batch` run never accepts a session.
> * Use [Query Agent](https://docs.archetypeai.app/api-reference/agents/instances/query-agent.md) for a single request and answer; use this endpoint for one open session over many payloads.
> * A `503` carries a `Retry-After` header giving the number of seconds to wait before opening a session again.
> * Over a session, `status` is how you tell an answer from a failure, since there is no HTTP status line per frame.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.