Skip to content

Latest commit

 

History

History
343 lines (280 loc) · 10 KB

File metadata and controls

343 lines (280 loc) · 10 KB
title Chat quickstart
subtitle Build your first text-based conversation with a Vapi assistant in 5 minutes
slug chat/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 Vapi 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

Go to [dashboard.vapi.ai](https://dashboard.vapi.ai) and log in to your account. Click on your profile in the top right, then select `Vapi API Keys`. Copy your Private API Key. You'll need this for all chat requests.
<Warning>
Keep this key secure - never expose it in client-side code.
</Warning>

2. Create or Select an Assistant

In your Vapi dashboard, click `Assistants` in the left sidebar. - 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?` Update the system prompt to:
```txt title="System Prompt" maxLines=8
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.
```
After publishing, copy the Assistant ID from the URL or assistant details. You'll need this for API calls.

3. Send Your First Chat Message

Replace `YOUR_API_KEY` and `your-assistant-id` with your actual values:
```bash title="First Chat Request"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id",
    "input": "Hi, I need help with my TechFlow account"
  }'
```
You should receive a JSON response like:
```json title="Chat Response"
{
  "id": "chat_abc123",
  "assistantId": "your-assistant-id",
  "messages": [
    {
      "role": "user",
      "content": "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?"
    }
  ],
  "createdAt": "2024-01-15T09:30:00Z",
  "updatedAt": "2024-01-15T09:30:00Z"
}
```

4. Build a Multi-Turn Conversation

Use the `previousChatId` from the first response to maintain context:
```bash title="Follow-up Message"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id",
    "previousChatId": "chat_abc123",
    "input": "I forgot my password and can't log in"
  }'
```
Send another message to verify the assistant remembers the conversation:
```bash title="Context Test"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id", 
    "previousChatId": "chat_abc123",
    "input": "What was my original question?"
  }'
```

5. Pass Dynamic Variables

In your assistant's system prompt, you can reference dynamic variables using `{{variableName}}` syntax:
```txt title="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}}
```
Use `assistantOverrides.variableValues` to pass dynamic data:
```bash title="Chat Request with Variables"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id",
    "input": "I need help with my account",
    "assistantOverrides": {
      "variableValues": {
        "companyName": "TechFlow Solutions",
        "serviceType": "software",
        "customerTier": "Premium"
      }
    }
  }'
```

6. Integrate with TypeScript

Here's a TypeScript function you can use in your application:
```typescript title="chat.ts"
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

interface ChatApiResponse {
  id: string;
  assistantId: string;
  messages: ChatMessage[];
  output: ChatMessage[];
  createdAt: string;
  updatedAt: string;
  orgId?: string;
  sessionId?: string;
  name?: string;
}

interface ChatResponse {
  chatId: string;
  response: string;
  fullData: ChatApiResponse;
}

async function sendChatMessage(
  message: string, 
  previousChatId?: string
): Promise<ChatResponse> {
  const response = await fetch('https://api.vapi.ai/chat', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      assistantId: 'your-assistant-id',
      input: message,
      ...(previousChatId && { previousChatId })
    })
  });

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

  const chat: ChatApiResponse = await response.json();
  return {
    chatId: chat.id,
    response: chat.output[0].content,
    fullData: chat
  };
}

// Usage example
const firstMessage = await sendChatMessage("Hello, I need help");
console.log(firstMessage.response);

const followUp = await sendChatMessage("Tell me more", firstMessage.chatId);
console.log(followUp.response);
```
Run your TypeScript code to verify the chat integration works correctly.

7. Test Your Chat Bot

Try these test cases to ensure your chat bot works correctly:
```bash title="Test Case 1: General Question"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id",
    "input": "What are your business hours?"
  }'
```

```bash title="Test Case 2: Technical Issue"
curl -X POST https://api.vapi.ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistantId": "your-assistant-id",
    "input": "My app keeps crashing when I try to export data"
  }'
```
Send follow-up messages using `previousChatId` to ensure context is maintained.

Limitations

**Current chat functionality limitations:** - 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.

Next Steps

Take your chat bot to the next level:

Need help? Chat with the team on our [Discord](https://discord.com/invite/pUFNcf2WmH) or mention us on [X/Twitter](https://x.com/Vapi_AI).