"""ORM model for per-tool-call (skill-call) metrics.""" from __future__ import annotations from datetime import UTC, datetime from sqlalchemy import Index, Integer, String, Text from sqlalchemy.orm import Mapped, mapped_column from deerflow.persistence.base import Base from deerflow.persistence.types import BeijingDateTime class ToolCallMetricRow(Base): """One row per completed (or failed) tool / skill invocation. Unlike :class:`LlmCallMetricRow` this also captures *self-handled* failures — search tools that swallow an HTTP 429/403 and return an error payload instead of raising — so an admin can see "retrieval failed" / "IP blocked" events that never surfaced as exceptions. """ __tablename__ = "tool_call_metrics" __table_args__ = ( Index("ix_tool_call_metrics_created_user", "created_at", "user_id"), Index("ix_tool_call_metrics_run_created", "run_id", "created_at"), Index("ix_tool_call_metrics_created_skill_user", "created_at", "skill_name", "user_id"), Index("ix_tool_call_metrics_created_tool_user", "created_at", "tool_name", "user_id"), ) id: Mapped[str] = mapped_column(String(64), primary_key=True) created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC), index=True) user_id: Mapped[str | None] = mapped_column(String(64), index=True) thread_id: Mapped[str | None] = mapped_column(String(64), index=True) run_id: Mapped[str | None] = mapped_column(String(64), index=True) agent_name: Mapped[str | None] = mapped_column(String(128), index=True) tool_name: Mapped[str | None] = mapped_column(String(128), index=True) # The specific Agent Skill targeted by a skill tool call (from the call's # ``name`` argument); null for non-skill tool calls. skill_name: Mapped[str | None] = mapped_column(String(128), index=True) duration_ms: Mapped[int] = mapped_column(Integer, default=0) # "success" or "error". status: Mapped[str] = mapped_column(String(16), default="success", index=True) # Coarse failure bucket; null on success. error_category: Mapped[str | None] = mapped_column(String(32), index=True) error_message: Mapped[str | None] = mapped_column(Text) def to_dict(self) -> dict: return { "id": self.id, "created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at, "user_id": self.user_id, "thread_id": self.thread_id, "run_id": self.run_id, "agent_name": self.agent_name, "tool_name": self.tool_name, "skill_name": self.skill_name, "duration_ms": self.duration_ms, "status": self.status, "error_category": self.error_category, "error_message": self.error_message, }