DEV Community

Vaibhav Suryawanshi
Vaibhav Suryawanshi

Posted on

Designing Reliable Multi-Turn LLM Chatbots in Python: Lessons from Building StudyBuddy

Most introductory tutorials on Large Language Model (LLM) integration end the moment a script prints a single completion in the terminal. While that proves your API key works, real-world conversational assistants demand far more architectural discipline. Because raw LLM endpoints are completely stateless, every request is processed in isolation unless the client application manages conversation history, enforces strict behavioral boundaries, and handles upstream API failures gracefully.

During my Artificial Intelligence internship at Valentius Kryptix, I engineered StudyBuddy, a command-line conversational study assistant built in Python using the official Google GenAI SDK (google-genai). Rather than treating the LLM as a black-box text generator, I designed StudyBuddy around four core engineering pillars: credential hygiene, strict system prompt guardrails, bounded sliding-window memory, and automated multi-model fallbacks.

  1. Why Stateless LLM APIs Require Client-Side State Architecture

When a Python application calls a foundation model endpoint, the server processes the incoming token sequence, generates the next probable tokens, and immediately forgets the interaction. If a student asks a follow-up question like "Can you give me a small example of that?", a stateless wrapper has no idea what "that" refers to.

At the same time, naively appending every message to an ever-growing list creates new problems:

Rising Latency and Token Overhead: Re-sending thousands of historical tokens on every turn slows down responses and increases API consumption.

Topic Drift and Verbosity: Without strong instructions, general-purpose models generate dense walls of text that overwhelm terminal users or veer off into unrelated topics.

Single-Model Fragility: Relying on a single hardcoded model identifier leaves the application vulnerable to 503 capacity spikes or 404 model deprecations.

Solving these issues cleanly inside a lightweight CLI tool became the primary engineering focus of StudyBuddy.

  1. Securing Credentials and Isolating the Python Environment

Before writing any inference logic, isolating dependencies and protecting secrets is essential. Hardcoding API keys directly inside source scripts is one of the most common security mistakes when publishing projects to GitHub.

StudyBuddy avoids this by pairing a dedicated Python virtual environment (venv) with python-dotenv:

Environment Separation: Secrets such as GEMINI_API_KEY live exclusively in a local .env file that is ignored by Git via .gitignore.

Developer Onboarding: A sanitized .env.example file documents the exact configuration keys needed so anyone cloning the repository can set up their environment in seconds.

Fail-Fast Validation: At startup, app.py checks whether GEMINI_API_KEY is loaded. If missing, it exits cleanly using sys.exit() with a clear instruction instead of crashing mid-session with an unhandled authentication traceback.

  1. Enforcing Persona and Anti-Hallucination Guardrails

A study assistant used inside a terminal window needs to be concise, accurate, and strictly focused on academic progress. To achieve consistent behavior across every conversational turn, I crafted a dedicated SYSTEM_PROMPT that acts as a persistent behavioral contract:

Brevity and Clarity: The prompt instructs the assistant to explain concepts simply with short, practical examples while keeping answers under 150 words unless the student explicitly requests deeper elaboration.

Academic Domain Focus: StudyBuddy is scoped specifically to studying, learning, and career preparation. If a user asks an off-topic question, the model politely steers the conversation back toward educational goals.

Anti-Hallucination Rule: Instead of guessing or inventing plausible-sounding misinformation when uncertain, the model is explicitly instructed to respond with "I'm not sure".

Interactive Terminal Controls: Alongside natural language prompts, the command loop intercepts utility commands—typing reset wipes the in-memory conversation buffer so the student can start a fresh topic cleanly, while quit exits the program gracefully.

  1. Bounding Context with a Sliding Memory Window (MAX_MESSAGES = 10)

To support natural multi-turn follow-ups without unbounded token growth, StudyBuddy manages conversation state using a sliding context window controlled by MAX_MESSAGES = 10.

Before each API request, the application slices the stored message history so only the most recent ten messages (the last five user-assistant turns) are sent to Gemini:

Immediate Working Memory: Five full exchanges provide plenty of context for the assistant to remember the student's name, degree program, and active study topic across follow-up prompts.

Predictable Performance: Because payload size is capped at ten messages, response speed and token usage remain consistent even during extended study sessions.

Verified Multi-Turn Recall: In terminal testing, I introduced myself as a Computer Science and Engineering (CSE) student named Vaibhav, asked for a two-line explanation of Python lists, requested a short code snippet without repeating the topic name, asked for a real-life whiteboard analogy, and then verified that the assistant still remembered my name and major five turns later.

  1. Resilience Through Ordered Model Fallbacks

Cloud AI endpoints occasionally experience transient traffic spikes (503 Service Unavailable) or lifecycle updates (404 Not Found) when preview models are retired. Hardcoding a single model name turns a temporary upstream hiccup into an application crash.

StudyBuddy solves this with an ordered MODELS fallback chain configurable via .env (GEMINI_MODELS or GEMINI_MODEL), defaulting to:

  1. gemini-3.8-flash

  2. gemini-3.5-flash

  3. gemini-flash-latest

  4. gemini-flash-lite-latest

During inference, the application iterates sequentially through this candidate list. If the primary model returns a transient availability error, the exception handler catches it and automatically retries the request against the next model in the chain—keeping the student's study session uninterrupted.

Explore the Complete Implementation

If you want to dive deeper into the full Python code structure, environment configuration, and terminal test outputs behind this project, Read the full article on the Valentius Kryptix engineering blog.

You can also inspect the complete source code and setup guide on GitHub: https://github.com/vaibhavsw942/LLM-Chatbot.git

Top comments (0)