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
  • 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

1

Open the CallHQ Dashboard

Go to web.callhq.ai and log in to your account.
2

Navigate to API Keys

Click on your profile in the top right, then select API Keys.
3

Copy your API key

Copy your API Key. You’ll need this for all chat requests.
Keep this key secure - never expose it in client-side code.

2. Create or Select an Assistant

1

Navigate to Assistants

In your CallHQ dashboard, click Assistants in the left sidebar.
2

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?
3

Configure the system prompt

Update the system prompt to:
System Prompt
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.
4

Copy the Assistant ID

After publishing, copy the Assistant ID from the URL or assistant details. You’ll need this for API calls.

3. Create a Chat Session

1

Create a session

First, create a chat session with your assistant:
Create Session
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"
  }'
2

Verify the session response

You should receive a JSON response like:
Session Response
{
  "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"
  }
}

4. Send Your First Chat Message

1

Test with curl

Use the session ID from the previous step to send your first message:
First Chat Request
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"
  }'
2

Verify the response

You should receive a JSON response like:
Chat Response
{
  "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"
  }
}

5. Build a Multi-Turn Conversation

1

Continue the conversation

Use the same session ID to maintain context across multiple messages:
Follow-up Message
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"
  }'
2

Test context awareness

Send another message to verify the assistant remembers the conversation:
Context Test
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?"
  }'
3

View conversation history

Retrieve the full conversation history for the session:
Get Session History
curl -X GET https://api.callhq.ai/api/chats/session/session-abc123 \
  -H "x-api-key: YOUR_API_KEY"

6. Pass Dynamic Variables

1

Configure variables in your assistant

In your assistant’s system prompt, you can reference dynamic variables using {{variableName}} syntax:
System Prompt with Variables
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}}
2

Pass variables in your chat request

Use assistantOverrides.variableValues to pass dynamic data:
Chat Request with Variables
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"
      }
    }
  }'

7. Integrate with TypeScript

1

Create a simple chat function

Here’s a TypeScript function you can use in your application:
chat.ts
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);
2

Test your integration

Run your TypeScript code to verify the chat integration works correctly.

8. Test Your Chat Bot

1

Test various scenarios

Try these test cases to ensure your chat bot works correctly:
Test Case 1: General Question
# 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?"
  }'
Test Case 2: Technical Issue
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"
  }'
2

Verify conversation memory

Send follow-up messages using the same session ID to ensure context is maintained.
3

Check conversation history

Retrieve the full conversation to verify all messages are stored:
Get Full Conversation
curl -X GET https://api.callhq.ai/api/chats/session/session-id-from-above \
  -H "x-api-key: YOUR_API_KEY"

Limitations

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

Webhook Support

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.