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 d0ed244294 - Show all commits
+43 -14
View File
@@ -29,6 +29,41 @@ def _atomic_write_json(path: Path, value: object) -> None:
raise
def _sanitize_openai_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Remove incomplete tool-call chains before sending history to OpenAI APIs."""
result: list[dict[str, Any]] = []
i = 0
while i < len(messages):
message = dict(messages[i])
if message.get("role") == "tool":
i += 1
continue
calls = message.get("tool_calls") if message.get("role") == "assistant" else None
if not calls:
result.append(message); i += 1; continue
following: list[dict[str, Any]] = []
j = i + 1
while j < len(messages) and messages[j].get("role") == "tool":
following.append(dict(messages[j])); j += 1
by_name = {item.get("name"): item for item in following}
valid_calls: list[dict[str, Any]] = []
valid_tools: list[dict[str, Any]] = []
for call in calls:
fn = call.get("function", {})
tool = next((item for item in following if item.get("tool_call_id") == call.get("id")
or item.get("name") == fn.get("name")), None)
if tool is not None:
tool = dict(tool); tool["tool_call_id"] = call.get("id")
valid_calls.append(dict(call)); valid_tools.append(tool)
if valid_calls:
message["tool_calls"] = valid_calls
result.append(message); result.extend(valid_tools)
elif message.get("content"):
result.append({"role": "assistant", "content": message["content"]})
i = j
return result
def _part_text(part: Any) -> str:
return str(getattr(part, "text", "") or "")
@@ -65,8 +100,8 @@ class ConversationManager:
ids = pending.get(name, [])
call_id = ids.pop(0) if ids else f"call_{turn}_{name}"
result = response.get("response", {})
normalized.append({"role":"tool", "tool_call_id":call_id,
"name":name, "content":str(result.get("result", result))})
normalized.append({"role":"tool", "tool_call_id":call_id, "name":name,
"content":str(result.get("result", result))})
else:
normalized.append({"role":"user", "content":"".join(p.get("text", "") for p in parts)})
elif role == "model":
@@ -89,21 +124,18 @@ class ConversationManager:
return self._cache[key]
def _save(self, chat_id: int, thread_id: Optional[int]) -> None:
_atomic_write_json(_session_file(self.data_dir, chat_id, thread_id),
self._cache[self._key(chat_id, thread_id)])
_atomic_write_json(_session_file(self.data_dir, chat_id, thread_id), self._cache[self._key(chat_id, thread_id)])
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 = []
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 {}
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})
@@ -111,8 +143,7 @@ class ConversationManager:
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)
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))
@@ -120,12 +151,11 @@ class ConversationManager:
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))
return _sanitize_openai_messages(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)
@@ -152,6 +182,5 @@ class ConversationManager:
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()
try: _session_file(self.data_dir, chat_id, thread_id).unlink()
except FileNotFoundError: pass