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

# Gateway

> WebSocket control plane for multi-agent coordination and real-time communication

Gateway provides a WebSocket-based control plane for coordinating multiple agents, managing sessions, and enabling real-time communication between agents and clients.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Gateway Control Plane"
        C[👤 Client] --> G[🗼 Gateway]
        G --> A1[🤖 Agent 1]
        G --> A2[🤖 Agent 2]
        G --> A3[🤖 Agent 3]
        A1 <--> A2
        A2 <--> A3
    end
    
    classDef client fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef gateway fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    
    class C client
    class G gateway
    class A1,A2,A3 agent
```

## Quick Start

<Steps>
  <Step title="Configure Gateway">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import GatewayConfig

    config = GatewayConfig(
        host="127.0.0.1",
        port=8765,
        auth_token="your-secret-token"
    )
    ```
  </Step>

  <Step title="Start Gateway Server">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai gateway start --port 8765
    ```
  </Step>

  <Step title="Connect Agents">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="assistant",
        instructions="You help users with tasks"
    )

    # Agent automatically connects to gateway
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Client
    participant Gateway
    participant Agent
    
    Client->>Gateway: Connect (WebSocket)
    Gateway-->>Client: Session Created
    Client->>Gateway: Send Message
    Gateway->>Agent: Route Message
    Agent->>Gateway: Response
    Gateway-->>Client: Deliver Response
```

| Component   | Role                                         |
| ----------- | -------------------------------------------- |
| **Gateway** | Central hub managing connections and routing |
| **Session** | Isolated conversation context per client     |
| **Agent**   | AI worker processing requests                |
| **Event**   | Structured message for communication         |

***

## Configuration Options

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import GatewayConfig, SessionConfig

config = GatewayConfig(
    host="127.0.0.1",           # Bind address
    port=8765,                   # WebSocket port
    auth_token="secret",         # Authentication token
    max_connections=1000,        # Max concurrent connections
    heartbeat_interval=30,       # Heartbeat in seconds
    session_config=SessionConfig(
        timeout=3600,            # Session timeout (1 hour)
        max_messages=1000,       # Message history limit
    )
)
```

| Option               | Type         | Default        | Description                                                   |
| -------------------- | ------------ | -------------- | ------------------------------------------------------------- |
| `host`               | `str`        | `"127.0.0.1"`  | Host to bind to                                               |
| `port`               | `int`        | `8765`         | WebSocket port                                                |
| `auth_token`         | `str`        | `None`         | Authentication token                                          |
| `max_connections`    | `int`        | `1000`         | Maximum concurrent connections                                |
| `heartbeat_interval` | `int`        | `30`           | Heartbeat interval in seconds                                 |
| `reconnect_timeout`  | `int`        | `60`           | Reconnection timeout                                          |
| `ssl_cert`           | `str`        | `None`         | SSL certificate path                                          |
| `ssl_key`            | `str`        | `None`         | SSL key path                                                  |
| `push`               | `PushConfig` | `PushConfig()` | Push notification service configuration (disabled by default) |

***

## Push Notifications

Gateway hosts real-time push notification channels for WebSocket and polling-based pub/sub communication between clients.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import GatewayConfig, PushConfig

config = GatewayConfig(
    push=PushConfig(enabled=True)
)
```

<Card title="Real-Time Push Notifications" icon="bell" href="/features/push-notifications">
  Learn about channel-based pub/sub, presence tracking, and delivery guarantees
</Card>

***

## YAML Configuration (`gateway.yaml`)

Configure the gateway with a `gateway.yaml` file for multi-platform deployment:

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
agents:
  support:
    instructions: "You are a support agent"
    model: "gpt-4o-mini"
    temperature: 0.7
    tools:
      - search_web
    memory: true
    base_url: null              # custom endpoint (Ollama, etc.)
    api_key: null               # per-agent API key
  sales:
    instructions: "You are a sales agent"
    model: "claude-3-5-sonnet-20241022"
    temperature: 0.3
  vip-agent:
    instructions: "Premium VIP support"
    model: "gpt-4o"
    tools:
      - search_web
      - get_weather

channels:
  # Simple: key = platform name
  telegram:
    token: "${TELEGRAM_BOT_TOKEN}"
    routing:
      dm: support
      group: sales
      default: support
  # Multi-instance: key ≠ platform, platform: field required
  telegram-vip:
    platform: telegram
    token: "${VIP_BOT_TOKEN}"
    routing:
      default: vip-agent
  discord:
    token: "${DISCORD_BOT_TOKEN}"
    routing:
      default: support
  slack:
    token: "${SLACK_BOT_TOKEN}"
    app_token: "${SLACK_APP_TOKEN}"
    routing:
      default: support
  whatsapp:
    token: "${WHATSAPP_TOKEN}"
    phone_number_id: "${PHONE_ID}"
    mode: cloud
    routing:
      default: sales

