fix: persist memory across Docker restarts #2

Closed
Barsic Bot wants to merge 21 commits from fix/persistent-memory-docker into master
pull from: fix/persistent-memory-docker
Showing only changes of commit 9a7bb3378a - Show all commits
+119 -127
View File
@@ -1,165 +1,157 @@
"""Topic-isolated conversation history management supporting multiple LLM formats.""" """Persistent, topic-isolated conversation history for all LLM providers."""
import json import json
import logging import logging
import os import os
import tempfile import tempfile
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
from google.genai import types from google.genai import types
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def _session_file(data_dir: Path, chat_id: int, thread_id: Optional[int]) -> Path: def _session_file(data_dir: Path, chat_id: int, thread_id: Optional[int]) -> Path:
thread_suffix = f"thread_{thread_id}" if thread_id is not None else "main" suffix = f"thread_{thread_id}" if thread_id is not None else "main"
return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json" return data_dir / "sessions" / f"session_{chat_id}_{suffix}.json"
def _atomic_write_json(path: Path, value: object) -> None: def _atomic_write_json(path: Path, value: object) -> None:
"""Write JSON durably without exposing a partially-written target file."""
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(value, ensure_ascii=False, indent=2) fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
try: try:
with os.fdopen(fd, "w", encoding="utf-8") as f: with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(payload) json.dump(value, f, ensure_ascii=False, indent=2)
f.flush() f.flush(); os.fsync(f.fileno())
os.fsync(f.fileno()) os.replace(name, path)
os.replace(tmp_name, path)
except Exception: except Exception:
try: try: os.unlink(name)
os.unlink(tmp_name) except OSError: pass
except OSError:
pass
raise raise
def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]: def _part_text(part: Any) -> str:
"""Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.""" return str(getattr(part, "text", "") or "")
sanitized: list[dict[str, Any]] = []
i = 0
n = len(raw_messages)
while i < n:
msg = dict(raw_messages[i])
role = msg.get("role")
if role == "tool":
i += 1
continue
if role == "assistant" and msg.get("tool_calls"):
tool_calls = [dict(tc) for tc in msg["tool_calls"]]
j = i + 1
tool_responses: list[dict[str, Any]] = []
while j < n and raw_messages[j].get("role") == "tool":
tool_responses.append(dict(raw_messages[j]))
j += 1
if not tool_responses:
if msg.get("content"):
sanitized.append({"role": "assistant", "content": msg["content"]})
i += 1
continue
if len(tool_calls) == len(tool_responses):
for tc, tr in zip(tool_calls, tool_responses):
tr["tool_call_id"] = tc["id"]
sanitized.append({"role": "assistant", "content": msg.get("content"), "tool_calls": tool_calls})
sanitized.extend(tool_responses)
else:
matched_pairs = []
remaining_responses = list(tool_responses)
for tc in tool_calls:
tc_id = tc.get("id")
tc_name = tc.get("function", {}).get("name")
found_idx = next((idx for idx, tr in enumerate(remaining_responses)
if tr.get("tool_call_id") == tc_id or tr.get("name") == tc_name), None)
if found_idx is not None:
tr = remaining_responses.pop(found_idx)
tr["tool_call_id"] = tc_id
matched_pairs.append((tc, tr))
if matched_pairs:
sanitized.append({"role": "assistant", "content": msg.get("content"),
"tool_calls": [p[0] for p in matched_pairs]})
sanitized.extend(p[1] for p in matched_pairs)
elif msg.get("content"):
sanitized.append({"role": "assistant", "content": msg["content"]})
i = j
continue
sanitized.append(msg)
i += 1
return sanitized
class ConversationManager: class ConversationManager:
"""Manages chat and topic history with disk persistence and multi-provider format support.""" """Stores each chat/topic history in DATA_DIR/sessions on durable storage."""
def __init__(self, data_dir: Path, max_turns: int = 20) -> None: def __init__(self, data_dir: Path, max_turns: int = 20) -> None:
self.data_dir = Path(data_dir).expanduser().resolve() self.data_dir = Path(data_dir).expanduser().resolve()
self.max_turns = max_turns self.max_turns = max_turns
self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {} self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {}
(self.data_dir / "sessions").mkdir(parents=True, exist_ok=True) (self.data_dir / "sessions").mkdir(parents=True, exist_ok=True)
def _get_key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]: def _key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]:
return (chat_id, thread_id) return chat_id, thread_id
def _load_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]: def _load(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
key = self._get_key(chat_id, thread_id) key = self._key(chat_id, thread_id)
if key in self._cache: if key in self._cache: return self._cache[key]
return self._cache[key] path = _session_file(self.data_dir, chat_id, thread_id)
file_path = _session_file(self.data_dir, chat_id, thread_id) if not path.exists(): self._cache[key] = []; return self._cache[key]
if not file_path.exists():
self._cache[key] = []
return self._cache[key]
try: try:
with file_path.open("r", encoding="utf-8") as f: raw = json.loads(path.read_text(encoding="utf-8"))
raw_data = json.load(f)
normalized: list[dict[str, Any]] = [] normalized: list[dict[str, Any]] = []
pending_tool_call_ids: dict[str, list[str]] = {} pending: dict[str, list[str]] = {}
for turn_idx, item in enumerate(raw_data): for turn, item in enumerate(raw):
if "parts" in item: if "parts" not in item:
role = item.get("role", "user") normalized.append(item); continue
parts = item.get("parts", []) role, parts = item.get("role", "user"), item.get("parts", [])
if role == "user": if role == "user":
fr_parts = [p for p in parts if "function_response" in p] responses = [p["function_response"] for p in parts if "function_response" in p]
if fr_parts: if responses:
for p in fr_parts: for response in responses:
fr = p["function_response"] name = response.get("name", "tool")
fn_name = fr.get("name", "tool") ids = pending.get(name, [])
call_id = (pending_tool_call_ids.get(fn_name) or [f"call_{turn_idx}_{fn_name}"]).pop(0) call_id = ids.pop(0) if ids else f"call_{turn}_{name}"
resp = fr.get("response", {}) result = response.get("response", {})
normalized.append({"role": "tool", "tool_call_id": call_id, "name": fn_name, normalized.append({"role":"tool", "tool_call_id":call_id,
"content": str(resp.get("result", json.dumps(resp, ensure_ascii=False)))}) "name":name, "content":str(result.get("result", result))})
else: else:
normalized.append({"role": "user", "content": "".join(p.get("text", "") for p in parts)}) normalized.append({"role":"user", "content":"".join(p.get("text", "") for p in parts)})
elif role == "model": elif role == "model":
fc_parts = [p for p in parts if "function_call" in p] calls = [p["function_call"] for p in parts if "function_call" in p]
if fc_parts: if calls:
tcs = [] tool_calls = []
for idx, p in enumerate(fc_parts): for idx, call in enumerate(calls):
fc = p["function_call"] name = call.get("name", "tool"); call_id = f"call_{turn}_{idx}_{name}"
fn_name = fc.get("name", "tool") pending.setdefault(name, []).append(call_id)
call_id = f"call_{turn_idx}_{idx}_{fn_name}" args = call.get("args", {})
pending_tool_call_ids.setdefault(fn_name, []).append(call_id) tool_calls.append({"id":call_id,"type":"function","function":{
args = fc.get("args", {}) "name":name,"arguments":json.dumps(args, ensure_ascii=False)}})
tcs.append({"id": call_id, "type": "function", "function": {"name": fn_name, normalized.append({"role":"assistant","content":None,"tool_calls":tool_calls})
"arguments": json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else str(args)}}) else:
normalized.append({"role": "assistant", "content": None, "tool_calls": tcs}) normalized.append({"role":"assistant","content":"".join(p.get("text", "") for p in parts)})
else:
normalized.append({"role": "assistant", "content": "".join(p.get("text", "") for p in parts)})
else:
normalized.append(item)
self._cache[key] = normalized self._cache[key] = normalized
return normalized except Exception:
except Exception as e: logger.exception("Failed to load session history from %s", path)
logger.error("Failed to load session history from %s: %s", file_path, e)
self._cache[key] = [] self._cache[key] = []
return self._cache[key] return self._cache[key]
def _save_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> None: def _save(self, chat_id: int, thread_id: Optional[int]) -> None:
key = self._get_key(chat_id, thread_id) _atomic_write_json(_session_file(self.data_dir, chat_id, thread_id),
try: self._cache[self._key(chat_id, thread_id)])
_atomic_write_json(_session_file(self.data_dir, chat_id, thread_id), self._cache.get(key, []))
except OSError as e:
logger.error("Failed to persist session to %s: %s", _session_file(self.data_dir, chat_id, thread_id), e)
raise
# The compatibility and append/clear methods below are unchanged. def _content_to_messages(self, content: types.Content) -> list[dict[str, Any]]:
role = "assistant" if content.role in ("model", "assistant") else "user"
messages: list[dict[str, Any]] = []
text = ""; calls = []
for part in content.parts or []:
if getattr(part, "function_call", None):
call = part.function_call; name = call.name or "tool"
calls.append({"id":f"call_{os.urandom(6).hex()}","type":"function",
"function":{"name":name,"arguments":json.dumps(dict(call.args or {}), ensure_ascii=False)}})
elif getattr(part, "function_response", None):
response = part.function_response; name = response.name or "tool"
value = response.response or {}
messages.append({"role":"tool","name":name,"content":str(value.get("result", value))})
else: text += _part_text(part)
if calls: messages.insert(0, {"role":role,"content":text or None,"tool_calls":calls})
elif text or not messages: messages.insert(0, {"role":role,"content":text})
return messages
def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None:
self._load(chat_id, thread_id).extend(self._content_to_messages(content))
self._trim_and_save(chat_id, thread_id)
def append_turn_sequence(self, chat_id: int, thread_id: Optional[int], contents: list[types.Content]) -> None:
for content in contents: self._load(chat_id, thread_id).extend(self._content_to_messages(content))
self._trim_and_save(chat_id, thread_id)
def _trim_and_save(self, chat_id: int, thread_id: Optional[int]) -> None:
items = self._load(chat_id, thread_id)
# max_turns is a safety bound, while preserving complete recent messages.
if len(items) > self.max_turns * 4: del items[:-self.max_turns * 4]
self._save(chat_id, thread_id)
def get_openai_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
return list(self._load(chat_id, thread_id))
def append_openai_turn_sequence(self, chat_id: int, thread_id: Optional[int], messages: list[dict[str, Any]]) -> None:
self._load(chat_id, thread_id).extend(messages); self._trim_and_save(chat_id, thread_id)
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
result = []
for message in self._load(chat_id, thread_id):
role = message.get("role")
if role == "tool":
result.append(types.Content(role="user", parts=[types.Part.from_function_response(
name=message.get("name", "tool"), response={"result": str(message.get("content", ""))})]))
elif message.get("tool_calls"):
parts = []
for call in message["tool_calls"]:
fn = call.get("function", {}); args = fn.get("arguments", "{}")
try: args = json.loads(args) if isinstance(args, str) else args
except json.JSONDecodeError: args = {}
parts.append(types.Part.from_function_call(name=fn.get("name", "tool"), args=args))
result.append(types.Content(role="model", parts=parts))
else:
result.append(types.Content(role="model" if role == "assistant" else "user",
parts=[types.Part.from_text(text=str(message.get("content", "")))]))
return result
def clear(self, chat_id: int, thread_id: Optional[int]) -> None:
self._cache[self._key(chat_id, thread_id)] = []
path = _session_file(self.data_dir, chat_id, thread_id)
try: path.unlink()
except FileNotFoundError: pass