How nGPT Manages Conversation Memory and Chat History in Interactive Sessions

nGPT maintains conversation memory as a chronological Python list of role-content dictionaries that is passed to the LLM on every request, automatically persisted to JSON session files in ~/.config/ngpt/history/, and indexed via session-index.json with automatic validation and repair capabilities.

nGPT implements a persistent conversation memory system that enables context-aware dialogue across interactive chat sessions. According to the nazdridoy/ngpt source code, the architecture relies on a simple list-based approach where each message turn is appended to a conversation array, passed to the model for full context retrieval, and automatically serialized to disk after every assistant response. This design ensures seamless continuity between sessions while providing robust file management through an intelligent indexing system.

Core Architecture of nGPT Conversation Memory

The In-Memory Conversation List

At the heart of nGPT's memory system is a Python list named conversation that stores message dictionaries in OpenAI-compatible format. Each dictionary contains role and content keys, with roles being system, user, or assistant. In ngpt/cli/modes/interactive.py, the interactive_chat_session() function initializes this list with a system prompt (lines 96-108), then appends user messages as {"role":"user","content":<text>} (lines 55-57) and assistant responses as {"role":"assistant","content":<reply>} (lines 60-63).

Persistent Storage and the History Directory

Every session is persisted to the user's configuration directory at ~/.config/ngpt/history/. The SessionManager class in ngpt/cli/handlers/session_handler.py manages this location via _get_history_dir(), creating individual JSON files named session_<id>.json for each conversation. These files store the complete message array, enabling full session restoration across application restarts.

Message Lifecycle in Interactive Sessions

Initialization and Web Search Augmentation

When a session begins, interactive_chat_session() creates a fresh conversation list containing only the system message. If the user provides an initial prompt, it is stored for later session naming. When --web-search is enabled, the raw user prompt is replaced with enriched search context before being appended to the history (lines 63-99 in ngpt/cli/modes/interactive.py), ensuring the LLM receives augmented context while the saved session records the enriched version.

Model Invocation and Auto-Save Mechanism

The complete conversation list is passed to client.chat() on every turn (lines 37-47), giving the LLM full access to prior dialogue. After receiving the assistant's response, the system immediately invokes auto_save_session() (lines 12-35 in ngpt/cli/handlers/session_handler.py), which serializes the entire message array to JSON and updates the session index. This ensures zero data loss even if the application crashes between turns.

Session Index Management and CLI Commands

The Session Index File

nGPT maintains a master registry in session-index.json that tracks all saved sessions with their IDs, human-readable names derived from first prompts, and timestamps. The SessionManager.get_session_index() method loads this file, while validate_session_index() automatically repairs discrepancies between the index and actual session files on disk, preventing orphaned or missing entries.

Resetting and Loading Conversations

The /reset command triggers clear_conversation_history() (lines 7-9 in ngpt/cli/handlers/session_handler.py), which returns a new list containing only the original system prompt and clears all in-memory session metadata. Conversely, the /sessions command launches handle_session_management() (lines 66-86), allowing users to select, rename, or delete previous sessions by loading their JSON files via load_session() and swapping the active conversation reference.

Working with nGPT Session Files Programmatically

The following examples demonstrate how to interact with nGPT's conversation memory system directly:

Start an interactive chat session:

from ngpt.cli.modes.interactive import interactive_chat_session
from ngpt.api.client import NGPTClient

client = NGPTClient()
args = type('Args', (), {
    'web_search': False,
    'temperature': 0.7,
    'top_p': 0.9,
    'max_tokens': 1024,
    'preprompt': None,
})

interactive_chat_session(client, args)

Read a saved session from disk:

import json
from pathlib import Path
from ngpt.core.config import get_config_dir

history_dir = get_config_dir() / "history"
session_file = history_dir / "session_20240307_123456_abcd1234.json"

with open(session_file, "r") as f:
    conversation = json.load(f)
    
print(conversation[-2:])  # Last user and assistant turn

Reset conversation history programmatically:

from ngpt.cli.handlers.session_handler import clear_conversation_history

system_prompt = "You are a helpful assistant."
conversation = [{"role": "system", "content": system_prompt}]
conversation = clear_conversation_history(conversation, system_prompt)

Summary

  • nGPT stores conversation history as a Python list of {"role": "...", "content": "..."} dictionaries passed to the LLM on every request for full context awareness.
  • Sessions persist automatically after each turn to ~/.config/ngpt/history/session_<id>.json via auto_save_session() in ngpt/cli/handlers/session_handler.py.
  • The session-index.json file maintains a validated registry of all saved conversations with automatic repair capabilities provided by SessionManager.validate_session_index().
  • Interactive commands /reset and /sessions manipulate memory through clear_conversation_history() and handle_session_management().
  • Web search augmentation occurs before message appending, ensuring enriched context enters the persistent history rather than the raw user query.

Frequently Asked Questions

Where does nGPT store conversation history files?

nGPT saves all session files in the ~/.config/ngpt/history/ directory as individual JSON files named session_<id>.json. A master index file session-index.json tracks metadata for all sessions, and the SessionManager class automatically validates this index against actual disk contents to prevent synchronization errors.

How does nGPT handle conversation resets during a chat?

When a user types /reset, the system calls clear_conversation_history() from ngpt/cli/handlers/session_handler.py, which returns a fresh list containing only the original system prompt. This clears both the in-memory conversation variable and session metadata, forcing the creation of a new session file on the next user input.

Can nGPT restore previous chat sessions?

Yes, the /sessions command invokes handle_session_management() to display all indexed sessions. When a user selects a session, load_session() reads the corresponding JSON file from the history directory and replaces the current conversation list, allowing seamless continuation of previous conversations with full context intact.

Does web search affect how nGPT stores conversation memory?

When --web-search is enabled, nGPT augments the user prompt with search results before appending it to the conversation history in interactive_chat_session(). The enriched version replaces the original in the conversation list, meaning the saved session contains the search-augmented context that was actually sent to the model, not the raw user query.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →