Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16a3dcb6ca | ||
|
|
89f617d62b | ||
|
|
bc3ecbdcfb | ||
|
|
aeadee8b0e | ||
|
|
447fc56e2d | ||
|
|
a49ec32948 | ||
|
|
27ffbef0c5 | ||
|
|
ddd999c938 | ||
|
|
d0ed244294 | ||
|
|
85e4411496 | ||
|
|
264095255d | ||
|
|
a588bec86f | ||
|
|
de95f36df6 | ||
|
|
cc385be9cf | ||
|
|
870b3ffec4 | ||
|
|
6031fa4fd0 | ||
|
|
9a7bb3378a | ||
|
|
346187ab19 | ||
|
|
fc2275ca06 | ||
|
|
d449fd6905 | ||
|
|
ca647d2298 |
No files matched your search
+3
-1
@@ -8,6 +8,9 @@ services:
|
|||||||
init: true
|
init: true
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
|
environment:
|
||||||
|
# Keep every persistence-aware component on the mounted host directory.
|
||||||
|
DATA_DIR: /app/data
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
# Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal
|
# Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
@@ -21,4 +24,3 @@ services:
|
|||||||
# Uncomment to mount credentials files if placed in project root:
|
# Uncomment to mount credentials files if placed in project root:
|
||||||
# - ./service_account.json:/app/service_account.json:ro
|
# - ./service_account.json:/app/service_account.json:ro
|
||||||
# - ./credentials.json:/app/credentials.json:ro
|
# - ./credentials.json:/app/credentials.json:ro
|
||||||
# - ./gcal.json:/app/gcal.json:ro
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Docker persistence runbook
|
||||||
|
|
||||||
|
The bot stores all runtime state under `DATA_DIR`:
|
||||||
|
|
||||||
|
- `data/global_memory.json` — global facts and preferences;
|
||||||
|
- `data/sessions/` — topic conversation histories;
|
||||||
|
- `data/calendar_token.json` — OAuth refresh token when used.
|
||||||
|
|
||||||
|
`docker-compose.yml` explicitly sets `DATA_DIR=/app/data` and mounts `./data:/app/data`. Do not use `docker compose down -v` as a substitute for a backup: named volumes are not used by this compose file, but the host `data/` directory must be kept.
|
||||||
|
|
||||||
|
## Safe upgrade
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p data
|
||||||
|
cp -a data "data.backup.$(date +%Y%m%d-%H%M%S)"
|
||||||
|
git pull
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
If the old container contained the only copy of the state, copy it before removing that container:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker cp homeagent:/app/data/. ./data/
|
||||||
|
```
|
||||||
|
|
||||||
|
Check that the files are visible from the new container:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec homeagent sh -lc 'printf "DATA_DIR=%s\\n" "$DATA_DIR"; ls -la /app/data; test -f /app/data/global_memory.json && head -c 1 /app/data/global_memory.json'
|
||||||
|
```
|
||||||
|
|
||||||
|
A previous `No space left on device` error can still prevent persistence. Check the host before deployment:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
df -h .
|
||||||
|
docker system df
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not delete Docker data or the host `data/` directory until a backup has been verified.
|
||||||
+145
-350
@@ -1,391 +1,186 @@
|
|||||||
"""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 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 _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
def _atomic_write_json(path: Path, value: object) -> None:
|
||||||
"""Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(value, f, ensure_ascii=False, indent=2)
|
||||||
|
f.flush(); os.fsync(f.fileno())
|
||||||
|
os.replace(name, path)
|
||||||
|
except Exception:
|
||||||
|
try: os.unlink(name)
|
||||||
|
except OSError: pass
|
||||||
|
raise
|
||||||
|
|
||||||
Ensures that:
|
|
||||||
1. Every assistant message with tool_calls is immediately followed by tool messages for ALL tool_call_ids.
|
def _sanitize_openai_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
2. Tool responses matching call IDs are properly aligned.
|
"""Remove incomplete tool-call chains before sending history to OpenAI APIs."""
|
||||||
3. Dangling tool calls or orphan tool messages are safely cleaned up.
|
result: list[dict[str, Any]] = []
|
||||||
"""
|
|
||||||
sanitized: list[dict[str, Any]] = []
|
|
||||||
i = 0
|
i = 0
|
||||||
n = len(raw_messages)
|
while i < len(messages):
|
||||||
|
message = dict(messages[i])
|
||||||
while i < n:
|
if message.get("role") == "tool":
|
||||||
msg = dict(raw_messages[i])
|
|
||||||
role = msg.get("role")
|
|
||||||
|
|
||||||
if role == "tool":
|
|
||||||
# Orphan tool response without preceding assistant tool_calls -> drop it
|
|
||||||
i += 1
|
i += 1
|
||||||
continue
|
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
|
||||||
|
|
||||||
if role == "assistant" and msg.get("tool_calls"):
|
|
||||||
tool_calls = [dict(tc) for tc in msg["tool_calls"]]
|
|
||||||
# Look ahead for following tool messages
|
|
||||||
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:
|
def _part_text(part: Any) -> str:
|
||||||
# No tool responses followed this assistant message!
|
return str(getattr(part, "text", "") or "")
|
||||||
# Strip tool_calls to prevent API 400 error.
|
|
||||||
if msg.get("content"):
|
|
||||||
sanitized.append({"role": "assistant", "content": msg["content"]})
|
|
||||||
i += 1
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Ensure 1-to-1 matching tool_call_id
|
|
||||||
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:
|
|
||||||
# Different counts: match by name or existing ID
|
|
||||||
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 = None
|
|
||||||
for idx, tr in enumerate(remaining_responses):
|
|
||||||
if tr.get("tool_call_id") == tc_id or tr.get("name") == tc_name:
|
|
||||||
found_idx = idx
|
|
||||||
break
|
|
||||||
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:
|
|
||||||
valid_tool_calls = [pair[0] for pair in matched_pairs]
|
|
||||||
valid_tool_responses = [pair[1] for pair in matched_pairs]
|
|
||||||
sanitized.append({
|
|
||||||
"role": "assistant",
|
|
||||||
"content": msg.get("content"),
|
|
||||||
"tool_calls": valid_tool_calls,
|
|
||||||
})
|
|
||||||
sanitized.extend(valid_tool_responses)
|
|
||||||
elif msg.get("content"):
|
|
||||||
sanitized.append({"role": "assistant", "content": msg["content"]})
|
|
||||||
|
|
||||||
i = j
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Normal user or assistant message
|
|
||||||
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 = data_dir
|
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]]:
|
|
||||||
"""Load and normalize messages from disk into universal dictionary format."""
|
|
||||||
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:
|
try:
|
||||||
with open(file_path, "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, item in enumerate(raw):
|
||||||
for turn_idx, item in enumerate(raw_data):
|
if "parts" not in item:
|
||||||
# 1. Check if legacy Gemini format with "parts"
|
normalized.append(item); continue
|
||||||
if "parts" in item:
|
role, parts = item.get("role", "user"), item.get("parts", [])
|
||||||
role = item.get("role", "user")
|
if role == "user":
|
||||||
parts = item.get("parts", [])
|
responses = [p["function_response"] for p in parts if "function_response" in p]
|
||||||
if role == "user":
|
if responses:
|
||||||
# Check for function_response
|
for response in responses:
|
||||||
fr_parts = [p for p in parts if "function_response" in p]
|
name = response.get("name", "tool")
|
||||||
if fr_parts:
|
ids = pending.get(name, [])
|
||||||
for p in fr_parts:
|
call_id = ids.pop(0) if ids else f"call_{turn}_{name}"
|
||||||
fr = p["function_response"]
|
result = response.get("response", {})
|
||||||
fn_name = fr.get("name", "tool")
|
normalized.append({"role":"tool", "tool_call_id":call_id, "name":name,
|
||||||
if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]:
|
"content":str(result.get("result", result))})
|
||||||
call_id = pending_tool_call_ids[fn_name].pop(0)
|
else:
|
||||||
else:
|
normalized.append({"role":"user", "content":"".join(p.get("text", "") for p in parts)})
|
||||||
call_id = f"call_{turn_idx}_{fn_name}"
|
elif role == "model":
|
||||||
|
calls = [p["function_call"] for p in parts if "function_call" in p]
|
||||||
resp = fr.get("response", {})
|
if calls:
|
||||||
res_val = resp.get("result", json.dumps(resp, ensure_ascii=False))
|
tool_calls = []
|
||||||
normalized.append({
|
for idx, call in enumerate(calls):
|
||||||
"role": "tool",
|
name = call.get("name", "tool"); call_id = f"call_{turn}_{idx}_{name}"
|
||||||
"tool_call_id": call_id,
|
pending.setdefault(name, []).append(call_id)
|
||||||
"name": fn_name,
|
args = call.get("args", {})
|
||||||
"content": str(res_val),
|
tool_calls.append({"id":call_id,"type":"function","function":{
|
||||||
})
|
"name":name,"arguments":json.dumps(args, ensure_ascii=False)}})
|
||||||
else:
|
normalized.append({"role":"assistant","content":None,"tool_calls":tool_calls})
|
||||||
text = "".join(p.get("text", "") for p in parts)
|
else:
|
||||||
normalized.append({"role": "user", "content": text})
|
normalized.append({"role":"assistant","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:
|
|
||||||
text = "".join(p.get("text", "") for p in parts)
|
|
||||||
normalized.append({"role": "assistant", "content": text})
|
|
||||||
else:
|
|
||||||
# 2. Already normalized message format
|
|
||||||
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), self._cache[self._key(chat_id, thread_id)])
|
||||||
messages = self._cache.get(key, [])
|
|
||||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
|
||||||
|
|
||||||
try:
|
def _content_to_messages(self, content: types.Content) -> list[dict[str, Any]]:
|
||||||
with open(file_path, "w", encoding="utf-8") as f:
|
role = "assistant" if content.role in ("model", "assistant") else "user"
|
||||||
json.dump(messages, f, ensure_ascii=False, indent=2)
|
messages: list[dict[str, Any]] = []; text = ""; calls = []
|
||||||
except Exception as e:
|
for part in content.parts or []:
|
||||||
logger.error("Failed to persist session to %s: %s", file_path, e)
|
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",
|
||||||
# Gemini Compatibility API
|
"function":{"name":name,"arguments":json.dumps(dict(call.args or {}), ensure_ascii=False)}})
|
||||||
# --------------------------------------------------------------------------
|
elif getattr(part, "function_response", None):
|
||||||
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
response = part.function_response; name = response.name or "tool"; value = response.response or {}
|
||||||
"""Retrieve conversation history converted into Gemini types.Content objects."""
|
messages.append({"role":"tool","name":name,"content":str(value.get("result", value))})
|
||||||
messages = self._load_raw_messages(chat_id, thread_id)
|
else: text += _part_text(part)
|
||||||
gemini_history: list[types.Content] = []
|
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})
|
||||||
for msg in messages:
|
return messages
|
||||||
role = msg.get("role", "user")
|
|
||||||
content = msg.get("content")
|
|
||||||
tool_calls = msg.get("tool_calls")
|
|
||||||
|
|
||||||
if role == "user":
|
|
||||||
gemini_history.append(
|
|
||||||
types.Content(
|
|
||||||
role="user",
|
|
||||||
parts=[types.Part.from_text(text=str(content or ""))],
|
|
||||||
)
|
|
||||||
)
|
|
||||||
elif role == "assistant":
|
|
||||||
if tool_calls:
|
|
||||||
parts = []
|
|
||||||
for tc in tool_calls:
|
|
||||||
fn = tc.get("function", {})
|
|
||||||
fn_name = fn.get("name", "")
|
|
||||||
raw_args = fn.get("arguments", "{}")
|
|
||||||
if isinstance(raw_args, str):
|
|
||||||
try:
|
|
||||||
args = json.loads(raw_args)
|
|
||||||
except Exception:
|
|
||||||
args = {}
|
|
||||||
elif isinstance(raw_args, dict):
|
|
||||||
args = raw_args
|
|
||||||
else:
|
|
||||||
args = {}
|
|
||||||
parts.append(types.Part.from_function_call(name=fn_name, args=args))
|
|
||||||
gemini_history.append(types.Content(role="model", parts=parts))
|
|
||||||
else:
|
|
||||||
gemini_history.append(
|
|
||||||
types.Content(
|
|
||||||
role="model",
|
|
||||||
parts=[types.Part.from_text(text=str(content or ""))],
|
|
||||||
)
|
|
||||||
)
|
|
||||||
elif role == "tool":
|
|
||||||
tool_name = msg.get("name") or "tool"
|
|
||||||
gemini_history.append(
|
|
||||||
types.Content(
|
|
||||||
role="user",
|
|
||||||
parts=[
|
|
||||||
types.Part.from_function_response(
|
|
||||||
name=tool_name,
|
|
||||||
response={"result": str(content or "")},
|
|
||||||
)
|
|
||||||
],
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return gemini_history
|
|
||||||
|
|
||||||
def append_turn_sequence(
|
|
||||||
self, chat_id: int, thread_id: Optional[int], contents: list[types.Content]
|
|
||||||
) -> None:
|
|
||||||
"""Append multiple Gemini types.Content objects to conversation history."""
|
|
||||||
key = self._get_key(chat_id, thread_id)
|
|
||||||
messages = self._load_raw_messages(chat_id, thread_id)
|
|
||||||
pending_tool_call_ids: dict[str, list[str]] = {}
|
|
||||||
|
|
||||||
for content in contents:
|
|
||||||
role = content.role
|
|
||||||
parts = content.parts or []
|
|
||||||
if role == "user":
|
|
||||||
fr_parts = [p for p in parts if p.function_response]
|
|
||||||
if fr_parts:
|
|
||||||
for p in fr_parts:
|
|
||||||
fr = p.function_response
|
|
||||||
fn_name = fr.name
|
|
||||||
if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]:
|
|
||||||
call_id = pending_tool_call_ids[fn_name].pop(0)
|
|
||||||
else:
|
|
||||||
call_id = f"call_{len(messages)}_{fn_name}"
|
|
||||||
|
|
||||||
resp = dict(fr.response) if fr.response else {}
|
|
||||||
res_val = resp.get("result", json.dumps(resp, ensure_ascii=False))
|
|
||||||
messages.append({
|
|
||||||
"role": "tool",
|
|
||||||
"tool_call_id": call_id,
|
|
||||||
"name": fn_name,
|
|
||||||
"content": str(res_val),
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
text = "".join(p.text for p in parts if p.text)
|
|
||||||
messages.append({"role": "user", "content": text})
|
|
||||||
elif role == "model":
|
|
||||||
fc_parts = [p for p in parts if p.function_call]
|
|
||||||
if fc_parts:
|
|
||||||
tcs = []
|
|
||||||
for idx, p in enumerate(fc_parts):
|
|
||||||
fc = p.function_call
|
|
||||||
fn_name = fc.name
|
|
||||||
call_id = f"call_{len(messages)}_{idx}_{fn_name}"
|
|
||||||
pending_tool_call_ids.setdefault(fn_name, []).append(call_id)
|
|
||||||
args = dict(fc.args) if fc.args else {}
|
|
||||||
tcs.append({
|
|
||||||
"id": call_id,
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": fn_name,
|
|
||||||
"arguments": json.dumps(args, ensure_ascii=False),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
messages.append({"role": "assistant", "content": None, "tool_calls": tcs})
|
|
||||||
else:
|
|
||||||
text = "".join(p.text for p in parts if p.text)
|
|
||||||
messages.append({"role": "assistant", "content": text})
|
|
||||||
|
|
||||||
if len(messages) > self.max_turns * 2:
|
|
||||||
messages = messages[-self.max_turns * 2 :]
|
|
||||||
|
|
||||||
self._cache[key] = messages
|
|
||||||
self._save_raw_messages(chat_id, thread_id)
|
|
||||||
|
|
||||||
def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None:
|
def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None:
|
||||||
"""Add a single content turn (Gemini compatibility)."""
|
self._load(chat_id, thread_id).extend(self._content_to_messages(content)); self._trim_and_save(chat_id, thread_id)
|
||||||
self.append_turn_sequence(chat_id, thread_id, [content])
|
|
||||||
|
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)
|
||||||
|
if len(items) > self.max_turns * 4: del items[:-self.max_turns * 4]
|
||||||
|
self._save(chat_id, thread_id)
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# OpenAI / DeepSeek Compatibility API
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def get_openai_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
def get_openai_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
||||||
"""Retrieve conversation history in sanitized standard OpenAI messages list format."""
|
return _sanitize_openai_messages(list(self._load(chat_id, thread_id)))
|
||||||
raw_messages = self._load_raw_messages(chat_id, thread_id)
|
|
||||||
openai_msgs: list[dict[str, Any]] = []
|
|
||||||
|
|
||||||
for msg in raw_messages:
|
def append_openai_turn_sequence(self, chat_id: int, thread_id: Optional[int], messages: list[dict[str, Any]]) -> None:
|
||||||
role = msg.get("role", "user")
|
self._load(chat_id, thread_id).extend(messages); self._trim_and_save(chat_id, thread_id)
|
||||||
out: dict[str, Any] = {"role": role}
|
|
||||||
|
|
||||||
if role == "user":
|
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
||||||
out["content"] = str(msg.get("content") or "")
|
result = []
|
||||||
elif role == "assistant":
|
for message in self._load(chat_id, thread_id):
|
||||||
out["content"] = msg.get("content")
|
role = message.get("role")
|
||||||
if msg.get("tool_calls"):
|
if role == "tool":
|
||||||
out["tool_calls"] = msg["tool_calls"]
|
result.append(types.Content(role="user", parts=[types.Part.from_function_response(
|
||||||
elif role == "tool":
|
name=message.get("name", "tool"), response={"result": str(message.get("content", ""))})]))
|
||||||
out["tool_call_id"] = msg.get("tool_call_id", "call_default")
|
elif message.get("tool_calls"):
|
||||||
out["name"] = msg.get("name", "tool")
|
parts = []
|
||||||
out["content"] = str(msg.get("content") or "")
|
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
|
||||||
|
|
||||||
openai_msgs.append(out)
|
|
||||||
|
|
||||||
# Apply strict DeepSeek/OpenAI tool call chain sanitizer
|
|
||||||
sanitized = _sanitize_openai_messages(openai_msgs)
|
|
||||||
return sanitized
|
|
||||||
|
|
||||||
def append_openai_turn_sequence(
|
|
||||||
self, chat_id: int, thread_id: Optional[int], new_messages: list[dict[str, Any]]
|
|
||||||
) -> None:
|
|
||||||
"""Append messages generated in an OpenAI-compatible turn sequence."""
|
|
||||||
key = self._get_key(chat_id, thread_id)
|
|
||||||
messages = self._load_raw_messages(chat_id, thread_id)
|
|
||||||
|
|
||||||
for m in new_messages:
|
|
||||||
if m.get("role") == "system":
|
|
||||||
continue
|
|
||||||
messages.append(m)
|
|
||||||
|
|
||||||
if len(messages) > self.max_turns * 2:
|
|
||||||
messages = messages[-self.max_turns * 2 :]
|
|
||||||
|
|
||||||
self._cache[key] = messages
|
|
||||||
self._save_raw_messages(chat_id, thread_id)
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# Common Utilities
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def clear(self, chat_id: int, thread_id: Optional[int]) -> None:
|
def clear(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||||
"""Clear the history for this topic."""
|
self._cache[self._key(chat_id, thread_id)] = []
|
||||||
key = self._get_key(chat_id, thread_id)
|
try: _session_file(self.data_dir, chat_id, thread_id).unlink()
|
||||||
self._cache[key] = []
|
except FileNotFoundError: pass
|
||||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
|
||||||
if file_path.exists():
|
|
||||||
file_path.unlink()
|
|
||||||
logger.info("Cleared conversation history for chat=%s, thread=%s", chat_id, thread_id)
|
|
||||||
+26
-127
@@ -19,154 +19,53 @@ logger = logging.getLogger(__name__)
|
|||||||
class GeminiAgent(BaseAgent):
|
class GeminiAgent(BaseAgent):
|
||||||
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, settings=None, registry=None, conversation_manager=None):
|
||||||
self,
|
|
||||||
settings: Optional[Settings] = None,
|
|
||||||
registry: Optional[ToolRegistry] = None,
|
|
||||||
conversation_manager: Optional[ConversationManager] = None,
|
|
||||||
) -> None:
|
|
||||||
self.settings = settings or get_settings()
|
self.settings = settings or get_settings()
|
||||||
self.registry = registry or get_tool_registry()
|
self.registry = registry or get_tool_registry()
|
||||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||||
|
|
||||||
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
||||||
self._client: Optional[genai.Client] = None
|
self._client = genai.Client(api_key=api_key) if api_key else None
|
||||||
if api_key:
|
if not api_key: logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
||||||
self._client = genai.Client(api_key=api_key)
|
|
||||||
else:
|
|
||||||
logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
|
||||||
|
|
||||||
def _build_system_instruction(self) -> str:
|
def _build_system_instruction(self) -> str:
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||||
memory_summary = get_global_memory().get_memory_summary()
|
memory = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
||||||
|
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, dt_context, memory]))
|
||||||
|
|
||||||
parts = [
|
def _get_tools_config(self):
|
||||||
self.settings.SYSTEM_INSTRUCTION,
|
|
||||||
dt_context,
|
|
||||||
]
|
|
||||||
if memory_summary:
|
|
||||||
parts.append(memory_summary)
|
|
||||||
|
|
||||||
return "\n\n".join(parts)
|
|
||||||
|
|
||||||
def _get_tools_config(self) -> Optional[list[types.Tool]]:
|
|
||||||
declarations = self.registry.get_function_declarations()
|
declarations = self.registry.get_function_declarations()
|
||||||
if not declarations:
|
return [types.Tool(function_declarations=declarations)] if declarations else None
|
||||||
return None
|
|
||||||
return [types.Tool(function_declarations=declarations)]
|
|
||||||
|
|
||||||
async def chat(
|
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 8, on_progress=None) -> str:
|
||||||
self,
|
|
||||||
chat_id: int,
|
|
||||||
thread_id: Optional[int],
|
|
||||||
user_message: str,
|
|
||||||
max_tool_iterations: int = 8,
|
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
|
||||||
) -> str:
|
|
||||||
"""Process a user message within the topic context, running tools as requested by Gemini."""
|
|
||||||
if not self._client:
|
if not self._client:
|
||||||
return (
|
return "⚠️ **Google AI Studio API Key не настроен.**\nПожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота."
|
||||||
"⚠️ **Google AI Studio API Key не настроен.**\n"
|
|
||||||
"Пожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота.\n"
|
|
||||||
"Получить ключ можно бесплатно в [Google AI Studio](https://aistudio.google.com/)."
|
|
||||||
)
|
|
||||||
|
|
||||||
# 1. Fetch current conversation history
|
|
||||||
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
||||||
|
user_content = types.Content(role="user", parts=[types.Part.from_text(text=user_message)])
|
||||||
# 2. Add current user message
|
|
||||||
user_content = types.Content(
|
|
||||||
role="user",
|
|
||||||
parts=[types.Part.from_text(text=user_message)],
|
|
||||||
)
|
|
||||||
history.append(user_content)
|
history.append(user_content)
|
||||||
|
turn_contents = [user_content]
|
||||||
turn_contents: list[types.Content] = [user_content]
|
config = types.GenerateContentConfig(system_instruction=self._build_system_instruction(), tools=self._get_tools_config(), temperature=0.4)
|
||||||
system_instruction = self._build_system_instruction()
|
|
||||||
tools_config = self._get_tools_config()
|
|
||||||
|
|
||||||
config = types.GenerateContentConfig(
|
|
||||||
system_instruction=system_instruction,
|
|
||||||
tools=tools_config,
|
|
||||||
temperature=0.4,
|
|
||||||
)
|
|
||||||
|
|
||||||
for iteration in range(max_tool_iterations):
|
for iteration in range(max_tool_iterations):
|
||||||
logger.debug(
|
if on_progress: await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||||
"Gemini request turn: chat=%d, thread=%s, iteration=%d, history_len=%d",
|
|
||||||
chat_id,
|
|
||||||
thread_id,
|
|
||||||
iteration,
|
|
||||||
len(history),
|
|
||||||
)
|
|
||||||
|
|
||||||
if on_progress:
|
|
||||||
if iteration == 0:
|
|
||||||
await on_progress("🤔 Формирую ответ...")
|
|
||||||
else:
|
|
||||||
await on_progress(f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await self._client.aio.models.generate_content(
|
response = await self._client.aio.models.generate_content(model=self.settings.GEMINI_MODEL, contents=history, config=config)
|
||||||
model=self.settings.GEMINI_MODEL,
|
|
||||||
contents=history,
|
|
||||||
config=config,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error calling Gemini API: %s", e)
|
logger.exception("Error calling Gemini API: %s", e)
|
||||||
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
||||||
|
if not response.function_calls:
|
||||||
# Check if model requested function calls
|
|
||||||
function_calls = response.function_calls
|
|
||||||
if not function_calls:
|
|
||||||
# Final response reached
|
|
||||||
final_text = response.text or "*(Пустой ответ)*"
|
final_text = response.text or "*(Пустой ответ)*"
|
||||||
model_content = types.Content(
|
turn_contents.append(types.Content(role="model", parts=[types.Part.from_text(text=final_text)]))
|
||||||
role="model",
|
|
||||||
parts=[types.Part.from_text(text=final_text)],
|
|
||||||
)
|
|
||||||
turn_contents.append(model_content)
|
|
||||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||||
return final_text
|
return final_text
|
||||||
|
|
||||||
# Model produced function calls
|
|
||||||
# Save the model's message with function calls
|
|
||||||
candidate = response.candidates[0] if response.candidates else None
|
candidate = response.candidates[0] if response.candidates else None
|
||||||
model_parts = candidate.content.parts if (candidate and candidate.content) else []
|
model_content = types.Content(role="model", parts=candidate.content.parts if candidate and candidate.content else [])
|
||||||
model_content = types.Content(role="model", parts=model_parts)
|
history.append(model_content); turn_contents.append(model_content)
|
||||||
history.append(model_content)
|
response_parts = []
|
||||||
turn_contents.append(model_content)
|
for fc in response.function_calls:
|
||||||
|
result = await self.registry.execute(fc.name, dict(fc.args) if fc.args else {})
|
||||||
# Execute all function calls requested by the model in this step
|
response_parts.append(types.Part.from_function_response(name=fc.name, response={"result": result}))
|
||||||
response_parts: list[types.Part] = []
|
tool_content = types.Content(role="user", parts=response_parts)
|
||||||
for idx, fc in enumerate(function_calls, 1):
|
history.append(tool_content); turn_contents.append(tool_content)
|
||||||
fc_name = fc.name
|
warning = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||||
fc_args = dict(fc.args) if fc.args else {}
|
|
||||||
|
|
||||||
if on_progress:
|
|
||||||
from homeagent.bot.progress import format_tool_progress
|
|
||||||
|
|
||||||
step_info = f"[{idx}/{len(function_calls)}] " if len(function_calls) > 1 else ""
|
|
||||||
desc = format_tool_progress(fc_name, fc_args)
|
|
||||||
await on_progress(f"⏳ {step_info}{desc}")
|
|
||||||
|
|
||||||
logger.info("Executing function call: %s(%s)", fc_name, fc_args)
|
|
||||||
tool_result = await self.registry.execute(fc_name, fc_args)
|
|
||||||
|
|
||||||
response_parts.append(
|
|
||||||
types.Part.from_function_response(
|
|
||||||
name=fc_name,
|
|
||||||
response={"result": tool_result},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
tool_response_content = types.Content(role="user", parts=response_parts)
|
|
||||||
history.append(tool_response_content)
|
|
||||||
turn_contents.append(tool_response_content)
|
|
||||||
|
|
||||||
# If exceeded max iterations, return warning
|
|
||||||
warning_msg = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
|
||||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||||
return warning_msg
|
return warning
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""OpenAI-compatible Agent supporting DeepSeek, OpenRouter, Ollama, and OpenAI."""
|
"""OpenAI-compatible Agent supporting DeepSeek and OpenAI APIs."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -18,200 +18,74 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class OpenAIAgent(BaseAgent):
|
class OpenAIAgent(BaseAgent):
|
||||||
"""Agent orchestrator for DeepSeek and OpenAI-compatible models."""
|
def __init__(self, settings=None, registry=None, conversation_manager=None, provider_override=None):
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
settings: Optional[Settings] = None,
|
|
||||||
registry: Optional[ToolRegistry] = None,
|
|
||||||
conversation_manager: Optional[ConversationManager] = None,
|
|
||||||
provider_override: Optional[str] = None,
|
|
||||||
) -> None:
|
|
||||||
self.settings = settings or get_settings()
|
self.settings = settings or get_settings()
|
||||||
self.registry = registry or get_tool_registry()
|
self.registry = registry or get_tool_registry()
|
||||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||||
self.provider = provider_override or self.settings.LLM_PROVIDER
|
self.provider = provider_override or self.settings.LLM_PROVIDER
|
||||||
|
|
||||||
# Resolve configuration based on provider
|
|
||||||
if self.provider == "deepseek":
|
if self.provider == "deepseek":
|
||||||
api_key_secret = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
key = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
||||||
self.api_key = api_key_secret.get_secret_value() if api_key_secret else ""
|
|
||||||
self.base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
self.base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
||||||
self.model = self.settings.DEEPSEEK_MODEL or "deepseek-chat"
|
self.model = self.settings.DEEPSEEK_MODEL or "deepseek-chat"
|
||||||
else:
|
else:
|
||||||
api_key_secret = self.settings.OPENAI_API_KEY
|
key = self.settings.OPENAI_API_KEY
|
||||||
self.api_key = api_key_secret.get_secret_value() if api_key_secret else ""
|
|
||||||
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
||||||
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
|
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
|
||||||
|
self.api_key = key.get_secret_value() if key else ""
|
||||||
self._client: Optional[AsyncOpenAI] = None
|
self._client: Optional[AsyncOpenAI] = AsyncOpenAI(
|
||||||
if self.api_key:
|
api_key=self.api_key, base_url=self.base_url, timeout=60.0
|
||||||
self._client = AsyncOpenAI(
|
) if self.api_key else None
|
||||||
api_key=self.api_key,
|
|
||||||
base_url=self.base_url,
|
|
||||||
timeout=60.0,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.warning(
|
|
||||||
"API key for %s is not set. OpenAIAgent will return configuration prompt.",
|
|
||||||
self.provider.upper(),
|
|
||||||
)
|
|
||||||
|
|
||||||
def _build_system_instruction(self) -> str:
|
def _build_system_instruction(self) -> str:
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||||
memory_summary = get_global_memory().get_memory_summary()
|
memory = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
||||||
|
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, context, memory]))
|
||||||
|
|
||||||
parts = [
|
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 100, on_progress: Optional[Callable[[str], Awaitable[None]]] = None) -> str:
|
||||||
self.settings.SYSTEM_INSTRUCTION,
|
|
||||||
dt_context,
|
|
||||||
]
|
|
||||||
if memory_summary:
|
|
||||||
parts.append(memory_summary)
|
|
||||||
|
|
||||||
return "\n\n".join(parts)
|
|
||||||
|
|
||||||
async def chat(
|
|
||||||
self,
|
|
||||||
chat_id: int,
|
|
||||||
thread_id: Optional[int],
|
|
||||||
user_message: str,
|
|
||||||
max_tool_iterations: int = 100,
|
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
|
||||||
) -> str:
|
|
||||||
"""Process user message within topic context using DeepSeek / OpenAI API."""
|
|
||||||
if not self._client:
|
if not self._client:
|
||||||
if self.provider == "deepseek":
|
if self.provider == "deepseek":
|
||||||
return (
|
return "⚠️ **DeepSeek API Key не настроен.**\nДобавьте `DEEPSEEK_API_KEY` в `.env` и перезапустите бота."
|
||||||
"⚠️ **DeepSeek API Key не настроен.**\n\n"
|
return "⚠️ **OpenAI / OpenAI-compatible API Key не настроен**.\nДобавьте `OPENAI_API_KEY` в `.env` и перезапустите бота."
|
||||||
"Пожалуйста, добавьте ваш ключ в `.env`:\n"
|
|
||||||
"```env\n"
|
|
||||||
"LLM_PROVIDER=deepseek\n"
|
|
||||||
"DEEPSEEK_API_KEY=sk-...\n"
|
|
||||||
"DEEPSEEK_MODEL=deepseek-chat\n"
|
|
||||||
"```\n"
|
|
||||||
"Получить ключ можно на платформе [DeepSeek Platform](https://platform.deepseek.com)."
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return (
|
|
||||||
"⚠️ **OpenAI / OpenAI-compatible API Key не настроен.**\n\n"
|
|
||||||
"Пожалуйста, добавьте ваш ключ в `.env`:\n"
|
|
||||||
"```env\n"
|
|
||||||
"LLM_PROVIDER=openai\n"
|
|
||||||
"OPENAI_API_KEY=sk-...\n"
|
|
||||||
"OPENAI_BASE_URL=https://api.openai.com/v1\n"
|
|
||||||
"OPENAI_MODEL=gpt-4o\n"
|
|
||||||
"```"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 1. Fetch current conversation history
|
|
||||||
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
||||||
|
|
||||||
# 2. Add current user message
|
|
||||||
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
|
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
|
||||||
history.append(user_turn)
|
working: list[dict[str, Any]] = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn]
|
||||||
|
sequence: list[dict[str, Any]] = [user_turn]
|
||||||
system_instruction = self._build_system_instruction()
|
|
||||||
working_messages: list[dict[str, Any]] = [
|
|
||||||
{"role": "system", "content": system_instruction},
|
|
||||||
*history,
|
|
||||||
]
|
|
||||||
|
|
||||||
turn_sequence: list[dict[str, Any]] = [user_turn]
|
|
||||||
tools = self.registry.get_openai_tools()
|
tools = self.registry.get_openai_tools()
|
||||||
|
|
||||||
for iteration in range(max_tool_iterations):
|
for iteration in range(max_tool_iterations):
|
||||||
logger.debug(
|
|
||||||
"OpenAI/DeepSeek request turn: chat=%d, thread=%s, iteration=%d, model=%s",
|
|
||||||
chat_id,
|
|
||||||
thread_id,
|
|
||||||
iteration,
|
|
||||||
self.model,
|
|
||||||
)
|
|
||||||
|
|
||||||
if on_progress:
|
if on_progress:
|
||||||
if iteration == 0:
|
await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||||
await on_progress("🤔 Формирую ответ...")
|
kwargs: dict[str, Any] = {"model": self.model, "messages": working, "temperature": 0.3}
|
||||||
else:
|
if tools: kwargs["tools"] = tools
|
||||||
await on_progress(f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
|
||||||
|
|
||||||
kwargs: dict[str, Any] = {
|
|
||||||
"model": self.model,
|
|
||||||
"messages": working_messages,
|
|
||||||
"temperature": 0.3,
|
|
||||||
}
|
|
||||||
if tools:
|
|
||||||
kwargs["tools"] = tools
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await self._client.chat.completions.create(**kwargs)
|
response = await self._client.chat.completions.create(**kwargs)
|
||||||
except openai.APIError as e:
|
except openai.APIError as e:
|
||||||
logger.exception("OpenAI/DeepSeek API error: %s", e)
|
logger.exception("OpenAI API error")
|
||||||
return f"⚠️ Ошибка обращения к {self.provider.upper()} API ({e.code or 'Error'}): {e.message}"
|
return f"⚠️ Ошибка обращения к {self.provider.upper()} API ({e.code or 'Error'}): {e.message}"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Unexpected error calling %s: %s", self.provider, e)
|
logger.exception("Unexpected API error")
|
||||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {str(e)}"
|
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}"
|
||||||
|
message = response.choices[0].message
|
||||||
choice = response.choices[0]
|
if not message.tool_calls:
|
||||||
choice_message = choice.message
|
final = message.content or "*(Пустой ответ)*"
|
||||||
|
sequence.append({"role": "assistant", "content": final})
|
||||||
# Check if model requested function calls
|
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
||||||
tool_calls = choice_message.tool_calls
|
return final
|
||||||
if not tool_calls:
|
assistant_message = {"role": "assistant", "content": message.content, "tool_calls": [
|
||||||
final_text = choice_message.content or "*(Пустой ответ)*"
|
{"id": call.id, "type": "function", "function": {"name": call.function.name, "arguments": call.function.arguments}}
|
||||||
model_turn = {"role": "assistant", "content": final_text}
|
for call in message.tool_calls
|
||||||
turn_sequence.append(model_turn)
|
]}
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
working.append(assistant_message); sequence.append(assistant_message)
|
||||||
return final_text
|
for index, call in enumerate(message.tool_calls, 1):
|
||||||
|
try: args = json.loads(call.function.arguments or "{}")
|
||||||
# Model produced tool calls
|
except Exception: args = {}
|
||||||
assistant_turn: dict[str, Any] = {
|
|
||||||
"role": "assistant",
|
|
||||||
"content": choice_message.content,
|
|
||||||
"tool_calls": [
|
|
||||||
{
|
|
||||||
"id": tc.id,
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": tc.function.name,
|
|
||||||
"arguments": tc.function.arguments,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
for tc in tool_calls
|
|
||||||
],
|
|
||||||
}
|
|
||||||
working_messages.append(assistant_turn)
|
|
||||||
turn_sequence.append(assistant_turn)
|
|
||||||
|
|
||||||
# Execute all tool calls
|
|
||||||
for idx, tc in enumerate(tool_calls, 1):
|
|
||||||
fn_name = tc.function.name
|
|
||||||
raw_args = tc.function.arguments or "{}"
|
|
||||||
try:
|
|
||||||
fn_args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
|
|
||||||
except Exception as parse_err:
|
|
||||||
logger.warning("Failed parsing arguments for %s: %s", fn_name, parse_err)
|
|
||||||
fn_args = {}
|
|
||||||
|
|
||||||
if on_progress:
|
if on_progress:
|
||||||
from homeagent.bot.progress import format_tool_progress
|
from homeagent.bot.progress import format_tool_progress
|
||||||
|
prefix = f"[{index}/{len(message.tool_calls)}] " if len(message.tool_calls) > 1 else ""
|
||||||
step_info = f"[{idx}/{len(tool_calls)}] " if len(tool_calls) > 1 else ""
|
await on_progress(f"⏳ {prefix}{format_tool_progress(call.function.name, args)}")
|
||||||
desc = format_tool_progress(fn_name, fn_args)
|
result = await self.registry.execute(call.function.name, args)
|
||||||
await on_progress(f"⏳ {step_info}{desc}")
|
tool_message = {"role": "tool", "tool_call_id": call.id, "name": call.function.name, "content": result}
|
||||||
|
working.append(tool_message); sequence.append(tool_message)
|
||||||
logger.info("Executing OpenAI/DeepSeek tool call: %s(%s)", fn_name, fn_args)
|
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
||||||
tool_result = await self.registry.execute(fn_name, fn_args)
|
return "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||||
|
|
||||||
tool_response_msg: dict[str, Any] = {
|
|
||||||
"role": "tool",
|
|
||||||
"tool_call_id": tc.id,
|
|
||||||
"name": fn_name,
|
|
||||||
"content": tool_result,
|
|
||||||
}
|
|
||||||
working_messages.append(tool_response_msg)
|
|
||||||
turn_sequence.append(tool_response_msg)
|
|
||||||
|
|
||||||
warning_msg = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
|
||||||
return warning_msg
|
|
||||||
@@ -14,6 +14,7 @@ from homeagent.agent.factory import create_agent
|
|||||||
from homeagent.bot.handlers import create_bot_router
|
from homeagent.bot.handlers import create_bot_router
|
||||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.config import Settings, get_settings
|
||||||
|
from homeagent.memory.global_memory import configure_global_memory_path
|
||||||
from homeagent.skills.manager import SkillManager
|
from homeagent.skills.manager import SkillManager
|
||||||
from homeagent.tools.loader import load_extensions_from_directory
|
from homeagent.tools.loader import load_extensions_from_directory
|
||||||
from homeagent.tools.registry import get_tool_registry
|
from homeagent.tools.registry import get_tool_registry
|
||||||
@@ -22,56 +23,42 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class TelegramAgentApp:
|
class TelegramAgentApp:
|
||||||
"""Orchestrates Telegram bot lifecycle, middlewares, and agent components."""
|
"""Orchestrates Telegram bot lifecycle, middleware, and durable components."""
|
||||||
|
|
||||||
def __init__(self, settings: Optional[Settings] = None) -> None:
|
def __init__(self, settings: Optional[Settings] = None) -> None:
|
||||||
self.settings = settings or get_settings()
|
self.settings = settings or get_settings()
|
||||||
|
self.settings.DATA_DIR = self.settings.DATA_DIR.expanduser().resolve()
|
||||||
|
self.settings.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
configure_global_memory_path(self.settings.DATA_DIR / "global_memory.json")
|
||||||
|
logger.info("Persistent data directory: %s", self.settings.DATA_DIR)
|
||||||
|
|
||||||
self.registry = get_tool_registry()
|
self.registry = get_tool_registry()
|
||||||
|
|
||||||
# Load dynamic extensions from directory
|
|
||||||
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
||||||
|
|
||||||
# Initialize skills
|
|
||||||
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
||||||
|
self.agent: BaseAgent = create_agent(settings=self.settings, registry=self.registry)
|
||||||
# Initialize LLM agent according to active provider (Gemini, DeepSeek, or OpenAI)
|
|
||||||
self.agent: BaseAgent = create_agent(
|
|
||||||
settings=self.settings,
|
|
||||||
registry=self.registry,
|
|
||||||
)
|
|
||||||
|
|
||||||
token = self.settings.TELEGRAM_BOT_TOKEN.get_secret_value().strip()
|
token = self.settings.TELEGRAM_BOT_TOKEN.get_secret_value().strip()
|
||||||
self.bot: Optional[Bot] = None
|
self.bot: Optional[Bot] = None
|
||||||
self.dp = Dispatcher()
|
self.dp = Dispatcher()
|
||||||
|
|
||||||
if token:
|
if token:
|
||||||
try:
|
try:
|
||||||
self.bot = Bot(
|
self.bot = Bot(token=token, default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN))
|
||||||
token=token,
|
|
||||||
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
||||||
|
|
||||||
# Enforce strict whitelist middleware on message and ghost/guest events
|
|
||||||
whitelist_middleware = WhitelistMiddleware(self.settings)
|
whitelist_middleware = WhitelistMiddleware(self.settings)
|
||||||
self.dp.message.middleware(whitelist_middleware)
|
self.dp.message.middleware(whitelist_middleware)
|
||||||
self.dp.guest_message.middleware(whitelist_middleware)
|
self.dp.guest_message.middleware(whitelist_middleware)
|
||||||
|
self.dp.include_router(create_bot_router(
|
||||||
# Register router
|
|
||||||
router = create_bot_router(
|
|
||||||
settings=self.settings,
|
settings=self.settings,
|
||||||
agent=self.agent,
|
agent=self.agent,
|
||||||
skill_manager=self.skill_manager,
|
skill_manager=self.skill_manager,
|
||||||
tool_registry=self.registry,
|
tool_registry=self.registry,
|
||||||
)
|
))
|
||||||
self.dp.include_router(router)
|
|
||||||
|
|
||||||
async def _setup_commands(self) -> None:
|
async def _setup_commands(self) -> None:
|
||||||
"""Register command menu in Telegram UI."""
|
|
||||||
if not self.bot:
|
if not self.bot:
|
||||||
return
|
return
|
||||||
|
|
||||||
commands = [
|
commands = [
|
||||||
BotCommand(command="start", description="Запустить бота / статус"),
|
BotCommand(command="start", description="Запустить бота / статус"),
|
||||||
BotCommand(command="skills", description="Список доступных скиллов"),
|
BotCommand(command="skills", description="Список доступных скиллов"),
|
||||||
@@ -85,10 +72,8 @@ class TelegramAgentApp:
|
|||||||
logger.warning("Failed to set bot commands menu: %s", e)
|
logger.warning("Failed to set bot commands menu: %s", e)
|
||||||
|
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
"""Start Telegram bot polling."""
|
|
||||||
if not self.bot:
|
if not self.bot:
|
||||||
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
||||||
|
|
||||||
logger.info("Starting HomeAgent Telegram Bot...")
|
logger.info("Starting HomeAgent Telegram Bot...")
|
||||||
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
|
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
|
||||||
logger.info("Ghost Bot Mode: %s", "Enabled (Bot API 10.0+ guest_message)" if self.settings.GHOST_MODE_ENABLED else "Disabled")
|
logger.info("Ghost Bot Mode: %s", "Enabled (Bot API 10.0+ guest_message)" if self.settings.GHOST_MODE_ENABLED else "Disabled")
|
||||||
@@ -97,11 +82,8 @@ class TelegramAgentApp:
|
|||||||
logger.info("Subagent Model: %s", self.settings.get_active_subagent_model())
|
logger.info("Subagent Model: %s", self.settings.get_active_subagent_model())
|
||||||
logger.info("Registered Tools (%d): %s", len(self.registry.list_tools()), [t.name for t in self.registry.list_tools()])
|
logger.info("Registered Tools (%d): %s", len(self.registry.list_tools()), [t.name for t in self.registry.list_tools()])
|
||||||
logger.info("Loaded Skills (%d): %s", len(self.skill_manager.list_skills()), [s.name for s in self.skill_manager.list_skills()])
|
logger.info("Loaded Skills (%d): %s", len(self.skill_manager.list_skills()), [s.name for s in self.skill_manager.list_skills()])
|
||||||
|
|
||||||
await self._setup_commands()
|
await self._setup_commands()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Delete any webhooks and start polling with automatically resolved update types (including guest_message)
|
|
||||||
await self.bot.delete_webhook(drop_pending_updates=True)
|
await self.bot.delete_webhook(drop_pending_updates=True)
|
||||||
allowed_updates = self.dp.resolve_used_update_types()
|
allowed_updates = self.dp.resolve_used_update_types()
|
||||||
logger.info("Polling with allowed_updates: %s", allowed_updates)
|
logger.info("Polling with allowed_updates: %s", allowed_updates)
|
||||||
|
|||||||
+61
-196
@@ -7,220 +7,85 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(
|
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||||
env_file=".env",
|
|
||||||
env_file_encoding="utf-8",
|
|
||||||
extra="ignore",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Telegram Bot
|
TELEGRAM_BOT_TOKEN: SecretStr = Field(default=SecretStr(""))
|
||||||
TELEGRAM_BOT_TOKEN: SecretStr = Field(
|
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(default_factory=list)
|
||||||
default=SecretStr(""),
|
GHOST_MODE_ENABLED: bool = True
|
||||||
description="Telegram bot token obtained from @BotFather",
|
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = "gemini"
|
||||||
)
|
GEMINI_API_KEY: SecretStr = Field(default=SecretStr(""))
|
||||||
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(
|
GEMINI_MODEL: str = "gemini-2.5-pro"
|
||||||
default_factory=list,
|
GEMINI_SUBAGENT_MODEL: str = "gemini-2.5-flash"
|
||||||
description="List of Telegram User IDs allowed to interact with the bot. Whitelist only.",
|
DEEPSEEK_API_KEY: Optional[SecretStr] = None
|
||||||
)
|
DEEPSEEK_BASE_URL: str = "https://api.deepseek.com"
|
||||||
GHOST_MODE_ENABLED: bool = Field(
|
DEEPSEEK_MODEL: str = "deepseek-chat"
|
||||||
default=True,
|
DEEPSEEK_SUBAGENT_MODEL: str = "deepseek-chat"
|
||||||
description="Enable or disable Ghost/Guest Bot mode (Telegram Bot API 10.0+ guest_message). Allows responding in chats without being added as a member.",
|
OPENAI_API_KEY: Optional[SecretStr] = None
|
||||||
)
|
OPENAI_BASE_URL: str = "https://api.openai.com/v1"
|
||||||
|
OPENAI_MODEL: str = "gpt-4o"
|
||||||
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
OPENAI_SUBAGENT_MODEL: str = "gpt-4o-mini"
|
||||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
SYSTEM_INSTRUCTION: str = "Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram."
|
||||||
default="gemini",
|
JIRA_ENABLED: bool = True
|
||||||
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
JIRA_URL: Optional[str] = None
|
||||||
)
|
JIRA_EMAIL: Optional[str] = None
|
||||||
|
JIRA_API_TOKEN: Optional[SecretStr] = None
|
||||||
# Google AI Studio (Gemini)
|
JIRA_PERSONAL_ACCESS_TOKEN: Optional[SecretStr] = None
|
||||||
GEMINI_API_KEY: SecretStr = Field(
|
GITEA_ENABLED: bool = True
|
||||||
default=SecretStr(""),
|
GITEA_URL: str = "https://git.timka.su"
|
||||||
description="Google AI Studio API Key",
|
GITEA_TOKEN: Optional[SecretStr] = None
|
||||||
)
|
WEB_SEARCH_ENABLED: bool = True
|
||||||
GEMINI_MODEL: str = Field(
|
WEB_SEARCH_PROVIDER: Literal["duckduckgo", "tavily", "searxng"] = "duckduckgo"
|
||||||
default="gemini-2.5-pro",
|
TAVILY_API_KEY: Optional[SecretStr] = None
|
||||||
description="Gemini orchestrator model name (e.g. gemini-3.1-pro, gemini-2.5-pro)",
|
SEARXNG_URL: Optional[str] = None
|
||||||
)
|
SANDBOX_ENABLED: bool = True
|
||||||
GEMINI_SUBAGENT_MODEL: str = Field(
|
SANDBOX_BACKEND: Literal["auto", "bwrap", "docker", "process"] = "auto"
|
||||||
default="gemini-2.5-flash",
|
SANDBOX_TIMEOUT_SECONDS: int = 30
|
||||||
description="Fast Gemini model used for subagent tasks (e.g. gemini-2.5-flash)",
|
SANDBOX_MEMORY_LIMIT_MB: int = 512
|
||||||
)
|
SANDBOX_CPU_LIMIT: float = 1.0
|
||||||
|
SANDBOX_ALLOW_NETWORK: bool = False
|
||||||
# DeepSeek API (https://api.deepseek.com)
|
SANDBOX_DOCKER_IMAGE: str = "python:3.12-slim"
|
||||||
DEEPSEEK_API_KEY: Optional[SecretStr] = Field(
|
GOOGLE_CALENDAR_ENABLED: bool = True
|
||||||
default=None,
|
GOOGLE_CALENDAR_ID: str = "primary"
|
||||||
description="DeepSeek API Key (https://platform.deepseek.com)",
|
GOOGLE_ADDITIONAL_CALENDAR_IDS: list[str] = Field(default_factory=list)
|
||||||
)
|
GOOGLE_AUTH_TYPE: Literal["auto", "service_account", "oauth2"] = "auto"
|
||||||
DEEPSEEK_BASE_URL: str = Field(
|
GOOGLE_SERVICE_ACCOUNT_FILE: Optional[str] = "service_account.json"
|
||||||
default="https://api.deepseek.com",
|
GOOGLE_OAUTH_CREDENTIALS_FILE: Optional[str] = "credentials.json"
|
||||||
description="DeepSeek base URL (default: https://api.deepseek.com)",
|
GOOGLE_OAUTH_TOKEN_FILE: str = "data/calendar_token.json"
|
||||||
)
|
DATA_DIR: Path = Path("data")
|
||||||
DEEPSEEK_MODEL: str = Field(
|
SKILLS_DIR: Path = Path("skills")
|
||||||
default="deepseek-chat",
|
EXTENSIONS_DIR: Path = Path("extensions")
|
||||||
description="DeepSeek model name (e.g. deepseek-chat, deepseek-reasoner)",
|
LOG_LEVEL: str = "INFO"
|
||||||
)
|
|
||||||
DEEPSEEK_SUBAGENT_MODEL: str = Field(
|
|
||||||
default="deepseek-chat",
|
|
||||||
description="Fast DeepSeek model for subagents",
|
|
||||||
)
|
|
||||||
|
|
||||||
# OpenAI-Compatible API (OpenAI, OpenRouter, Groq, Ollama, vLLM, etc.)
|
|
||||||
OPENAI_API_KEY: Optional[SecretStr] = Field(
|
|
||||||
default=None,
|
|
||||||
description="OpenAI or OpenAI-compatible API Key",
|
|
||||||
)
|
|
||||||
OPENAI_BASE_URL: str = Field(
|
|
||||||
default="https://api.openai.com/v1",
|
|
||||||
description="Base URL for OpenAI-compatible endpoint (e.g. https://openrouter.ai/api/v1, http://localhost:11434/v1)",
|
|
||||||
)
|
|
||||||
OPENAI_MODEL: str = Field(
|
|
||||||
default="gpt-4o",
|
|
||||||
description="Model name for OpenAI-compatible endpoint",
|
|
||||||
)
|
|
||||||
OPENAI_SUBAGENT_MODEL: str = Field(
|
|
||||||
default="gpt-4o-mini",
|
|
||||||
description="Fast model for subagents on OpenAI-compatible endpoint",
|
|
||||||
)
|
|
||||||
|
|
||||||
SYSTEM_INSTRUCTION: str = Field(
|
|
||||||
default=(
|
|
||||||
"Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram. "
|
|
||||||
"Ты помогаешь пользователю управлять задачами в Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
|
||||||
"искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), "
|
|
||||||
"помнить важные факты и выполнять специализированные скиллы. "
|
|
||||||
"Для быстрого и эффективного сбора данных из нескольких источников ты можешь запускать быстрых подагентов параллельно "
|
|
||||||
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Jira, третий ищет информацию в интернете). "
|
|
||||||
"Отвечай емко, красиво и структурированно, используя Markdown для списков, жирного шрифта и таблиц. "
|
|
||||||
"Всегда выполняй действия через доступные инструменты (tools), если требуется проверить актуальные данные или совершить действие."
|
|
||||||
),
|
|
||||||
description="Default system instruction for Gemini",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Jira Integration
|
|
||||||
JIRA_ENABLED: bool = Field(default=True, description="Enable or disable Jira tools")
|
|
||||||
JIRA_URL: Optional[str] = Field(default=None, description="Base Jira URL, e.g. https://your-domain.atlassian.net")
|
|
||||||
JIRA_EMAIL: Optional[str] = Field(default=None, description="Jira user email")
|
|
||||||
JIRA_API_TOKEN: Optional[SecretStr] = Field(default=None, description="Jira Atlassian API Token")
|
|
||||||
JIRA_PERSONAL_ACCESS_TOKEN: Optional[SecretStr] = Field(default=None, description="Jira PAT (for Server/Data Center)")
|
|
||||||
|
|
||||||
# Gitea Integration
|
|
||||||
GITEA_ENABLED: bool = Field(default=True, description="Enable or disable Gitea tools")
|
|
||||||
GITEA_URL: str = Field(default="https://git.timka.su", description="Base Gitea URL (e.g. https://git.timka.su)")
|
|
||||||
GITEA_TOKEN: Optional[SecretStr] = Field(default=None, description="Gitea Personal Access Token")
|
|
||||||
|
|
||||||
# Web Search Integration
|
|
||||||
WEB_SEARCH_ENABLED: bool = Field(default=True, description="Enable or disable web search tools")
|
|
||||||
WEB_SEARCH_PROVIDER: Literal["duckduckgo", "tavily", "searxng"] = Field(
|
|
||||||
default="duckduckgo",
|
|
||||||
description="Search provider: 'duckduckgo', 'tavily', or 'searxng'",
|
|
||||||
)
|
|
||||||
TAVILY_API_KEY: Optional[SecretStr] = Field(default=None, description="Tavily API Key (optional)")
|
|
||||||
SEARXNG_URL: Optional[str] = Field(default=None, description="SearXNG instance URL (optional)")
|
|
||||||
|
|
||||||
# Code Sandbox Integration
|
|
||||||
SANDBOX_ENABLED: bool = Field(default=True, description="Enable or disable isolated code execution sandbox")
|
|
||||||
SANDBOX_BACKEND: Literal["auto", "bwrap", "docker", "process"] = Field(
|
|
||||||
default="auto",
|
|
||||||
description="Sandbox backend: 'auto' (bwrap -> docker -> process), 'bwrap', 'docker', or 'process'",
|
|
||||||
)
|
|
||||||
SANDBOX_TIMEOUT_SECONDS: int = Field(default=30, description="Max execution time in seconds")
|
|
||||||
SANDBOX_MEMORY_LIMIT_MB: int = Field(default=512, description="Max RAM allowed for sandbox process in MB")
|
|
||||||
SANDBOX_CPU_LIMIT: float = Field(default=1.0, description="CPU cores limit")
|
|
||||||
SANDBOX_ALLOW_NETWORK: bool = Field(default=False, description="Allow outbound network in sandbox (disabled by default)")
|
|
||||||
SANDBOX_DOCKER_IMAGE: str = Field(default="python:3.12-slim", description="Docker image used if docker backend is active")
|
|
||||||
|
|
||||||
# Google Calendar Integration
|
|
||||||
GOOGLE_CALENDAR_ENABLED: bool = Field(default=True, description="Enable or disable Google Calendar tools")
|
|
||||||
GOOGLE_CALENDAR_ID: str = Field(default="primary", description="Primary calendar ID or user email (default 'primary')")
|
|
||||||
GOOGLE_ADDITIONAL_CALENDAR_IDS: list[str] = Field(
|
|
||||||
default_factory=list,
|
|
||||||
description="List of additional Google Calendar IDs to always monitor",
|
|
||||||
)
|
|
||||||
GOOGLE_AUTH_TYPE: Literal["auto", "service_account", "oauth2"] = Field(
|
|
||||||
default="auto",
|
|
||||||
description="Authentication method for Google Calendar: 'auto', 'service_account', or 'oauth2'",
|
|
||||||
)
|
|
||||||
GOOGLE_SERVICE_ACCOUNT_FILE: Optional[str] = Field(
|
|
||||||
default="service_account.json",
|
|
||||||
description="Path to service account JSON credentials",
|
|
||||||
)
|
|
||||||
GOOGLE_OAUTH_CREDENTIALS_FILE: Optional[str] = Field(
|
|
||||||
default="credentials.json",
|
|
||||||
description="Path to OAuth2 client credentials JSON file",
|
|
||||||
)
|
|
||||||
GOOGLE_OAUTH_TOKEN_FILE: str = Field(
|
|
||||||
default="data/calendar_token.json",
|
|
||||||
description="Path where OAuth2 refresh token is saved",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Storage and paths
|
|
||||||
DATA_DIR: Path = Field(default=Path("data"), description="Directory for storing sessions and memory")
|
|
||||||
SKILLS_DIR: Path = Field(default=Path("skills"), description="Directory with skills markdown files")
|
|
||||||
EXTENSIONS_DIR: Path = Field(default=Path("extensions"), description="Directory with dynamic extensions")
|
|
||||||
LOG_LEVEL: str = Field(default="INFO", description="Logging level")
|
|
||||||
|
|
||||||
def get_active_provider_name(self) -> str:
|
def get_active_provider_name(self) -> str:
|
||||||
if self.LLM_PROVIDER == "deepseek":
|
return {"deepseek": "DeepSeek", "openai": "OpenAI-Compatible"}.get(self.LLM_PROVIDER, "Google Gemini")
|
||||||
return "DeepSeek"
|
|
||||||
if self.LLM_PROVIDER == "openai":
|
|
||||||
return "OpenAI-Compatible"
|
|
||||||
return "Google Gemini"
|
|
||||||
|
|
||||||
def get_active_model(self) -> str:
|
def get_active_model(self) -> str:
|
||||||
if self.LLM_PROVIDER == "deepseek":
|
return {"deepseek": self.DEEPSEEK_MODEL, "openai": self.OPENAI_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_MODEL)
|
||||||
return self.DEEPSEEK_MODEL
|
|
||||||
if self.LLM_PROVIDER == "openai":
|
|
||||||
return self.OPENAI_MODEL
|
|
||||||
return self.GEMINI_MODEL
|
|
||||||
|
|
||||||
def get_active_subagent_model(self) -> str:
|
def get_active_subagent_model(self) -> str:
|
||||||
if self.LLM_PROVIDER == "deepseek":
|
return {"deepseek": self.DEEPSEEK_SUBAGENT_MODEL, "openai": self.OPENAI_SUBAGENT_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_SUBAGENT_MODEL)
|
||||||
return self.DEEPSEEK_SUBAGENT_MODEL
|
|
||||||
if self.LLM_PROVIDER == "openai":
|
|
||||||
return self.OPENAI_SUBAGENT_MODEL
|
|
||||||
return self.GEMINI_SUBAGENT_MODEL
|
|
||||||
|
|
||||||
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
||||||
@classmethod
|
@classmethod
|
||||||
def parse_allowed_user_ids(cls, v: object) -> list[int]:
|
def parse_allowed_user_ids(cls, value: object) -> list[int]:
|
||||||
if isinstance(v, str):
|
if isinstance(value, str):
|
||||||
v = v.strip()
|
return [int(item.strip()) for item in value.strip().replace("[", "").replace("]", "").split(",") if item.strip()]
|
||||||
if not v:
|
if isinstance(value, (int, float)): return [int(value)]
|
||||||
return []
|
if isinstance(value, (list, tuple, set)): return [int(item) for item in value]
|
||||||
# Supports "123, 456" or "[123, 456]"
|
|
||||||
clean = v.replace("[", "").replace("]", "")
|
|
||||||
return [int(item.strip()) for item in clean.split(",") if item.strip()]
|
|
||||||
if isinstance(v, (int, float)):
|
|
||||||
return [int(v)]
|
|
||||||
if isinstance(v, (list, tuple, set)):
|
|
||||||
return [int(item) for item in v]
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@field_validator("GOOGLE_ADDITIONAL_CALENDAR_IDS", mode="after")
|
@field_validator("GOOGLE_ADDITIONAL_CALENDAR_IDS", mode="after")
|
||||||
@classmethod
|
@classmethod
|
||||||
def parse_calendar_ids(cls, v: object) -> list[str]:
|
def parse_calendar_ids(cls, value: object) -> list[str]:
|
||||||
if isinstance(v, str):
|
if isinstance(value, str): return [item.strip() for item in value.strip("[] ").replace('"', '').replace("'", '').split(",") if item.strip()]
|
||||||
v = v.strip()
|
if isinstance(value, (list, tuple, set)): return [str(item).strip() for item in value if str(item).strip()]
|
||||||
if not v:
|
|
||||||
return []
|
|
||||||
if v.startswith("[") and v.endswith("]"):
|
|
||||||
import json
|
|
||||||
try:
|
|
||||||
parsed = json.loads(v)
|
|
||||||
if isinstance(parsed, list):
|
|
||||||
return [str(item).strip() for item in parsed if str(item).strip()]
|
|
||||||
except Exception:
|
|
||||||
clean = v.replace("[", "").replace("]", "").replace('"', "").replace("'", "")
|
|
||||||
return [item.strip() for item in clean.split(",") if item.strip()]
|
|
||||||
return [item.strip() for item in v.split(",") if item.strip()]
|
|
||||||
if isinstance(v, (list, tuple, set)):
|
|
||||||
return [str(item).strip() for item in v if str(item).strip()]
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
"""Retrieve application settings."""
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
settings.DATA_DIR = settings.DATA_DIR.expanduser().resolve()
|
||||||
|
settings.SKILLS_DIR = settings.SKILLS_DIR.expanduser().resolve()
|
||||||
|
settings.EXTENSIONS_DIR = settings.EXTENSIONS_DIR.expanduser().resolve()
|
||||||
settings.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
settings.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
return settings
|
return settings
|
||||||
@@ -1,5 +1,27 @@
|
|||||||
"""Memory package for HomeAgent."""
|
"""Memory package for HomeAgent."""
|
||||||
|
|
||||||
from homeagent.memory.global_memory import GlobalMemory, MemoryItem, get_global_memory
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
__all__ = ["GlobalMemory", "MemoryItem", "get_global_memory"]
|
from homeagent.memory.global_memory import (
|
||||||
|
GlobalMemory,
|
||||||
|
MemoryItem,
|
||||||
|
configure_global_memory_path,
|
||||||
|
get_global_memory,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_configured_global_memory(data_dir: Optional[Path] = None) -> GlobalMemory:
|
||||||
|
"""Return global memory under the configured durable data directory."""
|
||||||
|
if data_dir is None:
|
||||||
|
return get_global_memory()
|
||||||
|
return get_global_memory(Path(data_dir) / "global_memory.json")
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"GlobalMemory",
|
||||||
|
"MemoryItem",
|
||||||
|
"configure_global_memory_path",
|
||||||
|
"get_global_memory",
|
||||||
|
"get_configured_global_memory",
|
||||||
|
]
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
import uuid
|
import uuid
|
||||||
from dataclasses import asdict, dataclass, field
|
from dataclasses import asdict, dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -21,9 +23,8 @@ class MemoryItem:
|
|||||||
|
|
||||||
class GlobalMemory:
|
class GlobalMemory:
|
||||||
"""Persistent global memory store shared across all forum topics."""
|
"""Persistent global memory store shared across all forum topics."""
|
||||||
|
|
||||||
def __init__(self, storage_path: Path):
|
def __init__(self, storage_path: Path):
|
||||||
self.storage_path = storage_path
|
self.storage_path = Path(storage_path).expanduser().resolve()
|
||||||
self._items: dict[str, MemoryItem] = {}
|
self._items: dict[str, MemoryItem] = {}
|
||||||
self._load()
|
self._load()
|
||||||
|
|
||||||
@@ -31,80 +32,83 @@ class GlobalMemory:
|
|||||||
if not self.storage_path.exists():
|
if not self.storage_path.exists():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
with open(self.storage_path, "r", encoding="utf-8") as f:
|
with self.storage_path.open("r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
for item_data in data:
|
if not isinstance(data, list):
|
||||||
item = MemoryItem(**item_data)
|
raise ValueError("memory file must contain a JSON list")
|
||||||
self._items[item.id] = item
|
for item_data in data:
|
||||||
|
item = MemoryItem(**item_data)
|
||||||
|
self._items[item.id] = item
|
||||||
logger.info("Loaded %d items into global memory from %s", len(self._items), self.storage_path)
|
logger.info("Loaded %d items into global memory from %s", len(self._items), self.storage_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||||
|
|
||||||
def _save(self) -> None:
|
def _save(self) -> None:
|
||||||
|
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
|
||||||
|
fd, tmp_name = tempfile.mkstemp(prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent)
|
||||||
try:
|
try:
|
||||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||||
with open(self.storage_path, "w", encoding="utf-8") as f:
|
f.write(payload)
|
||||||
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
f.flush()
|
||||||
except Exception as e:
|
os.fsync(f.fileno())
|
||||||
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
os.replace(tmp_name, self.storage_path)
|
||||||
|
try:
|
||||||
|
dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY)
|
||||||
|
try: os.fsync(dir_fd)
|
||||||
|
finally: os.close(dir_fd)
|
||||||
|
except OSError: logger.debug("Directory fsync unavailable for %s", self.storage_path.parent)
|
||||||
|
except Exception:
|
||||||
|
try: os.unlink(tmp_name)
|
||||||
|
except OSError: pass
|
||||||
|
raise
|
||||||
|
|
||||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||||
"""Add a new fact or preference to global memory."""
|
item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
|
||||||
item_id = str(uuid.uuid4())[:8]
|
self._items[item.id] = item
|
||||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
|
||||||
self._items[item_id] = item
|
|
||||||
self._save()
|
self._save()
|
||||||
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
logger.info("Added fact [%s] in category '%s': %s", item.id, item.category, item.fact)
|
||||||
return item
|
return item
|
||||||
|
|
||||||
def remove_fact(self, fact_id: str) -> bool:
|
def remove_fact(self, fact_id: str) -> bool:
|
||||||
"""Remove a fact by its ID."""
|
if fact_id not in self._items: return False
|
||||||
if fact_id in self._items:
|
del self._items[fact_id]; self._save(); return True
|
||||||
del self._items[fact_id]
|
|
||||||
self._save()
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||||
"""List all facts, optionally filtered by category."""
|
|
||||||
if category:
|
if category:
|
||||||
cat = category.strip().lower()
|
cat = category.strip().lower()
|
||||||
return [item for item in self._items.values() if item.category == cat]
|
return [item for item in self._items.values() if item.category == cat]
|
||||||
return list(self._items.values())
|
return list(self._items.values())
|
||||||
|
|
||||||
def search(self, query: str) -> list[MemoryItem]:
|
def search(self, query: str) -> list[MemoryItem]:
|
||||||
"""Search memory for keywords in query."""
|
|
||||||
q = query.lower()
|
q = query.lower()
|
||||||
return [
|
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
||||||
item for item in self._items.values()
|
|
||||||
if q in item.fact.lower() or q in item.category.lower()
|
|
||||||
]
|
|
||||||
|
|
||||||
def clear(self) -> None:
|
def clear(self) -> None:
|
||||||
"""Clear all stored memory."""
|
self._items.clear(); self._save()
|
||||||
self._items.clear()
|
|
||||||
self._save()
|
|
||||||
|
|
||||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||||
"""Produce a formatted summary of remembered facts for the system prompt."""
|
if not self._items: return ""
|
||||||
if not self._items:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||||
items = list(self._items.values())[-max_items:]
|
for item in list(self._items.values())[-max_items:]:
|
||||||
for item in items:
|
|
||||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
# Singleton instance container
|
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
||||||
_global_memory_instance: Optional[GlobalMemory] = None
|
_configured_memory_path: Optional[Path] = None
|
||||||
|
|
||||||
|
|
||||||
|
def configure_global_memory_path(storage_path: Path) -> None:
|
||||||
|
"""Set the process-wide memory file before agents and handlers are created."""
|
||||||
|
global _configured_memory_path
|
||||||
|
_configured_memory_path = Path(storage_path).expanduser().resolve()
|
||||||
|
|
||||||
|
|
||||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||||
global _global_memory_instance
|
if storage_path is None:
|
||||||
if _global_memory_instance is None:
|
storage_path = _configured_memory_path or (Path(os.getenv("DATA_DIR", "data")) / "global_memory.json")
|
||||||
if storage_path is None:
|
path = Path(storage_path).expanduser().resolve()
|
||||||
storage_path = Path("data") / "global_memory.json"
|
if path not in _global_memory_instances:
|
||||||
_global_memory_instance = GlobalMemory(storage_path)
|
_global_memory_instances[path] = GlobalMemory(path)
|
||||||
return _global_memory_instance
|
return _global_memory_instances[path]
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Regression coverage for session persistence on the mounted data directory."""
|
||||||
|
|
||||||
|
from google.genai import types
|
||||||
|
|
||||||
|
from homeagent.agent.conversation import ConversationManager
|
||||||
|
|
||||||
|
|
||||||
|
def test_conversation_file_survives_restart_and_is_atomic(tmp_path):
|
||||||
|
manager = ConversationManager(tmp_path, max_turns=5)
|
||||||
|
manager.append_content(
|
||||||
|
42,
|
||||||
|
None,
|
||||||
|
types.Content(role="user", parts=[types.Part.from_text(text="persist me")]),
|
||||||
|
)
|
||||||
|
|
||||||
|
session_file = tmp_path / "sessions" / "session_42_main.json"
|
||||||
|
assert session_file.exists()
|
||||||
|
assert not list(session_file.parent.glob("*.tmp"))
|
||||||
|
|
||||||
|
restarted = ConversationManager(tmp_path, max_turns=5)
|
||||||
|
history = restarted.get_history(42, None)
|
||||||
|
assert len(history) == 1
|
||||||
|
assert history[0].parts[0].text == "persist me"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""Regression coverage for configured global-memory location."""
|
||||||
|
|
||||||
|
from homeagent.memory.global_memory import configure_global_memory_path, get_global_memory
|
||||||
|
|
||||||
|
|
||||||
|
def test_configured_memory_path_is_used(tmp_path):
|
||||||
|
configured = tmp_path / "mounted-data" / "global_memory.json"
|
||||||
|
configure_global_memory_path(configured)
|
||||||
|
|
||||||
|
memory = get_global_memory()
|
||||||
|
memory.add_fact("configured path survives restart")
|
||||||
|
|
||||||
|
assert configured.exists()
|
||||||
|
assert "configured path survives restart" in configured.read_text(encoding="utf-8")
|
||||||
Reference in new issue
Block a user