Today we are going to solve two common roadblocks that every beginner hits when building a chatbot in Python:

Why does the chatbot forget what we just talked about between two messages?

Why does it lose the entire conversation the moment we close and restart the script?

If you have little or no background with AI APIs or JSON files, do not worry. We will start from the ground up with simple ideas and clear examples so you can build a practical, generic HelpBot with confidence.

1. Why Your Chatbot Forgets: The "Stateless" Secret

Picture a normal chat with a colleague. In your first message, you ask, "What is a variable in Python?" Your colleague gives an explanation. In your second message, you simply say, "Give me an example." Because both of you can see the chat thread above, your colleague immediately knows you mean a Python variable example.

Large Language Models (LLMs) work differently: they are stateless by default. Each API request is treated independently, with no built-in memory of earlier requests. If you send only "Give me an example", the model has no way of knowing whether you want a Python code example, a spreadsheet formula, or a project update.

The fix: If the model does not store conversation state on its own, your application must keep track of the chat history and send the relevant messages along with each new request.

2. Plain Text Input vs. Structured messages (OpenAI Style)

For a single standalone prompt, passing plain text is straightforward. For an ongoing conversation, however, we pass a list of message dictionaries, where each entry specifies a role and content.

The Three Roles and Their Priority Order
system (Rules / Highest Priority): Sets the assistant's behavior, tone, guidelines, and boundaries. Skipping it leaves the model on default settings, which can make answers overly long, brief, or inconsistent.

user (Task / Input): Represents the current question, prompt, or instruction from the person using the chat.

assistant (Memory): Stores the model's earlier responses so follow-up questions stay grounded in what was already said.

In priority terms, system > user > assistant, meaning system-level instructions take precedence in shaping how the model responds.

Code Example 1: Adding Memory in a Chat Loop (OpenAI SDK)

# --- START SNIPPET 1: Generic Chatbot with In-Memory History (OpenAI) --- from dotenv import load_dotenv from openai import OpenAI def get_client() -> OpenAI: """Load environment variables (such as OPENAI_API_KEY) and return a client.""" load_dotenv() return OpenAI() def ask_bot(client: OpenAI, messages: list[dict]) -> str: """Send the full conversation history to the model and return the text reply.""" response = client.responses.create( model="gpt-5.1", input=messages, # Passing the full list preserves context across turns ) return response.output_text def run_chat() -> None: """Run an interactive CLI chatbot that remembers chat turns while running.""" client = get_client() # Initialize with a system message to define tone and behavior messages = [ { "role": "system", "content": "You are HelpBot, a clear and helpful assistant. Keep answers easy to follow.", } ] print("HelpBot is ready! Type 'exit' to quit.\n") while True: user_text = input("You: ").strip() # Exit the loop cleanly when requested if user_text.lower() == "exit": print("HelpBot: Goodbye! Have a great day.") break # Ignore blank inputs if not user_text: continue # 1. Record the user's message in the conversation list messages.append({"role": "user", "content": user_text}) # 2. Request a response using the full conversation history reply = ask_bot(client, messages) print(f"Bot: {reply}\n") # 3. Record the assistant's response so follow-ups have context messages.append({"role": "assistant", "content": reply}) if __name__ == "__main__": try: run_chat() except Exception as err: print("Something went wrong:", err) # --- END SNIPPET 1 --- 

3. Doing the Same Thing with Gemini (config, contents, and Parts)

Now let's look at how the Gemini SDK handles this. Rather than placing a "system" item inside a flat messages list, client.models.generate_content(...) separates configuration from conversation history using two main parameters:

  1. config (types.GenerateContentConfig): Accepts system_instruction to define behavioral rules.
  2. contents: Accepts a list of types.Content objects representing individual conversation turns.

Why does Gemini structure each turn with types.Content and types.Part? Because a single turn can combine text, images, audio, video, or files inside parts=[...]. In addition, Gemini's Content turns use "user" for the human side and "model" for the AI's replies.

Code Example 2: Adding Memory in a Chat Loop (Gemini SDK)

# --- START SNIPPET 2: Generic Chatbot with In-Memory History (Gemini) --- from dotenv import load_dotenv from google import genai from google.genai import types def get_gemini_client() -> genai.Client: """Load environment variables (such as GEMINI_API_KEY) and create a client.""" load_dotenv() return genai.Client() def ask_gemini(client: genai.Client, history: list[types.Content]) -> str: """Send structured Content turns and system instructions to Gemini.""" response = client.models.generate_content( model="gemini-2.5-flash", config=types.GenerateContentConfig( system_instruction="You are HelpBot, a clear and helpful assistant. Keep answers easy to follow." ), contents=history, ) return response.text def run_gemini_chat() -> None: """Run a multi-turn Gemini chatbot in the terminal.""" client = get_gemini_client() history: list[types.Content] = [] print("Gemini HelpBot is ready! Type 'exit' to quit.\n") while True: user_input = input("You: ").strip() if user_input.lower() == "exit": print("Bot: Goodbye! See you next time.") break if not user_input: continue # Append a user Content turn with a text Part history.append( types.Content( role="user", parts=[types.Part(text=user_input)], ) ) # Generate a response with full turn history ai_reply = ask_gemini(client, history) print(f"Bot: {ai_reply}\n") # Append the model's reply to preserve conversation continuity history.append( types.Content( role="model", parts=[types.Part(text=ai_reply)], ) ) if __name__ == "__main__": try: run_gemini_chat() except Exception as err: print("Error:", err) # --- END SNIPPET 2 --- 

