mirror of
https://github.com/ZTatman/Nadir.git
synced 2026-11-22 04:47:58 +00:00
Merge pull request #2 from ZTatman/feat/phase-1-backend-restructure
Restructure into backend/ and fix module import side effects
This commit is contained in:
commit
d31c28b0ea
12 changed files with 148 additions and 94 deletions
20
.claude/launch.json
Normal file
20
.claude/launch.json
Normal file
|
|
@ -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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
19
backend/db.py
Normal file
19
backend/db.py
Normal file
|
|
@ -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"}
|
||||||
|
)
|
||||||
|
|
@ -1,8 +1,3 @@
|
||||||
import openai
|
|
||||||
import streamlit
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("Hello from nadir!")
|
print("Hello from nadir!")
|
||||||
|
|
||||||
91
backend/query.py
Normal file
91
backend/query.py
Normal file
|
|
@ -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...")
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from db import get_collection
|
from db import get_diary_collection
|
||||||
from models import JournalEntry, MoodTag
|
from models import JournalEntry, MoodTag
|
||||||
|
|
||||||
# from pydantic import BaseModel
|
# from pydantic import BaseModel
|
||||||
|
|
||||||
collection = get_collection()
|
collection = get_diary_collection()
|
||||||
|
|
||||||
|
|
||||||
def add_entry(transcript: str, moods: list[MoodTag], tags: list[str]):
|
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])
|
collection.add(ids=[entry.id], documents=[entry.transcript], metadatas=[metadata])
|
||||||
|
|
||||||
|
|
||||||
# Test voice entry
|
if __name__ == "__main__":
|
||||||
add_entry(
|
# Test voice entry
|
||||||
transcript=(
|
add_entry(
|
||||||
"Feeling pretty scattered today. Work was overwhelming and I "
|
transcript=(
|
||||||
"snapped at a colleague over something small. Didn't sleep well "
|
"Feeling pretty scattered today. Work was overwhelming and I "
|
||||||
"last night and skipped lunch which always makes things worse."
|
"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),
|
moods=[
|
||||||
MoodTag(name="anxious", intensity=6),
|
MoodTag(name="irritable", intensity=7),
|
||||||
MoodTag(name="ashamed", intensity=4),
|
MoodTag(name="anxious", intensity=6),
|
||||||
],
|
MoodTag(name="ashamed", intensity=4),
|
||||||
tags=["work", "poor sleep", "skipped meal"],
|
],
|
||||||
)
|
tags=["work", "poor sleep", "skipped meal"],
|
||||||
|
)
|
||||||
0
uv.lock → backend/uv.lock
generated
0
uv.lock → backend/uv.lock
generated
11
db.py
11
db.py
|
|
@ -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"}
|
|
||||||
)
|
|
||||||
62
query.py
62
query.py
|
|
@ -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...")
|
|
||||||
Loading…
Add table
Reference in a new issue