routing_service.py 3.64 KB
from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional

from sqlalchemy.orm import Session as OrmSession

from app.infrastructure.llm_client import LLMClient
from app.infrastructure.session_store import SessionStore
from app.model.agent import Agent
from app.schema.routing import (
    ChatCompletionResponse,
    HandoffInfo,
    IntentInfo,
    RoutingInfo,
)


_STEWARD_CODE = "steward"


class RoutingService:
    def __init__(self, db: OrmSession, session_store: SessionStore, llm: LLMClient) -> None:
        self.db = db
        self.session_store = session_store
        self.llm = llm

    def route(
        self,
        session_id: str,
        user_id: str,
        channel: str,
        query: str,
        mentioned_agent_code: Optional[str] = None,
    ) -> ChatCompletionResponse:
        now = datetime.now(timezone.utc)

        target_agent: Optional[Agent] = None
        routing_reason: str = ""
        prev_agent_id: Optional[int] = None
        intent_info: Optional[IntentInfo] = None

        if mentioned_agent_code:
            agent = self.db.query(Agent).filter(
                Agent.code == mentioned_agent_code,
                Agent.is_deleted == False,
            ).first()
            if not agent:
                raise ValueError(f"Agent不存在: {mentioned_agent_code}")
            target_agent = agent
            routing_reason = "mention"
            existing = self.session_store.get(session_id)
            if existing and existing.get("current_agent_id"):
                prev_agent_id = existing["current_agent_id"]
        else:
            existing = self.session_store.get(session_id)
            if existing and existing.get("current_agent_id"):
                inherited_id = existing["current_agent_id"]
                agent = self.db.query(Agent).filter(
                    Agent.id == inherited_id,
                    Agent.is_deleted == False,
                ).first()
                if agent:
                    prev_agent_id = inherited_id
                    target_agent = agent
                    routing_reason = "inheritance"

            if not target_agent:
                steward = self.db.query(Agent).filter(
                    Agent.code == _STEWARD_CODE,
                    Agent.is_deleted == False,
                ).first()
                if not steward:
                    raise ValueError("管家Agent未配置")
                target_agent = steward
                routing_reason = "default"

        if routing_reason != "mention":
            intent_str, confidence = self.llm.recognize_intent(query)
            intent_info = IntentInfo(intent=intent_str, confidence=confidence)

        handoff: Optional[HandoffInfo] = None
        if prev_agent_id is not None and prev_agent_id != target_agent.id:
            from_agent = self.db.query(Agent).filter(Agent.id == prev_agent_id).first()
            from_name = from_agent.name if from_agent else "未知"
            handoff = HandoffInfo(
                from_agent_id=prev_agent_id,
                from_agent_name=from_name,
                to_agent_id=target_agent.id,
                to_agent_name=target_agent.name,
                handoff_message=f"收到,已转交给{target_agent.name}处理。",
            )

        routing = RoutingInfo(
            agent_id=target_agent.id,
            agent_code=target_agent.code,
            agent_name=target_agent.name,
            routing_reason=routing_reason,
        )

        return ChatCompletionResponse(
            session_id=session_id,
            routing=routing,
            intent=intent_info,
            handoff=handoff,
            created_at=now,
        )