GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - Roaljh/Memory-Chat-API: AI chat backend with persistent memory across conversations — FastAPI, PostgreSQL, Qdrant vector search

BranchesTags
Open more actions menu

Latest commit

 

History

4 Commits
4 Commits

Folders and files

NameName
Last commit message
Last commit date
backend
backend
 
 
docs
docs
 
 
Dockerfile
Dockerfile
 
 
README.md
README.md
 
 
docker-compose.yml
docker-compose.yml
 
 

Repository files navigation

RecallWeave

A research-oriented project on persistent conversational memory. RecallWeave currently provides a baseline chat backend with cross-conversation semantic retrieval. Its next research phase will investigate whether time-aware, versioned memories can reduce outdated answers compared with retrieving similar past messages.

Research status: Work in progress. The time-aware memory design and its evaluation are planned work; they are not implemented yet. The current system is the baseline described below.


Research direction

Research question

Do time-aware, versioned memories reduce outdated answers compared with retrieving semantically similar past messages?

For example, if someone first says they live in Delhi and later says they moved to Pune, the system should distinguish what is currently true from what used to be true, and answer questions about either time period accurately.

Planned investigation

  • Extract candidate facts or events from conversations and retain links to their source messages.
  • Track when a fact was true and when the system learned it, preserving updates and contradictions instead of silently overwriting history.
  • Retrieve memories using semantic relevance alongside time and structured metadata.
  • Compare this approach against the existing vector-retrieval baseline.
  • Evaluate multi-session recall, temporal questions, changed facts, abstention when evidence is insufficient, retrieval quality, latency, and token cost.

LongMemEval is a candidate benchmark for long-term conversational memory. Benchmark selection, implementation, and results are still in progress; no performance improvements are claimed yet.

Current versus planned

Capability Status
Persist conversations in PostgreSQL Implemented
Semantic retrieval of past messages with Qdrant Implemented baseline
Extract structured facts and events Planned
Preserve temporal versions and contradictions Planned
Benchmark against the current baseline Planned

What it does

RecallWeave is a research prototype for persistent conversational memory, built with FastAPI, PostgreSQL, and Qdrant. The current implementation is a baseline that retrieves semantically similar messages from earlier conversations.


The current backend has two memory layers:

  • Short-term memory — full conversation history is stored in PostgreSQL and sent to the LLM on every message, so the AI remembers everything said within a thread.
  • Long-term memory — every message is embedded into a vector and stored in Qdrant. On each new message, the system searches for semantically similar content from past conversations and injects it into the AI's context. The AI can recall things you said weeks ago, in a completely different conversation.

Tech stack

Layer Technology
API framework FastAPI (async)
LLM provider Groq (OpenAI-compatible — swappable)
Relational DB PostgreSQL 16
Vector DB Qdrant
Embeddings all-MiniLM-L6-v2 via sentence-transformers (runs locally)
DB migrations Alembic
HTTP client httpx (async)
Containerization Docker + Docker Compose

Architecture

User Request
     │
     ▼
FastAPI (chat.py)
     │
     ├── 1. Get or create User + Conversation (PostgreSQL)
     ├── 2. Load last 20 messages from conversation (short-term memory)
     ├── 3. Search Qdrant for semantically similar past messages (long-term memory)
     ├── 4. Build prompt: system + memory context + history + new message
     ├── 5. Send to LLM API → get reply
     ├── 6. Save user message + reply to PostgreSQL
     └── 7. Embed + store both messages in Qdrant

Project structure

Memory-Chat-API/
├── backend/
│   ├── app/
│   │   ├── main.py                  # App entry point, startup hooks
│   │   ├── core/
│   │   │   └── config.py            # All settings loaded from .env
│   │   ├── db/
│   │   │   └── session.py           # Async SQLAlchemy engine + session factory
│   │   ├── models/
│   │   │   └── models.py            # DB models: User, Conversation, Message
│   │   ├── api/
│   │   │   ├── chat.py              # POST /api/chat and POST /api/chat/stream
│   │   │   └── conversations.py     # GET/DELETE /api/conversations
│   │   └── services/
│   │       ├── llm_service.py       # LLM API client (OpenAI-compatible)
│   │       ├── conversation_service.py  # DB operations for conversations/messages
│   │       └── memory_service.py    # Qdrant vector storage + semantic search
│   ├── alembic/                     # Database migration scripts
│   ├── .env.example                 # Template for environment variables
│   ├── requirements.txt             # Python dependencies
│   └── stream_test.py               # Manual integration test for streaming
├── docker-compose.yml               # PostgreSQL + Qdrant containers
├── Dockerfile                       # Backend container
└── README.md

Getting started

Prerequisites

  • Python 3.11+
  • Docker Desktop
  • A Groq API key (free)

1. Clone the repo

