diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..dbd8fde --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,20 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "FastAPI backend", + "runtimeExecutable": "uv", + "runtimeArgs": [ + "run", + "uvicorn", + "backend.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/backend/db.py b/backend/db.py new file mode 100644 index 0000000..d07e341 --- /dev/null +++ b/backend/db.py @@ -0,0 +1,19 @@ +from functools import lru_cache +from pathlib import Path + +import chromadb + +_DB_PATH = str(Path(__file__).parent / "chroma_db") + + +@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( + name="diary", metadata={"hnsw:space": "cosine"} + ) diff --git a/main.py b/backend/main.py similarity index 70% rename from main.py rename to backend/main.py index b11b522..dd9799a 100644 --- a/main.py +++ b/backend/main.py @@ -1,8 +1,3 @@ -import openai -import streamlit - - - def main(): print("Hello from nadir!") 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..b434199 --- /dev/null +++ b/backend/query.py @@ -0,0 +1,91 @@ +from functools import lru_cache + +from db import get_diary_collection +from dotenv import load_dotenv +from openai import OpenAI + +model = "llama3.2" + + +@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: + """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 + """ + # 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." + + # ── 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, strict=True): + 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 ────────────────────────── +try: + response = client.with_options(timeout=30.0).chat.completions.create( + model=model, messages=[{"role": "user", "content": prompt}] + ) +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 + 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 61% rename from store.py rename to backend/store.py index 0d9d219..235335a 100644 --- a/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]): @@ -33,17 +34,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/db.py b/db.py deleted file mode 100644 index af7e2a2..0000000 --- a/db.py +++ /dev/null @@ -1,11 +0,0 @@ -import chromadb - - -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") - return client.get_or_create_collection( - name="diary", metadata={"hnsw:space": "cosine"} - ) 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...")