memorymind / chatbot.py
killbizz's picture
feat: multi-user memory namespacing and FastAPI backend
f37d148
Raw History Blame Contribute Delete
4 kB
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()