fix(admin): 优化聊天日志报表
This commit is contained in:
1 parent
c38a56536e
commit
757231e3d5
14 files changed
+584
-108
No files matched your search
+2
-2
@@ -136,7 +136,7 @@ FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
|
||||
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
|
||||
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95 # 答案聚类相似度阈值(0~1),RAG 长文可适当调低至 0.80~0.85
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # 最大答案簇占比下限(0~1),分歧过大则跳过;可降至 0.4 便于测试
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相似度阈值,恢复聚类时生效
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
+115
-3
@@ -18,6 +18,7 @@ from sqlalchemy.orm import joinedload
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import requests
|
||||
import uuid
|
||||
@@ -1105,13 +1106,59 @@ def dismiss_faq_candidate():
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""
|
||||
聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。
|
||||
Query: user_page(默认 1)、user_page_size(默认 10,最大 50)
|
||||
"""
|
||||
total = db.session.query(ChatLog).count()
|
||||
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
|
||||
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
|
||||
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
user_page = 1
|
||||
try:
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(User.username)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_total = len(by_user_top)
|
||||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||||
user_page = min(user_page, user_pages)
|
||||
offset = (user_page - 1) * user_page_size
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
|
||||
return jsonify({
|
||||
'total': total,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
'user_pages': user_pages,
|
||||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
@@ -1186,9 +1233,74 @@ def count_general_feedbacks_report():
|
||||
total = query.count()
|
||||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||||
|
||||
def _chat_logs_report_query():
|
||||
"""
|
||||
聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。
|
||||
核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。
|
||||
"""
|
||||
return (
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||||
)
|
||||
|
||||
|
||||
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
|
||||
"""
|
||||
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
|
||||
保留 id 供前端批量删除使用,默认不在表格列中展示。
|
||||
"""
|
||||
created_at = log.created_at.isoformat() if log.created_at else None
|
||||
return {
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username or '',
|
||||
'created_at': created_at,
|
||||
'query': log.query,
|
||||
'answer': log.answer,
|
||||
'session_id': log.session_id,
|
||||
'tokens_used': log.tokens_used,
|
||||
'message_type': log.message_type,
|
||||
}
|
||||
|
||||
|
||||
def _apply_chat_logs_report_filters(query):
|
||||
"""
|
||||
对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。
|
||||
"""
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def _list_chat_logs_report():
|
||||
"""管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。"""
|
||||
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
|
||||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
items = query.limit(100).all()
|
||||
rows = [_serialize_chat_log_report_row(log, username, agent_name) for log, username, agent_name in items]
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table):
|
||||
if table == 'chat_logs':
|
||||
return _list_chat_logs_report()
|
||||
|
||||
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
|
||||
model = model_map.get(table)
|
||||
if not model:
|
||||
|
||||
@@ -22,21 +22,19 @@ backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
## 最佳答案选取规则(HOT_FAQ_ANSWER_RULES)
|
||||
|
||||
1. **答案聚类**:对组内每条 ChatLog 的 answer 做相似度聚类(SequenceMatcher ≥ FAQ_HOT_ANSWER_SIMILARITY,默认 0.95)。
|
||||
2. **一致性门槛**:最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE(默认 0.6);否则视为答案分歧过大,整组跳过。
|
||||
3. **在最大簇内选代表答案**,优先级:
|
||||
1. ~~**答案聚类**~~(已暂时关闭):原按 FAQ_HOT_ANSWER_SIMILARITY 对 answer 聚类。
|
||||
2. ~~**一致性门槛**~~(已暂时关闭):原要求最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE。
|
||||
3. **在组内选代表答案**,优先级:
|
||||
a. Feedback.score ≥ FAQ_HOT_GOOD_SCORE(默认 4)的记录中,取 created_at 最新;
|
||||
b. 否则排除 Feedback.score ≤ FAQ_HOT_BAD_SCORE(默认 2)的记录,取 created_at 最新;
|
||||
c. 否则取簇内 created_at 最新的 answer。
|
||||
c. 否则取组内 created_at 最新的 answer。
|
||||
4. **canonical_query**:取该组内出现次数最多的原始 query 文本(非归一化,便于人工阅读)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
@@ -73,8 +71,7 @@ HOT_FAQ_AGGREGATOR_DOC_SELECTION = (
|
||||
)
|
||||
|
||||
HOT_FAQ_AGGREGATOR_DOC_ANSWER = (
|
||||
'答案按相似度聚类,最大簇占比需≥dominance 阈值;'
|
||||
'在最大簇内优先选好评最新,其次无差评最新,最后取最新记录。'
|
||||
'答案聚类与一致性门槛已暂时关闭;在组内按反馈优先级选代表答案。'
|
||||
)
|
||||
|
||||
|
||||
@@ -161,8 +158,10 @@ class HotFaqAggregator:
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_SELECTION,
|
||||
},
|
||||
'answer': {
|
||||
# 答案聚类 / 一致性门槛已暂时关闭,以下配置保留供日后恢复
|
||||
'answer_similarity': float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95)),
|
||||
'answer_dominance': float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6)),
|
||||
'answer_clustering_enabled': False,
|
||||
'good_feedback_score': int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4)),
|
||||
'bad_feedback_score': int(cls._cfg('FAQ_HOT_BAD_SCORE', 2)),
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_ANSWER,
|
||||
@@ -332,17 +331,19 @@ class HotFaqAggregator:
|
||||
rows: list[_LogRow],
|
||||
) -> tuple[Optional[HotFaqCandidate], Optional[str]]:
|
||||
"""从一组 ChatLog 构建热点候选;失败时返回 skip reason。"""
|
||||
dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
|
||||
clusters = cls._cluster_answers(rows)
|
||||
if not clusters:
|
||||
return None, 'empty_answer_clusters'
|
||||
# [DISABLED] 答案聚类 + 一致性门槛(answer_divergence)已暂时关闭,直接在整组内选代表答案。
|
||||
# dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
|
||||
# similarity_threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
|
||||
# largest_rows = cls._largest_similarity_cluster(rows, similarity_threshold)
|
||||
# dominance = len(largest_rows) / len(rows) if rows else 0.0
|
||||
# if dominance < dominance_threshold:
|
||||
# relaxed = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY_RELAXED', 0.70))
|
||||
# ...
|
||||
# if dominance < dominance_threshold:
|
||||
# return None, f'answer_divergence:{dominance:.2f}'
|
||||
|
||||
largest = max(clusters, key=lambda c: len(c['rows']))
|
||||
dominance = len(largest['rows']) / len(rows)
|
||||
if dominance < dominance_threshold:
|
||||
return None, f'answer_divergence:{dominance:.2f}'
|
||||
|
||||
rep = cls._pick_representative_answer(largest['rows'])
|
||||
dominance = 1.0
|
||||
rep = cls._pick_representative_answer(rows)
|
||||
if not rep:
|
||||
return None, 'no_representative_answer'
|
||||
|
||||
@@ -371,44 +372,25 @@ class HotFaqAggregator:
|
||||
retriever_resources=rep.retriever_resources,
|
||||
), None
|
||||
|
||||
@classmethod
|
||||
def _cluster_answers(cls, rows: list[_LogRow]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 answer 按相似度聚类(贪心:与簇代表相似度 ≥ 阈值则归入)。
|
||||
@returns [{'representative': str, 'rows': [_LogRow, ...]}, ...]
|
||||
"""
|
||||
threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
|
||||
clusters: list[dict[str, Any]] = []
|
||||
|
||||
for row in rows:
|
||||
answer = row.answer.strip()
|
||||
if not answer:
|
||||
continue
|
||||
placed = False
|
||||
for cluster in clusters:
|
||||
rep = cluster['representative']
|
||||
if cls._answer_similarity(rep, answer) >= threshold:
|
||||
cluster['rows'].append(row)
|
||||
placed = True
|
||||
break
|
||||
if not placed:
|
||||
clusters.append({'representative': answer, 'rows': [row]})
|
||||
return clusters
|
||||
|
||||
@staticmethod
|
||||
def _answer_similarity(a: str, b: str) -> float:
|
||||
"""计算两段答案文本相似度(0~1)。"""
|
||||
left = re.sub(r'\s+', ' ', a.strip())
|
||||
right = re.sub(r'\s+', ' ', b.strip())
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return SequenceMatcher(None, left, right).ratio()
|
||||
# [DISABLED] 答案聚类相关方法(恢复 FAQ_HOT_ANSWER_SIMILARITY / DOMINANCE 检查时可启用)
|
||||
#
|
||||
# @classmethod
|
||||
# def _largest_similarity_cluster(cls, rows: list[_LogRow], threshold: float) -> list[_LogRow]:
|
||||
# ...
|
||||
#
|
||||
# @classmethod
|
||||
# def _cluster_answers(cls, rows: list[_LogRow], *, threshold: float | None = None) -> list[dict[str, Any]]:
|
||||
# ...
|
||||
#
|
||||
# @staticmethod
|
||||
# def _answer_similarity(a: str, b: str) -> float:
|
||||
# ...
|
||||
|
||||
@classmethod
|
||||
def _pick_representative_answer(cls, rows: list[_LogRow]) -> Optional[_LogRow]:
|
||||
"""
|
||||
在 dominant 簇内按反馈优先级选取最佳 ChatLog 行。
|
||||
优先级:好评最新 > 无差评最新 > 簇内最新。
|
||||
在组内按反馈优先级选取最佳 ChatLog 行。
|
||||
优先级:好评最新 > 无差评最新 > 组内最新。
|
||||
"""
|
||||
good_score = int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4))
|
||||
bad_score = int(cls._cfg('FAQ_HOT_BAD_SCORE', 2))
|
||||
|
||||
@@ -267,6 +267,11 @@ def test_reports(client, admin_headers):
|
||||
assert 'total' in data
|
||||
assert 'by_user' in data
|
||||
assert 'by_agent' in data
|
||||
assert 'user_total' in data
|
||||
assert 'user_page' in data
|
||||
assert 'user_page_size' in data
|
||||
assert 'user_pages' in data
|
||||
assert 'user_top_limit' in data
|
||||
|
||||
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_hot_faq_aggregator.py
|
||||
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、答案聚类与代表答案选取。
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、代表答案选取。
|
||||
"""
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator, _LogRow
|
||||
@@ -15,15 +14,19 @@ def test_normalize_faq_query_strips_punctuation_and_space():
|
||||
assert normalize_faq_query('公司几点上班?') == normalize_faq_query('公司 几点上班')
|
||||
|
||||
|
||||
def test_answer_cluster_merges_similar_answers():
|
||||
"""相似度≥阈值的答案应归入同一簇。"""
|
||||
rows = [
|
||||
_LogRow(1, 1, 1, 'q', '工作日8:30到17:30', 100, 10, datetime.utcnow()),
|
||||
_LogRow(2, 2, 1, 'q', '工作日 8:30 到 17:30', 100, 10, datetime.utcnow()),
|
||||
]
|
||||
clusters = HotFaqAggregator._cluster_answers(rows)
|
||||
assert len(clusters) == 1
|
||||
assert len(clusters[0]['rows']) == 2
|
||||
def test_build_candidate_accepts_divergent_answers_when_clustering_disabled(app, monkeypatch):
|
||||
"""答案聚类关闭时,即使答案分歧较大也应生成热点候选。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is not None
|
||||
assert reason is None
|
||||
assert candidate.ask_count_7d == 6
|
||||
|
||||
|
||||
def test_pick_representative_prefers_good_feedback():
|
||||
@@ -37,17 +40,3 @@ def test_pick_representative_prefers_good_feedback():
|
||||
assert picked is not None
|
||||
assert picked.chat_log_id == 2
|
||||
assert picked.answer == 'answer B'
|
||||
|
||||
|
||||
def test_build_candidate_rejects_divergent_answers(app, monkeypatch):
|
||||
"""答案分歧过大时应跳过该热点组。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is None
|
||||
assert reason and reason.startswith('answer_divergence')
|
||||
@@ -0,0 +1,211 @@
|
||||
# 错误处理规范
|
||||
|
||||
> 更新时间:2026-06-22
|
||||
> 适用范围:HXOPS 前后端 API 与 UI 错误反馈
|
||||
> 读者:组内同事、AI 编程助手
|
||||
> 文档定位:**错误契约、分层职责与禁止项**的权威说明。`AGENTS.md` §8 仅保留强约束摘要,细则以本文为准。
|
||||
|
||||
---
|
||||
|
||||
## 1. 统一错误契约
|
||||
|
||||
前后端 JSON API 采用 **Envelope** 结构(由 `ENABLE_API_ENVELOPE` 与全局 handler 保证)。
|
||||
|
||||
**成功:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": { },
|
||||
"request_id": "req_abc123",
|
||||
"timestamp": "2026-06-22T08:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**失败:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "USER.EMAIL_EXISTS",
|
||||
"message": "Email already exists",
|
||||
"details": { "field": "email" },
|
||||
"retryable": false
|
||||
},
|
||||
"request_id": "req_abc123",
|
||||
"timestamp": "2026-06-22T08:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `error.code` | 机器可读错误码,格式 `DOMAIN.SUBTYPE`(如 `AUTH.UNAUTHORIZED`) |
|
||||
| `error.message` | 英文或简短说明,供日志与 fallback;**前端优先用 i18n 映射** |
|
||||
| `error.details` | 可选结构化信息(字段名、冲突项等),供前端分支逻辑 |
|
||||
| `error.retryable` | 是否建议用户重试(503 等) |
|
||||
| `request_id` | 与 `X-Request-Id` 对齐,便于排障 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 后端规范
|
||||
|
||||
### 2.1 分层职责
|
||||
|
||||
| 层 | 职责 |
|
||||
|----|------|
|
||||
| **Route(`api/`)** | 参数读取、权限装饰器、调用 service;**不**手写 `jsonify({"error": ...})` |
|
||||
| **Service(`services/`)** | 业务校验失败 `raise AppError` 子类;不构造 HTTP Response |
|
||||
| **全局 handler(`app/__init__.py`)** | 捕获 `AppError` / `HTTPException` / 未预期异常 → `error_payload` |
|
||||
|
||||
### 2.2 使用 `app/errors.py`
|
||||
|
||||
优先使用已有子类,语义不明确时再 `raise AppError(...)`:
|
||||
|
||||
| 异常 | 典型 HTTP | 默认 code |
|
||||
|------|-----------|-----------|
|
||||
| `ValidationError` | 400 | `VALIDATION.INVALID_PARAM` |
|
||||
| `UnauthorizedError` | 401 | `AUTH.UNAUTHORIZED` |
|
||||
| `ForbiddenError` | 403 | `AUTH.FORBIDDEN` |
|
||||
| `NotFoundError` | 404 | `RESOURCE.NOT_FOUND` |
|
||||
| `ConflictError` | 409 | `RESOURCE.CONFLICT`(可自定义 code) |
|
||||
| `ServiceUnavailableError` | 503 | `SYSTEM.SERVICE_UNAVAILABLE` |
|
||||
|
||||
**示例(service / route):**
|
||||
|
||||
```python
|
||||
from app.errors import ValidationError, NotFoundError, ConflictError
|
||||
|
||||
if not name:
|
||||
raise ValidationError("Name is required")
|
||||
if not row:
|
||||
raise NotFoundError("Agent not found")
|
||||
if email_exists:
|
||||
raise ConflictError("Email already exists", code="USER.EMAIL_EXISTS", details={"field": "email"})
|
||||
```
|
||||
|
||||
**成功响应:** 使用 `app.response_utils.ok(data)`,或在 envelope 开启时返回 plain dict(由 `@app.after_request` 包装)。
|
||||
|
||||
### 2.3 错误码命名
|
||||
|
||||
- 格式:`<域>.<语义>`,全大写,点号分隔。
|
||||
- 域示例:`AUTH`、`USER`、`RESOURCE`、`VALIDATION`、`KB`、`WECOM`、`SYSTEM`。
|
||||
- **新增 code 必须同步前端四语言** `locales/*/errors.json` → `errors.codes.<CODE_WITH_UNDERSCORES>`(`.` 换 `_`)。
|
||||
|
||||
### 2.4 禁止项(后端)
|
||||
|
||||
| ❌ 不要 | ✅ 应该 |
|
||||
|---------|---------|
|
||||
| `return jsonify({"error": "Not found"}), 404` | `raise NotFoundError(...)` |
|
||||
| `return jsonify({"ok": False, "error": "..."}), 400` | `raise ValidationError(...)` |
|
||||
| 在 service 里 `return (jsonify(...), 4xx)` | `raise AppError` 交给 handler |
|
||||
| 500 时把堆栈/ SQL 返回给客户端 | 日志记录细节;客户端仅 `SYSTEM.INTERNAL_ERROR` |
|
||||
| 随意字符串作 code(`"not_found"`) | `RESOURCE.NOT_FOUND` 等规范 code |
|
||||
|
||||
> 历史路由(如部分 `workspace_shipping_notice.py`)仍有 legacy `{"error": "..."}` 写法;**新接口与改动处须改为 `AppError`**,逐步收敛。
|
||||
|
||||
---
|
||||
|
||||
## 3. 前端规范
|
||||
|
||||
### 3.1 分层职责
|
||||
|
||||
| 层 | 职责 |
|
||||
|----|------|
|
||||
| **`shared/api/client.ts`** | 唯一 JSON 客户端:`requestJson` 解析 envelope,失败抛 `BusinessError`(含 `code` / `message` / `details` / `status` / `requestId`) |
|
||||
| **`features/*/api/*.api.ts`** | 只组装 URL 与 body,调用 `requestJson`;**不** catch 后改写成字符串 |
|
||||
| **Composables / Views** | catch `BusinessError`,用 `useMessage()` 或域内 resolver 展示;按 `status` / `code` 做分支(401 跳登录等) |
|
||||
| **Components** | 一般不 catch API;由父级注入错误状态或回调 |
|
||||
|
||||
### 3.2 `BusinessError` 与 i18n
|
||||
|
||||
`requestJson` 抛出前已通过 `resolveLocalizedErrorMessage` 将 `error.code` 映射到 `errors.codes.*`(四语言 `errors.json`)。
|
||||
|
||||
**Composable 中展示错误(推荐):**
|
||||
|
||||
```typescript
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const msg = useMessage();
|
||||
|
||||
try {
|
||||
await saveProfile(payload);
|
||||
msg.success(t('workspace.profile.msg.saved'));
|
||||
} catch (e) {
|
||||
const message = e instanceof BusinessError
|
||||
? e.message
|
||||
: t('workspace.profile.msg.saveFailed');
|
||||
msg.error(message);
|
||||
}
|
||||
```
|
||||
|
||||
**按状态分支:**
|
||||
|
||||
```typescript
|
||||
catch (e) {
|
||||
if (e instanceof BusinessError && e.status === 401) {
|
||||
msg.error(t('login.loginRequired'));
|
||||
return;
|
||||
}
|
||||
if (e instanceof BusinessError && e.status === 403) {
|
||||
msg.error(e.message);
|
||||
return;
|
||||
}
|
||||
msg.error(e instanceof Error ? e.message : t('errors.generic'));
|
||||
}
|
||||
```
|
||||
|
||||
**域内复杂映射**(如 Casdoor 登录):在 `shared/utils/` 或 feature `utils/` 提供 `resolveXxxErrorMessage(err: BusinessError, t)`,避免 View 内重复 if-else。
|
||||
|
||||
### 3.3 表单校验 vs 服务端错误
|
||||
|
||||
| 类型 | 处理方式 |
|
||||
|------|----------|
|
||||
| 前端必填 / 格式 | 提交前校验,`msg.warning(t('...'))`,不发起请求 |
|
||||
| 服务端业务拒绝 | API 抛 `BusinessError`,展示 `e.message`(已 i18n) |
|
||||
| 字段级错误 | 读 `e.details.field`,高亮对应表单项 |
|
||||
|
||||
### 3.4 SSE / 流式对话
|
||||
|
||||
对话流式接口**不走** `requestJson`,错误处理在 `features/chat/composables/useChat.ts` 内完成(解析 SSE event、断线重试等)。勿用 Axios 替代。
|
||||
|
||||
### 3.5 禁止项(前端)
|
||||
|
||||
| ❌ 不要 | ✅ 应该 |
|
||||
|---------|---------|
|
||||
| 在组件里直接 `fetch('/api/...')` | `features/*/api/*.api.ts` + `requestJson` |
|
||||
| `(e as Error).message` 且不判断类型 | 优先 `instanceof BusinessError` |
|
||||
| catch 后静默吞掉(无 UI、无日志) | `msg.error` 或向上抛出 |
|
||||
| catch 里硬编码中文 | `e.message`(已映射)或 `t('errors....')` |
|
||||
| 在 `*.api.ts` 里 `msg.error` | API 层只抛错,UI 层负责展示 |
|
||||
| 新增后端 code 却不加 `errors.json` | 四语言同步 `errors.codes.*` |
|
||||
|
||||
---
|
||||
|
||||
## 4. 新增错误码检查清单
|
||||
|
||||
1. 后端:在 `app/errors.py` 选用或新增语义明确的 `code`。
|
||||
2. 前端:在 `locales/{zh-CN,zh-TW,en,th}/errors.json` 的 `codes` 下增加键(`USER.EMAIL_EXISTS` → `USER_EMAIL_EXISTS`)。
|
||||
3. 若需按 `details` 分支,在 composable 文档注释中说明字段约定。
|
||||
4. 自测:触发该错误,确认四语言文案与 HTTP 状态码正确。
|
||||
|
||||
---
|
||||
|
||||
## 5. 相关文件
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `backend/app/errors.py` | 业务异常类型 |
|
||||
| `backend/app/response_utils.py` | `ok()`、`error_payload()` |
|
||||
| `backend/app/__init__.py` | 全局 errorhandler、envelope 包装 |
|
||||
| `frontend/src/shared/api/client.ts` | `requestJson`、`BusinessError` |
|
||||
| `frontend/src/locales/*/errors.json` | 错误码 i18n |
|
||||
| `frontend/src/shared/composables/useMessage.ts` | 全局 error/success 弹窗 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 相关文档
|
||||
|
||||
- [AGENTS.md](../../AGENTS.md) §8 — 红线摘要
|
||||
- [frontend_architecture_refactor.md](../refactor/frontend_architecture_refactor.md) — 前端分层与 API 层约束
|
||||
@@ -7,6 +7,7 @@ import { requestJson } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
import type { UsageReport } from '../types/report.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
@@ -161,7 +162,21 @@ export const getAdminDashboardBadges = () =>
|
||||
requestJson<AdminDashboardBadges>('/api/admin/dashboard/badges', auth());
|
||||
|
||||
// Reports
|
||||
export const getAdminUsageReport = () => requestJson<any>('/api/admin/reports/usage', auth());
|
||||
export interface AdminUsageReportParams {
|
||||
user_page?: number;
|
||||
user_page_size?: number;
|
||||
}
|
||||
|
||||
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.user_page != null) qs.set('user_page', String(params.user_page));
|
||||
if (params.user_page_size != null) qs.set('user_page_size', String(params.user_page_size));
|
||||
const query = qs.toString();
|
||||
return requestJson<UsageReport>(
|
||||
`/api/admin/reports/usage${query ? `?${query}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
|
||||
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
|
||||
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
|
||||
|
||||
@@ -13,6 +13,16 @@ const { t } = useI18n();
|
||||
|
||||
const {
|
||||
usageReport,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageUserPageButtons,
|
||||
goToUsageUserPage,
|
||||
prevUsageUserPage,
|
||||
nextUsageUserPage,
|
||||
isLoading,
|
||||
currentTable,
|
||||
tableData,
|
||||
@@ -359,15 +369,6 @@ onMounted(() => {
|
||||
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
|
||||
<h3 class="section-title text-lg mb-6">{{ t('admin.report.usage') }}</h3>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div class="card p-6">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byUser') }}</h4>
|
||||
<div class="space-y-3">
|
||||
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
|
||||
<span class="font-medium text-secondary">{{ u.username }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card p-6">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
|
||||
<div class="space-y-3">
|
||||
@@ -377,6 +378,71 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card p-6 flex flex-col">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1">
|
||||
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
|
||||
<span class="font-medium text-secondary">{{ u.username }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
|
||||
</div>
|
||||
<div v-if="usageReport.by_user.length === 0" class="text-center text-muted text-sm py-6">
|
||||
{{ t('admin.report.usageByUserEmpty') }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="usageUserTotal > 0" class="mt-4 flex flex-col gap-3 border-t border-default pt-4">
|
||||
<div class="text-xs text-secondary">
|
||||
{{ t('admin.report.paginationSummary', { total: usageUserTotal, page: usageUserPage, pages: usageUserTotalPages }) }}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-2 text-xs text-secondary">
|
||||
<span>{{ t('admin.report.perPage') }}</span>
|
||||
<span class="relative inline-flex items-center">
|
||||
<select
|
||||
v-model.number="usageUserPageSize"
|
||||
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
|
||||
>
|
||||
<option v-for="size in usageUserPageSizeOptions" :key="`usage-user-size-${size}`" :value="size">{{ size }}</option>
|
||||
</select>
|
||||
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
<span>{{ t('admin.report.itemsUnit') }}</span>
|
||||
</label>
|
||||
<button
|
||||
@click="prevUsageUserPage"
|
||||
:disabled="usageUserPage <= 1"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.prevPage') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="btn in usageUserPageButtons"
|
||||
:key="`usage-user-page-btn-${btn}`"
|
||||
:disabled="btn === -1"
|
||||
@click="btn !== -1 && goToUsageUserPage(btn)"
|
||||
class="admin-report-page-btn"
|
||||
:class="btn === -1
|
||||
? 'border-transparent text-muted cursor-default opacity-100'
|
||||
: btn === usageUserPage
|
||||
? 'admin-report-page-btn--active'
|
||||
: ''"
|
||||
>
|
||||
{{ btn === -1 ? '...' : btn }}
|
||||
</button>
|
||||
<button
|
||||
@click="nextUsageUserPage"
|
||||
:disabled="usageUserPage >= usageUserTotalPages"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.nextPage') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -24,12 +24,62 @@ import type {
|
||||
} from '@/features/admin/types/report.types';
|
||||
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
||||
|
||||
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
|
||||
const CHAT_LOGS_REPORT_KEYS = [
|
||||
'agent_name',
|
||||
'username',
|
||||
'created_at',
|
||||
'query',
|
||||
'answer',
|
||||
'session_id',
|
||||
'tokens_used',
|
||||
'message_type',
|
||||
] as const;
|
||||
|
||||
const CHAT_LOGS_TABLE_KEYS = ['id', ...CHAT_LOGS_REPORT_KEYS] as const;
|
||||
|
||||
export function useReportsAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
const msg = useMessage();
|
||||
const route = useRoute();
|
||||
|
||||
const usageReport = ref<UsageReport | null>(null);
|
||||
const usageUserPage = ref(1);
|
||||
const usageUserPageSize = ref(10);
|
||||
const usageUserPageSizeOptions = [5, 10, 20, 50];
|
||||
|
||||
const loadUsageReport = async (): Promise<void> => {
|
||||
try {
|
||||
usageReport.value = await getAdminUsageReport({
|
||||
user_page: usageUserPage.value,
|
||||
user_page_size: usageUserPageSize.value,
|
||||
});
|
||||
const pages = usageReport.value?.user_pages ?? 1;
|
||||
if (usageUserPage.value > pages) {
|
||||
usageUserPage.value = pages;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading usage report:', e);
|
||||
}
|
||||
};
|
||||
|
||||
const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1));
|
||||
const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
|
||||
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50);
|
||||
const usageUserPageButtons = computed(() =>
|
||||
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
|
||||
);
|
||||
|
||||
const goToUsageUserPage = (page: number): void => {
|
||||
usageUserPage.value = Math.min(Math.max(1, page), usageUserTotalPages.value);
|
||||
void loadUsageReport();
|
||||
};
|
||||
const prevUsageUserPage = () => goToUsageUserPage(usageUserPage.value - 1);
|
||||
const nextUsageUserPage = () => goToUsageUserPage(usageUserPage.value + 1);
|
||||
|
||||
const loadReports = async (): Promise<void> => {
|
||||
await loadUsageReport();
|
||||
};
|
||||
const isLoading = ref(true);
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
@@ -73,14 +123,6 @@ export function useReportsAdmin() {
|
||||
},
|
||||
);
|
||||
|
||||
const loadReports = async (): Promise<void> => {
|
||||
try {
|
||||
usageReport.value = await getAdminUsageReport();
|
||||
} catch (e) {
|
||||
console.error('Error loading reports:', e);
|
||||
}
|
||||
};
|
||||
|
||||
// 报表相关状态
|
||||
const tableData = ref<any[]>([]);
|
||||
const isFullScreen = ref(false);
|
||||
@@ -117,7 +159,11 @@ const loadTableData = async () => {
|
||||
try {
|
||||
tableData.value = await getAdminReportTable(url);
|
||||
if (tableData.value.length > 0) {
|
||||
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
|
||||
const rowKeys = Object.keys(tableData.value[0] || {});
|
||||
const columnKeys = currentTable.value === 'chat_logs'
|
||||
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
|
||||
: rowKeys;
|
||||
initChatLogsColumns(columnKeys);
|
||||
}
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
const validIds = new Set(
|
||||
@@ -149,10 +195,11 @@ const saveChatLogsColumns = () => {
|
||||
const initChatLogsColumns = (keys: string[]) => {
|
||||
chatLogsWrapEnabled.value = false;
|
||||
chatLogsWrapMaxHeight.value = 120;
|
||||
const hideByDefault = currentTable.value === 'chat_logs' && keys.includes('id');
|
||||
const defaults: ReportColumnConfig[] = keys.map((k) => ({
|
||||
key: k,
|
||||
visible: true,
|
||||
width: k === 'id' ? 90 : 180
|
||||
visible: hideByDefault ? k !== 'id' : true,
|
||||
width: k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180,
|
||||
}));
|
||||
|
||||
let merged = defaults;
|
||||
@@ -165,8 +212,8 @@ const initChatLogsColumns = (keys: string[]) => {
|
||||
const missing = keys.filter((k) => !order.includes(k));
|
||||
merged = [...order, ...missing].map((k) => ({
|
||||
key: k,
|
||||
visible: savedMap.get(k)?.visible ?? true,
|
||||
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : 180),
|
||||
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
|
||||
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180),
|
||||
}));
|
||||
if (!Array.isArray(parsed)) {
|
||||
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
|
||||
@@ -190,7 +237,11 @@ const resetChatLogsColumns = () => {
|
||||
chatLogsWrapMaxHeight.value = 120;
|
||||
chatLogsSortRules.value = [];
|
||||
reportHeaderSort.value = null;
|
||||
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
|
||||
const rowKeys = Object.keys(tableData.value[0] || {});
|
||||
const columnKeys = currentTable.value === 'chat_logs'
|
||||
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
|
||||
: rowKeys;
|
||||
initChatLogsColumns(columnKeys);
|
||||
saveChatLogsColumns();
|
||||
};
|
||||
|
||||
@@ -269,7 +320,15 @@ const loadTableCount = async (table: string) => {
|
||||
|
||||
const exportToExcel = () => {
|
||||
if (tableData.value.length === 0) return;
|
||||
const ws = XLSX.utils.json_to_sheet(tableData.value);
|
||||
const keys = visibleReportKeys.value;
|
||||
const rows = tableData.value.map((row) => {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of keys) {
|
||||
out[getReportColumnLabel(key)] = getReportCellValue(row, key);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
const ws = XLSX.utils.json_to_sheet(rows.length > 0 ? rows : tableData.value);
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, currentTable.value);
|
||||
XLSX.writeFile(wb, `${currentTable.value}_report_${new Date().toISOString().split('T')[0]}.xlsx`);
|
||||
@@ -309,6 +368,11 @@ const visibleReportKeys = computed(() => {
|
||||
return feedbackFixedOrder.filter((k) => available.has(k));
|
||||
}
|
||||
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
const available = new Set(keys);
|
||||
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
|
||||
}
|
||||
|
||||
return keys;
|
||||
});
|
||||
|
||||
@@ -772,6 +836,11 @@ watch(columnFilters, () => {
|
||||
reportCurrentPage.value = 1;
|
||||
}, { deep: true });
|
||||
|
||||
watch(usageUserPageSize, () => {
|
||||
usageUserPage.value = 1;
|
||||
void loadUsageReport();
|
||||
});
|
||||
|
||||
watch([reportPageSize, sortedTableData], () => {
|
||||
if (reportCurrentPage.value > reportTotalPages.value) {
|
||||
reportCurrentPage.value = reportTotalPages.value;
|
||||
@@ -801,6 +870,16 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
|
||||
return {
|
||||
usageReport,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageUserPageButtons,
|
||||
goToUsageUserPage,
|
||||
prevUsageUserPage,
|
||||
nextUsageUserPage,
|
||||
isLoading,
|
||||
currentTable,
|
||||
tableData,
|
||||
|
||||
@@ -7,7 +7,12 @@ export interface UsageReport {
|
||||
total: number;
|
||||
by_user: { username: string; count: number }[];
|
||||
by_agent: { agent: string; count: number }[];
|
||||
by_day: { date: string; count: number }[];
|
||||
by_day?: { date: string; count: number }[];
|
||||
user_total: number;
|
||||
user_page: number;
|
||||
user_page_size: number;
|
||||
user_pages: number;
|
||||
user_top_limit: number;
|
||||
}
|
||||
|
||||
export interface ReportColumnConfig {
|
||||
|
||||
@@ -626,6 +626,8 @@
|
||||
"usage": "Usage Analytics",
|
||||
"byUser": "Requests by User",
|
||||
"byAgent": "Requests by Agent",
|
||||
"usageByUserTopHint": "Top {limit} users by chat volume",
|
||||
"usageByUserEmpty": "No user chat activity yet",
|
||||
"columns": {
|
||||
"id": "ID",
|
||||
"user_id": "User ID",
|
||||
@@ -670,6 +672,7 @@
|
||||
"model": "Model",
|
||||
"tokens": "Tokens",
|
||||
"tokens_used": "Tokens Used",
|
||||
"message_type": "Message Type",
|
||||
"tokens_prompt": "Prompt Tokens",
|
||||
"tokens_completion": "Completion Tokens",
|
||||
"total_tokens": "Total Tokens",
|
||||
|
||||
@@ -631,6 +631,8 @@
|
||||
"usage": "การวิเคราะห์การใช้งาน",
|
||||
"byUser": "ตามผู้ใช้",
|
||||
"byAgent": "ตามตัวแทน",
|
||||
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
|
||||
"usageByUserEmpty": "ยังไม่มีบันทึกการสนทนาของผู้ใช้",
|
||||
"columns": {
|
||||
"id": "ID",
|
||||
"user_id": "รหัสผู้ใช้",
|
||||
@@ -675,6 +677,7 @@
|
||||
"model": "โมเดล",
|
||||
"tokens": "โทเค็น",
|
||||
"tokens_used": "โทเค็นที่ใช้",
|
||||
"message_type": "Message Type",
|
||||
"tokens_prompt": "โทเค็นพรอมป์ต์",
|
||||
"tokens_completion": "โทเค็นผลลัพธ์",
|
||||
"total_tokens": "โทเค็นรวม",
|
||||
|
||||
@@ -627,6 +627,8 @@
|
||||
"usage": "使用分析",
|
||||
"byUser": "按用户统计",
|
||||
"byAgent": "按应用统计",
|
||||
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
|
||||
"usageByUserEmpty": "暂无用户对话记录",
|
||||
"columns": {
|
||||
"id": "ID",
|
||||
"user_id": "用户 ID",
|
||||
@@ -671,6 +673,7 @@
|
||||
"model": "模型",
|
||||
"tokens": "Token 数",
|
||||
"tokens_used": "已用 Token",
|
||||
"message_type": "Message Type",
|
||||
"tokens_prompt": "提示词 Token",
|
||||
"tokens_completion": "补全 Token",
|
||||
"total_tokens": "总 Token",
|
||||
|
||||
@@ -631,6 +631,8 @@
|
||||
"usage": "使用分析",
|
||||
"byUser": "按用戶統計",
|
||||
"byAgent": "按應用統計",
|
||||
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
|
||||
"usageByUserEmpty": "暫無用戶對話記錄",
|
||||
"columns": {
|
||||
"id": "ID",
|
||||
"user_id": "用戶 ID",
|
||||
@@ -675,6 +677,7 @@
|
||||
"model": "模型",
|
||||
"tokens": "Token 數",
|
||||
"tokens_used": "已用 Token",
|
||||
"message_type": "Message Type",
|
||||
"tokens_prompt": "提示詞 Token",
|
||||
"tokens_completion": "補全 Token",
|
||||
"total_tokens": "總 Token",
|
||||
|
||||
Reference in new issue
Block a user