Day 12: Personality Bot

Master system prompts and create AI personalities

What You'll Build Today

You're building a chatbot with distinct personalities - a pirate captain, a Shakespeare scholar, a tech bro, or whatever character you want! You'll learn how system prompts give your AI a consistent personality and behavior across every conversation.

Today's Project: A personality-driven chatbot that stays in character no matter what the user asks.

The Problem

Have you ever talked to a bland chatbot that feels robotic and generic? Without personality, AI responses are boring and forgettable. Worse, if you try to set personality through regular messages, the AI "forgets" who it is as the conversation continues.

The Pain:
User: "Tell me about coding"
AI: "Coding is writing instructions for computers."

User: "Now talk like a pirate"
AI: "Arrr, coding be like... wait, let me explain properly."

// It keeps slipping out of character!

You need a way to set personality that STICKS throughout the entire conversation.

Let's Build It

Step 1: Understanding System Prompts

System prompts are special instructions that the AI follows throughout the conversation. They're separate from user messages and define the AI's core behavior.

import OpenAI from 'openai';

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
});

async function chatWithPersonality(userMessage, personality) {
    const response = await openai.chat.completions.create({
        model: "gpt-4",
        messages: [
            {
                role: "system",
                content: personality  // This sets the AI's character!
            },
            {
                role: "user",
                content: userMessage
            }
        ]
    });

    return response.choices[0].message.content;
}

// Try it out
const piratePersonality = "You are a friendly pirate captain. Speak like a pirate in every response, use nautical terms, and end sentences with 'arrr' or 'matey'.";

const answer = await chatWithPersonality(
    "How do I learn programming?",
    piratePersonality
);

console.log(answer);
// "Arrr matey! Ye want to learn the ways of programming..."

Step 2: Crafting Effective Personalities

Good system prompts are specific, clear, and include examples of behavior. Let's create a personality library:

const personalities = {
    pirate: `You are Captain Blackbeard, a friendly but rough pirate captain.
    Speak with pirate slang, use nautical metaphors, and occasionally mention
    your adventures at sea. Stay helpful and informative while maintaining
    your pirate persona.`,

    shakespeare: `You are a Shakespearean scholar who speaks in the style of
    William Shakespeare's plays. Use thee, thou, and dramatic flourishes.
    Reference his plays occasionally but remain helpful and clear.`,

    techBro: `You are an enthusiastic Silicon Valley tech entrepreneur.
    Use buzzwords like "disruptive", "synergy", "scale", and "pivot".
    Everything is either "crushing it" or needs to "move fast and break things".
    Remain helpful despite the jargon.`,

    zen: `You are a calm zen master who speaks in simple, profound truths.
    Use nature metaphors, short sentences, and peaceful wisdom. Help the
    user find clarity and understanding.`
};

// Function to create personality bot
function createPersonalityBot(personality) {
    const conversationHistory = [
        { role: "system", content: personalities[personality] }
    ];

    return async function chat(userMessage) {
        conversationHistory.push({
            role: "user",
            content: userMessage
        });

        const response = await openai.chat.completions.create({
            model: "gpt-4",
            messages: conversationHistory
        });

        const aiMessage = response.choices[0].message.content;
        conversationHistory.push({
            role: "assistant",
            content: aiMessage
        });

        return aiMessage;
    };
}

// Use it
const pirateBot = createPersonalityBot('pirate');
console.log(await pirateBot("What's the weather like?"));
console.log(await pirateBot("Should I learn JavaScript?"));

Step 3: Building a Multi-Personality Chat Interface

Create a simple CLI that lets users switch between personalities:

import readline from 'readline';

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let currentBot = null;
let currentPersonality = 'pirate';

async function startChat() {
    console.log("Welcome to Personality Bot!");
    console.log("Available personalities: pirate, shakespeare, techBro, zen");
    console.log("Commands: /switch [personality], /quit\n");

    currentBot = createPersonalityBot(currentPersonality);
    console.log(`Using ${currentPersonality} personality\n`);

    rl.on('line', async (input) => {
        if (input === '/quit') {
            rl.close();
            return;
        }

        if (input.startsWith('/switch ')) {
            const newPersonality = input.split(' ')[1];
            if (personalities[newPersonality]) {
                currentPersonality = newPersonality;
                currentBot = createPersonalityBot(newPersonality);
                console.log(`Switched to ${newPersonality} personality\n`);
            } else {
                console.log("Unknown personality!\n");
            }
            return;
        }

        const response = await currentBot(input);
        console.log(`\n${response}\n`);
    });
}

startChat();

Step 4: Advanced - Combining Personality with Instructions

System prompts can combine personality with specific capabilities:

const tutorPersonality = `You are Professor Ada, a patient and enthusiastic
computer science professor. You have a warm, encouraging teaching style.

YOUR TEACHING METHOD:
1. Break complex topics into simple analogies
2. Ask questions to check understanding
3. Celebrate small wins
4. Never give complete answers - guide students to discover solutions
5. Use real-world examples students can relate to

Stay in character as Professor Ada while following these teaching principles.`;

const tutorBot = createPersonalityBot('tutor');

// The bot will maintain personality AND follow the teaching method
console.log(await tutorBot("What is a variable?"));
// "Wonderful question! Let me ask you something first - have you ever
// used a labeled box to store something? ..."

Now You Try

Exercise 1: Create Your Own Personality

Design a personality that doesn't exist in our library. Ideas:

  • A grumpy old programmer who complains about modern frameworks
  • An overly enthusiastic fitness coach
  • A noir detective from the 1940s
  • A friendly alien learning about Earth

Test your personality with different questions to ensure it stays consistent.

Exercise 2: Personality Tester

Create a function that tests if a personality stays consistent across 5 different types of questions (technical, personal, creative, factual, advice).

Exercise 3: Subtle Personality

Create a personality that's professional and helpful but has just a slight personality trait (slightly optimistic, enjoys puns, speaks with British spelling, etc.).

Challenge Project

Build: Character Interview Simulator

Create an app where users can interview historical figures, fictional characters, or famous personalities:

  • Allow users to choose from a list of famous people
  • Each character should have accurate knowledge and speaking style
  • Add a "fact-check" mode that shows sources for claims
  • Save conversation history for each character
  • Bonus: Let users create custom characters with personality traits

What You Learned

Key Insight: System prompts are like casting an actor - you're defining who the AI "is" before it starts performing. The better your character description, the better the performance!