git clone https://github.com/Roaljh/Memory-Chat-API.git
cd Memory-Chat-API

2. Set up environment variables

cd backend
cp .env.example .env

Edit .env and fill in your values:

LLM_API_KEY=your-groq-api-key-here
LLM_API_BASE=https://api.groq.com/openai/v1

3. Start the databases

cd ..
docker-compose up -d

This starts PostgreSQL on port 5432 and Qdrant on port 6333.

4. Install dependencies

cd backend
pip install -r requirements.txt

First install takes a few minutes — it downloads PyTorch and the sentence-transformers embedding model (~90MB, one time only).

5. Start the server

uvicorn app.main:app --reload

On first startup the server will:

  • Create all database tables automatically
  • Initialize the Qdrant vector collection
  • Download the embedding model if not already cached

Visit http://localhost:8000/docs for the interactive API documentation.


API reference

POST /api/chat

Non-streaming chat. Returns the full reply in one response.

Request body:

{
  "message": "Hello, my name is Alex",
  "username": "alex",
  "conversation_id": "optional-uuid-to-continue-existing-conversation"
}

Response:

{
  "reply": "Hi Alex! How can I help you today?",
  "conversation_id": "d653dc16-8a2e-49d1-ab05-46ec7469b3ca"
}

POST /api/chat/stream

Streaming chat. Returns the reply as a Server-Sent Events (SSE) stream — tokens arrive as they're generated, like a typing effect.

Same request body as /api/chat. The conversation_id is returned in the X-Conversation-Id response header.

SSE format:

data: Hello
data:  Alex
data: !
data: [DONE]

GET /api/conversations?username=alex

Lists all conversations for a user, newest first.

Response:

[
  {
    "id": "d653dc16-8a2e-49d1-ab05-46ec7469b3ca",
    "title": "Hello, my name is Alex",
    "created_at": "2026-09-10T12:00:00+00:00",
    "updated_at": "2026-09-10T12:05:00+00:00",
    "message_count": 0
  }
]

GET /api/conversations/{conversation_id}

Returns a single conversation with all its messages.


DELETE /api/conversations/{conversation_id}

Deletes a conversation and all its messages.


GET /health

Health check endpoint.

{ "status": "ok", "environment": "development" }

How memory works

Short-term (within a conversation)

Every message is stored in PostgreSQL. When you send a new message with a conversation_id, the last 20 messages are loaded and sent to the LLM as conversation history. The AI has full context of the current thread.

Long-term (across conversations)

Every message is embedded using all-MiniLM-L6-v2 — a local embedding model that converts text into a 384-dimensional vector representing its semantic meaning. These vectors are stored in Qdrant with metadata (user ID, conversation ID, role).

Before each LLM call, the system runs a cosine similarity search in Qdrant to find the most relevant things the user has said in other conversations. Results above a relevance threshold are formatted and injected into the system prompt.

This means: even in a brand new conversation, the AI can recall facts from weeks ago.


Swapping the LLM provider

The LLM client uses the OpenAI /chat/completions wire format, which is supported by most providers. To switch:

  1. Update LLM_API_KEY and LLM_API_BASE in your .env
  2. Update self.model in backend/app/services/llm_service.py
Provider LLM_API_BASE Example model
Groq https://api.groq.com/openai/v1 openai/gpt-oss-20b
OpenAI https://api.openai.com/v1 gpt-4o
Together AI https://api.together.xyz/v1 meta-llama/Llama-3-70b
Ollama (local) http://localhost:11434/v1 llama3

Environment variables

Variable Required Default Description
LLM_API_KEY Yes — API key for your LLM provider
LLM_API_BASE No Groq URL Base URL for the LLM API
POSTGRES_URL No localhost PostgreSQL connection string
QDRANT_URL No localhost:6333 Qdrant connection URL
QDRANT_API_KEY No — Qdrant API key (for cloud deployments)
DEBUG No false Enables SQL query logging
ENVIRONMENT No development Environment name

Running with Docker

To run the entire stack (backend + databases) in containers:

docker-compose up --build

The backend Dockerfile is at the root of the repo.


Research roadmap

  • Define a reproducible evaluation set and baseline measurements
  • Extract candidate facts and events with source-message provenance
  • Add temporal versions for changed or conflicting facts
  • Implement time-aware retrieval and evidence-grounded answers
  • Compare against the existing vector-search baseline and report accuracy, outdated-answer rate, retrieval quality, latency, and token cost

This roadmap is in progress. These items are proposed work, not completed features. Authentication, a frontend, and multimodal memory are outside the current research scope.


License

MIT

About

AI chat backend with persistent memory across conversations — FastAPI, PostgreSQL, Qdrant vector search

Topics

fastapillmmemory-aipostgresqlpythonqdrantragsentence-transformersvector-database

Resources

Readme
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.