4. Making Memory Permanent: Saving Chats with JSON

Our bot now keeps track of the conversation while the script is running. However, once the program stops and starts again, that in-memory list is gone.

To persist chat history across runs, we write the list of message dictionaries to a JSON file on disk. JSON mirrors Python lists and dictionaries closely, which lets us preserve nested structure and message roles cleanly without inventing custom text delimiters.

Three Core json Functions

  • json.dumps(obj): Serializes a Python object into a JSON string in memory.

  • json.dump(obj, file): Writes a serialized Python object directly to an open file on disk.

  • json.load(file): Parses a JSON file from disk back into a Python list or dict.

Code Example 3: Standalone JSON Save & Load Demo

# --- START SNIPPET 3: Basic JSON Save & Load Example --- import json SAMPLE_FILE = "demo_chat.json" chat_log = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is JSON?"}, {"role": "assistant", "content": "JSON is a lightweight text format for structured data."}, ] # 1. Convert Python object to a JSON string (in memory) json_preview = json.dumps(chat_log, indent=2) print("JSON String Preview:\n", json_preview) # 2. Save the Python list of dicts to a file on disk with open(SAMPLE_FILE, "w", encoding="utf-8") as f: json.dump(chat_log, f, indent=4) # 3. Read the JSON file back into a Python list with open(SAMPLE_FILE, "r", encoding="utf-8") as f: loaded_log = json.load(f) print("\nLoaded back type:", type(loaded_log)) print("First message role:", loaded_log[0]["role"]) # --- END SNIPPET 3 --- 

5. Putting It Together: A Persistent Chatbot

Let's combine everything into a single, reusable HelpBot script that: Loads existing messages from chat_history.json on startup if the file exists, or initializes a new list with a system message if it does not.Keeps each message's role and content intact across sessions.Writes the updated conversation to chat_history.json when the user types exit.

Code Example 4: Full Persistent Chatbot in Python

# --- START SNIPPET 4: Complete Persistent Chatbot with JSON --- import json import os from dotenv import load_dotenv from openai import OpenAI HISTORY_FILE = "chat_history.json" def get_client() -> OpenAI: """Initialize the OpenAI client after loading environment variables.""" load_dotenv() return OpenAI() def load_history() -> tuple[list[dict], bool]: """ Load chat history from disk if available. Returns (messages, is_new_session). """ if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, "r", encoding="utf-8") as file: return json.load(file), False default_messages = [ { "role": "system", "content": ( "You are HelpBot, a clear and reliable assistant. " "Provide concise, accurate answers and stay on topic." ), } ] return default_messages, True def save_history(messages: list[dict]) -> None: """Persist the conversation list to a JSON file.""" with open(HISTORY_FILE, "w", encoding="utf-8") as file: json.dump(messages, file, indent=4) def get_ai_reply(client: OpenAI, messages: list[dict]) -> str: """Send the conversation history to the model and return the response text.""" response = client.responses.create( model="gpt-5.1", input=messages, ) return response.output_text def main() -> None: """Main chat loop with automatic load on startup and save on exit.""" client = get_client() messages, is_new = load_history() if is_new: print("Bot: Hello! I'm HelpBot. Ask a question or type 'exit' to save and quit.\n") else: print("Bot: Welcome back! Previous chat loaded. Type 'exit' to save and quit.\n") while True: user_input = input("You: ").strip() if user_input.lower() == "exit": save_history(messages) print("Chat saved to disk. Goodbye!") break if not user_input: continue messages.append({"role": "user", "content": user_input}) reply = get_ai_reply(client, messages) print(f"Bot: {reply}\n") messages.append({"role": "assistant", "content": reply}) if __name__ == "__main__": try: main() except Exception as ex: print("Error:", ex) # --- END SNIPPET 4 --- 

Key Takeaways:

LLMs are stateless: Your code must pass conversation history on each turn to maintain context.

SDK structures differ: OpenAI uses messages with system, user, and assistant roles, while Gemini uses GenerateContentConfig(system_instruction=...) and Content objects with parts.

JSON enables persistence: json.dump() saves structured message lists to disk, and json.load() restores them on subsequent runs.

Connects

Check out my other blogs:
Travel/Geo Blogs
Subscribe to my channel:
Youtube Channel
Instagram:
Destination Hideout