How to Build a Chatbot with API: Create an AI-Powered Chatbot Using InstantAPI
Alex Chen
Developer Advocate
Introduction
Chatbots are everywhere — from customer service widgets to internal Slack bots to interactive help desks. But building a chatbot that actually understands user intent and responds intelligently is harder than it looks. Most tutorials show you how to match keywords or use massive language models, but there is a middle ground: using purpose-built AI APIs to give your chatbot real intelligence without the complexity.
In this tutorial, you will learn how to build a chatbot with API calls to InstantAPI. We will use InstantAPI's summarization task to condense long user messages and conversation history, and the sentiment analysis task to detect user frustration and adapt the bot's tone. The result is a chatbot that is smarter than a keyword matcher but simpler and cheaper than running a full LLM.
By the end of this guide, you will have a working chatbot in both JavaScript and Python that can:
- Understand user messages through summarization
- Detect user mood through sentiment analysis
- Maintain conversation context
- Escalate to a human when the user is frustrated
Prerequisites
Before starting, you will need:
Architecture Overview
Our chatbot uses a simple but effective architecture:
This approach gives you the intelligence of AI without the cost or complexity of running a full conversational LLM for every message.
Step 1: Set Up the InstantAPI Client
JavaScript
const INSTANTAPI_KEY = process.env.INSTANTAPI_KEY;
const API_URL = "https://instantapis.net/api/v1/generate";
async function callInstantAPI(task, input, options = {}) {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${INSTANTAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ task, input, options }),
});
if (!response.ok) {
throw new Error(`InstantAPI error: ${response.status}`);
}
return response.json();
}
Python
import requests
import os
INSTANTAPI_KEY = os.environ.get("INSTANTAPI_KEY")
API_URL = "https://instantapis.net/api/v1/generate"
def call_instantapi(task: str, input_data: str, options: dict = None):
headers = {
"Authorization": f"Bearer {INSTANTAPI_KEY}",
"Content-Type": "application/json",
}
payload = {
"task": task,
"input": input_data,
"options": options or {},
}
response = requests.post(API_URL, json=payload, headers=headers)
response.raise_for_status()
return response.json()
Step 2: Build the Conversation Manager
A chatbot needs to track conversation history. Here is a simple conversation manager that stores messages and uses InstantAPI to summarize when the history gets too long.
JavaScript
class ConversationManager {
constructor(maxMessages = 10) {
this.messages = [];
this.maxMessages = maxMessages;
this.summary = "";
}
addMessage(role, content) {
this.messages.push({ role, content, timestamp: new Date().toISOString() });
}
getRecentMessages(count = 5) {
return this.messages.slice(-count);
}
async getContext() {
if (this.messages.length <= this.maxMessages) {
return this.messages.map(m => `${m.role}: ${m.content}`).join("\n");
}
// Summarize older messages to keep context manageable
const olderMessages = this.messages.slice(0, -5);
const olderText = olderMessages.map(m => `${m.role}: ${m.content}`).join("\n");
const result = await callInstantAPI("summarize", olderText, {
length: "short",
format: "plain_text",
});
this.summary = result.result.summary;
const recentText = this.messages.slice(-5)
.map(m => `${m.role}: ${m.content}`).join("\n");
return `Previous context: ${this.summary}\n\nRecent messages:\n${recentText}`;
}
}
Python
from datetime import datetime
class ConversationManager:
def __init__(self, max_messages=10):
self.messages = []
self.max_messages = max_messages
self.summary = ""
def add_message(self, role: str, content: str):
self.messages.append({
"role": role,
"content": content,
"timestamp": datetime.now().isoformat(),
})
def get_recent_messages(self, count=5):
return self.messages[-count:]
def get_context(self) -> str:
if len(self.messages) <= self.max_messages:
return "\n".join(
f"{m['role']}: {m['content']}" for m in self.messages
)
# Summarize older messages
older = self.messages[:-5]
older_text = "\n".join(
f"{m['role']}: {m['content']}" for m in older
)
result = call_instantapi("summarize", older_text, {
"length": "short",
"format": "plain_text",
})
self.summary = result["result"]["summary"]
recent_text = "\n".join(
f"{m['role']}: {m['content']}" for m in self.messages[-5:]
)
return f"Previous context: {self.summary}\n\nRecent messages:\n{recent_text}"
Step 3: Add Sentiment-Aware Response Logic
The chatbot should adapt its behavior based on how the user is feeling. We use InstantAPI's sentiment analysis to detect frustration, happiness, or neutral tones, and adjust the response accordingly.
JavaScript
class AIChatbot {
constructor() {
this.conversation = new ConversationManager();
this.negativeCount = 0;
this.escalated = false;
}
async processMessage(userMessage) {
// Add the user message to history
this.conversation.addMessage("user", userMessage);
// Analyze sentiment
const sentimentResult = await callInstantAPI("sentiment", userMessage);
const sentiment = sentimentResult.result.sentiment;
const confidence = sentimentResult.result.confidence;
// Track negative sentiment for escalation
if (sentiment === "negative" && confidence > 0.7) {
this.negativeCount++;
} else {
this.negativeCount = Math.max(0, this.negativeCount - 1);
}
// Check if we should escalate to a human
if (this.negativeCount >= 3 && !this.escalated) {
this.escalated = true;
const response = "I can see you are frustrated, and I completely understand. "
+ "Let me connect you with a human agent who can help resolve this right away. "
+ "Please hold on — someone will be with you shortly.";
this.conversation.addMessage("bot", response);
return { response, escalate: true, sentiment };
}
// Get conversation context
const context = await this.conversation.getContext();
// Generate response based on sentiment
let response;
if (sentiment === "negative") {
response = await this.generateEmpatheticResponse(context, userMessage);
} else if (sentiment === "positive") {
response = await this.generatePositiveResponse(context, userMessage);
} else {
response = await this.generateNeutralResponse(context, userMessage);
}
this.conversation.addMessage("bot", response);
return { response, escalate: false, sentiment };
}
async generateEmpatheticResponse(context, message) {
// Use summarization to extract the core issue
const result = await callInstantAPI("summarize", message, {
length: "short",
format: "plain_text",
});
const issue = result.result.summary;
return `I am sorry to hear about this issue: ${issue}. `
+ "Let me help you resolve this as quickly as possible. "
+ "Could you share any error messages or screenshots you are seeing?";
}
async generatePositiveResponse(context, message) {
return "That is great to hear! Is there anything else I can help you with today?";
}
async generateNeutralResponse(context, message) {
const result = await callInstantAPI("summarize", message, {
length: "short",
format: "plain_text",
});
const topic = result.result.summary;
return `I understand you are asking about: ${topic}. `
+ "Let me look into that for you. Could you provide a few more details?";
}
}
Python
class AIChatbot:
def __init__(self):
self.conversation = ConversationManager()
self.negative_count = 0
self.escalated = False
def process_message(self, user_message: str) -> dict:
self.conversation.add_message("user", user_message)
# Analyze sentiment
sentiment_result = call_instantapi("sentiment", user_message)
sentiment = sentiment_result["result"]["sentiment"]
confidence = sentiment_result["result"]["confidence"]
# Track negative sentiment
if sentiment == "negative" and confidence > 0.7:
self.negative_count += 1
else:
self.negative_count = max(0, self.negative_count - 1)
# Check escalation
if self.negative_count >= 3 and not self.escalated:
self.escalated = True
response = (
"I can see you are frustrated, and I completely understand. "
"Let me connect you with a human agent who can help resolve "
"this right away. Please hold on."
)
self.conversation.add_message("bot", response)
return {"response": response, "escalate": True, "sentiment": sentiment}
# Get context
context = self.conversation.get_context()
# Generate response based on sentiment
if sentiment == "negative":
response = self._empathetic_response(user_message)
elif sentiment == "positive":
response = "That is great to hear! Is there anything else I can help you with?"
else:
response = self._neutral_response(user_message)
self.conversation.add_message("bot", response)
return {"response": response, "escalate": False, "sentiment": sentiment}
def _empathetic_response(self, message: str) -> str:
result = call_instantapi("summarize", message, {
"length": "short",
"format": "plain_text",
})
issue = result["result"]["summary"]
return (
f"I am sorry to hear about this issue: {issue}. "
"Let me help you resolve this as quickly as possible. "
"Could you share any error messages or screenshots?"
)
def _neutral_response(self, message: str) -> str:
result = call_instantapi("summarize", message, {
"length": "short",
"format": "plain_text",
})
topic = result["result"]["summary"]
return (
f"I understand you are asking about: {topic}. "
"Let me look into that for you. Could you provide more details?"
)
Step 4: Create a Simple Web Interface
Here is a minimal Express.js server that exposes the chatbot as a REST API.
JavaScript (Express.js)
const express = require("express");
const app = express();
app.use(express.json());
// Store chatbot instances per session
const sessions = new Map();
app.post("/chat", async (req, res) => {
const { sessionId, message } = req.body;
if (!sessions.has(sessionId)) {
sessions.set(sessionId, new AIChatbot());
}
const bot = sessions.get(sessionId);
try {
const result = await bot.processMessage(message);
res.json(result);
} catch (err) {
console.error("Chat error:", err);
res.status(500).json({ error: "Something went wrong" });
}
});
app.listen(3000, () => {
console.log("Chatbot server running on port 3000");
});
Python (Flask)
from flask import Flask, request, jsonify
app = Flask(__name__)
sessions = {}
@app.route("/chat", methods=["POST"])
def chat():
data = request.get_json()
session_id = data.get("sessionId")
message = data.get("message")
if session_id not in sessions:
sessions[session_id] = AIChatbot()
bot = sessions[session_id]
try:
result = bot.process_message(message)
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(port=3000)
Step 5: Test Your Chatbot
You can test the chatbot with curl:
# Happy customer
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"sessionId": "user-123", "message": "Hi! I just signed up and everything looks great!"}'
# Frustrated customer
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"sessionId": "user-456", "message": "Nothing is working and I have been trying for hours!"}'
Cost Breakdown
Each chatbot message uses 1-2 API calls:
- Sentiment analysis: 1 call ($0.50) per message — always
- Summarization: 1 call ($0.50) when needed for context compression or response generation
For a chatbot handling 1,000 conversations per day with an average of 5 messages each, the cost is approximately $2,500 - $5,000/month. Compare this to the cost of building and hosting your own NLP pipeline, which can run $10,000+/month in infrastructure alone.
Advanced Enhancements
Once your basic chatbot is working, consider these upgrades:
extract task to pull out order numbers, email addresses, or product names from user messagestranslate task to auto-detect and translate messages from non-English speakersConclusion
You now have a working AI chatbot that uses InstantAPI to understand user messages through summarization and detect frustration through sentiment analysis. This architecture is simpler, cheaper, and more predictable than running a full conversational LLM — and it gives you fine-grained control over the bot's behavior.
Ready to build your own? Get your API key and start testing in the playground. Check the documentation for the full list of tasks and options, or explore pricing to estimate your costs at scale.
Ready to try InstantAPI?
Sign up today and get 10 free credits to explore all 6 AI capabilities. No credit card required.
Get 10 Free Credits