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

# Interfaces Overview

> Connect agents to messaging platforms with automatic sessions, hooks, and media handling.

An **Interface** connects a Definable agent to an external messaging platform — Telegram, Discord, Slack, voice phone calls, Desktop, CLI, or any custom channel. It handles the full lifecycle: receiving messages, managing sessions, resolving user identity, running the agent, and sending responses back.

## How It Works

Every incoming message flows through a structured pipeline:

```mermaid theme={null}
flowchart TD
  PlatformMsg["Platform Message"] --> Convert["1. Convert to InterfaceMessage"]
  Convert --> OnReceived["2. on_message_received hooks"]
  OnReceived --> ResolveId["3. Resolve identity"]
  ResolveId --> GetSession["4. Get or create session"]
  GetSession --> OnBefore["5. on_before_respond hooks"]
  OnBefore --> RunAgent["6. Run agent"]
  RunAgent --> BuildResp["7. Build InterfaceResponse"]
  BuildResp --> OnAfter["8. on_after_respond hooks"]
  OnAfter --> SendResp["9. Send response to platform"]
  SendResp --> UpdateSession["10. Update session history"]
```

Concurrency is controlled by a semaphore — multiple messages can be processed in parallel up to `max_concurrent_requests`. Errors at any step trigger `on_error` hooks and send a configurable error message to the user.

## Quick Example

Deploy an agent to Telegram in a few lines:

```python theme={null}
import asyncio
from definable.agent import Agent
from definable.model import OpenAIChat
from definable.agent.interface import TelegramInterface

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    instructions="You are a helpful assistant on Telegram.",
)

interface = TelegramInterface(agent=agent, bot_token="YOUR_BOT_TOKEN")

asyncio.run(interface.serve_forever())
```

That is all it takes. The interface handles session management, conversation history, media, and concurrent users automatically.

## Lifecycle

### Starting

<CodeGroup>
  ```python Context manager (recommended) theme={null}
  async with TelegramInterface(agent=agent, bot_token="YOUR_BOT_TOKEN") as interface:
      await interface.serve_forever()
  ```

  ```python Manual theme={null}
  interface = TelegramInterface(agent=agent, bot_token="YOUR_BOT_TOKEN")
  await interface.start()
  # ...
  await interface.stop()
  ```

  ```python Blocking theme={null}
  # Starts automatically if not running, blocks until stopped
  asyncio.run(interface.serve_forever())
  ```
</CodeGroup>

### Stopping

The interface shuts down gracefully on `KeyboardInterrupt` or when `stop()` is called. All active connections and resources are cleaned up.

## BaseInterface Constructor

All interfaces accept these parameters:

<ParamField path="agent" type="Agent" required>
  The Definable agent that processes messages.
</ParamField>

<ParamField path="**kwargs" type="Any">
  Platform-specific parameters passed directly (e.g., `bot_token`, `mode`, `allowed_user_ids`). See each interface's reference for available parameters.
</ParamField>

<ParamField path="session_manager" type="SessionManager">
  Custom session manager. A default one is created if not provided.
</ParamField>

<ParamField path="hooks" type="List[InterfaceHook]">
  List of hooks to attach. Can also be added later with `.add_hook()`.
</ParamField>

<ParamField path="identity_resolver" type="IdentityResolver">
  Cross-platform identity resolver. Maps platform user IDs to canonical user IDs for shared memory. See [Identity Resolution](/interfaces/identity).
</ParamField>

## Common Parameters

All interfaces accept these base parameters as keyword arguments:

| Parameter                        | Type   | Default                            | Description                              |
| -------------------------------- | ------ | ---------------------------------- | ---------------------------------------- |
| `platform`                       | `str`  | `""`                               | Platform identifier                      |
| `max_session_history`            | `int`  | `50`                               | Maximum messages kept in session history |
| `session_ttl_seconds`            | `int`  | `3600`                             | Session expiry time (1 hour)             |
| `max_concurrent_requests`        | `int`  | `10`                               | Max simultaneous agent calls             |
| `error_message`                  | `str`  | `"Sorry, something went wrong..."` | Message sent to user on error            |
| `typing_indicator`               | `bool` | `True`                             | Show typing indicator while processing   |
| `max_message_length`             | `int`  | `4096`                             | Max characters per outgoing message      |
| `rate_limit_messages_per_minute` | `int`  | `30`                               | Per-user rate limit                      |

```python theme={null}
interface = TelegramInterface(
    agent=agent,
    bot_token="YOUR_BOT_TOKEN",
    max_concurrent_requests=20,
    session_ttl_seconds=7200,
)
```

## Adding Hooks

Chain hooks with `.add_hook()`:

```python theme={null}
from definable.agent.interface import TelegramInterface, LoggingHook, AllowlistHook

interface = (
    TelegramInterface(agent=agent, bot_token="YOUR_BOT_TOKEN")
    .add_hook(LoggingHook())
    .add_hook(AllowlistHook(allowed_user_ids={"12345", "67890"}))
)
```

## Key Concepts

<CardGroup cols={2}>
  <Card title="Sessions" icon="clock-rotate-left" href="/interfaces/sessions">
    Automatic per-user session management with history, state, and TTL expiry.
  </Card>

  <Card title="Hooks" icon="anchor" href="/interfaces/hooks">
    Intercept messages and responses with composable hook functions.
  </Card>

  <Card title="Telegram" icon="paper-plane" href="/interfaces/telegram">
    Deploy to Telegram with polling or webhooks, media support, and access control.
  </Card>

  <Card title="Discord" icon="discord" href="/interfaces/discord">
    Deploy to Discord with guild/DM support, attachments, and access control.
  </Card>

  <Card title="Slack" icon="slack" href="/interfaces/slack">
    Deploy to Slack with Socket Mode, Block Kit interactions, and slash commands.
  </Card>

  <Card title="WebSocket" icon="bolt" href="/interfaces/websocket">
    Real-time bidirectional communication via JSON WebSocket protocol.
  </Card>

  <Card title="WhatsApp" icon="comment-sms" href="/interfaces/whatsapp">
    Connect to WhatsApp via the Twilio WhatsApp API.
  </Card>

  <Card title="Email" icon="envelope" href="/interfaces/email">
    IMAP polling + SMTP sending with thread tracking.
  </Card>

  <Card title="Call (Voice)" icon="phone" href="/interfaces/call">
    Voice calls via Twilio ConversationRelay.
  </Card>

  <Card title="Identity" icon="fingerprint" href="/interfaces/identity">
    Map users across platforms to a single canonical identity.
  </Card>

  <Card title="Multi-Interface" icon="server" href="/interfaces/multi-interface">
    Run multiple interfaces concurrently with automatic restart.
  </Card>

  <Card title="Custom Interfaces" icon="code" href="/interfaces/custom-interfaces">
    Build your own interface for any messaging platform.
  </Card>
</CardGroup>

## Usage Examples

<CardGroup cols={2}>
  <Card title="Telegram Bot" icon="paper-plane" href="/interfaces/usage/telegram-bot">
    Step-by-step: agent with tools, memory, and voice notes.
  </Card>

  <Card title="Discord Bot" icon="discord" href="/interfaces/usage/discord-bot">
    Step-by-step: agent with tools and persistent memory.
  </Card>

  <Card title="Slack Bot" icon="slack" href="/interfaces/usage/slack-bot">
    Step-by-step: agent with tools and slash commands.
  </Card>

  <Card title="Multi-Platform" icon="server" href="/interfaces/usage/multi-platform">
    Serve one agent across Telegram, Discord, and Slack.
  </Card>
</CardGroup>
