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 <noreply@anthropic.com>
This commit is contained in:
ZTatman 2026-03-18 16:30:34 -04:00
parent 47fa83d441
commit 0c0ba74c09
11 changed files with 109 additions and 77 deletions

11
.claude/launch.json Normal file
View file

@ -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
}
]
}

View file

@ -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"}
)

79
backend/query.py Normal file
View file

@ -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...")

View file

@ -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"],
)

View file

View file

@ -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...")