File size: 1,938 Bytes
59784d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os

from dotenv import load_dotenv
from groq import Groq

load_dotenv()

_client = Groq(api_key=os.getenv("GROQ_API_KEY"))

_SYSTEM_PROMPT = """You are a fact extractor. Analyze the conversation and extract personal facts about the user.

Return ONLY a valid JSON array. Each item must have exactly two keys:
- "type": one of "personal", "preference", "goal", "problem", "context"
- "fact": a short, clear statement written in third person

Rules:
- Only extract facts explicitly stated by the user — do not infer or guess
- Each fact must be self-contained and specific
- If nothing is extractable, return []
- Never include facts about the assistant

Examples of good output:
[
  {"type": "personal", "fact": "user's name is Stefan"},
  {"type": "preference", "fact": "user prefers dark mode"},
  {"type": "goal", "fact": "user wants to become a senior engineer"},
  {"type": "problem", "fact": "user is struggling with time management"},
  {"type": "context", "fact": "user is working on a Python project"}
]"""


def extract_facts(user_message: str, bot_reply: str) -> list[dict]:
    conversation = f"User: {user_message}\nAssistant: {bot_reply}"
    try:
        response = _client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": _SYSTEM_PROMPT},
                {"role": "user", "content": conversation},
            ],
            temperature=0.1,
            max_tokens=512,
        )
        raw = response.choices[0].message.content.strip()

        if raw.startswith("```"):
            raw = raw.split("```")[1]
            if raw.startswith("json"):
                raw = raw[4:]
            raw = raw.strip()

        facts = json.loads(raw)
        if not isinstance(facts, list):
            return []

        return [f for f in facts if "type" in f and "fact" in f]

    except Exception:
        return []