From 0c0ba74c0957e5fd59df85cc6e3b2812f4d786ee Mon Sep 17 00:00:00 2001 From: ZTatman Date: Wed, 18 Mar 2026 16:30:34 -0400 Subject: [PATCH] Phase 1: restructure into backend/ and fix module import side effects - Move all Python source files into backend/ directory - Fix db.py: use absolute path (Path(__file__).parent) for chroma_db so the DB is always found regardless of where the server is launched from - Fix store.py: guard test entry under if __name__ == "__main__" to prevent duplicate inserts on every import - Fix query.py: extract query_entries(question) -> str function and move interactive loop under __main__ guard so it can be imported cleanly by FastAPI without blocking on input() - Add .claude/launch.json with FastAPI dev server configuration Co-Authored-By: Claude Sonnet 4.6 --- .claude/launch.json | 11 ++++ PLAN.md => backend/PLAN.md | 0 README.md => backend/README.md | 0 db.py => backend/db.py | 5 +- main.py => backend/main.py | 0 models.py => backend/models.py | 0 pyproject.toml => backend/pyproject.toml | 0 backend/query.py | 79 ++++++++++++++++++++++++ store.py => backend/store.py | 29 ++++----- uv.lock => backend/uv.lock | 0 query.py | 62 ------------------- 11 files changed, 109 insertions(+), 77 deletions(-) create mode 100644 .claude/launch.json rename PLAN.md => backend/PLAN.md (100%) rename README.md => backend/README.md (100%) rename db.py => backend/db.py (68%) rename main.py => backend/main.py (100%) rename models.py => backend/models.py (100%) rename pyproject.toml => backend/pyproject.toml (100%) create mode 100644 backend/query.py rename store.py => backend/store.py (65%) rename uv.lock => backend/uv.lock (100%) delete mode 100644 query.py diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..39769cb --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "FastAPI backend", + "runtimeExecutable": "uv", + "runtimeArgs": ["run", "uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"], + "port": 8000 + } + ] +} diff --git a/PLAN.md b/backend/PLAN.md similarity index 100% rename from PLAN.md rename to backend/PLAN.md diff --git a/README.md b/backend/README.md similarity index 100% rename from README.md rename to backend/README.md diff --git a/db.py b/backend/db.py similarity index 68% rename from db.py rename to backend/db.py index af7e2a2..1a802aa 100644 --- a/db.py +++ b/backend/db.py @@ -1,11 +1,14 @@ import chromadb +from pathlib import Path + +_DB_PATH = str(Path(__file__).parent / "chroma_db") def get_collection(): """ Retrieves chromadb collection by either retrieving one that was already created or by creating a new one """ - client = chromadb.PersistentClient("./chroma_db") + client = chromadb.PersistentClient(_DB_PATH) return client.get_or_create_collection( name="diary", metadata={"hnsw:space": "cosine"} ) diff --git a/main.py b/backend/main.py similarity index 100% rename from main.py rename to backend/main.py diff --git a/models.py b/backend/models.py similarity index 100% rename from models.py rename to backend/models.py diff --git a/pyproject.toml b/backend/pyproject.toml similarity index 100% rename from pyproject.toml rename to backend/pyproject.toml diff --git a/backend/query.py b/backend/query.py new file mode 100644 index 0000000..79e3dff --- /dev/null +++ b/backend/query.py @@ -0,0 +1,79 @@ +from openai import OpenAI +from dotenv import load_dotenv +from db import get_collection + +if not load_dotenv(): + print("⚠️ Warning: .env file not found") + +model = "llama3.2" + +# create openai client for local model +client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") + +# connect to chromadb +collection = get_collection() + + +def query_entries(user_question: str) -> str: + """Query the diary entries using RAG and return an AI-generated answer. + + Args: + user_question: The question to ask about emotional patterns + + Returns: + A string response from the AI based on relevant diary entries + """ + n = min(3, collection.count()) + if n == 0: + return "No diary entries found. Record some entries first." + + # ── 1. Retrieve relevant entries from ChromaDB ──────────────────── + results = collection.query(query_texts=[user_question], n_results=n) + documents = results["documents"][0] + metadatas = results["metadatas"][0] + + # ── 2. Build context string ──────────────────────────────────────── + context = "" + for doc, meta in zip(documents, metadatas): + moods = meta.get("moods", "unknown") or "unknown" + tags = meta.get("tags", "none") or "none" + context += ( + f"Date: {meta.get('date', 'unknown')} | Moods: {moods} | Tags: {tags}\n" + ) + context += f"Entry: {doc}\n\n" + + # ── 3. Build prompt ──────────────────────────────────────────────── + prompt = f""" + You are a warm, concise journaling assistant. + Answer in 1-2 sentences maximum. + Always end by asking if the user wants to explore further. + Use only the journal entries below — do not invent details. + + Journal entries: + {context} + + Question: {user_question} + """ + + # ── 4. Send to model and return response ────────────────────────── + response = client.chat.completions.create( + model=model, messages=[{"role": "user", "content": prompt}] + ) + return response.choices[0].message.content + + +if __name__ == "__main__": + # Interactive CLI loop for testing + try: + user_question = input( + "Ask a question about your emotional patterns (q to quit): " + ).strip() + + while True: + if user_question.lower() == "q": + break + + print("\n\n" + query_entries(user_question)) + user_question = input("\nAsk another question (q to quit): ").strip() + finally: + print("Chat ended...") diff --git a/store.py b/backend/store.py similarity index 65% rename from store.py rename to backend/store.py index 0d9d219..5abc49e 100644 --- a/store.py +++ b/backend/store.py @@ -33,17 +33,18 @@ def add_entry(transcript: str, moods: list[MoodTag], tags: list[str]): collection.add(ids=[entry.id], documents=[entry.transcript], metadatas=[metadata]) -# Test voice entry -add_entry( - transcript=( - "Feeling pretty scattered today. Work was overwhelming and I " - "snapped at a colleague over something small. Didn't sleep well " - "last night and skipped lunch which always makes things worse." - ), - moods=[ - MoodTag(name="irritable", intensity=7), - MoodTag(name="anxious", intensity=6), - MoodTag(name="ashamed", intensity=4), - ], - tags=["work", "poor sleep", "skipped meal"], -) +if __name__ == "__main__": + # Test voice entry + add_entry( + transcript=( + "Feeling pretty scattered today. Work was overwhelming and I " + "snapped at a colleague over something small. Didn't sleep well " + "last night and skipped lunch which always makes things worse." + ), + moods=[ + MoodTag(name="irritable", intensity=7), + MoodTag(name="anxious", intensity=6), + MoodTag(name="ashamed", intensity=4), + ], + tags=["work", "poor sleep", "skipped meal"], + ) diff --git a/uv.lock b/backend/uv.lock similarity index 100% rename from uv.lock rename to backend/uv.lock diff --git a/query.py b/query.py deleted file mode 100644 index e3f9ef2..0000000 --- a/query.py +++ /dev/null @@ -1,62 +0,0 @@ -from openai import OpenAI -from dotenv import load_dotenv -from db import get_collection - -if not load_dotenv(): - print("⚠️ Warning: .env file not found") - -model = "llama3.2" - -# create openai client for local model -client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") - -# connect and query chromadb -collection = get_collection() - -# Use a simple loop for now to discuss with your diary entries -try: - user_question = input( - "Ask a question about your emotional patterns (q to quit): " - ).strip() - - while True: - # check if user quitting - if user_question.lower() == "q": - break - - # ── 1. Retrieve relevant entries from ChromaDB ──────────────────── - results = collection.query(query_texts=[user_question], n_results=3) - documents = results["documents"][0] - metadatas = results["metadatas"][0] - - # ── 2. Build context string — prompt built AFTER this loop ──────── - context = "" - for doc, meta in zip(documents, metadatas): - moods = meta.get("moods", "unknown") or "unknown" - tags = meta.get("tags", "none") or "none" - context += ( - f"Date: {meta.get('date', 'unknown')} | Moods: {moods} | Tags: {tags}\n" - ) - context += f"Entry: {doc}\n\n" - - # ── 3. Build prompt once, after all entries are in context ───────── - prompt = f""" - You are a warm, concise journaling assistant. - Answer in 1-2 sentences maximum. - Always end by asking if the user wants to explore further. - Use only the journal entries below — do not invent details. - - Journal entries: - {context} - - Question: {user_question} - """ - - # ── 4. Send to model and print response ─────────────────────────── - response = client.chat.completions.create( - model=model, messages=[{"role": "user", "content": prompt}] - ) - print("\n\n" + response.choices[0].message.content) - user_question = input("\nAsk another question (q to quit): ").strip() -finally: - print("Chat ended...")