Guided Project: AI Chatbot
Build a complete multi-turn AI chatbot with streaming, session management, and a system persona.
Guided Project: AI Chatbot
Build a full-featured conversational AI chatbot with streaming responses, conversation history, and a configurable persona. This is the foundational project every AI developer should have in their portfolio.
---
What You'll Build
A Python-based AI chatbot that:
- Maintains multi-turn conversation history
- Streams responses for real-time feel
- Has a configurable system persona
- Handles errors gracefully
- Manages context window limits
---
Step 1: Project Setup
mkdir ai-chatbot && cd ai-chatbot
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install openai python-dotenvCreate .env:
OPENAI_API_KEY=your-key-here---
Step 2: Core Chat Logic
Create chatbot.py:
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
SYSTEM_PROMPT = """You are a helpful AI assistant named Alex.
You're friendly, concise, and knowledgeable.
When you don't know something, say so honestly.
Keep responses under 200 words unless more detail is requested."""
MAX_MESSAGES = 20 # limit history to prevent context overflow
class Chatbot:
def __init__(self, system_prompt: str = SYSTEM_PROMPT):
self.messages = [{"role": "system", "content": system_prompt}]
def _trim_history(self):
if len(self.messages) > MAX_MESSAGES:
# Keep system prompt + last MAX_MESSAGES-1 messages
self.messages = [self.messages[0]] + self.messages[-(MAX_MESSAGES - 1):]
def chat(self, user_input: str) -> str:
self.messages.append({"role": "user", "content": user_input})
self._trim_history()
full_response = ""
# Stream the response token-by-token
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=self.messages,
max_tokens=400,
stream=True,
)
for chunk in stream:
text = chunk.choices[0].delta.content or ""
print(text, end="", flush=True)
full_response += text
print() # newline after streaming
self.messages.append({"role": "assistant", "content": full_response})
return full_response---
Step 3: CLI Interface
# Add to chatbot.py:
def main():
print("AI Chatbot | Type 'quit' to exit, 'reset' to clear history")
print("-" * 50)
bot = Chatbot()
while True:
try:
user_input = input("\nYou: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye!")
break
if not user_input:
continue
if user_input.lower() == "quit":
print("Goodbye!")
break
if user_input.lower() == "reset":
bot = Chatbot()
print("[Conversation reset]")
continue
print("\nAlex: ", end="")
bot.chat(user_input)
if __name__ == "__main__":
main()---
Step 4: Run It
python chatbot.py---
Step 5: Enhancements (Choose 2)
Once the base chatbot works, add at least 2 of the following:
1. Conversation export — save command writes history to a JSON file
2. Multiple personas — command-line arg to choose persona (tutor, assistant, creative writer)
3. Token tracking — display token count and estimated cost after each message
4. Markdown rendering — use the rich library to render formatted responses
5. Input validation — warn when input is very long and offer to truncate
---
Completion Criteria
- [ ] Multi-turn conversation works correctly
- [ ] Streaming renders token-by-token
- [ ] History is trimmed at the configured limit
- [ ] At least 2 enhancements implemented
- [ ] README.md with setup instructions