diff --git a/src/homeagent/agent/conversation.py b/src/homeagent/agent/conversation.py index 1dc5369..2a8707b 100644 --- a/src/homeagent/agent/conversation.py +++ b/src/homeagent/agent/conversation.py @@ -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 logging import os import tempfile from pathlib import Path from typing import Any, Optional - from google.genai import types logger = logging.getLogger(__name__) 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" - return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json" + suffix = f"thread_{thread_id}" if thread_id is not None else "main" + return data_dir / "sessions" / f"session_{chat_id}_{suffix}.json" 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) - payload = json.dumps(value, ensure_ascii=False, indent=2) - fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) + fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as f: - f.write(payload) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp_name, path) + json.dump(value, f, ensure_ascii=False, indent=2) + f.flush(); os.fsync(f.fileno()) + os.replace(name, path) except Exception: - try: - os.unlink(tmp_name) - except OSError: - pass + try: os.unlink(name) + except OSError: pass raise -def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.""" - 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 +def _part_text(part: Any) -> str: + return str(getattr(part, "text", "") or "") 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: self.data_dir = Path(data_dir).expanduser().resolve() self.max_turns = max_turns self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {} (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]]: - return (chat_id, thread_id) + def _key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]: + return chat_id, thread_id - def _load_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]: - key = self._get_key(chat_id, thread_id) - if key in self._cache: - return self._cache[key] - file_path = _session_file(self.data_dir, chat_id, thread_id) - if not file_path.exists(): - self._cache[key] = [] - return self._cache[key] + def _load(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]: + key = self._key(chat_id, thread_id) + if key in self._cache: return self._cache[key] + path = _session_file(self.data_dir, chat_id, thread_id) + if not path.exists(): self._cache[key] = []; return self._cache[key] try: - with file_path.open("r", encoding="utf-8") as f: - raw_data = json.load(f) + raw = json.loads(path.read_text(encoding="utf-8")) normalized: list[dict[str, Any]] = [] - pending_tool_call_ids: dict[str, list[str]] = {} - for turn_idx, item in enumerate(raw_data): - if "parts" in item: - role = item.get("role", "user") - parts = item.get("parts", []) - if role == "user": - fr_parts = [p for p in parts if "function_response" in p] - if fr_parts: - for p in fr_parts: - fr = p["function_response"] - fn_name = fr.get("name", "tool") - call_id = (pending_tool_call_ids.get(fn_name) or [f"call_{turn_idx}_{fn_name}"]).pop(0) - resp = fr.get("response", {}) - normalized.append({"role": "tool", "tool_call_id": call_id, "name": fn_name, - "content": str(resp.get("result", json.dumps(resp, ensure_ascii=False)))}) - else: - normalized.append({"role": "user", "content": "".join(p.get("text", "") for p in parts)}) - elif role == "model": - fc_parts = [p for p in parts if "function_call" in p] - if fc_parts: - tcs = [] - for idx, p in enumerate(fc_parts): - fc = p["function_call"] - fn_name = fc.get("name", "tool") - call_id = f"call_{turn_idx}_{idx}_{fn_name}" - pending_tool_call_ids.setdefault(fn_name, []).append(call_id) - args = fc.get("args", {}) - tcs.append({"id": call_id, "type": "function", "function": {"name": fn_name, - "arguments": json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else str(args)}}) - normalized.append({"role": "assistant", "content": None, "tool_calls": tcs}) - else: - normalized.append({"role": "assistant", "content": "".join(p.get("text", "") for p in parts)}) - else: - normalized.append(item) + pending: dict[str, list[str]] = {} + for turn, item in enumerate(raw): + if "parts" not in item: + normalized.append(item); continue + role, parts = item.get("role", "user"), item.get("parts", []) + if role == "user": + responses = [p["function_response"] for p in parts if "function_response" in p] + if responses: + for response in responses: + name = response.get("name", "tool") + 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))}) + else: + normalized.append({"role":"user", "content":"".join(p.get("text", "") for p in parts)}) + elif role == "model": + calls = [p["function_call"] for p in parts if "function_call" in p] + if calls: + tool_calls = [] + for idx, call in enumerate(calls): + name = call.get("name", "tool"); call_id = f"call_{turn}_{idx}_{name}" + pending.setdefault(name, []).append(call_id) + args = call.get("args", {}) + tool_calls.append({"id":call_id,"type":"function","function":{ + "name":name,"arguments":json.dumps(args, ensure_ascii=False)}}) + normalized.append({"role":"assistant","content":None,"tool_calls":tool_calls}) + else: + normalized.append({"role":"assistant","content":"".join(p.get("text", "") for p in parts)}) self._cache[key] = normalized - return normalized - except Exception as e: - logger.error("Failed to load session history from %s: %s", file_path, e) + except Exception: + logger.exception("Failed to load session history from %s", path) self._cache[key] = [] - return self._cache[key] + return self._cache[key] - def _save_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> None: - key = self._get_key(chat_id, thread_id) - try: - _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 + 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)]) - # 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