File size: 1,134 Bytes
6df4ebe
a8426e5
6df4ebe
a8426e5
6df4ebe
 
a8426e5
 
 
 
 
 
 
 
6df4ebe
a8426e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from openai import OpenAI

_client = None


def _get_client():
    global _client
    if _client is None:
        api_key = os.getenv("OPENAI_API_KEY")
        if not api_key:
            raise RuntimeError("OPENAI_API_KEY is not set in the environment.")
        _client = OpenAI(api_key=api_key)
    return _client


def generate_answer(question: str, contexts):
    contexts = contexts or []
    context_block = "\n".join(f"- {c}" for c in contexts) or "No stored memories yet."

    system = (
        "You are MnemoSense, an external memory assistant. "
        "Answer questions **only** using the provided memories. "
        "If the answer is not present, say you don't know."
    )

    client = _get_client()
    resp = client.chat.completions.create(
        model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
        messages=[
            {"role": "system", "content": system},
            {
                "role": "user",
                "content": f"Memories:\n{context_block}\n\nQuestion: {question}",
            },
        ],
        temperature=0.3,
    )
    return resp.choices[0].message.content.strip()