Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
107 lines
3.7 KiB
Python
107 lines
3.7 KiB
Python
"""Short-lived chat context. No filesystem, database or network access."""
|
|
import time
|
|
|
|
CHAT_MEMORY_LIMIT = 10
|
|
MEM_CHAR_BUDGET = 24000
|
|
_CHAT_MEMORY = {}
|
|
_CHAT_MEMORY_TTL = 3600
|
|
_CHAT_MEMORY_USERS = 1000
|
|
|
|
# [FILES 2310] прикреплённый файл живёт в том же коротком in-memory контексте:
|
|
# без БД и файловой системы, умирает вместе с процессом и по TTL.
|
|
FILE_CHAR_BUDGET = 16000
|
|
_FILE_TTL = 3600
|
|
_FILE_USERS = 500
|
|
_FILES = {} # uid -> (ts, name, kind, text)
|
|
|
|
|
|
def _memory_expire():
|
|
now = time.monotonic()
|
|
for uid, (ts, _) in list(_CHAT_MEMORY.items()):
|
|
if now - ts >= _CHAT_MEMORY_TTL:
|
|
_CHAT_MEMORY.pop(uid, None)
|
|
|
|
|
|
def mem_add(uid, role, content):
|
|
if role not in ("user", "assistant") or not isinstance(content, str) or not content.strip():
|
|
return
|
|
_memory_expire()
|
|
if uid not in _CHAT_MEMORY and len(_CHAT_MEMORY) >= _CHAT_MEMORY_USERS:
|
|
_CHAT_MEMORY.pop(min(_CHAT_MEMORY, key=lambda key: _CHAT_MEMORY[key][0]))
|
|
messages = _CHAT_MEMORY.get(uid, (0, []))[1]
|
|
messages.append({"role": role, "content": content[:4000]})
|
|
del messages[:-CHAT_MEMORY_LIMIT]
|
|
_CHAT_MEMORY[uid] = (time.monotonic(), messages)
|
|
|
|
|
|
def mem_load(uid, n=CHAT_MEMORY_LIMIT, budget=MEM_CHAR_BUDGET):
|
|
_memory_expire()
|
|
if n <= 0:
|
|
return []
|
|
messages = _CHAT_MEMORY.get(uid, (0, []))[1][-min(n, CHAT_MEMORY_LIMIT):]
|
|
result, total = [], 0
|
|
for message in reversed(messages):
|
|
size = len(message["content"])
|
|
if budget is not None and total + size > budget:
|
|
break
|
|
result.append(dict(message))
|
|
total += size
|
|
return list(reversed(result))
|
|
|
|
|
|
def _file_expire():
|
|
now = time.monotonic()
|
|
for uid, entry in list(_FILES.items()):
|
|
if now - entry[0] >= _FILE_TTL:
|
|
_FILES.pop(uid, None)
|
|
|
|
|
|
def file_attach(uid, name, kind, text):
|
|
"""Положить извлечённый текст файла в контекст юзера. Пустой текст игнорируется."""
|
|
if not isinstance(text, str) or not text.strip():
|
|
return False
|
|
_file_expire()
|
|
if uid not in _FILES and len(_FILES) >= _FILE_USERS:
|
|
_FILES.pop(min(_FILES, key=lambda key: _FILES[key][0]))
|
|
body = text.strip()
|
|
truncated = len(body) > FILE_CHAR_BUDGET
|
|
if truncated:
|
|
body = body[:FILE_CHAR_BUDGET].rstrip() + "\n[…обрезано по бюджету контекста]"
|
|
_FILES[uid] = (time.monotonic(), str(name)[:120], str(kind)[:20], body)
|
|
return True
|
|
|
|
|
|
def file_context(uid):
|
|
"""Сообщение с содержимым файла для вставки в msgs, либо пустой список."""
|
|
_file_expire()
|
|
entry = _FILES.get(uid)
|
|
if not entry:
|
|
return []
|
|
_, name, kind, body = entry
|
|
head = f"[Прикреплённый файл {name} ({kind or 'текст'}) — учитывай его содержимое в ответе]"
|
|
return [{"role": "user", "content": f"{head}\n{body}"}]
|
|
|
|
|
|
def file_info(uid):
|
|
"""Сведения о прикреплённом файле: name/kind/chars/age_sec, либо None."""
|
|
_file_expire()
|
|
entry = _FILES.get(uid)
|
|
if not entry:
|
|
return None
|
|
ts, name, kind, body = entry
|
|
return {"name": name, "kind": kind, "chars": len(body),
|
|
"age_sec": int(time.monotonic() - ts)}
|
|
|
|
|
|
def file_clear(uid):
|
|
_FILES.pop(uid, None)
|
|
|
|
|
|
def mem_count(uid):
|
|
return len(mem_load(uid, budget=None))
|
|
|
|
|
|
def clear_memory(uid):
|
|
_CHAT_MEMORY.pop(uid, None)
|
|
file_clear(uid)
|