From 0c0ba74c0957e5fd59df85cc6e3b2812f4d786ee Mon Sep 17 00:00:00 2001 From: ZTatman Date: Wed, 18 Mar 2026 16:30:34 -0400 Subject: [PATCH 1/3] 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...") From 9d4f96e4051028dcc7d386dc15e69cd1380e9b9b Mon Sep 17 00:00:00 2001 From: ZTatman Date: Wed, 18 Mar 2026 18:46:20 -0400 Subject: [PATCH 2/3] refactor: fix import time sideffects in query.py, db.py, organize imports --- .claude/launch.json | 11 ++++++++++- backend/db.py | 13 +++++++++---- backend/main.py | 5 ----- backend/query.py | 29 +++++++++++++++++++---------- backend/store.py | 5 +++-- 5 files changed, 41 insertions(+), 22 deletions(-) diff --git a/.claude/launch.json b/.claude/launch.json index 39769cb..dbd8fde 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -4,7 +4,16 @@ { "name": "FastAPI backend", "runtimeExecutable": "uv", - "runtimeArgs": ["run", "uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"], + "runtimeArgs": [ + "run", + "uvicorn", + "backend.main:app", + "--reload", + "--host", + "0.0.0.0", + "--port", + "8000" + ], "port": 8000 } ] diff --git a/backend/db.py b/backend/db.py index 1a802aa..d07e341 100644 --- a/backend/db.py +++ b/backend/db.py @@ -1,12 +1,17 @@ -import chromadb +from functools import lru_cache from pathlib import Path +import chromadb + _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 +@lru_cache(maxsize=1) +def get_diary_collection(): + """Retrieves diary chromadb collection by either retrieving one that was already created or by creating a new one + + Returns: + A chromadb collection with the name "diary" """ client = chromadb.PersistentClient(_DB_PATH) return client.get_or_create_collection( diff --git a/backend/main.py b/backend/main.py index b11b522..dd9799a 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,8 +1,3 @@ -import openai -import streamlit - - - def main(): print("Hello from nadir!") diff --git a/backend/query.py b/backend/query.py index 79e3dff..815dea4 100644 --- a/backend/query.py +++ b/backend/query.py @@ -1,17 +1,22 @@ -from openai import OpenAI -from dotenv import load_dotenv -from db import get_collection +from functools import lru_cache -if not load_dotenv(): - print("⚠️ Warning: .env file not found") +from db import get_diary_collection +from dotenv import load_dotenv +from openai import OpenAI 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() +@lru_cache(maxsize=1) +def get_openai_client(): + """Loads environement variables and creates a cached OpenAI client. + + Returns: + An OpenAI client + """ + load_dotenv() + client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") + return client def query_entries(user_question: str) -> str: @@ -23,6 +28,10 @@ def query_entries(user_question: str) -> str: Returns: A string response from the AI based on relevant diary entries """ + # create openai client and connect to chromadb + client = get_openai_client() + collection = get_diary_collection() + n = min(3, collection.count()) if n == 0: return "No diary entries found. Record some entries first." @@ -34,7 +43,7 @@ def query_entries(user_question: str) -> str: # ── 2. Build context string ──────────────────────────────────────── context = "" - for doc, meta in zip(documents, metadatas): + for doc, meta in zip(documents, metadatas, strict=True): moods = meta.get("moods", "unknown") or "unknown" tags = meta.get("tags", "none") or "none" context += ( diff --git a/backend/store.py b/backend/store.py index 5abc49e..235335a 100644 --- a/backend/store.py +++ b/backend/store.py @@ -1,11 +1,12 @@ import uuid from datetime import datetime -from db import get_collection +from db import get_diary_collection from models import JournalEntry, MoodTag + # from pydantic import BaseModel -collection = get_collection() +collection = get_diary_collection() def add_entry(transcript: str, moods: list[MoodTag], tags: list[str]): From 6fdf8f67ddc6522dca44aa3bd7b9cb61332763e1 Mon Sep 17 00:00:00 2001 From: Zach Tatman Date: Wed, 18 Mar 2026 23:02:34 -0400 Subject: [PATCH 3/3] Update backend/query.py Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- backend/query.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/query.py b/backend/query.py index 815dea4..b434199 100644 --- a/backend/query.py +++ b/backend/query.py @@ -65,11 +65,14 @@ def query_entries(user_question: str) -> str: """ # ── 4. Send to model and return response ────────────────────────── - response = client.chat.completions.create( +try: + response = client.with_options(timeout=30.0).chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}] ) - return response.choices[0].message.content +except (APITimeoutError, APIConnectionError): + return "I couldn't reach the local model right now. Please try again." +return (response.choices[0].message.content or "").strip() if __name__ == "__main__": # Interactive CLI loop for testing