intermediate20 min read· Module 8, Lesson 2
🤖Project: Build a Chatbot
Create a full conversational AI chatbot from scratch
Project: Build a Chatbot
Let's build a complete chatbot that maintains conversation history and has a personality.
What We're Building
A CLI chatbot that:
- Maintains conversation history
- Has a customizable personality via system prompt
- Shows token usage
- Can be stopped with "exit"
Step 1: Setup
mkdir my-chatbot
cd my-chatbot
npm init -y
npm install @anthropic-ai/sdkStep 2: The Code
Create chatbot.js:
import Anthropic from "@anthropic-ai/sdk";
import readline from "readline";
const client = new Anthropic();
const SYSTEM_PROMPT = `You are Luna, a friendly and knowledgeable AI assistant.
Personality traits:
- Warm and encouraging
- Uses simple language, avoids jargon
- Gives practical examples
- Admits when you don't know something
- Keeps responses concise (under 200 words unless asked for more)`;
const conversationHistory = [];
let totalInputTokens = 0;
let totalOutputTokens = 0;
async function chat(userMessage) {
conversationHistory.push({
role: "user",
content: userMessage
});
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
system: SYSTEM_PROMPT,
messages: conversationHistory
});
const assistantMessage = response.content[0].text;
totalInputTokens += response.usage.input_tokens;
totalOutputTokens += response.usage.output_tokens;
conversationHistory.push({
role: "assistant",
content: assistantMessage
});
return assistantMessage;
}
// CLI Interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log("\n🌙 Luna is ready! Type 'exit' to quit.\n");
function prompt() {
rl.question("You: ", async (input) => {
const trimmed = input.trim();
if (trimmed.toLowerCase() === "exit") {
console.log(`\nTotal tokens used: ${totalInputTokens} input, ${totalOutputTokens} output`);
console.log("Goodbye! 👋");
rl.close();
return;
}
if (!trimmed) {
prompt();
return;
}
try {
const response = await chat(trimmed);
console.log(`\nLuna: ${response}\n`);
} catch (error) {
console.error("Error:", error.message);
}
prompt();
});
}
prompt();Step 3: Run It
node chatbot.jsStep 4: Customize
Try changing the SYSTEM_PROMPT to create different personalities:
- Code Tutor: "You are a patient coding tutor who teaches through examples..."
- Chef: "You are a creative chef who suggests recipes based on ingredients..."
- Fitness Coach: "You are an encouraging fitness coach who creates workout plans..."
Challenges to Try
- Add streaming — show Luna's response word by word
- Save history — persist conversations to a file
- Add commands — /clear, /save, /personality
- Web UI — turn this into a web app with Next.js
Next up: Build a code review tool that analyzes files.