How to Use Channel-Based Function Calling with Dispatch
This tutorial demonstrates how to implement channel-based function calling using the dispatch() method in ChatBotKit. This approach is ideal for background AI tasks where the conversation runs asynchronously on the server.
Learning Objectives
By the end of this tutorial, you will be able to:
- Use the
dispatch()method to start background conversations - Subscribe to conversation events via channels
- Implement static function results for predetermined responses
- Implement channel-based function results for dynamic execution
- Handle the
waitForChannelMessageBeginevent to execute functions
Prerequisites
- Node.js 18+ installed
- A ChatBotKit account with an API secret
- Basic understanding of async/await and event streams
Estimated time: 20 minutes
Understanding Dispatch vs Complete
ChatBotKit offers two primary ways to run conversations:
| Method | Execution | Best For |
|---|---|---|
dispatch() | Background/async | Long-running tasks, webhooks, background processing |
complete() | Inline/blocking | Interactive chat, real-time responses |
The dispatch() method starts a conversation that runs in the background on the server. It immediately returns a channelId that you can subscribe to for receiving events.
Step 1: Set Up Your Project
Create a new Node.js project and install the ChatBotKit SDK:
Create a .env file with your API secret:
CHATBOTKIT_API_SECRET=your_api_secret_here
Step 2: Create the Main Script
Create a file called index.js:
Step 3: Define Functions with Different Result Types
ChatBotKit supports two types of function results:
Static Results
Static results return predetermined data immediately to the AI:
Channel-Based Results
Channel-based results require you to execute the function and publish the result:
Step 4: Dispatch the Conversation
Use dispatch() to start the background conversation:
Step 5: Subscribe to Events
Subscribe to the channel to receive events as the conversation progresses:
Step 6: Handle Channel Function Calls
When you receive a waitForChannelMessageBegin event, execute the function and publish the result:
Complete Example
Here's the complete working example:
Troubleshooting
Channel ID Too Short
Channel IDs must be at least 16 characters. Use randomBytes(16).toString('hex') to generate sufficiently long IDs.
Missing Function Result
If you don't publish a result to the channel, the conversation will timeout. Always handle waitForChannelMessageBegin events.
Event Structure
Remember that events from channel.subscribe() come wrapped: the actual event type is in event.data.type, not event.type.
Next Steps
- Learn about inline function calling with complete()
- Explore caller-handled pure functions
- Read about building agentic systems