Projects · · 5 min read

How I Manage Python Chatbot Conversation History with Gemini and Supabase

A practical guide on how I store, fetch, and summarize chat history in Python using Gemini and Supabase without exceeding token limits.

A laptop on a desk showing Python script code and Supabase database tables for chatbot chat history.

When building interactive conversational tools, handling python chatbot conversation history effectively is one of the first major challenges you run into. When I started writing basic AI scripts in VS Code here in Pundri, my chatbot would treat every single prompt like a brand new interaction. If I gave it my name in one prompt, it would completely forget it by the next turn. To make conversations feel natural without exceeding model context windows or wasting API tokens, I had to build a clean way to store, retrieve, and summarize past messages. In this post, I will share how I built a practical memory system using Python, Gemini, and Supabase.

Managing Python Chatbot Conversation History Efficiently

At first glance, keeping track of a chat transcript seems easy: you just keep an array of user and model messages in memory and pass the whole list back to the API on every call. However, as your conversation grows longer, two main problems arise quickly: strict token limits and slow response times. Sending thousands of words back and forth with every message slows down your app and wastes context.

When I was setting up a Python AI development environment to build my personal tools, I realized that relying only on temporary Python list variables was not ideal. If the terminal closed or the script restarted, the entire conversation history disappeared. I needed a light database solution that could store message logs persistently while letting me retrieve just enough context for the current conversation.

Designing a Clean Supabase Schema for Chat Storage

To store the conversation across sessions, I turned to Supabase. PostgreSQL on Supabase gives me a reliable backend with a generous free tier, which is perfect for my side projects. I created a simple table named chat_messages to store individual messages.

The table structure is straightforward. Each row records a unique message ID, a session identifier so users can separate chat threads, the role of the speaker (user or model), the actual message text, and a timestamp. Having a dedicated session identifier allows the chatbot to organize messages into distinct threads easily.

create table chat_messages (
  id bigint generated by default as identity primary key,
  session_id text not null,
  role text not null,
  content text not null,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null
);

Retrieving and Formatting Recent Messages in Python

Once messages are saved in Supabase, the next step is retrieving them before sending a query to Gemini. Instead of loading the entire chat history from the beginning of time, I fetch only the most recent N messages (for instance, the last 10 turns). This keeps the prompt focused and response times fast.

Here is a simplified Python function showing how I query Supabase using the client library and convert the records into the structured format required by the Gemini API:

from supabase import create_client
import google.generativeai as genai

def get_recent_history(supabase_client, session_id: str, limit: int = 10):
    response = supabase_client.table("chat_messages") \
        .select("role, content") \
        .eq("session_id", session_id) \
        .order("created_at", desc=True) \
        .limit(limit) \
        .execute()
    
    # Reverse to maintain chronological order
    messages = list(reversed(response.data))
    
    formatted_history = []
    for msg in messages:
        formatted_history.append({
            "role": msg["role"],
            "parts": [msg["content"]]
        })
    return formatted_history

Summarizing Older Context with Gemini

Fetching only the last 10 messages works well for short interactions, but what if a user mentions something discussed 20 turns ago? If we simply throw away older messages, the assistant forgets important details like user preferences or task constraints.

To solve this, I added an automatic summarization step. When the total message count for a session exceeds a set threshold (say, 15 messages), the script takes the older messages, passes them to Gemini with a concise summarization prompt, and updates a separate session summary table.

When starting a new conversation session, I prepend this concise summary to the system instructions. That way, Gemini retains important background context without needing the raw text of 50 past messages. This approach was inspired by what I learned while adding vector search to my Python chatbot, where keeping data structured and compact keeps retrieval fast.

Putting the Step-by-Step Chat Loop Together

When a user enters a new prompt in the CLI, the program execution follows a clear sequence:

  • Save the new user prompt into the chat_messages table in Supabase.
  • Retrieve the active session summary along with the last 10 formatted messages.
  • Initialize the Gemini chat instance pre-loaded with this trimmed context.
  • Send the user input and receive the generated response.
  • Store the assistant response back into Supabase.
  • Trigger a background check to update the session summary if necessary.

Building this structured loop made my local terminal projects feel much more intelligent and coherent. The bot remembers key facts from earlier in the session, stays on topic during long debugging runs, and avoids context window errors. If you want to see other projects I have experimented with using Python and free tools, feel free to check out my projects or read how I built JARVIS for a broader look at personal assistants.

Practical Lessons and Key Takeaways

When I started out, I thought managing memory required complicated frameworks right away. But building a clean setup with standard SQL queries in Supabase and periodic summarization using Gemini taught me that simple data structures often work best.

If you are building your own terminal or web chatbot, here are my quick suggestions: start by capping your retrieved history to 6 to 10 turns, save raw messages in PostgreSQL, and only add background summarization when your session lengths require it. Keeping your pipeline clean makes debugging much easier when something breaks.

Frequently asked questions

How do you store chat history for a Python chatbot?

You can store chat history by saving every user prompt and assistant response into a database like Supabase with session identifiers and timestamps, then querying recent messages before sending new API requests.

How do you prevent a Python chatbot from hitting token limits?

You can prevent token limit issues by fetching only the last N recent messages for active context and periodically summarizing older messages with an LLM like Gemini.

Why use Supabase for Python chatbot conversation history?

Supabase provides a hosted PostgreSQL database with a generous free tier, fast SQL querying, and simple Python SDK integration, making it ideal for persistent chat logs.

Related posts