Projects · · 5 min read

How I Added Markdown Export to My Python Chatbot

A step-by-step guide on how I built a simple Python script to export chatbot conversation logs from Supabase into formatted Markdown files.

A code editor showing a clean markdown document with user and AI chatbot message headers next to a terminal window.

When building AI tools on my laptop here in Pundri, I often find myself having long technical discussions with my assistant. Whether I am asking for debugging help, reviewing logic, or brainstorming features, those chat transcripts quickly accumulate in my database. While storing conversations in a cloud database like Supabase is great for session persistence, sometimes I just want a plain text document on my computer that I can open in VS Code, read offline, or search through easily. That is why I decided to figure out how to export python chatbot history to markdown files directly from my terminal.

Why I Wanted to Export Python Chatbot History to Markdown

When I first built my assistant, I focused primarily on how to manage python chatbot conversation history inside Supabase so that the model remembered past context across user prompts. That solved the immediate memory problem, but it created a small bottleneck for me as a developer. Whenever I wanted to save a cool code snippet, a step-by-step tutorial, or an outline that Gemini generated during a chat session, I had to manually copy and paste text from the terminal into a separate notes app. If a session had twenty back-and-forth messages, copying everything by hand was tedious and prone to formatting errors.

Markdown was the obvious answer for this problem. Plain markdown files are lightweight, easy to read in any text editor, version-controllable with Git, and perfectly supported by tools like VS Code and Obsidian. By writing a short Python function, I could pull the raw JSON payload of any saved conversation from my database and render it into a beautifully formatted .md file in seconds, complete with titles, timestamps, and properly fenced code blocks.

Fetching Data and Building the Exporter Script

To get started, I made sure my local workspace was ready. If you are building along on your own machine, you can check my guide on setting up a python ai development environment to see the simple VS Code and Supabase setup I rely on. The export script requires two basic libraries: the official supabase Python SDK to retrieve stored chat logs, and Python's built-in pathlib and datetime modules to handle file creation and file names cleanly.

Here is the practical script I put together. It connects to Supabase, grabs all messages associated with a specific session ID, formats the text, and writes it out into a clean markdown document.

import os
from datetime import datetime
from pathlib import Path
from supabase import create_client, Client

SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")

supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

def export_session_to_markdown(session_id: str, output_dir: str = "exports"):
    response = (
        supabase.table("chat_messages")
        .select("role, content, created_at")
        .eq("session_id", session_id)
        .order("created_at", desc=False)
        .execute()
    )
    
    messages = response.data
    if not messages:
        print(f"No messages found for session: {session_id}")
        return

    Path(output_dir).mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = Path(output_dir) / f"chat_export_{session_id}_{timestamp}.md"

    md_content = []
    md_content.append(f"# Chat Export: Session {session_id}\n\n")
    md_content.append(f"**Exported on:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
    md_content.append(f"**Total Messages:** {len(messages)}\n\n")
    md_content.append("---\n\n")

    for msg in messages:
        role_name = "User" if msg["role"] == "user" else "Assistant"
        time_str = msg.get("created_at", "")[:19].replace("T", " ")
        
        md_content.append(f"### {role_name} ({time_str})\n\n")
        md_content.append(f"{msg['content'].strip()}\n\n")
        md_content.append("---\n\n")

    with open(filename, "w", encoding="utf-8") as f:
        f.writelines(md_content)

    print(f"Successfully exported chat history to {filename}")

if __name__ == "__main__":
    export_session_to_markdown("sample-session-123")

How to Export Python Chatbot History to Markdown Step by Step

Let us walk through how this script works under the hood. First, the script sends a select query to the chat_messages table in Supabase. Filtering by session_id ensures we only fetch messages relevant to the current conversation rather than pulling your entire database history. Ordering by created_at guarantees that the conversation flows chronologically, exactly as it happened in real time.

Next, the script constructs the markdown document line by line. I chose to use H3 headings for the roles so that when you open the file in a markdown viewer, you get a clean collapsible outline of who said what. Markdown automatically renders Gemini's generated python, bash, or JSON code blocks with full syntax highlighting. Because Gemini already outputs fenced code blocks using triple backticks, those blocks nest perfectly inside the final text file without requiring complex parsing.

Storing chats in a database keeps your app functioning, but having exportable text files keeps your notes accessible forever.

Adding Useful Customizations and Metadata

Once the basic export script was running, I added a few small details that made the output files even more useful. For instance, adding a metadata header at the top of the file—including total message count and export timestamp—makes it easy to index exported files later. If you want to take this further, you could add a quick Gemini summarization call right before writing the file, automatically generating a 2-sentence summary title for the header.

Another handy tweak I made was building a slash command right into my terminal interface. Typing /export while chatting triggers this function automatically using the active session ID, saving the file to my local exports directory without disrupting the conversation flow. If you want to explore other projects and tools I have built while learning Python and AI, feel free to visit my projects page.

My Practical Takeaway

Building small utility features like a markdown exporter reminded me that software development is not always about flashy new AI capabilities. Sometimes, the most satisfying features are the simple workflow tweaks that save you five minutes of manual copy-pasting every single day. If you are building your own Python AI assistant, I highly encourage you to add a local export script—it gives you total control over your data and turns your daily chat sessions into a permanent, searchable personal archive.

Frequently asked questions

Why export AI chat history to markdown instead of JSON?

Markdown files are human-readable, lightweight, and render styled text and code blocks cleanly in editors like VS Code. JSON is great for software storage, but markdown is much easier to read and search manually.

Can I run this export script locally without paid cloud tools?

Yes, you can run the script using standard Python libraries and free-tier Supabase. It reads directly from your existing database tables and saves markdown files to your local folder.

Does the exported markdown file preserve code syntax highlighting?

Yes, since models like Gemini already output code wrapped in triple backticks with language tags, those code blocks render automatically with full syntax highlighting when opened in a markdown viewer.

Related posts