Oliver-ai-bot_2.0/backend/app/tasks/agent_sync.py
Vadym Samoilenko f2b5dce63a feat: code interpreter, agent analytics/execute APIs, usage sync, RAG scoping fixes
**Phase 1 — Agent Usage Sync to AgentHub Collector**
- Add agent_usage service: per-agent stats (messages, tokens, conversations, unique users, first/last used)
- Collector sync now includes usage data in payload; sync_agent accepts optional db session
- Celery beat task runs every 6h to sync all active agents with fresh usage stats

**Phase 2 — LibreCodeInterpreter Integration**
- Add code-interpreter, redis, minio services to docker-compose.prod.yml
- CodeInterpreterTool (BaseTool): sandboxed execution via /exec, 13 languages, Python session persistence via conversation_id
- ToolContext extended with conversation_id and agent_slug
- enable_code_interpreter boolean on Agent model (migration 027), tool seeded in tool_definitions (migration 026)
- Code interpreter auto-injected into agent tools when enabled
- Frontend: CodeExecutionResult component with terminal-style stdout/stderr/files rendering

**Phase 3 — Agent API Endpoints**
- GET /api/v1/agents/{slug}/analytics — per-agent usage stats + daily time series
- POST /api/v1/agents/{slug}/execute — synchronous programmatic agent execution (non-SSE)
- Sub-routes registered before /{slug} to avoid FastAPI route conflict

**Phase 4 — Fix Department & Region RAG Scoping**
- Department filter now OR-includes global (null department) docs, matching region filter behaviour
- retriever.search_documents/retrieve_and_prepare/query accept department_ids/region_codes lists
- MatchAny used for multi-value Qdrant filters; chat.py passes full arrays from knowledge_scope
- Admin PATCH /users/{id} now validates region_code against the regions table

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 20:13:27 +01:00

38 lines
1.1 KiB
Python

"""
Celery Beat Task: Periodic Agent Collector Sync with Usage Stats
Runs every 6 hours, syncs all active/public agents to AgentHub collector
including usage metrics (conversations, messages, tokens, unique users).
"""
import asyncio
import logging
from celery_app import celery_app
from app.database import AsyncSessionLocal
from app.services.agent_collector import sync_all_agents_with_usage
logger = logging.getLogger(__name__)
async def _run_sync() -> None:
async with AsyncSessionLocal() as db:
await sync_all_agents_with_usage(db)
@celery_app.task(
name="app.tasks.agent_sync.sync_agents_usage",
bind=True,
max_retries=1,
default_retry_delay=60,
)
def sync_agents_usage(self) -> dict:
"""
Sync all active/public Nexus agents to the AgentHub collector,
including current usage statistics (messages, tokens, conversations, users).
"""
try:
asyncio.run(_run_sync())
return {"status": "ok"}
except Exception as exc: # noqa: BLE001
logger.error("agent_sync beat task failed: %s", exc)
raise self.retry(exc=exc)