Vineetha00 commited on
Commit
a8426e5
·
verified ·
1 Parent(s): 74d1e21

Update llm.py

Browse files
Files changed (1) hide show
  1. llm.py +34 -34
llm.py CHANGED
@@ -1,39 +1,39 @@
1
  import os
2
- from typing import List
3
- from summarize import mmr_summarize
4
 
5
- def _join(ctxs: List[str], max_chars=4000) -> str:
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 openai_answer(question: str, contexts: List[str]) -> str:
21
- try:
22
- from openai import OpenAI
23
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
24
- model = os.getenv("OPENAI_MODEL","gpt-4o-mini")
25
- system = "You are MnemoSense. Answer using ONLY the provided context. If insufficient, say you don't know."
26
- user = f"Context:\n{_join(contexts)}\n\nQuestion: {question}"
27
- resp = client.chat.completions.create(
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
- def answer(question: str, contexts: List[str]) -> str:
37
- if os.getenv("OPENAI_API_KEY"):
38
- return openai_answer(question, contexts)
39
- return local_answer(question, contexts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()