Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f8fe091e3 | ||
|
|
f8da5b24c4 | ||
|
|
6bf62bc331 |
No files matched your search
+1
-3
@@ -8,9 +8,6 @@ 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"
|
||||||
@@ -24,3 +21,4 @@ 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
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
# 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.
|
|
||||||
+353
-148
@@ -1,186 +1,391 @@
|
|||||||
"""Persistent, topic-isolated conversation history for all LLM providers."""
|
"""Topic-isolated conversation history management supporting multiple LLM formats."""
|
||||||
|
|
||||||
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:
|
||||||
suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
thread_suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
||||||
return data_dir / "sessions" / f"session_{chat_id}_{suffix}.json"
|
return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json"
|
||||||
|
|
||||||
|
|
||||||
def _atomic_write_json(path: Path, value: object) -> None:
|
def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
"""Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.
|
||||||
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:
|
||||||
def _sanitize_openai_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
1. Every assistant message with tool_calls is immediately followed by tool messages for ALL tool_call_ids.
|
||||||
"""Remove incomplete tool-call chains before sending history to OpenAI APIs."""
|
2. Tool responses matching call IDs are properly aligned.
|
||||||
result: list[dict[str, Any]] = []
|
3. Dangling tool calls or orphan tool messages are safely cleaned up.
|
||||||
|
"""
|
||||||
|
sanitized: list[dict[str, Any]] = []
|
||||||
i = 0
|
i = 0
|
||||||
while i < len(messages):
|
n = len(raw_messages)
|
||||||
message = dict(messages[i])
|
|
||||||
if message.get("role") == "tool":
|
while i < n:
|
||||||
|
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
|
||||||
|
|
||||||
def _part_text(part: Any) -> str:
|
if not tool_responses:
|
||||||
return str(getattr(part, "text", "") or "")
|
# No tool responses followed this assistant message!
|
||||||
|
# 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:
|
||||||
"""Stores each chat/topic history in DATA_DIR/sessions on durable storage."""
|
"""Manages chat and topic history with disk persistence and multi-provider format support."""
|
||||||
|
|
||||||
def __init__(self, data_dir: Path, max_turns: int = 20) -> None:
|
def __init__(self, data_dir: Path, max_turns: int = 20) -> None:
|
||||||
self.data_dir = Path(data_dir).expanduser().resolve()
|
self.data_dir = data_dir
|
||||||
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 _key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]:
|
def _get_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(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
def _load_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
||||||
key = self._key(chat_id, thread_id)
|
"""Load and normalize messages from disk into universal dictionary format."""
|
||||||
if key in self._cache: return self._cache[key]
|
key = self._get_key(chat_id, thread_id)
|
||||||
path = _session_file(self.data_dir, chat_id, thread_id)
|
if key in self._cache:
|
||||||
if not path.exists(): self._cache[key] = []; return self._cache[key]
|
return self._cache[key]
|
||||||
try:
|
|
||||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||||
normalized: list[dict[str, Any]] = []
|
if not file_path.exists():
|
||||||
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
|
|
||||||
except Exception:
|
|
||||||
logger.exception("Failed to load session history from %s", path)
|
|
||||||
self._cache[key] = []
|
self._cache[key] = []
|
||||||
return self._cache[key]
|
return self._cache[key]
|
||||||
|
|
||||||
def _save(self, chat_id: int, thread_id: Optional[int]) -> None:
|
try:
|
||||||
_atomic_write_json(_session_file(self.data_dir, chat_id, thread_id), self._cache[self._key(chat_id, thread_id)])
|
with open(file_path, "r", encoding="utf-8") as f:
|
||||||
|
raw_data = json.load(f)
|
||||||
|
|
||||||
def _content_to_messages(self, content: types.Content) -> list[dict[str, Any]]:
|
normalized: list[dict[str, Any]] = []
|
||||||
role = "assistant" if content.role in ("model", "assistant") else "user"
|
pending_tool_call_ids: dict[str, list[str]] = {}
|
||||||
messages: list[dict[str, Any]] = []; text = ""; calls = []
|
|
||||||
for part in content.parts or []:
|
for turn_idx, item in enumerate(raw_data):
|
||||||
if getattr(part, "function_call", None):
|
# 1. Check if legacy Gemini format with "parts"
|
||||||
call = part.function_call; name = call.name or "tool"
|
if "parts" in item:
|
||||||
calls.append({"id":f"call_{os.urandom(6).hex()}","type":"function",
|
role = item.get("role", "user")
|
||||||
"function":{"name":name,"arguments":json.dumps(dict(call.args or {}), ensure_ascii=False)}})
|
parts = item.get("parts", [])
|
||||||
elif getattr(part, "function_response", None):
|
if role == "user":
|
||||||
response = part.function_response; name = response.name or "tool"; value = response.response or {}
|
# Check for function_response
|
||||||
messages.append({"role":"tool","name":name,"content":str(value.get("result", value))})
|
fr_parts = [p for p in parts if "function_response" in p]
|
||||||
else: text += _part_text(part)
|
if fr_parts:
|
||||||
if calls: messages.insert(0, {"role":role,"content":text or None,"tool_calls":calls})
|
for p in fr_parts:
|
||||||
elif text or not messages: messages.insert(0, {"role":role,"content":text})
|
fr = p["function_response"]
|
||||||
return messages
|
fn_name = fr.get("name", "tool")
|
||||||
|
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_{turn_idx}_{fn_name}"
|
||||||
|
|
||||||
|
resp = fr.get("response", {})
|
||||||
|
res_val = resp.get("result", json.dumps(resp, ensure_ascii=False))
|
||||||
|
normalized.append({
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": call_id,
|
||||||
|
"name": fn_name,
|
||||||
|
"content": str(res_val),
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
text = "".join(p.get("text", "") for p in parts)
|
||||||
|
normalized.append({"role": "user", "content": text})
|
||||||
|
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
|
||||||
|
return normalized
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to load session history from %s: %s", file_path, e)
|
||||||
|
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)
|
||||||
|
messages = self._cache.get(key, [])
|
||||||
|
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(messages, f, ensure_ascii=False, indent=2)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to persist session to %s: %s", file_path, e)
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Gemini Compatibility API
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
||||||
|
"""Retrieve conversation history converted into Gemini types.Content objects."""
|
||||||
|
messages = self._load_raw_messages(chat_id, thread_id)
|
||||||
|
gemini_history: list[types.Content] = []
|
||||||
|
|
||||||
|
for msg in 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:
|
||||||
self._load(chat_id, thread_id).extend(self._content_to_messages(content)); self._trim_and_save(chat_id, thread_id)
|
"""Add a single content turn (Gemini compatibility)."""
|
||||||
|
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]]:
|
||||||
return _sanitize_openai_messages(list(self._load(chat_id, thread_id)))
|
"""Retrieve conversation history in sanitized standard OpenAI messages list format."""
|
||||||
|
raw_messages = self._load_raw_messages(chat_id, thread_id)
|
||||||
|
openai_msgs: list[dict[str, Any]] = []
|
||||||
|
|
||||||
def append_openai_turn_sequence(self, chat_id: int, thread_id: Optional[int], messages: list[dict[str, Any]]) -> None:
|
for msg in raw_messages:
|
||||||
self._load(chat_id, thread_id).extend(messages); self._trim_and_save(chat_id, thread_id)
|
role = msg.get("role", "user")
|
||||||
|
out: dict[str, Any] = {"role": role}
|
||||||
|
|
||||||
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
if role == "user":
|
||||||
result = []
|
out["content"] = str(msg.get("content") or "")
|
||||||
for message in self._load(chat_id, thread_id):
|
elif role == "assistant":
|
||||||
role = message.get("role")
|
out["content"] = msg.get("content")
|
||||||
if role == "tool":
|
if msg.get("tool_calls"):
|
||||||
result.append(types.Content(role="user", parts=[types.Part.from_function_response(
|
out["tool_calls"] = msg["tool_calls"]
|
||||||
name=message.get("name", "tool"), response={"result": str(message.get("content", ""))})]))
|
elif role == "tool":
|
||||||
elif message.get("tool_calls"):
|
out["tool_call_id"] = msg.get("tool_call_id", "call_default")
|
||||||
parts = []
|
out["name"] = msg.get("name", "tool")
|
||||||
for call in message["tool_calls"]:
|
out["content"] = str(msg.get("content") or "")
|
||||||
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:
|
||||||
self._cache[self._key(chat_id, thread_id)] = []
|
"""Clear the history for this topic."""
|
||||||
try: _session_file(self.data_dir, chat_id, thread_id).unlink()
|
key = self._get_key(chat_id, thread_id)
|
||||||
except FileNotFoundError: pass
|
self._cache[key] = []
|
||||||
|
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)
|
||||||
+127
-26
@@ -19,53 +19,154 @@ 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__(self, settings=None, registry=None, conversation_manager=None):
|
def __init__(
|
||||||
|
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 = genai.Client(api_key=api_key) if api_key else None
|
self._client: Optional[genai.Client] = None
|
||||||
if not api_key: logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
if api_key:
|
||||||
|
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 = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
memory_summary = get_global_memory().get_memory_summary()
|
||||||
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, dt_context, memory]))
|
|
||||||
|
|
||||||
def _get_tools_config(self):
|
parts = [
|
||||||
|
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()
|
||||||
return [types.Tool(function_declarations=declarations)] if declarations else None
|
if not declarations:
|
||||||
|
return None
|
||||||
|
return [types.Tool(function_declarations=declarations)]
|
||||||
|
|
||||||
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 8, on_progress=None) -> str:
|
async def chat(
|
||||||
|
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 "⚠️ **Google AI Studio API Key не настроен.**\nПожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота."
|
return (
|
||||||
|
"⚠️ **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]
|
|
||||||
config = types.GenerateContentConfig(system_instruction=self._build_system_instruction(), tools=self._get_tools_config(), temperature=0.4)
|
turn_contents: list[types.Content] = [user_content]
|
||||||
|
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):
|
||||||
if on_progress: await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
logger.debug(
|
||||||
|
"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(model=self.settings.GEMINI_MODEL, contents=history, config=config)
|
response = await self._client.aio.models.generate_content(
|
||||||
|
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 "*(Пустой ответ)*"
|
||||||
turn_contents.append(types.Content(role="model", parts=[types.Part.from_text(text=final_text)]))
|
model_content = types.Content(
|
||||||
|
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_content = types.Content(role="model", parts=candidate.content.parts if candidate and candidate.content else [])
|
model_parts = candidate.content.parts if (candidate and candidate.content) else []
|
||||||
history.append(model_content); turn_contents.append(model_content)
|
model_content = types.Content(role="model", parts=model_parts)
|
||||||
response_parts = []
|
history.append(model_content)
|
||||||
for fc in response.function_calls:
|
turn_contents.append(model_content)
|
||||||
result = await self.registry.execute(fc.name, dict(fc.args) if fc.args else {})
|
|
||||||
response_parts.append(types.Part.from_function_response(name=fc.name, response={"result": result}))
|
# Execute all function calls requested by the model in this step
|
||||||
tool_content = types.Content(role="user", parts=response_parts)
|
response_parts: list[types.Part] = []
|
||||||
history.append(tool_content); turn_contents.append(tool_content)
|
for idx, fc in enumerate(function_calls, 1):
|
||||||
warning = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
fc_name = fc.name
|
||||||
|
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
|
return warning_msg
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""OpenAI-compatible Agent supporting DeepSeek and OpenAI APIs."""
|
"""OpenAI-compatible Agent supporting DeepSeek, OpenRouter, Ollama, and OpenAI."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -18,74 +18,200 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class OpenAIAgent(BaseAgent):
|
class OpenAIAgent(BaseAgent):
|
||||||
def __init__(self, settings=None, registry=None, conversation_manager=None, provider_override=None):
|
"""Agent orchestrator for DeepSeek and OpenAI-compatible models."""
|
||||||
|
|
||||||
|
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":
|
||||||
key = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
api_key_secret = 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:
|
||||||
key = self.settings.OPENAI_API_KEY
|
api_key_secret = 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] = AsyncOpenAI(
|
self._client: Optional[AsyncOpenAI] = None
|
||||||
api_key=self.api_key, base_url=self.base_url, timeout=60.0
|
if self.api_key:
|
||||||
) if self.api_key else None
|
self._client = AsyncOpenAI(
|
||||||
|
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()
|
||||||
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 = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
memory_summary = get_global_memory().get_memory_summary()
|
||||||
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, context, memory]))
|
|
||||||
|
|
||||||
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:
|
parts = [
|
||||||
|
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 "⚠️ **DeepSeek API Key не настроен.**\nДобавьте `DEEPSEEK_API_KEY` в `.env` и перезапустите бота."
|
return (
|
||||||
return "⚠️ **OpenAI / OpenAI-compatible API Key не настроен**.\nДобавьте `OPENAI_API_KEY` в `.env` и перезапустите бота."
|
"⚠️ **DeepSeek API Key не настроен.**\n\n"
|
||||||
|
"Пожалуйста, добавьте ваш ключ в `.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}
|
||||||
working: list[dict[str, Any]] = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn]
|
history.append(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:
|
||||||
await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
if iteration == 0:
|
||||||
kwargs: dict[str, Any] = {"model": self.model, "messages": working, "temperature": 0.3}
|
await on_progress("🤔 Формирую ответ...")
|
||||||
if tools: kwargs["tools"] = tools
|
else:
|
||||||
|
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 API error")
|
logger.exception("OpenAI/DeepSeek API error: %s", e)
|
||||||
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 API error")
|
logger.exception("Unexpected error calling %s: %s", self.provider, e)
|
||||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}"
|
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {str(e)}"
|
||||||
message = response.choices[0].message
|
|
||||||
if not message.tool_calls:
|
choice = response.choices[0]
|
||||||
final = message.content or "*(Пустой ответ)*"
|
choice_message = choice.message
|
||||||
sequence.append({"role": "assistant", "content": final})
|
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
# Check if model requested function calls
|
||||||
return final
|
tool_calls = choice_message.tool_calls
|
||||||
assistant_message = {"role": "assistant", "content": message.content, "tool_calls": [
|
if not tool_calls:
|
||||||
{"id": call.id, "type": "function", "function": {"name": call.function.name, "arguments": call.function.arguments}}
|
final_text = choice_message.content or "*(Пустой ответ)*"
|
||||||
for call in message.tool_calls
|
model_turn = {"role": "assistant", "content": final_text}
|
||||||
]}
|
turn_sequence.append(model_turn)
|
||||||
working.append(assistant_message); sequence.append(assistant_message)
|
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
||||||
for index, call in enumerate(message.tool_calls, 1):
|
return final_text
|
||||||
try: args = json.loads(call.function.arguments or "{}")
|
|
||||||
except Exception: args = {}
|
# Model produced tool calls
|
||||||
|
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 ""
|
|
||||||
await on_progress(f"⏳ {prefix}{format_tool_progress(call.function.name, args)}")
|
step_info = f"[{idx}/{len(tool_calls)}] " if len(tool_calls) > 1 else ""
|
||||||
result = await self.registry.execute(call.function.name, args)
|
desc = format_tool_progress(fn_name, fn_args)
|
||||||
tool_message = {"role": "tool", "tool_call_id": call.id, "name": call.function.name, "content": result}
|
await on_progress(f"⏳ {step_info}{desc}")
|
||||||
working.append(tool_message); sequence.append(tool_message)
|
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
logger.info("Executing OpenAI/DeepSeek tool call: %s(%s)", fn_name, fn_args)
|
||||||
return "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
tool_result = await self.registry.execute(fn_name, fn_args)
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Retry Telegram requests that hit flood control (HTTP 429 / TelegramRetryAfter)."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING, Any, Iterable
|
||||||
|
|
||||||
|
from aiogram.client.session.middlewares.base import BaseRequestMiddleware, NextRequestMiddlewareType
|
||||||
|
from aiogram.exceptions import TelegramRetryAfter
|
||||||
|
from aiogram.methods import TelegramMethod
|
||||||
|
from aiogram.methods.base import Response, TelegramType
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from aiogram import Bot
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Methods used to deliver the final answer to the user.
|
||||||
|
# Progress edits (editMessageText) and deletes are intentionally excluded:
|
||||||
|
# they are cosmetic and must not stall the agent while it waits out a flood limit.
|
||||||
|
DEFAULT_RETRY_METHODS: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"sendRichMessage",
|
||||||
|
"sendMessage",
|
||||||
|
"answerGuestQuery",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FloodRetryMiddleware(BaseRequestMiddleware):
|
||||||
|
"""Session middleware that waits `retry_after` seconds and retries on flood control.
|
||||||
|
|
||||||
|
Only TelegramRetryAfter is retried: Telegram guarantees the request was rejected,
|
||||||
|
so a retry cannot produce a duplicate message. Network/5xx errors are not retried
|
||||||
|
because the message might already have been delivered.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
max_retries: int = 3,
|
||||||
|
max_wait: float = 60.0,
|
||||||
|
extra_delay: float = 0.5,
|
||||||
|
methods: Iterable[str] = DEFAULT_RETRY_METHODS,
|
||||||
|
) -> None:
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.max_wait = max_wait
|
||||||
|
self.extra_delay = extra_delay
|
||||||
|
self.methods = frozenset(methods)
|
||||||
|
|
||||||
|
def _should_retry(self, method: TelegramMethod[Any]) -> bool:
|
||||||
|
return getattr(method, "__api_method__", None) in self.methods
|
||||||
|
|
||||||
|
async def __call__(
|
||||||
|
self,
|
||||||
|
make_request: NextRequestMiddlewareType[TelegramType],
|
||||||
|
bot: "Bot",
|
||||||
|
method: TelegramMethod[TelegramType],
|
||||||
|
) -> Response[TelegramType]:
|
||||||
|
if not self._should_retry(method):
|
||||||
|
return await make_request(bot, method)
|
||||||
|
|
||||||
|
attempt = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
return await make_request(bot, method)
|
||||||
|
except TelegramRetryAfter as e:
|
||||||
|
attempt += 1
|
||||||
|
wait = float(e.retry_after) + self.extra_delay
|
||||||
|
if attempt > self.max_retries or wait > self.max_wait:
|
||||||
|
logger.error(
|
||||||
|
"Flood control on %s: giving up after %d attempt(s) (retry_after=%ss)",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
e.retry_after,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
logger.warning(
|
||||||
|
"Flood control on %s: retry %d/%d in %.1fs",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
self.max_retries,
|
||||||
|
wait,
|
||||||
|
)
|
||||||
|
await asyncio.sleep(wait)
|
||||||
@@ -13,8 +13,8 @@ from homeagent.agent.base import BaseAgent
|
|||||||
from homeagent.agent.factory import create_agent
|
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.bot.retry import FloodRetryMiddleware
|
||||||
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
|
||||||
@@ -23,42 +23,58 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class TelegramAgentApp:
|
class TelegramAgentApp:
|
||||||
"""Orchestrates Telegram bot lifecycle, middleware, and durable components."""
|
"""Orchestrates Telegram bot lifecycle, middlewares, and agent 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(token=token, default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN))
|
self.bot = Bot(
|
||||||
|
token=token,
|
||||||
|
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
||||||
|
)
|
||||||
|
# Retry final-answer sends (sendRichMessage/sendMessage/answerGuestQuery) on flood control
|
||||||
|
self.bot.session.middleware(FloodRetryMiddleware())
|
||||||
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="Список доступных скиллов"),
|
||||||
@@ -72,8 +88,10 @@ 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")
|
||||||
@@ -82,8 +100,11 @@ 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)
|
||||||
|
|||||||
+196
-61
@@ -7,85 +7,220 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env",
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
TELEGRAM_BOT_TOKEN: SecretStr = Field(default=SecretStr(""))
|
# Telegram Bot
|
||||||
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(default_factory=list)
|
TELEGRAM_BOT_TOKEN: SecretStr = Field(
|
||||||
GHOST_MODE_ENABLED: bool = True
|
default=SecretStr(""),
|
||||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = "gemini"
|
description="Telegram bot token obtained from @BotFather",
|
||||||
GEMINI_API_KEY: SecretStr = Field(default=SecretStr(""))
|
)
|
||||||
GEMINI_MODEL: str = "gemini-2.5-pro"
|
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(
|
||||||
GEMINI_SUBAGENT_MODEL: str = "gemini-2.5-flash"
|
default_factory=list,
|
||||||
DEEPSEEK_API_KEY: Optional[SecretStr] = None
|
description="List of Telegram User IDs allowed to interact with the bot. Whitelist only.",
|
||||||
DEEPSEEK_BASE_URL: str = "https://api.deepseek.com"
|
)
|
||||||
DEEPSEEK_MODEL: str = "deepseek-chat"
|
GHOST_MODE_ENABLED: bool = Field(
|
||||||
DEEPSEEK_SUBAGENT_MODEL: str = "deepseek-chat"
|
default=True,
|
||||||
OPENAI_API_KEY: Optional[SecretStr] = None
|
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_BASE_URL: str = "https://api.openai.com/v1"
|
)
|
||||||
OPENAI_MODEL: str = "gpt-4o"
|
|
||||||
OPENAI_SUBAGENT_MODEL: str = "gpt-4o-mini"
|
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
||||||
SYSTEM_INSTRUCTION: str = "Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram."
|
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
||||||
JIRA_ENABLED: bool = True
|
default="gemini",
|
||||||
JIRA_URL: Optional[str] = None
|
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
||||||
JIRA_EMAIL: Optional[str] = None
|
)
|
||||||
JIRA_API_TOKEN: Optional[SecretStr] = None
|
|
||||||
JIRA_PERSONAL_ACCESS_TOKEN: Optional[SecretStr] = None
|
# Google AI Studio (Gemini)
|
||||||
GITEA_ENABLED: bool = True
|
GEMINI_API_KEY: SecretStr = Field(
|
||||||
GITEA_URL: str = "https://git.timka.su"
|
default=SecretStr(""),
|
||||||
GITEA_TOKEN: Optional[SecretStr] = None
|
description="Google AI Studio API Key",
|
||||||
WEB_SEARCH_ENABLED: bool = True
|
)
|
||||||
WEB_SEARCH_PROVIDER: Literal["duckduckgo", "tavily", "searxng"] = "duckduckgo"
|
GEMINI_MODEL: str = Field(
|
||||||
TAVILY_API_KEY: Optional[SecretStr] = None
|
default="gemini-2.5-pro",
|
||||||
SEARXNG_URL: Optional[str] = None
|
description="Gemini orchestrator model name (e.g. gemini-3.1-pro, gemini-2.5-pro)",
|
||||||
SANDBOX_ENABLED: bool = True
|
)
|
||||||
SANDBOX_BACKEND: Literal["auto", "bwrap", "docker", "process"] = "auto"
|
GEMINI_SUBAGENT_MODEL: str = Field(
|
||||||
SANDBOX_TIMEOUT_SECONDS: int = 30
|
default="gemini-2.5-flash",
|
||||||
SANDBOX_MEMORY_LIMIT_MB: int = 512
|
description="Fast Gemini model used for subagent tasks (e.g. gemini-2.5-flash)",
|
||||||
SANDBOX_CPU_LIMIT: float = 1.0
|
)
|
||||||
SANDBOX_ALLOW_NETWORK: bool = False
|
|
||||||
SANDBOX_DOCKER_IMAGE: str = "python:3.12-slim"
|
# DeepSeek API (https://api.deepseek.com)
|
||||||
GOOGLE_CALENDAR_ENABLED: bool = True
|
DEEPSEEK_API_KEY: Optional[SecretStr] = Field(
|
||||||
GOOGLE_CALENDAR_ID: str = "primary"
|
default=None,
|
||||||
GOOGLE_ADDITIONAL_CALENDAR_IDS: list[str] = Field(default_factory=list)
|
description="DeepSeek API Key (https://platform.deepseek.com)",
|
||||||
GOOGLE_AUTH_TYPE: Literal["auto", "service_account", "oauth2"] = "auto"
|
)
|
||||||
GOOGLE_SERVICE_ACCOUNT_FILE: Optional[str] = "service_account.json"
|
DEEPSEEK_BASE_URL: str = Field(
|
||||||
GOOGLE_OAUTH_CREDENTIALS_FILE: Optional[str] = "credentials.json"
|
default="https://api.deepseek.com",
|
||||||
GOOGLE_OAUTH_TOKEN_FILE: str = "data/calendar_token.json"
|
description="DeepSeek base URL (default: https://api.deepseek.com)",
|
||||||
DATA_DIR: Path = Path("data")
|
)
|
||||||
SKILLS_DIR: Path = Path("skills")
|
DEEPSEEK_MODEL: str = Field(
|
||||||
EXTENSIONS_DIR: Path = Path("extensions")
|
default="deepseek-chat",
|
||||||
LOG_LEVEL: str = "INFO"
|
description="DeepSeek model name (e.g. deepseek-chat, deepseek-reasoner)",
|
||||||
|
)
|
||||||
|
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:
|
||||||
return {"deepseek": "DeepSeek", "openai": "OpenAI-Compatible"}.get(self.LLM_PROVIDER, "Google Gemini")
|
if self.LLM_PROVIDER == "deepseek":
|
||||||
|
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:
|
||||||
return {"deepseek": self.DEEPSEEK_MODEL, "openai": self.OPENAI_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_MODEL)
|
if self.LLM_PROVIDER == "deepseek":
|
||||||
|
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:
|
||||||
return {"deepseek": self.DEEPSEEK_SUBAGENT_MODEL, "openai": self.OPENAI_SUBAGENT_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_SUBAGENT_MODEL)
|
if self.LLM_PROVIDER == "deepseek":
|
||||||
|
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, value: object) -> list[int]:
|
def parse_allowed_user_ids(cls, v: object) -> list[int]:
|
||||||
if isinstance(value, str):
|
if isinstance(v, str):
|
||||||
return [int(item.strip()) for item in value.strip().replace("[", "").replace("]", "").split(",") if item.strip()]
|
v = v.strip()
|
||||||
if isinstance(value, (int, float)): return [int(value)]
|
if not v:
|
||||||
if isinstance(value, (list, tuple, set)): return [int(item) for item in value]
|
return []
|
||||||
|
# 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, value: object) -> list[str]:
|
def parse_calendar_ids(cls, v: object) -> list[str]:
|
||||||
if isinstance(value, str): return [item.strip() for item in value.strip("[] ").replace('"', '').replace("'", '').split(",") if item.strip()]
|
if isinstance(v, str):
|
||||||
if isinstance(value, (list, tuple, set)): return [str(item).strip() for item in value if str(item).strip()]
|
v = v.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,27 +1,5 @@
|
|||||||
"""Memory package for HomeAgent."""
|
"""Memory package for HomeAgent."""
|
||||||
|
|
||||||
from pathlib import Path
|
from homeagent.memory.global_memory import GlobalMemory, MemoryItem, get_global_memory
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from homeagent.memory.global_memory import (
|
__all__ = ["GlobalMemory", "MemoryItem", "get_global_memory"]
|
||||||
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,8 +2,6 @@
|
|||||||
|
|
||||||
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
|
||||||
@@ -23,8 +21,9 @@ 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 = Path(storage_path).expanduser().resolve()
|
self.storage_path = storage_path
|
||||||
self._items: dict[str, MemoryItem] = {}
|
self._items: dict[str, MemoryItem] = {}
|
||||||
self._load()
|
self._load()
|
||||||
|
|
||||||
@@ -32,83 +31,80 @@ class GlobalMemory:
|
|||||||
if not self.storage_path.exists():
|
if not self.storage_path.exists():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
with self.storage_path.open("r", encoding="utf-8") as f:
|
with open(self.storage_path, "r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
if not isinstance(data, list):
|
for item_data in data:
|
||||||
raise ValueError("memory file must contain a JSON list")
|
item = MemoryItem(**item_data)
|
||||||
for item_data in data:
|
self._items[item.id] = item
|
||||||
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:
|
||||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
f.write(payload)
|
with open(self.storage_path, "w", encoding="utf-8") as f:
|
||||||
f.flush()
|
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
||||||
os.fsync(f.fileno())
|
except Exception as e:
|
||||||
os.replace(tmp_name, self.storage_path)
|
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
||||||
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:
|
||||||
item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
|
"""Add a new fact or preference to global memory."""
|
||||||
self._items[item.id] = item
|
item_id = str(uuid.uuid4())[:8]
|
||||||
|
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:
|
||||||
if fact_id not in self._items: return False
|
"""Remove a fact by its ID."""
|
||||||
del self._items[fact_id]; self._save(); return True
|
if fact_id in self._items:
|
||||||
|
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 [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
return [
|
||||||
|
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:
|
||||||
self._items.clear(); self._save()
|
"""Clear all stored memory."""
|
||||||
|
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:
|
||||||
if not self._items: return ""
|
"""Produce a formatted summary of remembered facts for the system prompt."""
|
||||||
|
if not self._items:
|
||||||
|
return ""
|
||||||
|
|
||||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||||
for item in list(self._items.values())[-max_items:]:
|
items = 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)
|
||||||
|
|
||||||
|
|
||||||
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
# Singleton instance container
|
||||||
_configured_memory_path: Optional[Path] = None
|
_global_memory_instance: Optional[GlobalMemory] = 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:
|
||||||
if storage_path is None:
|
global _global_memory_instance
|
||||||
storage_path = _configured_memory_path or (Path(os.getenv("DATA_DIR", "data")) / "global_memory.json")
|
if _global_memory_instance is None:
|
||||||
path = Path(storage_path).expanduser().resolve()
|
if storage_path is None:
|
||||||
if path not in _global_memory_instances:
|
storage_path = Path("data") / "global_memory.json"
|
||||||
_global_memory_instances[path] = GlobalMemory(path)
|
_global_memory_instance = GlobalMemory(storage_path)
|
||||||
return _global_memory_instances[path]
|
return _global_memory_instance
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
"""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"
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
"""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")
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Unit tests for FloodRetryMiddleware (Telegram flood control retries)."""
|
||||||
|
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from aiogram.exceptions import TelegramBadRequest, TelegramRetryAfter
|
||||||
|
from aiogram.methods import EditMessageText, SendMessage
|
||||||
|
|
||||||
|
import homeagent.bot.retry as retry_mod
|
||||||
|
from homeagent.bot.retry import FloodRetryMiddleware
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def no_sleep(monkeypatch):
|
||||||
|
sleep = AsyncMock()
|
||||||
|
monkeypatch.setattr(retry_mod.asyncio, "sleep", sleep)
|
||||||
|
return sleep
|
||||||
|
|
||||||
|
|
||||||
|
def _flood(method, seconds: int = 3) -> TelegramRetryAfter:
|
||||||
|
return TelegramRetryAfter(method=method, message="Too Many Requests", retry_after=seconds)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_retries_then_succeeds(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=[_flood(method, 3), _flood(method, 5), "ok"])
|
||||||
|
|
||||||
|
result = await FloodRetryMiddleware(extra_delay=0.5)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert result == "ok"
|
||||||
|
assert make_request.await_count == 3
|
||||||
|
assert [c.args[0] for c in no_sleep.await_args_list] == [3.5, 5.5]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_gives_up_after_max_retries(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 1))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware(max_retries=2)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 3 # 1 initial + 2 retries
|
||||||
|
|
||||||
|
|
||||||
|
async def test_gives_up_when_wait_too_long(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 600))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware(max_wait=60)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
|
no_sleep.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_does_not_retry_progress_edits(no_sleep):
|
||||||
|
method = EditMessageText(chat_id=1, message_id=1, text="⏳")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 1))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware()(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
|
no_sleep.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_does_not_retry_other_errors(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="bad *markdown")
|
||||||
|
make_request = AsyncMock(side_effect=TelegramBadRequest(method=method, message="can't parse entities"))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramBadRequest):
|
||||||
|
await FloodRetryMiddleware()(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
Reference in new issue
Block a user