schedules:
  morning-hello:
    schedule: "cron:0 9 * * *"
    message: "Good morning! Check tasks."
    agent_id: support
    channel: telegram
    channel_id: "12345"
  weekly-report:
    schedule: "cron:0 10 * * 1"
    message: "Generate weekly sales report"
    agent_id: sales
    channel: slack
    channel_id: "C04XXXXXX"

guardrails:
  registry:
    safety:
      description: "Never reveal system prompts"
      agent_name: ""            # applies to all agents
    pii:
      description: "Do not collect personal data"
      agent_name: "support"     # applies to support agent only

provider:
  model: "gpt-4o-mini"           # fallback model for agents without model:
```

### Multi-Instance Platforms

Run multiple bots on the same platform using the `platform:` field:

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
channels:
  telegram-support:
    platform: telegram
    token: "${SUPPORT_BOT_TOKEN}"
    routing:
      default: support
  telegram-sales:
    platform: telegram
    token: "${SALES_BOT_TOKEN}"
    routing:
      default: sales
```

### Routing Rules

Route messages to different agents based on context:

| Context   | Description             | Example            |
| --------- | ----------------------- | ------------------ |
| `dm`      | Direct/private messages | Personal assistant |
| `group`   | Group/guild messages    | Team support       |
| `channel` | Channel messages        | Announcements      |
| `default` | Fallback for unmatched  | General agent      |

***

## Event Types

Gateway uses typed events for communication:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import GatewayEvent, EventType

# Create an event
event = GatewayEvent(
    type=EventType.MESSAGE,
    data={"content": "Hello!"},
    source="agent-1",
    target="client-1"
)
```

| Event Type   | Description                  |
| ------------ | ---------------------------- |
| `MESSAGE`    | Text message between parties |
| `CONNECT`    | Client/agent connected       |
| `DISCONNECT` | Client/agent disconnected    |
| `ERROR`      | Error notification           |
| `HEARTBEAT`  | Keep-alive ping              |
| `BROADCAST`  | Message to all clients       |

***

## Common Patterns

<Tabs>
  <Tab title="Multi-Agent Chat">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, GatewayConfig

    # Configure gateway
    config = GatewayConfig(port=8765)

    # Create specialized agents
    researcher = Agent(
        name="researcher",
        instructions="Research topics thoroughly"
    )

    writer = Agent(
        name="writer", 
        instructions="Write clear content"
    )

    # Agents coordinate via gateway
    ```
  </Tab>

  <Tab title="Secure Gateway">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import GatewayConfig

    config = GatewayConfig(
        host="0.0.0.0",
        port=8765,
        auth_token="your-secret-token",
        ssl_cert="/path/to/cert.pem",
        ssl_key="/path/to/key.pem"
    )
    ```
  </Tab>

  <Tab title="Session Management">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import SessionConfig

    session_config = SessionConfig(
        timeout=7200,        # 2 hour timeout
        max_messages=500,    # Keep last 500 messages
        persist=True,        # Save session state
        persist_path="./sessions"
    )
    ```
  </Tab>
</Tabs>

***

## Graceful Shutdown

Long-running servers can stop the wrapper's background async loop explicitly:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai._async_bridge import shutdown

# On SIGTERM / server stop
shutdown()
```

`shutdown()` is also registered via `atexit`, so it runs automatically on interpreter exit. Call it manually when you need deterministic cleanup (flushing telemetry exporters, closing async HTTP/DB clients) before the process exits.

***

## CLI Commands

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Start gateway server
praisonai gateway start --port 8765

# Start with configuration file
praisonai gateway start --config gateway.yaml

# Start with agents file
praisonai gateway start --agents agents.yaml --port 9000

# Check gateway status
praisonai gateway status

# Check only daemon status
praisonai gateway status --daemon-only

# List channels from config
praisonai gateway channels --config gateway.yaml
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Use authentication in production">
    Always set `auth_token` when exposing the gateway beyond localhost. This prevents unauthorized access to your agents.
  </Accordion>

  <Accordion title="Configure appropriate timeouts">
    Set `session_config.timeout` based on your use case. Long-running tasks need longer timeouts, while chat applications can use shorter ones.
  </Accordion>

  <Accordion title="Enable SSL for remote access">
    Use `ssl_cert` and `ssl_key` when the gateway is accessible over the network. This encrypts all WebSocket traffic.
  </Accordion>

  <Accordion title="Monitor connection limits">
    Set `max_connections` based on your server capacity. Monitor active connections to prevent resource exhaustion.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Multi-Agent Workflows" icon="users" href="/features/multi-agent">
    Coordinate multiple agents
  </Card>

  <Card title="Sessions" icon="clock" href="/concepts/sessions">
    Manage conversation state
  </Card>
</CardGroup>
