killbizz commited on
Commit
59784d3
·
1 Parent(s): 8549856

feat: Day 1 — memory core and fact extractor

Browse files

- memory.py: ChromaDB persistent store with cosine similarity, add/retrieve/correct/delete operations, deduplication and contradiction candidate detection
- extractor.py: Groq-based fact extraction returning structured JSON with graceful error handling
- test_extractor.py: smoke tests for extraction, storage, retrieval, and deduplication
- requirements.txt: pinned dependencies

Files changed (4) hide show
  1. extractor.py +60 -0
  2. memory.py +121 -0
  3. requirements.txt +5 -0
  4. test_extractor.py +62 -0
extractor.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ from dotenv import load_dotenv
5
+ from groq import Groq
6
+
7
+ load_dotenv()
8
+
9
+ _client = Groq(api_key=os.getenv("GROQ_API_KEY"))
10
+
11
+ _SYSTEM_PROMPT = """You are a fact extractor. Analyze the conversation and extract personal facts about the user.
12
+
13
+ Return ONLY a valid JSON array. Each item must have exactly two keys:
14
+ - "type": one of "personal", "preference", "goal", "problem", "context"
15
+ - "fact": a short, clear statement written in third person
16
+
17
+ Rules:
18
+ - Only extract facts explicitly stated by the user — do not infer or guess
19
+ - Each fact must be self-contained and specific
20
+ - If nothing is extractable, return []
21
+ - Never include facts about the assistant
22
+
23
+ Examples of good output:
24
+ [
25
+ {"type": "personal", "fact": "user's name is Stefan"},
26
+ {"type": "preference", "fact": "user prefers dark mode"},
27
+ {"type": "goal", "fact": "user wants to become a senior engineer"},
28
+ {"type": "problem", "fact": "user is struggling with time management"},
29
+ {"type": "context", "fact": "user is working on a Python project"}
30
+ ]"""
31
+
32
+
33
+ def extract_facts(user_message: str, bot_reply: str) -> list[dict]:
34
+ conversation = f"User: {user_message}\nAssistant: {bot_reply}"
35
+ try:
36
+ response = _client.chat.completions.create(
37
+ model="llama-3.3-70b-versatile",
38
+ messages=[
39
+ {"role": "system", "content": _SYSTEM_PROMPT},
40
+ {"role": "user", "content": conversation},
41
+ ],
42
+ temperature=0.1,
43
+ max_tokens=512,
44
+ )
45
+ raw = response.choices[0].message.content.strip()
46
+
47
+ if raw.startswith("```"):
48
+ raw = raw.split("```")[1]
49
+ if raw.startswith("json"):
50
+ raw = raw[4:]
51
+ raw = raw.strip()
52
+
53
+ facts = json.loads(raw)
54
+ if not isinstance(facts, list):
55
+ return []
56
+
57
+ return [f for f in facts if "type" in f and "fact" in f]
58
+
59
+ except Exception:
60
+ return []
memory.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from datetime import datetime, timezone
3
+
4
+ import chromadb
5
+ from sentence_transformers import SentenceTransformer
6
+
7
+ _model = SentenceTransformer("all-MiniLM-L6-v2")
8
+ _client = chromadb.PersistentClient(path="./chroma_store")
9
+ _collection = _client.get_or_create_collection(
10
+ name="user_memories",
11
+ metadata={"hnsw:space": "cosine"},
12
+ )
13
+
14
+
15
+ def get_embedding(text: str) -> list[float]:
16
+ return _model.encode(text).tolist()
17
+
18
+
19
+ def add_memory(fact: str, metadata: dict) -> str:
20
+ memory_id = str(uuid.uuid4())
21
+ embedding = get_embedding(fact)
22
+ meta = {
23
+ "timestamp": datetime.now(timezone.utc).isoformat(),
24
+ "usage_count": 0,
25
+ "type": metadata.get("type", "general"),
26
+ **metadata,
27
+ }
28
+ _collection.add(
29
+ ids=[memory_id],
30
+ embeddings=[embedding],
31
+ documents=[fact],
32
+ metadatas=[meta],
33
+ )
34
+ return memory_id
35
+
36
+
37
+ def retrieve_relevant(query: str, top_k: int = 5) -> list[dict]:
38
+ count = _collection.count()
39
+ if count == 0:
40
+ return []
41
+ n = min(top_k, count)
42
+ embedding = get_embedding(query)
43
+ results = _collection.query(query_embeddings=[embedding], n_results=n)
44
+ memories = []
45
+ for memory_id, fact, meta in zip(
46
+ results["ids"][0], results["documents"][0], results["metadatas"][0]
47
+ ):
48
+ memories.append({"id": memory_id, "fact": fact, "metadata": meta})
49
+ updated_meta = {**meta, "usage_count": meta.get("usage_count", 0) + 1}
50
+ _collection.update(ids=[memory_id], metadatas=[updated_meta])
51
+ return memories
52
+
53
+
54
+ def get_all_memories() -> list[dict]:
55
+ results = _collection.get()
56
+ memories = [
57
+ {"id": mid, "fact": doc, "metadata": meta}
58
+ for mid, doc, meta in zip(
59
+ results["ids"], results["documents"], results["metadatas"]
60
+ )
61
+ ]
62
+ return sorted(
63
+ memories, key=lambda m: m["metadata"].get("timestamp", ""), reverse=True
64
+ )
65
+
66
+
67
+ def is_duplicate(new_fact: str, threshold: float = 0.92) -> bool:
68
+ if _collection.count() == 0:
69
+ return False
70
+ embedding = get_embedding(new_fact)
71
+ results = _collection.query(query_embeddings=[embedding], n_results=1)
72
+ if not results["distances"][0]:
73
+ return False
74
+ similarity = 1 - results["distances"][0][0]
75
+ return similarity >= threshold
76
+
77
+
78
+ def get_contradiction_candidate(new_fact: str) -> dict | None:
79
+ """Return the closest memory in the 0.75–0.91 similarity range.
80
+ The caller (chatbot.py) decides via LLM whether it's a true contradiction."""
81
+ if _collection.count() == 0:
82
+ return None
83
+ embedding = get_embedding(new_fact)
84
+ results = _collection.query(query_embeddings=[embedding], n_results=1)
85
+ if not results["distances"][0]:
86
+ return None
87
+ distance = results["distances"][0][0]
88
+ similarity = 1 - distance
89
+ if 0.75 <= similarity < 0.92:
90
+ return {
91
+ "id": results["ids"][0][0],
92
+ "fact": results["documents"][0][0],
93
+ "similarity": similarity,
94
+ }
95
+ return None
96
+
97
+
98
+ def correct_memory(old_memory_id: str, new_fact: str) -> None:
99
+ embedding = get_embedding(new_fact)
100
+ existing = _collection.get(ids=[old_memory_id])
101
+ old_meta = existing["metadatas"][0] if existing["metadatas"] else {}
102
+ updated_meta = {
103
+ **old_meta,
104
+ "timestamp": datetime.now(timezone.utc).isoformat(),
105
+ "corrected": True,
106
+ }
107
+ _collection.update(
108
+ ids=[old_memory_id],
109
+ embeddings=[embedding],
110
+ documents=[new_fact],
111
+ metadatas=[updated_meta],
112
+ )
113
+
114
+
115
+ def delete_all_memories() -> None:
116
+ global _collection
117
+ _client.delete_collection("user_memories")
118
+ _collection = _client.get_or_create_collection(
119
+ name="user_memories",
120
+ metadata={"hnsw:space": "cosine"},
121
+ )
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit>=1.32.0
2
+ groq>=0.4.0
3
+ chromadb>=0.5.0
4
+ sentence-transformers>=3.0.0
5
+ python-dotenv>=1.0.0
test_extractor.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quick smoke test for Day 1 — run with: python test_extractor.py"""
2
+ from extractor import extract_facts
3
+ from memory import (
4
+ add_memory,
5
+ delete_all_memories,
6
+ get_all_memories,
7
+ is_duplicate,
8
+ retrieve_relevant,
9
+ )
10
+
11
+
12
+ def test_extraction():
13
+ print("=== Fact Extraction ===")
14
+ facts = extract_facts(
15
+ user_message="Hi, my name is Stefan and I'm a Python developer. I love working with AI.",
16
+ bot_reply="Nice to meet you, Stefan! AI development is fascinating.",
17
+ )
18
+ print(f"Extracted {len(facts)} facts:")
19
+ for f in facts:
20
+ print(f" [{f['type']}] {f['fact']}")
21
+ assert len(facts) > 0, "Extractor returned nothing — check GROQ_API_KEY"
22
+ return facts
23
+
24
+
25
+ def test_memory_store(facts):
26
+ print("\n=== Memory Storage ===")
27
+ delete_all_memories()
28
+ for f in facts:
29
+ mid = add_memory(f["fact"], {"type": f["type"]})
30
+ print(f" Stored: {f['fact']} (id: {mid[:8]}...)")
31
+ all_memories = get_all_memories()
32
+ print(f" Total in DB: {len(all_memories)}")
33
+ assert len(all_memories) == len(facts)
34
+
35
+
36
+ def test_retrieval():
37
+ print("\n=== Semantic Retrieval ===")
38
+ results = retrieve_relevant("what does the user do for work?")
39
+ print(f" Query: 'what does the user do for work?'")
40
+ for r in results:
41
+ print(f" → {r['fact']}")
42
+ assert len(results) > 0
43
+
44
+
45
+ def test_deduplication():
46
+ print("\n=== Deduplication ===")
47
+ dup = is_duplicate("user's name is Stefan")
48
+ print(f" is_duplicate('user's name is Stefan'): {dup} (expected: True)")
49
+
50
+ not_dup = is_duplicate("user lives in Tokyo and loves sushi")
51
+ print(f" is_duplicate('user lives in Tokyo...'): {not_dup} (expected: False)")
52
+
53
+ assert dup is True
54
+ assert not_dup is False
55
+
56
+
57
+ if __name__ == "__main__":
58
+ facts = test_extraction()
59
+ test_memory_store(facts)
60
+ test_retrieval()
61
+ test_deduplication()
62
+ print("\n✓ All Day 1 tests passed")