Spaces:
Sleeping
Sleeping
Update llm.py
Browse files
llm.py
CHANGED
|
@@ -1,39 +1,39 @@
|
|
| 1 |
import os
|
| 2 |
-
from
|
| 3 |
-
from summarize import mmr_summarize
|
| 4 |
|
| 5 |
-
|
| 6 |
-
out, used = [], 0
|
| 7 |
-
for c in (ctxs or []):
|
| 8 |
-
c = (c or "").strip()
|
| 9 |
-
if not c: continue
|
| 10 |
-
if used + len(c) > max_chars: break
|
| 11 |
-
out.append(c); used += len(c)
|
| 12 |
-
return "\n\n".join(out) if out else "(no context)"
|
| 13 |
|
| 14 |
-
def local_answer(question: str, contexts: List[str]) -> str:
|
| 15 |
-
ctx = _join(contexts, 3000)
|
| 16 |
-
if not ctx or ctx == "(no context)":
|
| 17 |
-
return "I don't have enough information yet."
|
| 18 |
-
return mmr_summarize(ctx, max_sentences=4)
|
| 19 |
|
| 20 |
-
def
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
model=model,
|
| 29 |
-
messages=[{"role":"system","content":system},{"role":"user","content":user}],
|
| 30 |
-
temperature=0.2,
|
| 31 |
-
)
|
| 32 |
-
return resp.choices[0].message.content.strip()
|
| 33 |
-
except Exception:
|
| 34 |
-
return "(local) " + local_answer(question, contexts)
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from openai import OpenAI
|
|
|
|
| 3 |
|
| 4 |
+
_client = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
def _get_client():
|
| 8 |
+
global _client
|
| 9 |
+
if _client is None:
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
if not api_key:
|
| 12 |
+
raise RuntimeError("OPENAI_API_KEY is not set in the environment.")
|
| 13 |
+
_client = OpenAI(api_key=api_key)
|
| 14 |
+
return _client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
|
| 17 |
+
def generate_answer(question: str, contexts):
|
| 18 |
+
contexts = contexts or []
|
| 19 |
+
context_block = "\n".join(f"- {c}" for c in contexts) or "No stored memories yet."
|
| 20 |
+
|
| 21 |
+
system = (
|
| 22 |
+
"You are MnemoSense, an external memory assistant. "
|
| 23 |
+
"Answer questions **only** using the provided memories. "
|
| 24 |
+
"If the answer is not present, say you don't know."
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
client = _get_client()
|
| 28 |
+
resp = client.chat.completions.create(
|
| 29 |
+
model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
|
| 30 |
+
messages=[
|
| 31 |
+
{"role": "system", "content": system},
|
| 32 |
+
{
|
| 33 |
+
"role": "user",
|
| 34 |
+
"content": f"Memories:\n{context_block}\n\nQuestion: {question}",
|
| 35 |
+
},
|
| 36 |
+
],
|
| 37 |
+
temperature=0.3,
|
| 38 |
+
)
|
| 39 |
+
return resp.choices[0].message.content.strip()
|