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
+8
-3
@@ -9,13 +9,18 @@ services:
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# Application path inside the container; this must match the mount target.
|
||||
# Keep every persistence-aware component on the mounted host directory.
|
||||
DATA_DIR: /app/data
|
||||
extra_hosts:
|
||||
# Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
# Override DATA_DIR_HOST in .env for a path outside the project directory.
|
||||
- "${DATA_DIR_HOST:-./data}:/app/data"
|
||||
# Persistent data: sessions, global memory, scratchpad notes, tokens
|
||||
- ./data:/app/data
|
||||
# Skills and extensions mounted for customization without rebuilding
|
||||
- ./skills:/app/skills:ro
|
||||
- ./extensions:/app/extensions:ro
|
||||
- ./gcal.json:/app/gcal.json:ro
|
||||
# Uncomment to mount credentials files if placed in project root:
|
||||
# - ./service_account.json:/app/service_account.json:ro
|
||||
# - ./credentials.json:/app/credentials.json:ro
|
||||
@@ -1,8 +0,0 @@
|
||||
# ==============================================================================
|
||||
# 5. Persistent Docker data directory (optional)
|
||||
# ==============================================================================
|
||||
# Host directory mounted to /app/data by docker-compose.yml.
|
||||
# Default is ./data next to docker-compose.yml.
|
||||
# Use an absolute path if the project directory is ephemeral:
|
||||
# DATA_DIR_HOST=/srv/homeagent/data
|
||||
|
||||
+16
-29
@@ -1,52 +1,39 @@
|
||||
# Durable Docker state
|
||||
# Docker persistence runbook
|
||||
|
||||
The bot stores runtime state in `/app/data`:
|
||||
The bot stores all runtime state under `DATA_DIR`:
|
||||
|
||||
- `global_memory.json` — global facts and preferences;
|
||||
- `sessions/` — conversation history;
|
||||
- `calendar_token.json` — Google OAuth token, if enabled.
|
||||
- `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` mounts the host directory `${DATA_DIR_HOST:-./data}` to `/app/data` and sets `DATA_DIR=/app/data` inside the container.
|
||||
`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.
|
||||
|
||||
## First deployment / migration
|
||||
|
||||
Back up the existing state before recreating the container:
|
||||
## Safe upgrade
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
cp -a data "data.backup.$(date +%Y%m%d-%H%M%S)"
|
||||
|
||||
# If the old container has the only copy, copy it BEFORE removing it:
|
||||
docker cp homeagent:/app/data/. ./data/
|
||||
|
||||
docker compose config
|
||||
git pull
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
If the old state was written into the container layer at another path, find it first:
|
||||
If the old container contained the only copy of the state, copy it before removing that container:
|
||||
|
||||
```bash
|
||||
docker exec homeagent sh -lc 'find /app /root -maxdepth 4 -type f \( -name global_memory.json -o -path "*/sessions/*.json" \) -print'
|
||||
docker cp homeagent:/app/data/. ./data/
|
||||
```
|
||||
|
||||
## Verify after restart
|
||||
Check that the files are visible from the new container:
|
||||
|
||||
```bash
|
||||
docker compose exec homeagent sh -lc '\
|
||||
printf "DATA_DIR=%s\\n" "$DATA_DIR"; \
|
||||
mount | grep /app/data; \
|
||||
ls -la /app/data; \
|
||||
find /app/data/sessions -type f 2>/dev/null | head'
|
||||
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'
|
||||
```
|
||||
|
||||
Then restart and verify the same files remain:
|
||||
A previous `No space left on device` error can still prevent persistence. Check the host before deployment:
|
||||
|
||||
```bash
|
||||
docker compose restart homeagent
|
||||
df -h .
|
||||
docker system df
|
||||
```
|
||||
|
||||
## Important
|
||||
|
||||
- Do not run `docker compose down -v` before backing up `data/`.
|
||||
- Check `df -h .` and `docker system df`: a previous `No space left on device` error can prevent writes.
|
||||
- This change cannot recover data that was already deleted; it only prevents future loss once deployed.
|
||||
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 logging
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from google.genai import types
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _session_file(data_dir: Path, chat_id: int, thread_id: Optional[int]) -> Path:
|
||||
thread_suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
||||
return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json"
|
||||
suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
||||
return data_dir / "sessions" / f"session_{chat_id}_{suffix}.json"
|
||||
|
||||
|
||||
def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.
|
||||
def _atomic_write_json(path: Path, value: object) -> None:
|
||||
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.
|
||||
2. Tool responses matching call IDs are properly aligned.
|
||||
3. Dangling tool calls or orphan tool messages are safely cleaned up.
|
||||
"""
|
||||
sanitized: list[dict[str, Any]] = []
|
||||
|
||||
def _sanitize_openai_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Remove incomplete tool-call chains before sending history to OpenAI APIs."""
|
||||
result: list[dict[str, Any]] = []
|
||||
i = 0
|
||||
n = len(raw_messages)
|
||||
|
||||
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
|
||||
while i < len(messages):
|
||||
message = dict(messages[i])
|
||||
if message.get("role") == "tool":
|
||||
i += 1
|
||||
continue
|
||||
calls = message.get("tool_calls") if message.get("role") == "assistant" else None
|
||||
if not calls:
|
||||
result.append(message); i += 1; continue
|
||||
following: list[dict[str, Any]] = []
|
||||
j = i + 1
|
||||
while j < len(messages) and messages[j].get("role") == "tool":
|
||||
following.append(dict(messages[j])); j += 1
|
||||
by_name = {item.get("name"): item for item in following}
|
||||
valid_calls: list[dict[str, Any]] = []
|
||||
valid_tools: list[dict[str, Any]] = []
|
||||
for call in calls:
|
||||
fn = call.get("function", {})
|
||||
tool = next((item for item in following if item.get("tool_call_id") == call.get("id")
|
||||
or item.get("name") == fn.get("name")), None)
|
||||
if tool is not None:
|
||||
tool = dict(tool); tool["tool_call_id"] = call.get("id")
|
||||
valid_calls.append(dict(call)); valid_tools.append(tool)
|
||||
if valid_calls:
|
||||
message["tool_calls"] = valid_calls
|
||||
result.append(message); result.extend(valid_tools)
|
||||
elif message.get("content"):
|
||||
result.append({"role": "assistant", "content": message["content"]})
|
||||
i = j
|
||||
return result
|
||||
|
||||
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:
|
||||
# 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
|
||||
def _part_text(part: Any) -> str:
|
||||
return str(getattr(part, "text", "") or "")
|
||||
|
||||
|
||||
class ConversationManager:
|
||||
"""Manages chat and topic history with disk persistence and multi-provider format support."""
|
||||
|
||||
"""Stores each chat/topic history in DATA_DIR/sessions on durable storage."""
|
||||
def __init__(self, data_dir: Path, max_turns: int = 20) -> None:
|
||||
self.data_dir = data_dir
|
||||
self.data_dir = Path(data_dir).expanduser().resolve()
|
||||
self.max_turns = max_turns
|
||||
self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {}
|
||||
(self.data_dir / "sessions").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _get_key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]:
|
||||
return (chat_id, thread_id)
|
||||
|
||||
def _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 _key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]:
|
||||
return chat_id, thread_id
|
||||
|
||||
def _load(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
||||
key = self._key(chat_id, thread_id)
|
||||
if key in self._cache: return self._cache[key]
|
||||
path = _session_file(self.data_dir, chat_id, thread_id)
|
||||
if not path.exists(): self._cache[key] = []; return self._cache[key]
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
raw_data = json.load(f)
|
||||
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
normalized: list[dict[str, Any]] = []
|
||||
pending_tool_call_ids: dict[str, list[str]] = {}
|
||||
|
||||
for turn_idx, item in enumerate(raw_data):
|
||||
# 1. Check if legacy Gemini format with "parts"
|
||||
if "parts" in item:
|
||||
role = item.get("role", "user")
|
||||
parts = item.get("parts", [])
|
||||
if role == "user":
|
||||
# Check for function_response
|
||||
fr_parts = [p for p in parts if "function_response" in p]
|
||||
if fr_parts:
|
||||
for p in fr_parts:
|
||||
fr = p["function_response"]
|
||||
fn_name = fr.get("name", "tool")
|
||||
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)
|
||||
|
||||
pending: dict[str, list[str]] = {}
|
||||
for turn, item in enumerate(raw):
|
||||
if "parts" not in item:
|
||||
normalized.append(item); continue
|
||||
role, parts = item.get("role", "user"), item.get("parts", [])
|
||||
if role == "user":
|
||||
responses = [p["function_response"] for p in parts if "function_response" in p]
|
||||
if responses:
|
||||
for response in responses:
|
||||
name = response.get("name", "tool")
|
||||
ids = pending.get(name, [])
|
||||
call_id = ids.pop(0) if ids else f"call_{turn}_{name}"
|
||||
result = response.get("response", {})
|
||||
normalized.append({"role":"tool", "tool_call_id":call_id, "name":name,
|
||||
"content":str(result.get("result", result))})
|
||||
else:
|
||||
normalized.append({"role":"user", "content":"".join(p.get("text", "") for p in parts)})
|
||||
elif role == "model":
|
||||
calls = [p["function_call"] for p in parts if "function_call" in p]
|
||||
if calls:
|
||||
tool_calls = []
|
||||
for idx, call in enumerate(calls):
|
||||
name = call.get("name", "tool"); call_id = f"call_{turn}_{idx}_{name}"
|
||||
pending.setdefault(name, []).append(call_id)
|
||||
args = call.get("args", {})
|
||||
tool_calls.append({"id":call_id,"type":"function","function":{
|
||||
"name":name,"arguments":json.dumps(args, ensure_ascii=False)}})
|
||||
normalized.append({"role":"assistant","content":None,"tool_calls":tool_calls})
|
||||
else:
|
||||
normalized.append({"role":"assistant","content":"".join(p.get("text", "") for p in parts)})
|
||||
self._cache[key] = normalized
|
||||
return normalized
|
||||
except Exception as e:
|
||||
logger.error("Failed to load session history from %s: %s", file_path, e)
|
||||
except Exception:
|
||||
logger.exception("Failed to load session history from %s", path)
|
||||
self._cache[key] = []
|
||||
return self._cache[key]
|
||||
return self._cache[key]
|
||||
|
||||
def _save_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
messages = self._cache.get(key, [])
|
||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||
def _save(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
_atomic_write_json(_session_file(self.data_dir, chat_id, thread_id), self._cache[self._key(chat_id, thread_id)])
|
||||
|
||||
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 _content_to_messages(self, content: types.Content) -> list[dict[str, Any]]:
|
||||
role = "assistant" if content.role in ("model", "assistant") else "user"
|
||||
messages: list[dict[str, Any]] = []; text = ""; calls = []
|
||||
for part in content.parts or []:
|
||||
if getattr(part, "function_call", None):
|
||||
call = part.function_call; name = call.name or "tool"
|
||||
calls.append({"id":f"call_{os.urandom(6).hex()}","type":"function",
|
||||
"function":{"name":name,"arguments":json.dumps(dict(call.args or {}), ensure_ascii=False)}})
|
||||
elif getattr(part, "function_response", None):
|
||||
response = part.function_response; name = response.name or "tool"; value = response.response or {}
|
||||
messages.append({"role":"tool","name":name,"content":str(value.get("result", value))})
|
||||
else: text += _part_text(part)
|
||||
if calls: messages.insert(0, {"role":role,"content":text or None,"tool_calls":calls})
|
||||
elif text or not messages: messages.insert(0, {"role":role,"content":text})
|
||||
return messages
|
||||
|
||||
def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None:
|
||||
"""Add a single content turn (Gemini compatibility)."""
|
||||
self.append_turn_sequence(chat_id, thread_id, [content])
|
||||
self._load(chat_id, thread_id).extend(self._content_to_messages(content)); self._trim_and_save(chat_id, thread_id)
|
||||
|
||||
def append_turn_sequence(self, chat_id: int, thread_id: Optional[int], contents: list[types.Content]) -> None:
|
||||
for content in contents: self._load(chat_id, thread_id).extend(self._content_to_messages(content))
|
||||
self._trim_and_save(chat_id, thread_id)
|
||||
|
||||
def _trim_and_save(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
items = self._load(chat_id, thread_id)
|
||||
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]]:
|
||||
"""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]] = []
|
||||
return _sanitize_openai_messages(list(self._load(chat_id, thread_id)))
|
||||
|
||||
for msg in raw_messages:
|
||||
role = msg.get("role", "user")
|
||||
out: dict[str, Any] = {"role": role}
|
||||
def append_openai_turn_sequence(self, chat_id: int, thread_id: Optional[int], messages: list[dict[str, Any]]) -> None:
|
||||
self._load(chat_id, thread_id).extend(messages); self._trim_and_save(chat_id, thread_id)
|
||||
|
||||
if role == "user":
|
||||
out["content"] = str(msg.get("content") or "")
|
||||
elif role == "assistant":
|
||||
out["content"] = msg.get("content")
|
||||
if msg.get("tool_calls"):
|
||||
out["tool_calls"] = msg["tool_calls"]
|
||||
elif role == "tool":
|
||||
out["tool_call_id"] = msg.get("tool_call_id", "call_default")
|
||||
out["name"] = msg.get("name", "tool")
|
||||
out["content"] = str(msg.get("content") or "")
|
||||
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
||||
result = []
|
||||
for message in self._load(chat_id, thread_id):
|
||||
role = message.get("role")
|
||||
if role == "tool":
|
||||
result.append(types.Content(role="user", parts=[types.Part.from_function_response(
|
||||
name=message.get("name", "tool"), response={"result": str(message.get("content", ""))})]))
|
||||
elif message.get("tool_calls"):
|
||||
parts = []
|
||||
for call in message["tool_calls"]:
|
||||
fn = call.get("function", {}); args = fn.get("arguments", "{}")
|
||||
try: args = json.loads(args) if isinstance(args, str) else args
|
||||
except json.JSONDecodeError: args = {}
|
||||
parts.append(types.Part.from_function_call(name=fn.get("name", "tool"), args=args))
|
||||
result.append(types.Content(role="model", parts=parts))
|
||||
else:
|
||||
result.append(types.Content(role="model" if role == "assistant" else "user",
|
||||
parts=[types.Part.from_text(text=str(message.get("content", "")))]))
|
||||
return result
|
||||
|
||||
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:
|
||||
"""Clear the history for this topic."""
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
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)
|
||||
self._cache[self._key(chat_id, thread_id)] = []
|
||||
try: _session_file(self.data_dir, chat_id, thread_id).unlink()
|
||||
except FileNotFoundError: pass
|
||||
+26
-127
@@ -19,154 +19,53 @@ logger = logging.getLogger(__name__)
|
||||
class GeminiAgent(BaseAgent):
|
||||
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
conversation_manager: Optional[ConversationManager] = None,
|
||||
) -> None:
|
||||
def __init__(self, settings=None, registry=None, conversation_manager=None):
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||
|
||||
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
||||
self._client: Optional[genai.Client] = None
|
||||
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.")
|
||||
self._client = genai.Client(api_key=api_key) if api_key else None
|
||||
if not api_key: logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
||||
|
||||
def _build_system_instruction(self) -> str:
|
||||
now = datetime.now()
|
||||
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 = [
|
||||
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]]:
|
||||
def _get_tools_config(self):
|
||||
declarations = self.registry.get_function_declarations()
|
||||
if not declarations:
|
||||
return None
|
||||
return [types.Tool(function_declarations=declarations)]
|
||||
return [types.Tool(function_declarations=declarations)] if declarations else None
|
||||
|
||||
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."""
|
||||
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 8, on_progress=None) -> str:
|
||||
if not self._client:
|
||||
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
|
||||
return "⚠️ **Google AI Studio API Key не настроен.**\nПожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота."
|
||||
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
||||
|
||||
# 2. Add current user message
|
||||
user_content = types.Content(
|
||||
role="user",
|
||||
parts=[types.Part.from_text(text=user_message)],
|
||||
)
|
||||
user_content = types.Content(role="user", parts=[types.Part.from_text(text=user_message)])
|
||||
history.append(user_content)
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
turn_contents = [user_content]
|
||||
config = types.GenerateContentConfig(system_instruction=self._build_system_instruction(), tools=self._get_tools_config(), temperature=0.4)
|
||||
for iteration in range(max_tool_iterations):
|
||||
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})...")
|
||||
|
||||
if on_progress: await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||
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:
|
||||
logger.exception("Error calling Gemini API: %s", e)
|
||||
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
||||
|
||||
# Check if model requested function calls
|
||||
function_calls = response.function_calls
|
||||
if not function_calls:
|
||||
# Final response reached
|
||||
if not response.function_calls:
|
||||
final_text = response.text or "*(Пустой ответ)*"
|
||||
model_content = types.Content(
|
||||
role="model",
|
||||
parts=[types.Part.from_text(text=final_text)],
|
||||
)
|
||||
turn_contents.append(model_content)
|
||||
turn_contents.append(types.Content(role="model", parts=[types.Part.from_text(text=final_text)]))
|
||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||
return final_text
|
||||
|
||||
# Model produced function calls
|
||||
# Save the model's message with function calls
|
||||
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=model_parts)
|
||||
history.append(model_content)
|
||||
turn_contents.append(model_content)
|
||||
|
||||
# Execute all function calls requested by the model in this step
|
||||
response_parts: list[types.Part] = []
|
||||
for idx, fc in enumerate(function_calls, 1):
|
||||
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 = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||
model_content = types.Content(role="model", parts=candidate.content.parts if candidate and candidate.content else [])
|
||||
history.append(model_content); turn_contents.append(model_content)
|
||||
response_parts = []
|
||||
for fc in response.function_calls:
|
||||
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}))
|
||||
tool_content = types.Content(role="user", parts=response_parts)
|
||||
history.append(tool_content); turn_contents.append(tool_content)
|
||||
warning = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||
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 logging
|
||||
@@ -18,200 +18,74 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OpenAIAgent(BaseAgent):
|
||||
"""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:
|
||||
def __init__(self, settings=None, registry=None, conversation_manager=None, provider_override=None):
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||
self.provider = provider_override or self.settings.LLM_PROVIDER
|
||||
|
||||
# Resolve configuration based on provider
|
||||
if self.provider == "deepseek":
|
||||
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 ""
|
||||
key = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
||||
self.base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
||||
self.model = self.settings.DEEPSEEK_MODEL or "deepseek-chat"
|
||||
else:
|
||||
api_key_secret = self.settings.OPENAI_API_KEY
|
||||
self.api_key = api_key_secret.get_secret_value() if api_key_secret else ""
|
||||
key = self.settings.OPENAI_API_KEY
|
||||
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
||||
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
|
||||
|
||||
self._client: Optional[AsyncOpenAI] = None
|
||||
if self.api_key:
|
||||
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(),
|
||||
)
|
||||
self.api_key = key.get_secret_value() if key else ""
|
||||
self._client: Optional[AsyncOpenAI] = AsyncOpenAI(
|
||||
api_key=self.api_key, base_url=self.base_url, timeout=60.0
|
||||
) if self.api_key else None
|
||||
|
||||
def _build_system_instruction(self) -> str:
|
||||
now = datetime.now()
|
||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||
memory_summary = get_global_memory().get_memory_summary()
|
||||
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()
|
||||
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, context, memory]))
|
||||
|
||||
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."""
|
||||
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:
|
||||
if not self._client:
|
||||
if self.provider == "deepseek":
|
||||
return (
|
||||
"⚠️ **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"
|
||||
"```"
|
||||
)
|
||||
return "⚠️ **DeepSeek API Key не настроен.**\nДобавьте `DEEPSEEK_API_KEY` в `.env` и перезапустите бота."
|
||||
return "⚠️ **OpenAI / OpenAI-compatible API Key не настроен**.\nДобавьте `OPENAI_API_KEY` в `.env` и перезапустите бота."
|
||||
|
||||
# 1. Fetch current conversation history
|
||||
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}
|
||||
history.append(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]
|
||||
working: list[dict[str, Any]] = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn]
|
||||
sequence: list[dict[str, Any]] = [user_turn]
|
||||
tools = self.registry.get_openai_tools()
|
||||
|
||||
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 iteration == 0:
|
||||
await on_progress("🤔 Формирую ответ...")
|
||||
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
|
||||
|
||||
await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||
kwargs: dict[str, Any] = {"model": self.model, "messages": working, "temperature": 0.3}
|
||||
if tools: kwargs["tools"] = tools
|
||||
try:
|
||||
response = await self._client.chat.completions.create(**kwargs)
|
||||
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}"
|
||||
except Exception as e:
|
||||
logger.exception("Unexpected error calling %s: %s", self.provider, e)
|
||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
choice = response.choices[0]
|
||||
choice_message = choice.message
|
||||
|
||||
# Check if model requested function calls
|
||||
tool_calls = choice_message.tool_calls
|
||||
if not tool_calls:
|
||||
final_text = choice_message.content or "*(Пустой ответ)*"
|
||||
model_turn = {"role": "assistant", "content": final_text}
|
||||
turn_sequence.append(model_turn)
|
||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
||||
return final_text
|
||||
|
||||
# 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 = {}
|
||||
|
||||
logger.exception("Unexpected API error")
|
||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}"
|
||||
message = response.choices[0].message
|
||||
if not message.tool_calls:
|
||||
final = message.content or "*(Пустой ответ)*"
|
||||
sequence.append({"role": "assistant", "content": final})
|
||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
||||
return final
|
||||
assistant_message = {"role": "assistant", "content": message.content, "tool_calls": [
|
||||
{"id": call.id, "type": "function", "function": {"name": call.function.name, "arguments": call.function.arguments}}
|
||||
for call in message.tool_calls
|
||||
]}
|
||||
working.append(assistant_message); sequence.append(assistant_message)
|
||||
for index, call in enumerate(message.tool_calls, 1):
|
||||
try: args = json.loads(call.function.arguments or "{}")
|
||||
except Exception: args = {}
|
||||
if on_progress:
|
||||
from homeagent.bot.progress import format_tool_progress
|
||||
|
||||
step_info = f"[{idx}/{len(tool_calls)}] " if len(tool_calls) > 1 else ""
|
||||
desc = format_tool_progress(fn_name, fn_args)
|
||||
await on_progress(f"⏳ {step_info}{desc}")
|
||||
|
||||
logger.info("Executing OpenAI/DeepSeek tool call: %s(%s)", fn_name, fn_args)
|
||||
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
|
||||
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)}")
|
||||
result = await self.registry.execute(call.function.name, args)
|
||||
tool_message = {"role": "tool", "tool_call_id": call.id, "name": call.function.name, "content": result}
|
||||
working.append(tool_message); sequence.append(tool_message)
|
||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
||||
return "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||
@@ -14,6 +14,7 @@ from homeagent.agent.factory import create_agent
|
||||
from homeagent.bot.handlers import create_bot_router
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
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.tools.loader import load_extensions_from_directory
|
||||
from homeagent.tools.registry import get_tool_registry
|
||||
@@ -22,56 +23,42 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
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:
|
||||
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()
|
||||
|
||||
# Load dynamic extensions from directory
|
||||
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
||||
|
||||
# Initialize skills
|
||||
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
||||
|
||||
# Initialize LLM agent according to active provider (Gemini, DeepSeek, or OpenAI)
|
||||
self.agent: BaseAgent = create_agent(
|
||||
settings=self.settings,
|
||||
registry=self.registry,
|
||||
)
|
||||
self.agent: BaseAgent = create_agent(settings=self.settings, registry=self.registry)
|
||||
|
||||
token = self.settings.TELEGRAM_BOT_TOKEN.get_secret_value().strip()
|
||||
self.bot: Optional[Bot] = None
|
||||
self.dp = Dispatcher()
|
||||
|
||||
if token:
|
||||
try:
|
||||
self.bot = Bot(
|
||||
token=token,
|
||||
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
||||
)
|
||||
self.bot = Bot(token=token, default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN))
|
||||
except Exception as 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)
|
||||
self.dp.message.middleware(whitelist_middleware)
|
||||
self.dp.guest_message.middleware(whitelist_middleware)
|
||||
|
||||
# Register router
|
||||
router = create_bot_router(
|
||||
self.dp.include_router(create_bot_router(
|
||||
settings=self.settings,
|
||||
agent=self.agent,
|
||||
skill_manager=self.skill_manager,
|
||||
tool_registry=self.registry,
|
||||
)
|
||||
self.dp.include_router(router)
|
||||
))
|
||||
|
||||
async def _setup_commands(self) -> None:
|
||||
"""Register command menu in Telegram UI."""
|
||||
if not self.bot:
|
||||
return
|
||||
|
||||
commands = [
|
||||
BotCommand(command="start", description="Запустить бота / статус"),
|
||||
BotCommand(command="skills", description="Список доступных скиллов"),
|
||||
@@ -85,10 +72,8 @@ class TelegramAgentApp:
|
||||
logger.warning("Failed to set bot commands menu: %s", e)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start Telegram bot polling."""
|
||||
if not self.bot:
|
||||
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
||||
|
||||
logger.info("Starting HomeAgent Telegram Bot...")
|
||||
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")
|
||||
@@ -97,11 +82,8 @@ class TelegramAgentApp:
|
||||
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("Loaded Skills (%d): %s", len(self.skill_manager.list_skills()), [s.name for s in self.skill_manager.list_skills()])
|
||||
|
||||
await self._setup_commands()
|
||||
|
||||
try:
|
||||
# Delete any webhooks and start polling with automatically resolved update types (including guest_message)
|
||||
await self.bot.delete_webhook(drop_pending_updates=True)
|
||||
allowed_updates = self.dp.resolve_used_update_types()
|
||||
logger.info("Polling with allowed_updates: %s", allowed_updates)
|
||||
|
||||
+61
-196
@@ -7,220 +7,85 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
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
|
||||
TELEGRAM_BOT_TOKEN: SecretStr = Field(
|
||||
default=SecretStr(""),
|
||||
description="Telegram bot token obtained from @BotFather",
|
||||
)
|
||||
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(
|
||||
default_factory=list,
|
||||
description="List of Telegram User IDs allowed to interact with the bot. Whitelist only.",
|
||||
)
|
||||
GHOST_MODE_ENABLED: bool = Field(
|
||||
default=True,
|
||||
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.",
|
||||
)
|
||||
|
||||
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
||||
default="gemini",
|
||||
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
||||
)
|
||||
|
||||
# Google AI Studio (Gemini)
|
||||
GEMINI_API_KEY: SecretStr = Field(
|
||||
default=SecretStr(""),
|
||||
description="Google AI Studio API Key",
|
||||
)
|
||||
GEMINI_MODEL: str = Field(
|
||||
default="gemini-2.5-pro",
|
||||
description="Gemini orchestrator model name (e.g. gemini-3.1-pro, gemini-2.5-pro)",
|
||||
)
|
||||
GEMINI_SUBAGENT_MODEL: str = Field(
|
||||
default="gemini-2.5-flash",
|
||||
description="Fast Gemini model used for subagent tasks (e.g. gemini-2.5-flash)",
|
||||
)
|
||||
|
||||
# DeepSeek API (https://api.deepseek.com)
|
||||
DEEPSEEK_API_KEY: Optional[SecretStr] = Field(
|
||||
default=None,
|
||||
description="DeepSeek API Key (https://platform.deepseek.com)",
|
||||
)
|
||||
DEEPSEEK_BASE_URL: str = Field(
|
||||
default="https://api.deepseek.com",
|
||||
description="DeepSeek base URL (default: https://api.deepseek.com)",
|
||||
)
|
||||
DEEPSEEK_MODEL: str = Field(
|
||||
default="deepseek-chat",
|
||||
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")
|
||||
TELEGRAM_BOT_TOKEN: SecretStr = Field(default=SecretStr(""))
|
||||
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(default_factory=list)
|
||||
GHOST_MODE_ENABLED: bool = True
|
||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = "gemini"
|
||||
GEMINI_API_KEY: SecretStr = Field(default=SecretStr(""))
|
||||
GEMINI_MODEL: str = "gemini-2.5-pro"
|
||||
GEMINI_SUBAGENT_MODEL: str = "gemini-2.5-flash"
|
||||
DEEPSEEK_API_KEY: Optional[SecretStr] = None
|
||||
DEEPSEEK_BASE_URL: str = "https://api.deepseek.com"
|
||||
DEEPSEEK_MODEL: str = "deepseek-chat"
|
||||
DEEPSEEK_SUBAGENT_MODEL: str = "deepseek-chat"
|
||||
OPENAI_API_KEY: Optional[SecretStr] = None
|
||||
OPENAI_BASE_URL: str = "https://api.openai.com/v1"
|
||||
OPENAI_MODEL: str = "gpt-4o"
|
||||
OPENAI_SUBAGENT_MODEL: str = "gpt-4o-mini"
|
||||
SYSTEM_INSTRUCTION: str = "Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram."
|
||||
JIRA_ENABLED: bool = True
|
||||
JIRA_URL: Optional[str] = None
|
||||
JIRA_EMAIL: Optional[str] = None
|
||||
JIRA_API_TOKEN: Optional[SecretStr] = None
|
||||
JIRA_PERSONAL_ACCESS_TOKEN: Optional[SecretStr] = None
|
||||
GITEA_ENABLED: bool = True
|
||||
GITEA_URL: str = "https://git.timka.su"
|
||||
GITEA_TOKEN: Optional[SecretStr] = None
|
||||
WEB_SEARCH_ENABLED: bool = True
|
||||
WEB_SEARCH_PROVIDER: Literal["duckduckgo", "tavily", "searxng"] = "duckduckgo"
|
||||
TAVILY_API_KEY: Optional[SecretStr] = None
|
||||
SEARXNG_URL: Optional[str] = None
|
||||
SANDBOX_ENABLED: bool = True
|
||||
SANDBOX_BACKEND: Literal["auto", "bwrap", "docker", "process"] = "auto"
|
||||
SANDBOX_TIMEOUT_SECONDS: int = 30
|
||||
SANDBOX_MEMORY_LIMIT_MB: int = 512
|
||||
SANDBOX_CPU_LIMIT: float = 1.0
|
||||
SANDBOX_ALLOW_NETWORK: bool = False
|
||||
SANDBOX_DOCKER_IMAGE: str = "python:3.12-slim"
|
||||
GOOGLE_CALENDAR_ENABLED: bool = True
|
||||
GOOGLE_CALENDAR_ID: str = "primary"
|
||||
GOOGLE_ADDITIONAL_CALENDAR_IDS: list[str] = Field(default_factory=list)
|
||||
GOOGLE_AUTH_TYPE: Literal["auto", "service_account", "oauth2"] = "auto"
|
||||
GOOGLE_SERVICE_ACCOUNT_FILE: Optional[str] = "service_account.json"
|
||||
GOOGLE_OAUTH_CREDENTIALS_FILE: Optional[str] = "credentials.json"
|
||||
GOOGLE_OAUTH_TOKEN_FILE: str = "data/calendar_token.json"
|
||||
DATA_DIR: Path = Path("data")
|
||||
SKILLS_DIR: Path = Path("skills")
|
||||
EXTENSIONS_DIR: Path = Path("extensions")
|
||||
LOG_LEVEL: str = "INFO"
|
||||
|
||||
def get_active_provider_name(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return "DeepSeek"
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return "OpenAI-Compatible"
|
||||
return "Google Gemini"
|
||||
return {"deepseek": "DeepSeek", "openai": "OpenAI-Compatible"}.get(self.LLM_PROVIDER, "Google Gemini")
|
||||
|
||||
def get_active_model(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return self.DEEPSEEK_MODEL
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return self.OPENAI_MODEL
|
||||
return self.GEMINI_MODEL
|
||||
return {"deepseek": self.DEEPSEEK_MODEL, "openai": self.OPENAI_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_MODEL)
|
||||
|
||||
def get_active_subagent_model(self) -> str:
|
||||
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
|
||||
return {"deepseek": self.DEEPSEEK_SUBAGENT_MODEL, "openai": self.OPENAI_SUBAGENT_MODEL}.get(self.LLM_PROVIDER, self.GEMINI_SUBAGENT_MODEL)
|
||||
|
||||
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
||||
@classmethod
|
||||
def parse_allowed_user_ids(cls, v: object) -> list[int]:
|
||||
if isinstance(v, str):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
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]
|
||||
def parse_allowed_user_ids(cls, value: object) -> list[int]:
|
||||
if isinstance(value, str):
|
||||
return [int(item.strip()) for item in value.strip().replace("[", "").replace("]", "").split(",") if item.strip()]
|
||||
if isinstance(value, (int, float)): return [int(value)]
|
||||
if isinstance(value, (list, tuple, set)): return [int(item) for item in value]
|
||||
return []
|
||||
|
||||
@field_validator("GOOGLE_ADDITIONAL_CALENDAR_IDS", mode="after")
|
||||
@classmethod
|
||||
def parse_calendar_ids(cls, v: object) -> list[str]:
|
||||
if isinstance(v, str):
|
||||
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()]
|
||||
def parse_calendar_ids(cls, value: object) -> list[str]:
|
||||
if isinstance(value, str): return [item.strip() for item in value.strip("[] ").replace('"', '').replace("'", '').split(",") if item.strip()]
|
||||
if isinstance(value, (list, tuple, set)): return [str(item).strip() for item in value if str(item).strip()]
|
||||
return []
|
||||
|
||||
|
||||
def get_settings() -> Settings:
|
||||
"""Retrieve application 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)
|
||||
return settings
|
||||
@@ -1,5 +1,27 @@
|
||||
"""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",
|
||||
]
|
||||
@@ -23,7 +23,6 @@ class MemoryItem:
|
||||
|
||||
class GlobalMemory:
|
||||
"""Persistent global memory store shared across all forum topics."""
|
||||
|
||||
def __init__(self, storage_path: Path):
|
||||
self.storage_path = Path(storage_path).expanduser().resolve()
|
||||
self._items: dict[str, MemoryItem] = {}
|
||||
@@ -47,20 +46,21 @@ class GlobalMemory:
|
||||
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, temporary_path = tempfile.mkstemp(
|
||||
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
|
||||
)
|
||||
fd, tmp_name = tempfile.mkstemp(prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(temporary_path, self.storage_path)
|
||||
except Exception:
|
||||
os.replace(tmp_name, self.storage_path)
|
||||
try:
|
||||
os.unlink(temporary_path)
|
||||
except OSError:
|
||||
pass
|
||||
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:
|
||||
@@ -71,11 +71,8 @@ class GlobalMemory:
|
||||
return item
|
||||
|
||||
def remove_fact(self, fact_id: str) -> bool:
|
||||
if fact_id not in self._items:
|
||||
return False
|
||||
del self._items[fact_id]
|
||||
self._save()
|
||||
return True
|
||||
if fact_id not in self._items: return False
|
||||
del self._items[fact_id]; self._save(); return True
|
||||
|
||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||
if category:
|
||||
@@ -88,12 +85,10 @@ class GlobalMemory:
|
||||
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
||||
|
||||
def clear(self) -> None:
|
||||
self._items.clear()
|
||||
self._save()
|
||||
self._items.clear(); self._save()
|
||||
|
||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||
if not self._items:
|
||||
return ""
|
||||
if not self._items: return ""
|
||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||
for item in list(self._items.values())[-max_items:]:
|
||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||
@@ -101,16 +96,18 @@ class GlobalMemory:
|
||||
|
||||
|
||||
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
||||
_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:
|
||||
"""Get the memory store keyed by its absolute path.
|
||||
|
||||
DATA_DIR is used in Docker and keeps this store aligned with the mounted
|
||||
application directory even when the process working directory changes.
|
||||
"""
|
||||
if storage_path is None:
|
||||
storage_path = Path(os.environ.get("DATA_DIR", "data")) / "global_memory.json"
|
||||
storage_path = _configured_memory_path or (Path(os.getenv("DATA_DIR", "data")) / "global_memory.json")
|
||||
path = Path(storage_path).expanduser().resolve()
|
||||
if path not in _global_memory_instances:
|
||||
_global_memory_instances[path] = GlobalMemory(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"
|
||||
@@ -1,24 +1,14 @@
|
||||
"""Regression tests for durable global memory."""
|
||||
"""Regression coverage for configured global-memory location."""
|
||||
|
||||
from homeagent.memory.global_memory import GlobalMemory, get_global_memory
|
||||
from homeagent.memory.global_memory import configure_global_memory_path, get_global_memory
|
||||
|
||||
|
||||
def test_memory_survives_new_instance(tmp_path):
|
||||
path = tmp_path / "data" / "global_memory.json"
|
||||
memory = GlobalMemory(path)
|
||||
item = memory.add_fact("сохранить после рестарта", category="reliability")
|
||||
def test_configured_memory_path_is_used(tmp_path):
|
||||
configured = tmp_path / "mounted-data" / "global_memory.json"
|
||||
configure_global_memory_path(configured)
|
||||
|
||||
restarted = GlobalMemory(path)
|
||||
assert restarted.search("рестарта")[0].id == item.id
|
||||
assert not list(path.parent.glob("*.tmp"))
|
||||
memory = get_global_memory()
|
||||
memory.add_fact("configured path survives restart")
|
||||
|
||||
|
||||
def test_memory_uses_distinct_paths(tmp_path):
|
||||
first_path = tmp_path / "one" / "global_memory.json"
|
||||
second_path = tmp_path / "two" / "global_memory.json"
|
||||
first = get_global_memory(first_path)
|
||||
second = get_global_memory(second_path)
|
||||
|
||||
assert first is not second
|
||||
first.add_fact("только в первом")
|
||||
assert second.list_facts() == []
|
||||
assert configured.exists()
|
||||
assert "configured path survives restart" in configured.read_text(encoding="utf-8")
|
||||
Reference in new issue
Block a user