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

# Quickstart

## Overview

Build a customer service chat bot that can handle text-based conversations through your application. Perfect for adding AI chat to websites, mobile apps, or messaging platforms.

**What You'll Build:**

* A working chat integration that responds to user messages
* Context-aware conversations that remember previous messages
* Both one-shot and multi-turn conversation patterns

**Agent Capabilities:**

* Instant text responses without voice processing
* Maintains conversation context across multiple messages
* Compatible with existing OpenAI workflows

## Prerequisites

* A [CallHQ account](https://web.callhq.ai/)
* An existing assistant or willingness to create one
* Basic knowledge of making API requests

## Scenario

We'll create a customer support chat for "TechFlow", a software company that wants to handle common questions via text chat before escalating to human agents.

***

## 1. Get Your API Credentials

<Steps>
  <Step title="Open the CallHQ Dashboard">
    Go to [web.callhq.ai](https://web.callhq.ai) and log in to your account.
  </Step>

  <Step title="Navigate to API Keys">
    Click on your profile in the top right, then select `API Keys`.
  </Step>

  <Step title="Copy your API key">
    Copy your API Key. You'll need this for all chat requests.

    <Warning>
      Keep this key secure - never expose it in client-side code.
    </Warning>
  </Step>
</Steps>

***

## 2. Create or Select an Assistant

<Steps>
  <Step title="Navigate to Assistants">
    In your CallHQ dashboard, click `Assistants` in the left sidebar.
  </Step>

  <Step title="Create a new assistant (or use existing)">
    * Click `Create Assistant` if you need a new one
    * Select `Blank Template` as your starting point
    * Name it `TechFlow Support`
    * Set the first message to: `Hello! I'm here to help with TechFlow questions. What can I assist you with today?`
  </Step>

  <Step title="Configure the system prompt">
    Update the system prompt to:

    ```txt title="System Prompt" maxLines=8 theme={null}
    You are a helpful customer support agent for TechFlow, a software company. 

    Your role:
    - Answer common questions about our products
    - Help troubleshoot basic issues  
    - Escalate complex problems to human agents

    Keep responses concise and helpful. Always maintain a friendly, professional tone.
    ```
  </Step>

  <Step title="Copy the Assistant ID">
    After publishing, copy the Assistant ID from the URL or assistant details. You'll need this for API calls.
  </Step>
</Steps>

***

## 3. Create a Chat Session

<Steps>
  <Step title="Create a session">
    First, create a chat session with your assistant:

    ```bash title="Create Session" theme={null}
    curl -X POST https://api.callhq.ai/api/sessions \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Customer Support Session",
        "assistantId": "your-assistant-id"
      }'
    ```
  </Step>

  <Step title="Verify the session response">
    You should receive a JSON response like:

    ```json title="Session Response" theme={null}
    {
      "message": "Session created successfully",
      "session": {
        "id": "session-abc123",
        "name": "Customer Support Session",
        "assistantId": "your-assistant-id",
        "status": "active",
        "messages": [],
        "createdAt": "2024-01-15T09:30:00Z",
        "updatedAt": "2024-01-15T09:30:00Z"
      }
    }
    ```
  </Step>
</Steps>

***

## 4. Send Your First Chat Message

<Steps>
  <Step title="Test with curl">
    Use the session ID from the previous step to send your first message:

    ```bash title="First Chat Request" theme={null}
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-abc123",
        "input": "Hi, I need help with my TechFlow account"
      }'
    ```
  </Step>

  <Step title="Verify the response">
    You should receive a JSON response like:

    ```json title="Chat Response" theme={null}
    {
      "message": "Chat created successfully",
      "chat": {
        "id": "chat-abc123",
        "sessionId": "session-abc123",
        "input": "Hi, I need help with my TechFlow account",
        "output": [
          {
            "role": "assistant",
            "content": "I'd be happy to help with your TechFlow account! What specific issue are you experiencing?"
          }
        ],
        "status": "active",
        "cost": 0.005,
        "createdAt": "2024-01-15T09:30:00Z",
        "updatedAt": "2024-01-15T09:30:00Z"
      }
    }
    ```
  </Step>
</Steps>

***

## 5. Build a Multi-Turn Conversation

<Steps>
  <Step title="Continue the conversation">
    Use the same session ID to maintain context across multiple messages:

    ```bash title="Follow-up Message" theme={null}
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-abc123",
        "input": "I forgot my password and can't log in"
      }'
    ```
  </Step>

  <Step title="Test context awareness">
    Send another message to verify the assistant remembers the conversation:

    ```bash title="Context Test" theme={null}
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-abc123",
        "input": "What was my original question?"
      }'
    ```
  </Step>

  <Step title="View conversation history">
    Retrieve the full conversation history for the session:

    ```bash title="Get Session History" theme={null}
    curl -X GET https://api.callhq.ai/api/chats/session/session-abc123 \
      -H "x-api-key: YOUR_API_KEY"
    ```
  </Step>
</Steps>

***

## 6. Pass Dynamic Variables

<Steps>
  <Step title="Configure variables in your assistant">
    In your assistant's system prompt, you can reference dynamic variables using `{{variableName}}` syntax:

    ```txt title="System Prompt with Variables" theme={null}
    You are a helpful customer support agent for {{companyName}}.

    Your role:
    - Answer questions about {{companyName}}'s products
    - Help customers with their {{serviceType}} needs
    - Escalate to human agents when needed

    Current customer tier: {{customerTier}}
    ```
  </Step>

  <Step title="Pass variables in your chat request">
    Use `assistantOverrides.variableValues` to pass dynamic data:

    ```bash title="Chat Request with Variables" theme={null}
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-abc123",
        "input": "I need help with my account",
        "assistantOverrides": {
          "variableValues": {
            "companyName": "TechFlow Solutions",
            "serviceType": "software",
            "customerTier": "Premium"
          }
        }
      }'
    ```
  </Step>
</Steps>

***

## 7. Integrate with TypeScript

<Steps>
  <Step title="Create a simple chat function">
    Here's a TypeScript function you can use in your application:

    ```typescript title="chat.ts" theme={null}
    interface ChatMessage {
      role: 'user' | 'assistant';
      content: string;
    }

    interface ChatApiResponse {
      message: string;
      chat: {
        id: string;
        sessionId: string;
        input: string;
        output: ChatMessage[];
        status: string;
        cost: number;
        createdAt: string;
        updatedAt: string;
      };
    }

    interface SessionResponse {
      message: string;
      session: {
        id: string;
        name: string;
        assistantId: string;
        status: string;
        messages: ChatMessage[];
        createdAt: string;
        updatedAt: string;
      };
    }

    class CallHQChat {
      private apiKey: string;
      private sessionId?: string;

      constructor(apiKey: string) {
        this.apiKey = apiKey;
      }

      async createSession(name: string, assistantId: string): Promise<string> {
        const response = await fetch('https://api.callhq.ai/api/sessions', {
          method: 'POST',
          headers: {
            'x-api-key': this.apiKey,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ name, assistantId })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const session: SessionResponse = await response.json();
        this.sessionId = session.session.id;
        return this.sessionId;
      }

      async sendMessage(message: string): Promise<string> {
        if (!this.sessionId) {
          throw new Error('No active session. Create a session first.');
        }

        const response = await fetch('https://api.callhq.ai/api/chats', {
          method: 'POST',
          headers: {
            'x-api-key': this.apiKey,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            sessionId: this.sessionId,
            input: message
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const chat: ChatApiResponse = await response.json();
        return chat.chat.output[0].content;
      }

      getSessionId(): string | undefined {
        return this.sessionId;
      }
    }

    // Usage example
    const chat = new CallHQChat('YOUR_API_KEY');

    // Create a session
    await chat.createSession('Customer Support', 'your-assistant-id');

    // Send messages
    const response1 = await chat.sendMessage("Hello, I need help");
    console.log(response1);

    const response2 = await chat.sendMessage("Tell me more");
    console.log(response2);
    ```
  </Step>

  <Step title="Test your integration">
    Run your TypeScript code to verify the chat integration works correctly.
  </Step>
</Steps>

***

## 8. Test Your Chat Bot

<Steps>
  <Step title="Test various scenarios">
    Try these test cases to ensure your chat bot works correctly:

    ```bash title="Test Case 1: General Question" theme={null}
    # First create a session
    curl -X POST https://api.callhq.ai/api/sessions \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Test Session",
        "assistantId": "your-assistant-id"
      }'

    # Then send a message (use the session ID from above)
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-id-from-above",
        "input": "What are your business hours?"
      }'
    ```

    ```bash title="Test Case 2: Technical Issue" theme={null}
    curl -X POST https://api.callhq.ai/api/chats \
      -H "x-api-key: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "sessionId": "session-id-from-above",
        "input": "My app keeps crashing when I try to export data"
      }'
    ```
  </Step>

  <Step title="Verify conversation memory">
    Send follow-up messages using the same session ID to ensure context is maintained.
  </Step>

  <Step title="Check conversation history">
    Retrieve the full conversation to verify all messages are stored:

    ```bash title="Get Full Conversation" theme={null}
    curl -X GET https://api.callhq.ai/api/chats/session/session-id-from-above \
      -H "x-api-key: YOUR_API_KEY"
    ```
  </Step>
</Steps>

## Limitations

<Note>
  **Current chat functionality limitations:**

  * "Query" tool for knowledge-base searches is not yet supported
  * Server webhook events (status updates, end-of-call reports, etc.) are not supported
</Note>

## Webhook Support

<Note>
  The chat API supports the following webhook events through server messaging:

  * **`chat.created`** - Triggered when a new chat conversation is initiated
  * **`chat.deleted`** - Triggered when a chat conversation is deleted

  To receive these webhooks, go to your Assistant page in the Dashboard and navigate to "Server Messaging" and select the events you want to receive.

  These webhooks are useful for tracking conversation analytics, maintaining conversation history in your own database, and triggering follow-up actions.
</Note>

<Callout>
  Need help? Contact the team at [hello@callhq.ai](mailto:hello@callhq.ai) or visit our [Dashboard](https://web.callhq.ai).
</Callout>
