File size: 4,615 Bytes
d6c1f0b
 
59784d3
 
 
d6c1f0b
4428b01
d6c1f0b
 
59784d3
d6c1f0b
 
4428b01
d6c1f0b
 
 
 
 
 
 
 
 
f37d148
 
d6c1f0b
 
 
 
 
 
f37d148
59784d3
 
 
4428b01
59784d3
 
f37d148
d6c1f0b
 
59784d3
86bc4c2
d6c1f0b
 
86bc4c2
 
59784d3
86bc4c2
59784d3
 
d6c1f0b
 
 
59784d3
 
 
 
f37d148
d6c1f0b
 
 
59784d3
 
d6c1f0b
 
 
 
 
 
59784d3
86bc4c2
d6c1f0b
 
 
 
86bc4c2
 
 
 
d6c1f0b
 
59784d3
 
 
f37d148
d6c1f0b
 
 
59784d3
d6c1f0b
 
59784d3
d6c1f0b
59784d3
 
f37d148
d6c1f0b
 
 
59784d3
d6c1f0b
 
59784d3
 
f37d148
d6c1f0b
 
 
59784d3
d6c1f0b
 
 
 
 
 
 
59784d3
d6c1f0b
 
 
59784d3
 
 
f37d148
d6c1f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59784d3
 
 
f37d148
d6c1f0b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import os
import re
import uuid
from datetime import datetime, timezone

from dotenv import load_dotenv
from fastembed import TextEmbedding
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, PointStruct, VectorParams

load_dotenv()

_model = TextEmbedding("BAAI/bge-small-en-v1.5")
_EMBEDDING_DIM = 384
_client = QdrantClient(
    url=os.getenv("QDRANT_CLUSTER_ENDPOINT"),
    api_key=os.getenv("QDRANT_API_KEY"),
)


def _col(user_id: str) -> str:
    return "user_" + re.sub(r"[^a-z0-9]", "_", user_id.lower())


def _ensure_collection(name: str) -> None:
    existing = {c.name for c in _client.get_collections().collections}
    if name not in existing:
        _client.create_collection(
            collection_name=name,
            vectors_config=VectorParams(size=_EMBEDDING_DIM, distance=Distance.COSINE),
        )


def get_embedding(text: str) -> list[float]:
    return list(list(_model.embed([text]))[0])


def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
    col = _col(user_id)
    _ensure_collection(col)
    memory_id = str(uuid.uuid4())
    now = datetime.now(timezone.utc).isoformat()
    payload = {
        "fact": fact,
        "timestamp": now,
        "last_used": now,
        "usage_count": 0,
        "confidence": 1,
        "type": metadata.get("type", "general"),
    }
    _client.upsert(
        collection_name=col,
        points=[PointStruct(id=memory_id, vector=get_embedding(fact), payload=payload)],
    )
    return memory_id


def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> list[dict]:
    col = _col(user_id)
    _ensure_collection(col)
    count = _client.get_collection(col).points_count
    if count == 0:
        return []
    response = _client.query_points(
        collection_name=col,
        query=get_embedding(query),
        limit=min(top_k, count),
        with_payload=True,
    )
    memories = []
    now = datetime.now(timezone.utc).isoformat()
    for hit in response.points:
        memories.append({"id": hit.id, "fact": hit.payload["fact"], "metadata": hit.payload})
        _client.set_payload(
            collection_name=col,
            payload={
                "usage_count": hit.payload.get("usage_count", 0) + 1,
                "last_used": now,
            },
            points=[hit.id],
        )
    return memories


def get_all_memories(user_id: str = "guest") -> list[dict]:
    col = _col(user_id)
    _ensure_collection(col)
    points, _ = _client.scroll(collection_name=col, limit=500, with_payload=True)
    memories = [
        {"id": str(p.id), "fact": p.payload["fact"], "metadata": p.payload}
        for p in points
    ]
    return sorted(memories, key=lambda m: m["metadata"].get("timestamp", ""), reverse=True)


def is_duplicate(new_fact: str, user_id: str = "guest", threshold: float = 0.92) -> bool:
    col = _col(user_id)
    _ensure_collection(col)
    if _client.get_collection(col).points_count == 0:
        return False
    response = _client.query_points(collection_name=col, query=get_embedding(new_fact), limit=1)
    return bool(response.points) and response.points[0].score >= threshold


def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
    col = _col(user_id)
    _ensure_collection(col)
    if _client.get_collection(col).points_count == 0:
        return None
    response = _client.query_points(
        collection_name=col,
        query=get_embedding(new_fact),
        limit=1,
        with_payload=True,
    )
    if not response.points:
        return None
    hit = response.points[0]
    if 0.75 <= hit.score < 0.92:
        return {"id": str(hit.id), "fact": hit.payload["fact"], "similarity": hit.score}
    return None


def correct_memory(old_memory_id: str, new_fact: str, user_id: str = "guest") -> None:
    col = _col(user_id)
    existing = _client.retrieve(collection_name=col, ids=[old_memory_id], with_payload=True)
    old_payload = existing[0].payload if existing else {}
    _client.upsert(
        collection_name=col,
        points=[
            PointStruct(
                id=old_memory_id,
                vector=get_embedding(new_fact),
                payload={
                    **old_payload,
                    "fact": new_fact,
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                    "corrected": True,
                },
            )
        ],
    )


def delete_all_memories(user_id: str = "guest") -> None:
    try:
        _client.delete_collection(_col(user_id))
    except Exception:
        pass