73 lines
2.5 KiB
Python
73 lines
2.5 KiB
Python
"""Read/export model diagnostics from the task's existing trace database."""
|
|
|
|
from datetime import UTC, datetime
|
|
import json
|
|
import time
|
|
|
|
from apps.admin_console.database.connection import db_session
|
|
|
|
|
|
def request_diagnostics(session_id: str, *, db_path=None, limit: int | None = None) -> dict:
|
|
with db_session(db_path) as conn:
|
|
session = conn.execute(
|
|
"SELECT status FROM sessions WHERE session_id = ?", (session_id,)
|
|
).fetchone()
|
|
sql = (
|
|
"SELECT payload FROM traces WHERE session_id = ? AND type = 'llm_diagnostic' "
|
|
"ORDER BY timestamp DESC"
|
|
)
|
|
params: tuple = (session_id,)
|
|
if limit is not None:
|
|
sql += " LIMIT ?"
|
|
params += (limit,)
|
|
rows = conn.execute(sql, params).fetchall()
|
|
requests = []
|
|
seen = set()
|
|
running = bool(session and session["status"] in {"running", "resuming"})
|
|
for row in rows:
|
|
try:
|
|
value = json.loads(row["payload"])
|
|
except (ValueError, TypeError):
|
|
continue
|
|
if not isinstance(value, dict):
|
|
continue
|
|
request_id = value.get("request_id")
|
|
value["active"] = (
|
|
running
|
|
and request_id not in seen
|
|
and value.get("phase")
|
|
in {
|
|
"waiting_response",
|
|
"waiting_output",
|
|
"receiving_output",
|
|
"generating_tool_arguments",
|
|
"retry_wait",
|
|
}
|
|
)
|
|
seen.add(request_id)
|
|
value["timestamps_utc"] = {
|
|
field: datetime.fromtimestamp(value[field], UTC).isoformat()
|
|
for field in (
|
|
"started_at",
|
|
"headers_at",
|
|
"first_output_at",
|
|
"last_output_at",
|
|
"ended_at",
|
|
"retry_at",
|
|
)
|
|
if isinstance(value.get(field), (int, float))
|
|
}
|
|
requests.append(value)
|
|
return {
|
|
"schema_version": 1,
|
|
"session_id": session_id,
|
|
"session_status": session["status"] if session else "unknown",
|
|
"collected_at": time.time(),
|
|
"requests": requests,
|
|
"note": "时间戳为 Unix 秒;timestamps_utc 为 UTC。HTTP 200 不代表完整输出。usage=null 表示服务未报告用量。历史任务没有记录的字段无法补推。",
|
|
}
|
|
|
|
|
|
def diagnostics_json(session_id: str) -> str:
|
|
return json.dumps(request_diagnostics(session_id), ensure_ascii=False, indent=2)
|