Spaces:
Sleeping
Sleeping
feat: chat logic with memory retrieval, prompt building, and contradiction detection
Browse files- chatbot.py +123 -0
chatbot.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from groq import Groq
|
| 5 |
+
|
| 6 |
+
from extractor import extract_facts
|
| 7 |
+
from memory import (
|
| 8 |
+
add_memory,
|
| 9 |
+
correct_memory,
|
| 10 |
+
get_contradiction_candidate,
|
| 11 |
+
is_duplicate,
|
| 12 |
+
retrieve_relevant,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 18 |
+
_MODEL = "llama-3.3-70b-versatile"
|
| 19 |
+
_MAX_HISTORY_TURNS = 10
|
| 20 |
+
|
| 21 |
+
_CONTRADICTION_PROMPT = """You are a fact checker. Do these two facts directly contradict each other?
|
| 22 |
+
|
| 23 |
+
Fact A: {fact_a}
|
| 24 |
+
Fact B: {fact_b}
|
| 25 |
+
|
| 26 |
+
Reply with only YES or NO."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def call_llm(messages: list[dict]) -> str:
|
| 30 |
+
response = _client.chat.completions.create(
|
| 31 |
+
model=_MODEL,
|
| 32 |
+
messages=messages,
|
| 33 |
+
temperature=0.7,
|
| 34 |
+
max_tokens=1024,
|
| 35 |
+
)
|
| 36 |
+
return response.choices[0].message.content.strip()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_system_prompt(memories: list[dict]) -> str:
|
| 40 |
+
base = "You are a helpful, friendly assistant with long-term memory.\n\n"
|
| 41 |
+
if not memories:
|
| 42 |
+
return base + "You don't know anything about this user yet. Learn from the conversation."
|
| 43 |
+
memory_lines = "\n".join(f"{i + 1}. {m['fact']}" for i, m in enumerate(memories))
|
| 44 |
+
return (
|
| 45 |
+
base
|
| 46 |
+
+ "Here is what you remember about this user:\n"
|
| 47 |
+
+ memory_lines
|
| 48 |
+
+ "\n\nUse this context naturally — don't recite it back, just let it inform your responses. "
|
| 49 |
+
+ "If the user corrects something you remembered, acknowledge it naturally."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_messages(
|
| 54 |
+
system_prompt: str, chat_history: list[dict], user_message: str
|
| 55 |
+
) -> list[dict]:
|
| 56 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 57 |
+
trimmed = chat_history[-(_MAX_HISTORY_TURNS * 2):]
|
| 58 |
+
messages.extend(trimmed)
|
| 59 |
+
messages.append({"role": "user", "content": user_message})
|
| 60 |
+
return messages
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _is_contradiction(fact_a: str, fact_b: str) -> bool:
|
| 64 |
+
try:
|
| 65 |
+
response = _client.chat.completions.create(
|
| 66 |
+
model=_MODEL,
|
| 67 |
+
messages=[
|
| 68 |
+
{
|
| 69 |
+
"role": "user",
|
| 70 |
+
"content": _CONTRADICTION_PROMPT.format(
|
| 71 |
+
fact_a=fact_a, fact_b=fact_b
|
| 72 |
+
),
|
| 73 |
+
}
|
| 74 |
+
],
|
| 75 |
+
temperature=0,
|
| 76 |
+
max_tokens=5,
|
| 77 |
+
)
|
| 78 |
+
return response.choices[0].message.content.strip().upper().startswith("YES")
|
| 79 |
+
except Exception:
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _process_new_facts(user_message: str, bot_reply: str) -> None:
|
| 84 |
+
facts = extract_facts(user_message, bot_reply)
|
| 85 |
+
for fact_data in facts:
|
| 86 |
+
fact = fact_data["fact"]
|
| 87 |
+
if is_duplicate(fact):
|
| 88 |
+
continue
|
| 89 |
+
candidate = get_contradiction_candidate(fact)
|
| 90 |
+
if candidate and _is_contradiction(candidate["fact"], fact):
|
| 91 |
+
correct_memory(candidate["id"], fact)
|
| 92 |
+
else:
|
| 93 |
+
add_memory(fact, {"type": fact_data.get("type", "general")})
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def chat(user_message: str, chat_history: list[dict]) -> tuple[str, list[str]]:
|
| 97 |
+
memories = retrieve_relevant(user_message)
|
| 98 |
+
used_ids = [m["id"] for m in memories]
|
| 99 |
+
|
| 100 |
+
system_prompt = build_system_prompt(memories)
|
| 101 |
+
messages = build_messages(system_prompt, chat_history, user_message)
|
| 102 |
+
|
| 103 |
+
bot_reply = call_llm(messages)
|
| 104 |
+
_process_new_facts(user_message, bot_reply)
|
| 105 |
+
|
| 106 |
+
return bot_reply, used_ids
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
print("MemoryMind — quick chat test (type 'quit' to exit)\n")
|
| 111 |
+
history = []
|
| 112 |
+
while True:
|
| 113 |
+
user_input = input("You: ").strip()
|
| 114 |
+
if user_input.lower() == "quit":
|
| 115 |
+
break
|
| 116 |
+
reply, used = chat(user_input, history)
|
| 117 |
+
history.append({"role": "user", "content": user_input})
|
| 118 |
+
history.append({"role": "assistant", "content": reply})
|
| 119 |
+
print(f"Bot: {reply}")
|
| 120 |
+
if used:
|
| 121 |
+
print(f" [used {len(used)} memories]\n")
|
| 122 |
+
else:
|
| 123 |
+
print()
|