File size: 2,429 Bytes
fbb4123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Write and read path for beliefs, plus the reasoning assembly.

The write path follows the plan: extract claims, classify volatility/source,
search for similar beliefs, judge agreement/contradiction, then store.
v2 keeps the deterministic store as the source of truth; a real LLM core plugs
into `core` without touching this path.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from .belief_store import BeliefStore
from .config import INITIAL_CONFIDENCE, RETRIEVE_K
from .core import Core, RuleCore
from .tools import Calculator, FileLookup, SandboxRun


class Memory:
    """Belief store + reasoning loop (read + write)."""

    def __init__(self, path: str = ":memory:"):
        self.store = BeliefStore(path)
        self.core = RuleCore()

    # -- write path -------------------------------------------------------
    def learn(
        self,
        claim: str,
        subject: Optional[str] = None,
        predicate: Optional[str] = None,
        obj: Optional[str] = None,
        source_type: str = "user",
        source_ref: Optional[str] = None,
        confidence: Optional[float] = None,
        volatility: Optional[str] = None,
    ) -> int:
        return self.store.learn(claim, subject, predicate, obj, source_type,
                                source_ref, confidence, volatility)

    def learn_many(self, facts: List[Dict[str, Any]]):
        for f in facts:
            self.store.learn(f["claim"], f.get("subject"), f.get("predicate"),
                             f.get("obj"), f.get("source_type"), f.get("source_ref"),
                             f.get("confidence"), f.get("volatility"))
        return self.size()

    def size(self) -> int:
        return self.store.count_active()

    # -- read path --------------------------------------------------------
    def retrieve(self, question: str, k: int = RETRIEVE_K) -> List[Dict[str, Any]]:
        return self.store.retrieve(question, k=k)

    # -- loop -------------------------------------------------------------
    def ask(self, question: str, tools=None) -> dict:
        return self.core.ask(question, self.store, tools or [])

    def forget(self, query: str, k: int = 10) -> int:
        return self.store.forget(query, k=k)

    def expiry_sweep(self) -> List[int]:
        return self.store.expiry_sweep()

    def cleanup(self, cap: int = 10000):
        self.store.cleanup(cap=cap)