Files
ewoooc/services/ai_orchestrator.py
ogt 5ef4151fa5 [V10.4-C] 三 AI NLP 鏈修復:Hermes/NemoTron/OpenClaw 全線串通
修復 P9-2 確認的自然語言對話完全失效問題:

- services/ai_orchestrator.py:
    4 處裸字串 SQL 全部包裝 text(),修復 SQLAlchemy 2.x ArgumentError
- services/hermes_analyst_service.py:
    新增 handle_l1() async 方法(Ollama hermes3 意圖分析 + rule-based fallback)
    asyncio.get_event_loop() → get_running_loop()(Py3.12+ 相容)
- services/nemoton_dispatcher_service.py:
    新增 handle_l2() async 方法(純 Python routing,不消耗 NIM 配額)
- services/openclaw_strategist_service.py:
    新增 generate_strategy_response()(Gemini 2.0 Flash,無 key 時優雅降級)
- telegram_ai_integration.py:
    整合 OpenClaw 為第三層(complexity >= 0.7 或 dispatch_to == "openclaw")
    _format_*_response 全改為繁體中文
    asyncio.get_event_loop() → get_running_loop()
    _extract_date_range "to" → "至"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-25 01:43:20 +08:00

111 lines
3.8 KiB
Python

# services/ai_orchestrator.py
import asyncio
import logging
from typing import Any, Dict, Optional
from sqlalchemy import text
from services.hermes_analyst_service import HermesAnalystService
from services.nemoton_dispatcher_service import NemotronDispatcher
from database.manager import get_session
from database.ai_models import AgentContext, ActionPlan
logger = logging.getLogger(__name__)
class AIOrchestrator:
"""
Coordination hub: handles EventRouter L1/L2, agent shared context, and closed-loop decision tracking.
Single file <= 100 lines.
"""
def __init__(self):
self.hermes = HermesAnalystService()
self.nemotron = NemotronDispatcher()
async def handle_l1(self, event: Dict[str, Any], session_id: str) -> Dict[str, Any]:
"""
L1: semantic translation + reason analysis (provided by Hermes).
Writes to agent_context and can be used as L2 context.
"""
ctx = await self._get_context(session_id)
result = await self.hermes.handle_l1(event, ctx)
await self._save_context(session_id, "hermes", result)
return result
async def handle_l2(self, event: Dict[str, Any], session_id: str) -> Dict[str, Any]:
"""
L2: planning + review gate.
Produces an ActionPlan awaiting approval (handled via Telegram callback).
"""
ctx = await self._get_context(session_id) # includes hermes analysis
result = await self.nemotron.handle_l2(event, ctx)
await self._save_action_plan(result)
# review gate handled by routes/bot_api_routes callback
return result
async def _get_context(self, session_id: str) -> Dict[str, Any]:
session = get_session()
try:
rows = session.execute(
text("SELECT context_key, context_val FROM agent_context WHERE session_id = :sid"),
{"sid": session_id},
).fetchall()
return {r[0]: r[1] for r in rows}
finally:
session.close()
async def _save_context(self, session_id: str, agent: str, payload: Dict[str, Any]) -> None:
session = get_session()
try:
session.execute(
text("DELETE FROM agent_context WHERE session_id = :sid AND agent_name = :ag"),
{"sid": session_id, "ag": agent},
)
session.execute(
text("""
INSERT INTO agent_context
(session_id, agent_name, context_key, context_val, created_at, ttl_minutes)
VALUES
(:sid, :ag, :ck, :cv, NOW(), 60)
"""),
{
"sid": session_id,
"ag": agent,
"ck": "latest",
"cv": payload,
},
)
session.commit()
except Exception as e:
session.rollback()
logger.error(f"[AIOrchestrator] save_context failed: {e}")
raise
finally:
session.close()
async def _save_action_plan(self, plan: Dict[str, Any]) -> None:
session = get_session()
try:
session.execute(
text("""
INSERT INTO action_plans
(session_id, plan_type, sku, payload, status, created_by)
VALUES
(:sid, :pt, :sku, :pl, 'pending', 'nemotron')
"""),
{
"sid": plan.get("session_id"),
"pt": plan.get("plan_type"),
"sku": plan.get("sku"),
"pl": plan,
},
)
session.commit()
except Exception as e:
session.rollback()
logger.error(f"[AIOrchestrator] save_action_plan failed: {e}")
raise
finally:
session.close()