File size: 4,000 Bytes
b1bcead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f37d148
b1bcead
 
 
f37d148
b1bcead
f37d148
b1bcead
f37d148
b1bcead
f37d148
b1bcead
 
f37d148
 
 
 
b1bcead
 
 
 
 
 
f37d148
b1bcead
 
 
 
 
f37d148
 
b1bcead
 
 
 
 
f37d148
b1bcead
 
 
 
 
 
 
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
import os

from dotenv import load_dotenv
from groq import Groq

from extractor import extract_facts
from memory import (
    add_memory,
    correct_memory,
    get_contradiction_candidate,
    is_duplicate,
    retrieve_relevant,
)

load_dotenv()

_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
_MODEL = "llama-3.3-70b-versatile"
_MAX_HISTORY_TURNS = 10

_CONTRADICTION_PROMPT = """You are a fact checker. Do these two facts directly contradict each other?

Fact A: {fact_a}
Fact B: {fact_b}

Reply with only YES or NO."""


def call_llm(messages: list[dict]) -> str:
    response = _client.chat.completions.create(
        model=_MODEL,
        messages=messages,
        temperature=0.7,
        max_tokens=1024,
    )
    return response.choices[0].message.content.strip()


def build_system_prompt(memories: list[dict]) -> str:
    base = "You are a helpful, friendly assistant with long-term memory.\n\n"
    if not memories:
        return base + "You don't know anything about this user yet. Learn from the conversation."
    memory_lines = "\n".join(f"{i + 1}. {m['fact']}" for i, m in enumerate(memories))
    return (
        base
        + "Here is what you remember about this user:\n"
        + memory_lines
        + "\n\nUse this context naturally — don't recite it back, just let it inform your responses. "
        + "If the user corrects something you remembered, acknowledge it naturally."
    )


def build_messages(
    system_prompt: str, chat_history: list[dict], user_message: str
) -> list[dict]:
    messages = [{"role": "system", "content": system_prompt}]
    trimmed = chat_history[-(_MAX_HISTORY_TURNS * 2):]
    messages.extend(trimmed)
    messages.append({"role": "user", "content": user_message})
    return messages


def _is_contradiction(fact_a: str, fact_b: str) -> bool:
    try:
        response = _client.chat.completions.create(
            model=_MODEL,
            messages=[
                {
                    "role": "user",
                    "content": _CONTRADICTION_PROMPT.format(
                        fact_a=fact_a, fact_b=fact_b
                    ),
                }
            ],
            temperature=0,
            max_tokens=5,
        )
        return response.choices[0].message.content.strip().upper().startswith("YES")
    except Exception:
        return False


def _process_new_facts(user_message: str, bot_reply: str, user_id: str) -> None:
    facts = extract_facts(user_message, bot_reply)
    for fact_data in facts:
        fact = fact_data["fact"]
        if is_duplicate(fact, user_id=user_id):
            continue
        candidate = get_contradiction_candidate(fact, user_id=user_id)
        if candidate and _is_contradiction(candidate["fact"], fact):
            correct_memory(candidate["id"], fact, user_id=user_id)
        else:
            add_memory(fact, {"type": fact_data.get("type", "general")}, user_id=user_id)


def chat(
    user_message: str, chat_history: list[dict], user_id: str = "guest"
) -> tuple[str, list[str]]:
    memories = retrieve_relevant(user_message, user_id=user_id)
    used_ids = [m["id"] for m in memories]

    system_prompt = build_system_prompt(memories)
    messages = build_messages(system_prompt, chat_history, user_message)

    bot_reply = call_llm(messages)
    _process_new_facts(user_message, bot_reply, user_id=user_id)

    return bot_reply, used_ids


if __name__ == "__main__":
    uid = input("Your username: ").strip() or "guest"
    print(f"Chatting as '{uid}' — type 'quit' to exit\n")
    history = []
    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == "quit":
            break
        reply, used = chat(user_input, history, user_id=uid)
        history.append({"role": "user", "content": user_input})
        history.append({"role": "assistant", "content": reply})
        print(f"Bot: {reply}")
        if used:
            print(f"     [used {len(used)} memories]\n")
        else:
            print()