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

# Build a Real-Time Text Chat Interface

> Build real-time text chat with AI agents using WebSocket connections for instant messaging.

Build a text chat interface with WebSockets. Establish connections, send messages, receive agent responses, and handle conversation lifecycle.

**What you'll learn:** Connection setup, message exchange, response handling, and conversation cleanup.

<Note>
  **Testing requires a valid API key.** Generate a web integration token from your agent's Web Integrations settings in the Dasha BlackBox dashboard before starting.
</Note>

## Prerequisites

Before you start, ensure you have:

* A Dasha BlackBox agent with chat enabled
* A web integration token (from Dashboard → Agent → Web Integrations)
* The `AllowWebChat` feature enabled on your web integration

<Accordion title="Connection flow">
  Text chat follows this message sequence:

  ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
  sequenceDiagram
      participant Client
      participant Server as Dasha BlackBox Server
      participant Agent as AI Agent

      Client->>Server: WebSocket connect
      Server->>Client: Connection established
      Client->>Server: initialize (callType: "chat")
      Server->>Client: event (name: "connection")

      Client->>Server: incomingChatMessage ("Hello")
      Server->>Client: text (source: "user", echo)
      Agent->>Server: Generate response
      Server->>Client: text (source: "assistant", response)

      Client->>Server: terminate
      Server->>Client: conversationResult
      Server->>Client: event (name: "closed")
  ```
</Accordion>

***

## Step 1: Establish connection

Connect to the WebSocket endpoint and send the `initialize` message:

<Accordion title="Example: WebSocket connection for chat">
  ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const token = 'YOUR_WEB_INTEGRATION_TOKEN';
  const ws = new WebSocket(
    `wss://blackbox.dasha.ai/api/v1/ws/webCall?token=${token}`
  );

  ws.onopen = () => {
    // Send initialize message to start chat session
    ws.send(JSON.stringify({
      type: 'initialize',
      timestamp: new Date().toISOString(),
      request: {
        callType: 'chat',
        additionalData: {
          // Custom data passed to agent prompts
          userId: 'user-123',
          context: 'support'
        }
      }
    }));
  };
  ```
</Accordion>

The server responds with a `connection` event when the agent session is ready:

<Accordion title="Example: Connection event response">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "event",
    "name": "connection",
    "timestamp": "2025-01-20T10:00:01Z",
    "data": {
      "recordId": "call-abc123"
    }
  }
  ```
</Accordion>

***

## Step 2: Send messages

Use the `incomingChatMessage` type to send text messages:

<Accordion title="Example: Send chat message">
  ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  function sendMessage(text) {
    if (ws.readyState !== WebSocket.OPEN) {
      console.error('WebSocket not connected');
      return;
    }

    ws.send(JSON.stringify({
      type: 'incomingChatMessage',
      content: text,
      timestamp: new Date().toISOString()
    }));
  }

  // Usage
  sendMessage('Hello, I need help with my order');
  ```
</Accordion>

### IncomingChatMessage schema

| Field       | Type                    | Required | Description                 |
| ----------- | ----------------------- | -------- | --------------------------- |
| `type`      | `"incomingChatMessage"` | Yes      | Message type identifier     |
| `content`   | `string`                | Yes      | Text message content        |
| `timestamp` | `string` (ISO 8601)     | Yes      | Message timestamp           |
| `channelId` | `string \| null`        | No       | Optional channel identifier |

***

## Step 3: Receive messages

Handle incoming messages from the server:

<Accordion title="Example: Handle incoming messages">
  ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  ws.onmessage = (event) => {
    const message = JSON.parse(event.data);

    switch (message.type) {
      case 'event':
        handleEvent(message);
        break;
      case 'text':
        handleTextMessage(message);
        break;
      case 'toolCall':
        handleToolCall(message);
        break;
      case 'toolCallResult':
        handleToolResult(message);
        break;
      case 'conversationResult':
        handleConversationResult(message);
        break;
      case 'error':
        handleError(message);
        break;
    }
  };

  function handleEvent(message) {
    switch (message.name) {
      case 'connection':
        console.log('Agent session ready');
        break;
      case 'opened':
        console.log('Conversation opened');
        break;
      case 'closed':
        console.log('Conversation closed');
        break;
    }
  }

  function handleTextMessage(message) {
    const { source, text } = message.content;

    if (source === 'assistant') {
      // Agent response
      displayAgentMessage(text);
    } else if (source === 'user') {
      // Echo of user message (for transcript)
      console.log('Message confirmed:', text);
    }
  }

  function handleError(message) {
    console.error('Error:', message.data.message);
    showErrorToUser(message.data.message);
  }
  ```
</Accordion>

### TextHistoryMessage schema

| Field               | Type                                    | Description                            |
| ------------------- | --------------------------------------- | -------------------------------------- |
| `type`              | `"text"`                                | Message type identifier                |
| `timestamp`         | `string` (ISO 8601)                     | Message timestamp                      |
| `content.source`    | `"assistant" \| "user"`                 | Message sender                         |
| `content.text`      | `string \| null`                        | Message text content                   |
| `content.name`      | `string \| null`                        | Optional sender name                   |
| `content.type`      | `"potential" \| "confident" \| "final"` | Recognition confidence (user messages) |
| `content.segmentId` | `string`                                | Segment identifier (user messages)     |

<Accordion title="TextHistoryMessage example">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "text",
    "timestamp": "2025-01-20T10:00:05Z",
    "content": {
      "source": "assistant",
      "text": "Hello! I'd be happy to help you with your order. Could you provide your order number?",
      "name": null
    }
  }
  ```
</Accordion>

***

## Step 4: End conversation

Send a `terminate` message and wait for the conversation result:

<Accordion title="Example: End conversation gracefully">
  ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  function endConversation() {
    return new Promise((resolve, reject) => {
      let conversationResult = null;
      const timeout = setTimeout(() => {
        reject(new Error('Timeout waiting for conversation result'));
      }, 5000);

      const originalHandler = ws.onmessage;
      ws.onmessage = (event) => {
        const message = JSON.parse(event.data);

        if (message.type === 'conversationResult') {
          conversationResult = message.result;
          clearTimeout(timeout);
          ws.onmessage = originalHandler;
          resolve(conversationResult);
        } else {
          originalHandler(event);
        }
      };

      ws.send(JSON.stringify({
        type: 'terminate',
        timestamp: new Date().toISOString()
      }));
    });
  }

  // Usage
  const result = await endConversation();
  console.log('Conversation summary:', result);
  ws.close();
  ```
</Accordion>

<Accordion title="ConversationResultHistoryMessage example">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "conversationResult",
    "timestamp": "2025-01-20T10:05:00Z",
    "result": {
      "status": "completed",
      "duration": 300,
      "metadata": {
        "callId": "call-abc123",
        "agentId": "agent-xyz"
      }
    }
  }
  ```
</Accordion>

***

## Next steps

<CardGroup cols={2}>
  <Card title="Message Reference" icon="book" href="/docs/websockets/message-reference">
    Complete schema documentation for all WebSocket messages
  </Card>

  <Card title="Voice Call Implementation" icon="phone" href="/docs/websockets/voice-call-implementation">
    Add WebRTC voice calls to your integration
  </Card>

  <Card title="Tool Execution" icon="wrench" href="/docs/websockets/tool-execution">
    Handle agent tool calls via WebSocket
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/docs/websockets/error-handling">
    Handle connection errors and edge cases
  </Card>
</CardGroup>
