Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf8c955d45 | ||
|
|
245484a0c5 | ||
|
|
2068421d41 | ||
|
|
7b1941fdaf | ||
|
|
f9c8bda6e0 | ||
|
|
ec7de645f4 | ||
|
|
efa63f9d25 | ||
|
|
c624d8f37c | ||
|
|
bb32884ecb | ||
|
|
df67a298be | ||
|
|
e1e50e884e | ||
|
|
a2504bce34 | ||
|
|
394a7786e0 | ||
|
|
019e1151d0 | ||
|
|
640edc4970 | ||
|
|
771c8456b8 | ||
|
|
2a7bb875f9 | ||
|
|
256d9f33e6 | ||
|
|
3788a93425 | ||
|
|
e8a1791c9f | ||
|
|
acde481bed | ||
|
|
26075272d6 | ||
|
|
a1fd8b074d | ||
|
|
2721da5d4c | ||
|
|
9d67b0544c | ||
|
|
4a95657030 | ||
|
|
d3d8d62b94 | ||
|
|
a08ec87b22 | ||
|
|
49f7503978 | ||
|
|
6da8c3938e | ||
|
|
6d06f9165c | ||
|
|
c32eed39bd | ||
|
|
46528eddbb | ||
|
|
97125d7b65 | ||
|
|
3c9d9518b1 | ||
|
|
be7d792dc2 | ||
|
|
e30e385f11 | ||
|
|
6890570142 | ||
|
|
75f53a7e8a | ||
|
|
0b00d6da45 | ||
|
|
7674729804 | ||
|
|
11b80b90f4 | ||
|
|
71a6403e5b | ||
|
|
5def2697de |
No files matched your search
@@ -0,0 +1,33 @@
|
|||||||
|
# Normalize all text files to LF on checkout/commit (root-cause fix for mixed line endings)
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
# Binary assets: never normalize line endings or diff as text
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.gif binary
|
||||||
|
*.ico binary
|
||||||
|
*.webp binary
|
||||||
|
*.woff binary
|
||||||
|
*.woff2 binary
|
||||||
|
*.ttf binary
|
||||||
|
*.eot binary
|
||||||
|
*.otf binary
|
||||||
|
*.pdf binary
|
||||||
|
*.zip binary
|
||||||
|
*.tar binary
|
||||||
|
*.gz binary
|
||||||
|
*.bz2 binary
|
||||||
|
*.7z binary
|
||||||
|
*.pyc binary
|
||||||
|
*.so binary
|
||||||
|
*.dll binary
|
||||||
|
*.exe binary
|
||||||
|
*.db binary
|
||||||
|
*.sqlite binary
|
||||||
|
*.sqlite3 binary
|
||||||
|
*.wasm binary
|
||||||
|
*.mp4 binary
|
||||||
|
*.mp3 binary
|
||||||
|
*.avi binary
|
||||||
|
*.mov binary
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""
|
||||||
|
AnySearch 联网检索客户端
|
||||||
|
======================
|
||||||
|
调用 AnySearch 网页/领域搜索 API (https://api.anysearch.com/v1/search),
|
||||||
|
为 AI 聊天注入实时联网检索结果,亦可被后端端点 / Agent 工具复用。
|
||||||
|
|
||||||
|
约束:平台容器存在智能路由代理,对外部 API 偶发重置;本客户端使用
|
||||||
|
trust_env=False 直连 (等价于 NO_PROXY=api.anysearch.com),规避代理重置。
|
||||||
|
失败一律返回空/降级结果,保证聊天链路不中断。
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import List, Dict, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger("aiflow.anysearch")
|
||||||
|
|
||||||
|
DEFAULT_API_URL = "https://api.anysearch.com/v1/search"
|
||||||
|
DEFAULT_ZONE = "cn"
|
||||||
|
REQUEST_TIMEOUT = 8.0
|
||||||
|
|
||||||
|
|
||||||
|
async def anysearch_search(
|
||||||
|
api_key: str,
|
||||||
|
api_url: str = DEFAULT_API_URL,
|
||||||
|
query: str = "",
|
||||||
|
top_k: int = 5,
|
||||||
|
zone: str = DEFAULT_ZONE,
|
||||||
|
freshness: Optional[str] = None,
|
||||||
|
timeout: float = REQUEST_TIMEOUT,
|
||||||
|
) -> List[Dict]:
|
||||||
|
"""调用 AnySearch 搜索,返回结构化结果列表。
|
||||||
|
|
||||||
|
每个结果:
|
||||||
|
{
|
||||||
|
"content": snippet 摘要文本,
|
||||||
|
"score": 0.9..0.5 递减,
|
||||||
|
"source": "web_anysearch",
|
||||||
|
"metadata": {"url", "title", "source_domain", "zone"}
|
||||||
|
}
|
||||||
|
失败时返回 [] (不抛异常)。
|
||||||
|
"""
|
||||||
|
if not api_key:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
except ImportError:
|
||||||
|
logger.warning("httpx not available for AnySearch")
|
||||||
|
return []
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"query": query,
|
||||||
|
"zone": zone,
|
||||||
|
"top_k": max(1, min(int(top_k), 20)),
|
||||||
|
}
|
||||||
|
if freshness:
|
||||||
|
payload["freshness"] = freshness
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
# trust_env=False -> 忽略容器内 HTTP(S)_PROXY,直连 api.anysearch.com
|
||||||
|
async with httpx.AsyncClient(trust_env=False, timeout=timeout) as client:
|
||||||
|
resp = await client.post(api_url, json=payload, headers=headers)
|
||||||
|
if resp.status_code != 200:
|
||||||
|
logger.warning(f"AnySearch HTTP {resp.status_code}: {resp.text[:200]}")
|
||||||
|
return []
|
||||||
|
data = resp.json()
|
||||||
|
if data.get("code") != 0:
|
||||||
|
logger.warning(f"AnySearch biz error: {data.get('message')}")
|
||||||
|
return []
|
||||||
|
results = (data.get("data") or {}).get("results") or []
|
||||||
|
hits = []
|
||||||
|
for idx, r in enumerate(results[:top_k]):
|
||||||
|
title = r.get("title", "") or ""
|
||||||
|
url = r.get("url", "") or ""
|
||||||
|
snippet = r.get("snippet") or r.get("content") or ""
|
||||||
|
if not snippet and not title:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
domain = urlparse(url).netloc
|
||||||
|
except Exception:
|
||||||
|
domain = ""
|
||||||
|
hits.append({
|
||||||
|
"content": snippet,
|
||||||
|
"score": max(0.4, 0.9 - idx * 0.08),
|
||||||
|
"source": "web_anysearch",
|
||||||
|
"metadata": {
|
||||||
|
"url": url,
|
||||||
|
"title": title,
|
||||||
|
"source_domain": domain,
|
||||||
|
"zone": zone,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return hits
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"AnySearch search failed: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def anysearch_health(api_key: str, api_url: str = DEFAULT_API_URL, timeout: float = REQUEST_TIMEOUT) -> Dict:
|
||||||
|
"""连通性探测:返回 {"status": "connected"/"disconnected", "detail": ...}。"""
|
||||||
|
if not api_key:
|
||||||
|
return {"status": "disconnected", "detail": "未配置 API Key", "connected": False, "usable": False}
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
async with httpx.AsyncClient(trust_env=False, timeout=timeout) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
api_url,
|
||||||
|
json={"query": "ping", "zone": DEFAULT_ZONE, "top_k": 1},
|
||||||
|
headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"},
|
||||||
|
)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
return {"status": "connected", "detail": "AnySearch 连接正常", "connected": True, "usable": True}
|
||||||
|
return {"status": "error", "detail": f"HTTP {resp.status_code}", "connected": False, "usable": False}
|
||||||
|
except Exception as e:
|
||||||
|
return {"status": "error", "detail": str(e)[:200], "connected": False, "usable": False}
|
||||||
|
|
||||||
|
|
||||||
|
def load_anysearch_config(db_session) -> Dict:
|
||||||
|
"""从 site_settings 读取全局 AnySearch 配置(失败返回空字典)。"""
|
||||||
|
if db_session is None:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
from app.models import SiteSetting
|
||||||
|
row = db_session.query(SiteSetting).filter(SiteSetting.key == "anysearch_config").first()
|
||||||
|
if not row or not row.value:
|
||||||
|
return {}
|
||||||
|
cfg = json.loads(row.value)
|
||||||
|
if not isinstance(cfg, dict):
|
||||||
|
return {}
|
||||||
|
return cfg
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"load_anysearch_config failed: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def save_anysearch_config(
|
||||||
|
db_session,
|
||||||
|
api_key: str,
|
||||||
|
is_enabled: bool = True,
|
||||||
|
api_url: str = DEFAULT_API_URL,
|
||||||
|
zone: str = DEFAULT_ZONE,
|
||||||
|
freshness: Optional[str] = None,
|
||||||
|
top_k: int = 5,
|
||||||
|
) -> bool:
|
||||||
|
"""保存/更新全局 AnySearch 配置到 site_settings。"""
|
||||||
|
if db_session is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
from app.models import SiteSetting
|
||||||
|
from datetime import datetime
|
||||||
|
cfg = {
|
||||||
|
"api_key": api_key.strip(),
|
||||||
|
"is_enabled": bool(is_enabled),
|
||||||
|
"api_url": api_url.strip() or DEFAULT_API_URL,
|
||||||
|
"zone": zone or DEFAULT_ZONE,
|
||||||
|
"freshness": freshness,
|
||||||
|
"top_k": max(1, min(int(top_k), 20)),
|
||||||
|
}
|
||||||
|
row = db_session.query(SiteSetting).filter(SiteSetting.key == "anysearch_config").first()
|
||||||
|
if row:
|
||||||
|
row.value = json.dumps(cfg, ensure_ascii=False)
|
||||||
|
row.updated_at = datetime.now()
|
||||||
|
else:
|
||||||
|
from app.models import gen_uuid
|
||||||
|
row = SiteSetting(id=gen_uuid(), key="anysearch_config", value=json.dumps(cfg, ensure_ascii=False))
|
||||||
|
db_session.add(row)
|
||||||
|
db_session.commit()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"save_anysearch_config failed: {e}")
|
||||||
|
try:
|
||||||
|
db_session.rollback()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
@@ -284,7 +284,7 @@ async def claim_achievement_reward(
|
|||||||
|
|
||||||
# Mark reward as claimed
|
# Mark reward as claimed
|
||||||
_execute_raw(db,
|
_execute_raw(db,
|
||||||
"UPDATE user_achievements SET reward_claimed = 1, claimed_at = NOW() WHERE user_id = :uid AND achievement_id = :aid",
|
"UPDATE user_achievements SET reward_claimed = true, claimed_at = NOW() WHERE user_id = :uid AND achievement_id = :aid",
|
||||||
{"uid": user_id, "aid": ach_id})
|
{"uid": user_id, "aid": ach_id})
|
||||||
|
|
||||||
return {"code": 0, "message": "奖励领取成功"}
|
return {"code": 0, "message": "奖励领取成功"}
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -316,7 +316,7 @@ async def create_dashboard(
|
|||||||
config_json = json.loads('[{"type":"stat","title":"暂无数据","metric":"none","chart_type":"number"}]')
|
config_json = json.loads('[{"type":"stat","title":"暂无数据","metric":"none","chart_type":"number"}]')
|
||||||
|
|
||||||
if is_default:
|
if is_default:
|
||||||
db.execute(text("UPDATE analytics_dashboards SET is_default=0"))
|
db.execute(text("UPDATE analytics_dashboards SET is_default=false"))
|
||||||
|
|
||||||
db.execute(text("""
|
db.execute(text("""
|
||||||
INSERT INTO analytics_dashboards (id, name, description, config, is_default, created_by)
|
INSERT INTO analytics_dashboards (id, name, description, config, is_default, created_by)
|
||||||
@@ -332,7 +332,7 @@ async def create_dashboard(
|
|||||||
@router.delete("/dashboards/{dashboard_id}")
|
@router.delete("/dashboards/{dashboard_id}")
|
||||||
async def delete_dashboard(dashboard_id: str, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
async def delete_dashboard(dashboard_id: str, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
||||||
"""删除仪表盘"""
|
"""删除仪表盘"""
|
||||||
db.execute(text("DELETE FROM analytics_dashboards WHERE id=:id AND is_default=0"), {"id": dashboard_id})
|
db.execute(text("DELETE FROM analytics_dashboards WHERE id=:id AND is_default=false"), {"id": dashboard_id})
|
||||||
db.commit()
|
db.commit()
|
||||||
return {"code": 200, "data": {"message": "仪表盘已删除"}}
|
return {"code": 200, "data": {"message": "仪表盘已删除"}}
|
||||||
|
|
||||||
|
|||||||
@@ -445,7 +445,7 @@ async def billing_stats(db: Session = Depends(get_db), user=Depends(get_current_
|
|||||||
SELECT DATE(created_at) as d, COALESCE(SUM(amount), 0) as rev
|
SELECT DATE(created_at) as d, COALESCE(SUM(amount), 0) as rev
|
||||||
FROM billing_transactions
|
FROM billing_transactions
|
||||||
WHERE transaction_type='recharge' AND status='completed'
|
WHERE transaction_type='recharge' AND status='completed'
|
||||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
|
AND created_at >= NOW() - INTERVAL '7 DAY'
|
||||||
GROUP BY DATE(created_at) ORDER BY d
|
GROUP BY DATE(created_at) ORDER BY d
|
||||||
""")).fetchall()
|
""")).fetchall()
|
||||||
daily_revenue = [{"date": str(r[0]), "revenue": float(r[1])} for r in revenue_7d]
|
daily_revenue = [{"date": str(r[0]), "revenue": float(r[1])} for r in revenue_7d]
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ async def get_execution_stats(db: Session = Depends(get_db), _=Depends(get_curre
|
|||||||
try:
|
try:
|
||||||
total = _execute_raw(db, "SELECT COUNT(*) as cnt FROM code_exec_tasks")[0]["cnt"]
|
total = _execute_raw(db, "SELECT COUNT(*) as cnt FROM code_exec_tasks")[0]["cnt"]
|
||||||
today = _execute_raw(db,
|
today = _execute_raw(db,
|
||||||
"SELECT COUNT(*) as cnt FROM code_exec_tasks WHERE DATE(created_at) = CURDATE()")[0]["cnt"]
|
"SELECT COUNT(*) as cnt FROM code_exec_tasks WHERE DATE(created_at) = CURRENT_DATE")[0]["cnt"]
|
||||||
success_count = _execute_raw(db,
|
success_count = _execute_raw(db,
|
||||||
"SELECT COUNT(*) as cnt FROM code_exec_tasks WHERE exit_code = 0 AND error IS NULL")[0]["cnt"]
|
"SELECT COUNT(*) as cnt FROM code_exec_tasks WHERE exit_code = 0 AND error IS NULL")[0]["cnt"]
|
||||||
failed_count = _execute_raw(db,
|
failed_count = _execute_raw(db,
|
||||||
|
|||||||
@@ -703,7 +703,7 @@ echo "Installation complete!"
|
|||||||
{d.get('version', '1.0.0')}
|
{d.get('version', '1.0.0')}
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
Run `bash install.sh` to install.
|
Run \"bash install.sh\" to install.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
A valid license key is required. Contact your administrator for details.
|
A valid license key is required. Contact your administrator for details.
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ async def get_im_bot_stats(user=Depends(get_current_user)):
|
|||||||
today_stats = _row_to_dict(rows[0]) if rows else {"msg_in": 0, "msg_out": 0, "users": 0, "errors": 0}
|
today_stats = _row_to_dict(rows[0]) if rows else {"msg_in": 0, "msg_out": 0, "users": 0, "errors": 0}
|
||||||
|
|
||||||
# Total routing rules
|
# Total routing rules
|
||||||
routes_count = _execute_raw(db, text("SELECT COUNT(*) as cnt FROM im_bot_routes WHERE is_active=1"))[0]._mapping['cnt']
|
routes_count = _execute_raw(db, text("SELECT COUNT(*) as cnt FROM im_bot_routes WHERE is_active=true"))[0]._mapping['cnt']
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
@@ -202,7 +202,7 @@ async def get_dashboard(user=Depends(get_current_user)):
|
|||||||
SUM(messages_out) as msg_out,
|
SUM(messages_out) as msg_out,
|
||||||
SUM(unique_users) as users
|
SUM(unique_users) as users
|
||||||
FROM im_bot_daily_stats
|
FROM im_bot_daily_stats
|
||||||
WHERE stat_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
|
WHERE stat_date >= CURRENT_DATE - INTERVAL '7 DAY'
|
||||||
GROUP BY stat_date
|
GROUP BY stat_date
|
||||||
ORDER BY stat_date
|
ORDER BY stat_date
|
||||||
"""))
|
"""))
|
||||||
@@ -217,7 +217,7 @@ async def get_dashboard(user=Depends(get_current_user)):
|
|||||||
LEFT JOIN (
|
LEFT JOIN (
|
||||||
SELECT channel_id, SUM(messages_in + messages_out) as msg_count
|
SELECT channel_id, SUM(messages_in + messages_out) as msg_count
|
||||||
FROM im_bot_daily_stats
|
FROM im_bot_daily_stats
|
||||||
WHERE stat_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
WHERE stat_date >= CURRENT_DATE - INTERVAL '30 DAY'
|
||||||
GROUP BY channel_id
|
GROUP BY channel_id
|
||||||
) s ON c.id = s.channel_id
|
) s ON c.id = s.channel_id
|
||||||
ORDER BY c.created_at DESC
|
ORDER BY c.created_at DESC
|
||||||
@@ -357,7 +357,7 @@ async def get_channel_detail(channel_id: str, user=Depends(get_current_user)):
|
|||||||
SELECT stat_date, messages_in, messages_out, unique_users, error_count
|
SELECT stat_date, messages_in, messages_out, unique_users, error_count
|
||||||
FROM im_bot_daily_stats
|
FROM im_bot_daily_stats
|
||||||
WHERE channel_id = :cid
|
WHERE channel_id = :cid
|
||||||
AND stat_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
|
AND stat_date >= CURRENT_DATE - INTERVAL '7 DAY'
|
||||||
ORDER BY stat_date
|
ORDER BY stat_date
|
||||||
"""), {"cid": channel_id})
|
"""), {"cid": channel_id})
|
||||||
channel['stats_7d'] = _rows_to_dict(stats)
|
channel['stats_7d'] = _rows_to_dict(stats)
|
||||||
@@ -428,7 +428,7 @@ async def activate_channel(channel_id: str, user=Depends(get_current_user)):
|
|||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
_execute_raw(db, text(
|
_execute_raw(db, text(
|
||||||
"UPDATE channels SET is_active=1, status='connected' WHERE id=:cid"
|
"UPDATE channels SET is_active=true, status='connected' WHERE id=:cid"
|
||||||
), {"cid": channel_id})
|
), {"cid": channel_id})
|
||||||
return {"success": True, "message": "Channel activated"}
|
return {"success": True, "message": "Channel activated"}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -443,7 +443,7 @@ async def deactivate_channel(channel_id: str, user=Depends(get_current_user)):
|
|||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
_execute_raw(db, text(
|
_execute_raw(db, text(
|
||||||
"UPDATE channels SET is_active=0, status='disconnected' WHERE id=:cid"
|
"UPDATE channels SET is_active=false, status='disconnected' WHERE id=:cid"
|
||||||
), {"cid": channel_id})
|
), {"cid": channel_id})
|
||||||
return {"success": True, "message": "Channel deactivated"}
|
return {"success": True, "message": "Channel deactivated"}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -30,6 +30,7 @@ Phase 3.3: Manage MCP servers, discover tools/resources, test connections
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import asyncio
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Body
|
from fastapi import APIRouter, Depends, HTTPException, Query, Body
|
||||||
|
|
||||||
|
|
||||||
@@ -842,110 +843,29 @@ def _test_mcp_server(server, db) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
if transport in ("streamable_http", "streamablehttp"):
|
if transport in ("streamable_http", "streamablehttp"):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
url = server.url
|
url = server.url
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if not url:
|
if not url:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["message"] = "Streamable HTTP endpoint URL is required"
|
result["message"] = "Streamable HTTP endpoint URL is required"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
# Use the real MCP SDK to verify connectivity (same as chat flow).
|
||||||
|
# A naive HTTP GET/POST can give false negatives for endpoints
|
||||||
|
# that only accept proper MCP JSON-RPC over POST (e.g., AnySearch).
|
||||||
# A real streamable-http MCP endpoint accepts POST JSON-RPC.
|
from ...mcp_client import list_mcp_tools as _lmt
|
||||||
|
hdrs = json.loads(server.headers) if isinstance(server.headers, str) else (server.headers or {})
|
||||||
|
sd = {"url": url, "transport_type": "streamable_http", "headers": hdrs}
|
||||||
|
import asyncio as _aio
|
||||||
# Some implementations also accept GET for SSE events.
|
tools = _aio.run(_lmt(sd, timeout=15))
|
||||||
|
result["success"] = bool(tools)
|
||||||
|
result["details"]["tools_count"] = len(tools)
|
||||||
|
result["details"]["tools"] = [t.get("name") for t in tools[:5]]
|
||||||
# Try GET first (cheapest), fall back to a minimal POST.
|
result["message"] = f"Connected — {len(tools)} tools available" if tools else "Connected but no tools found"
|
||||||
|
result["details"]["status_code"] = 200
|
||||||
|
if tools:
|
||||||
|
server.tools_count = len(tools)
|
||||||
resp = httpx.get(url, headers=req_headers, timeout=10.0, follow_redirects=True)
|
server.status = "connected"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if resp.status_code == 405:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
resp = httpx.post(
|
|
||||||
url,
|
|
||||||
headers=req_headers,
|
|
||||||
json={"jsonrpc": "2.0", "method": "initialize", "id": 1},
|
|
||||||
timeout=10.0,
|
|
||||||
follow_redirects=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Any HTTP response (including 4xx) means the host is reachable.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["success"] = resp.status_code < 500
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["message"] = f"HTTP responded with {resp.status_code}"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["details"]["status_code"] = resp.status_code
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["details"]["content_type"] = resp.headers.get("content-type", "")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["message"] = f"Connection refused - server may be down: {str(e)}"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
except httpx.TimeoutException:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
result["message"] = "Connection timed out"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
result["message"] = f"Connection failed: {str(e)}"
|
||||||
|
|
||||||
|
|
||||||
result["message"] = f"HTTP request failed: {str(e)}"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
elif transport == "sse":
|
elif transport == "sse":
|
||||||
|
|
||||||
@@ -3156,7 +3076,7 @@ async def test_mcp_connection(
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
result = _test_mcp_server(server, db)
|
result = await asyncio.get_running_loop().run_in_executor(None, _test_mcp_server, server, db)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+1201
-1192
File diff suppressed because it is too large.
Load diff
@@ -442,7 +442,7 @@ def revoke_license(
|
|||||||
raise HTTPException(404, "License not found")
|
raise HTTPException(404, "License not found")
|
||||||
|
|
||||||
_execute_raw(db, text(
|
_execute_raw(db, text(
|
||||||
"UPDATE offline_licenses SET status = 'revoked', revoked_reason = :reason, is_active = 0 WHERE id = :lid"
|
"UPDATE offline_licenses SET status = 'revoked', revoked_reason = :reason, is_active = false WHERE id = :lid"
|
||||||
), {"reason": reason, "lid": license_id})
|
), {"reason": reason, "lid": license_id})
|
||||||
|
|
||||||
return {"code": 0, "message": "License revoked"}
|
return {"code": 0, "message": "License revoked"}
|
||||||
@@ -623,7 +623,7 @@ def get_usage_stats(db: Session = Depends(get_db)):
|
|||||||
"SELECT COUNT(DISTINCT user_hash) FROM usage_reports"
|
"SELECT COUNT(DISTINCT user_hash) FROM usage_reports"
|
||||||
))
|
))
|
||||||
today_reports = _execute_raw(db, text(
|
today_reports = _execute_raw(db, text(
|
||||||
"SELECT COUNT(*) FROM usage_reports WHERE DATE(created_at) = CURDATE()"
|
"SELECT COUNT(*) FROM usage_reports WHERE DATE(created_at) = CURRENT_DATE"
|
||||||
))
|
))
|
||||||
by_type = _execute_raw(db, text(
|
by_type = _execute_raw(db, text(
|
||||||
"SELECT report_type, COUNT(*) as cnt FROM usage_reports GROUP BY report_type"
|
"SELECT report_type, COUNT(*) as cnt FROM usage_reports GROUP BY report_type"
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -37,17 +37,31 @@ SKILL_STATES = {
|
|||||||
"frozen": {"label": "已冻结", "color": "#EF4444", "description": "已停止使用"},
|
"frozen": {"label": "已冻结", "color": "#EF4444", "description": "已停止使用"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 业务场景分类(与前端「应用市场」保持一致,14 类岗位/职能视角)
|
||||||
|
# 统一标准:以前台 MARKET_SCENES 为准,后台技能管理也按此 14 类展示与筛选。
|
||||||
SKILL_CATEGORIES = [
|
SKILL_CATEGORIES = [
|
||||||
{"id": "writing", "label": "文字创作"},
|
{"id": "design", "label": "🎨 做设计"},
|
||||||
{"id": "coding", "label": "代码能力"},
|
{"id": "frontend", "label": "💻 写前端"},
|
||||||
{"id": "data_analysis", "label": "数据分析"},
|
{"id": "mobile", "label": "📱 做移动端"},
|
||||||
{"id": "qa", "label": "知识问答"},
|
{"id": "backend", "label": "🧪 后端/全栈"},
|
||||||
{"id": "automation", "label": "流程自动化"},
|
{"id": "qa", "label": "🧪 测试质量"},
|
||||||
{"id": "creativity", "label": "创意生成"},
|
{"id": "search", "label": "🔍 搜索信息"},
|
||||||
{"id": "communication", "label": "沟通协作"},
|
{"id": "docs", "label": "✍️ 写文档"},
|
||||||
{"id": "reasoning", "label": "逻辑推理"},
|
{"id": "marketing", "label": "📢 推广获客"},
|
||||||
{"id": "other", "label": "其他"},
|
{"id": "workflow", "label": "🔄 工作流"},
|
||||||
|
{"id": "secops", "label": "🛡️ 安全运维"},
|
||||||
|
{"id": "learning", "label": "🎓 学习教学"},
|
||||||
|
{"id": "video", "label": "🎬 视频多媒体"},
|
||||||
|
{"id": "collab", "label": "🏢 办公协作"},
|
||||||
|
{"id": "ai", "label": "🛠️ AI能力"},
|
||||||
]
|
]
|
||||||
|
_SCENE_IDS = {c["id"] for c in SKILL_CATEGORIES}
|
||||||
|
# 旧 9 类 taxonomy -> 14 场景 的兜底映射(仅用于历史数据 capability 缺失时)
|
||||||
|
_CATEGORY_TO_SCENE = {
|
||||||
|
"writing": "docs", "coding": "backend", "data_analysis": "backend",
|
||||||
|
"qa": "qa", "automation": "workflow", "creativity": "design",
|
||||||
|
"communication": "marketing", "reasoning": "search", "other": "workflow",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
@@ -65,7 +79,13 @@ def market_app_to_skill_dict(app: "MarketApp") -> dict:
|
|||||||
tags_list = json.loads(raw_tags) if isinstance(raw_tags, str) else list(raw_tags)
|
tags_list = json.loads(raw_tags) if isinstance(raw_tags, str) else list(raw_tags)
|
||||||
except Exception:
|
except Exception:
|
||||||
tags_list = [t.strip() for t in str(raw_tags).split(",")]
|
tags_list = [t.strip() for t in str(raw_tags).split(",")]
|
||||||
category = getattr(app, "category", None) or "other"
|
# 以业务场景(capability, 14 类)为分类标准,与前端应用市场统一;
|
||||||
|
# capability 缺失时回退到旧 9 类 category 映射出的场景。
|
||||||
|
raw_scene = getattr(app, "capability", None)
|
||||||
|
if raw_scene in _SCENE_IDS:
|
||||||
|
category = raw_scene
|
||||||
|
else:
|
||||||
|
category = _CATEGORY_TO_SCENE.get(getattr(app, "category", None), "workflow")
|
||||||
return {
|
return {
|
||||||
"id": app.id,
|
"id": app.id,
|
||||||
"user_id": getattr(app, "publisher_id", None) or "system",
|
"user_id": getattr(app, "publisher_id", None) or "system",
|
||||||
@@ -187,7 +207,8 @@ async def list_skills(
|
|||||||
or_(MarketApp.name.contains(keyword), MarketApp.description.contains(keyword))
|
or_(MarketApp.name.contains(keyword), MarketApp.description.contains(keyword))
|
||||||
)
|
)
|
||||||
if category:
|
if category:
|
||||||
mkt_query = mkt_query.filter(MarketApp.category == category)
|
# 分类筛选统一按业务场景(capability, 14 类)进行,与前端应用市场一致
|
||||||
|
mkt_query = mkt_query.filter(MarketApp.capability == category)
|
||||||
# 状态映射:主面板只展示已发布 → state='main';草稿/移除 → 'baby'
|
# 状态映射:主面板只展示已发布 → state='main';草稿/移除 → 'baby'
|
||||||
if state == "main":
|
if state == "main":
|
||||||
mkt_query = mkt_query.filter(MarketApp.status == "published")
|
mkt_query = mkt_query.filter(MarketApp.status == "published")
|
||||||
@@ -901,7 +922,7 @@ async def get_skills_stats(
|
|||||||
market_by_category = {}
|
market_by_category = {}
|
||||||
try:
|
try:
|
||||||
market_by_category_rows = db.execute(
|
market_by_category_rows = db.execute(
|
||||||
text("SELECT category, COUNT(*) FROM market_apps WHERE type='skill' AND category IS NOT NULL GROUP BY category")
|
text("SELECT capability, COUNT(*) FROM market_apps WHERE type='skill' AND capability IS NOT NULL GROUP BY capability")
|
||||||
).fetchall()
|
).fetchall()
|
||||||
market_by_category = {cat or "other": cnt for cat, cnt in market_by_category_rows}
|
market_by_category = {cat or "other": cnt for cat, cnt in market_by_category_rows}
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
+2818
-1385
File diff suppressed because it is too large.
Load diff
+2924
-1392
File diff suppressed because it is too large.
Load diff
@@ -1,319 +1,319 @@
|
|||||||
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
||||||
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_, desc, asc, func
|
from sqlalchemy import and_, desc, asc, func
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone, timedelta
|
from datetime import datetime, timezone, timedelta
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
import httpx
|
import httpx
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
from ..database import get_db, SessionLocal
|
from ..database import get_db, SessionLocal
|
||||||
from ..models import (
|
from ..models import (
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MCPServer,
|
MCPServer,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
gen_uuid
|
gen_uuid
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
)
|
)
|
||||||
from ..auth import get_current_user
|
from ..auth import get_current_user
|
||||||
from ..platform_knowledge import get_platform_knowledge
|
from ..platform_knowledge import get_platform_knowledge
|
||||||
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
||||||
from ..middleware.log_service import LogService
|
from ..middleware.log_service import LogService
|
||||||
from ..capability_registry import resolve_auto_model
|
from ..capability_registry import resolve_auto_model
|
||||||
from app.api.chat_utils import (cst_now)
|
from app.api.chat_utils import (cst_now)
|
||||||
|
|
||||||
def _build_knowledge_graph(db: Session, kb: KnowledgeBase) -> dict:
|
def _build_knowledge_graph(db: Session, kb: KnowledgeBase) -> dict:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""从知识库文档构建知识图谱节点和边,返回 graph_data。"""
|
"""从知识库文档构建知识图谱节点和边,返回 graph_data。"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
documents = db.query(KnowledgeDocument).filter(
|
documents = db.query(KnowledgeDocument).filter(
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
and_(
|
and_(
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
KnowledgeDocument.knowledge_base_id == kb.id,
|
KnowledgeDocument.knowledge_base_id == kb.id,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
KnowledgeDocument.status == "completed",
|
KnowledgeDocument.status == "completed",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_nodes = []
|
graph_nodes = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_edges = []
|
graph_edges = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
doc_entity_types = [
|
doc_entity_types = [
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{"type": "concept", "label": "核心概念"},
|
{"type": "concept", "label": "核心概念"},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{"type": "entity", "label": "关键实体"},
|
{"type": "entity", "label": "关键实体"},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{"type": "attribute", "label": "属性特征"},
|
{"type": "attribute", "label": "属性特征"},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{"type": "relation", "label": "关联关系"},
|
{"type": "relation", "label": "关联关系"},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for idx, doc in enumerate(documents):
|
for idx, doc in enumerate(documents):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
doc_node_id = f"doc-{doc.id[:8]}"
|
doc_node_id = f"doc-{doc.id[:8]}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_nodes.append({
|
graph_nodes.append({
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"id": doc_node_id, "label": doc.filename, "type": "document", "size": 18, "group": "document",
|
"id": doc_node_id, "label": doc.filename, "type": "document", "size": 18, "group": "document",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
filename_base = doc.filename.rsplit(".", 1)[0]
|
filename_base = doc.filename.rsplit(".", 1)[0]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
words = filename_base.replace("_", " ").replace("-", " ").split()
|
words = filename_base.replace("_", " ").replace("-", " ").split()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for wi, word in enumerate(words):
|
for wi, word in enumerate(words):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if len(word) >= 2:
|
if len(word) >= 2:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
entity_type = doc_entity_types[wi % len(doc_entity_types)]
|
entity_type = doc_entity_types[wi % len(doc_entity_types)]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
node_id = f"ent-{doc.id[:8]}-{wi}"
|
node_id = f"ent-{doc.id[:8]}-{wi}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_nodes.append({
|
graph_nodes.append({
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"id": node_id, "label": word, "type": entity_type["type"],
|
"id": node_id, "label": word, "type": entity_type["type"],
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"size": 10 + (wi % 8), "group": entity_type["type"],
|
"size": 10 + (wi % 8), "group": entity_type["type"],
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_edges.append({
|
graph_edges.append({
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"source": doc_node_id, "target": node_id,
|
"source": doc_node_id, "target": node_id,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"label": entity_type["label"], "weight": 0.5 + (0.5 / (wi + 1)),
|
"label": entity_type["label"], "weight": 0.5 + (0.5 / (wi + 1)),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for i in range(len(documents)):
|
for i in range(len(documents)):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for j in range(i + 1, len(documents)):
|
for j in range(i + 1, len(documents)):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
fi = documents[i].filename.lower().rsplit(".", 1)[0]
|
fi = documents[i].filename.lower().rsplit(".", 1)[0]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
fj = documents[j].filename.lower().rsplit(".", 1)[0]
|
fj = documents[j].filename.lower().rsplit(".", 1)[0]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
words_i = set(fi.replace("_", " ").replace("-", " ").split())
|
words_i = set(fi.replace("_", " ").replace("-", " ").split())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
words_j = set(fj.replace("_", " ").replace("-", " ").split())
|
words_j = set(fj.replace("_", " ").replace("-", " ").split())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
common = words_i & words_j
|
common = words_i & words_j
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if common and len(common) > 0:
|
if common and len(common) > 0:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_edges.append({
|
graph_edges.append({
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"source": f"doc-{documents[i].id[:8]}",
|
"source": f"doc-{documents[i].id[:8]}",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"target": f"doc-{documents[j].id[:8]}",
|
"target": f"doc-{documents[j].id[:8]}",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"label": f"共有关键词: {', '.join(list(common)[:3])}",
|
"label": f"共有关键词: {', '.join(list(common)[:3])}",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"weight": min(0.9, 0.3 * len(common)),
|
"weight": min(0.9, 0.3 * len(common)),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
graph_data = {
|
graph_data = {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"nodes": graph_nodes,
|
"nodes": graph_nodes,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"edges": graph_edges,
|
"edges": graph_edges,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"stats": {
|
"stats": {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"total_nodes": len(graph_nodes), "total_edges": len(graph_edges),
|
"total_nodes": len(graph_nodes), "total_edges": len(graph_edges),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"document_count": len(documents),
|
"document_count": len(documents),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
kb.knowledge_graph_count = len(graph_nodes)
|
kb.knowledge_graph_count = len(graph_nodes)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
kb.updated_at = cst_now()
|
kb.updated_at = cst_now()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return graph_data
|
return graph_data
|
||||||
+240
-240
@@ -1,240 +1,240 @@
|
|||||||
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
||||||
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_, desc, asc, func
|
from sqlalchemy import and_, desc, asc, func
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone, timedelta
|
from datetime import datetime, timezone, timedelta
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
import httpx
|
import httpx
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
from ..database import get_db, SessionLocal
|
from ..database import get_db, SessionLocal
|
||||||
from ..models import (
|
from ..models import (
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MCPServer,
|
MCPServer,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
gen_uuid
|
gen_uuid
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
)
|
)
|
||||||
from ..auth import get_current_user
|
from ..auth import get_current_user
|
||||||
from ..platform_knowledge import get_platform_knowledge
|
from ..platform_knowledge import get_platform_knowledge
|
||||||
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
||||||
from ..middleware.log_service import LogService
|
from ..middleware.log_service import LogService
|
||||||
from ..capability_registry import resolve_auto_model
|
from ..capability_registry import resolve_auto_model
|
||||||
|
|
||||||
def _resolve_market_mcp(db: Session, mcp_ids: list, user_id: str) -> list:
|
def _resolve_market_mcp(db: Session, mcp_ids: list, user_id: str) -> list:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
加载用户选择的 MCP 应用配置(MarketApp.type == 'mcp')。
|
加载用户选择的 MCP 应用配置(MarketApp.type == 'mcp')。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
返回: [{id, name, transport, endpoint, description}]
|
返回: [{id, name, transport, endpoint, description}]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if not mcp_ids:
|
if not mcp_ids:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
mcps = db.query(MarketApp).filter(
|
mcps = db.query(MarketApp).filter(
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MarketApp.id.in_(mcp_ids),
|
MarketApp.id.in_(mcp_ids),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MarketApp.type == "mcp"
|
MarketApp.type == "mcp"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for m in mcps:
|
for m in mcps:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
config = {}
|
config = {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if m.skill_content:
|
if m.skill_content:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
config = json.loads(m.skill_content)
|
config = json.loads(m.skill_content)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
config = {}
|
config = {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
results.append({
|
results.append({
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"id": m.id,
|
"id": m.id,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"name": m.name,
|
"name": m.name,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"transport": m.mcp_transport or config.get("transport", "stdio"),
|
"transport": m.mcp_transport or config.get("transport", "stdio"),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"endpoint": m.agent_endpoint or config.get("endpoint", "") or config.get("url", ""),
|
"endpoint": m.agent_endpoint or config.get("endpoint", "") or config.get("url", ""),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"description": m.description or config.get("description", ""),
|
"description": m.description or config.get("description", ""),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
def _resolve_active_mcp_servers(db: Session, mcp_ids: list) -> list:
|
def _resolve_active_mcp_servers(db: Session, mcp_ids: list) -> list:
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
解析用户选中的 MCP 服务连接信息(来自 mcp_servers 表,import 与后台添加通用)。
|
解析用户选中的 MCP 服务连接信息(来自 mcp_servers 表,import 与后台添加通用)。
|
||||||
|
|
||||||
返回: [{id, name, description, transport, endpoint, url, headers}]
|
返回: [{id, name, description, transport, endpoint, url, headers}]
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not mcp_ids:
|
if not mcp_ids:
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
servers = db.query(MCPServer).filter(
|
servers = db.query(MCPServer).filter(
|
||||||
|
|
||||||
MCPServer.id.in_(mcp_ids),
|
MCPServer.id.in_(mcp_ids),
|
||||||
|
|
||||||
MCPServer.is_enabled == True,
|
MCPServer.is_enabled == True,
|
||||||
|
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
out = []
|
out = []
|
||||||
|
|
||||||
for s in servers:
|
for s in servers:
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
headers = json.loads(s.headers) if isinstance(s.headers, str) else (s.headers or {})
|
headers = json.loads(s.headers) if isinstance(s.headers, str) else (s.headers or {})
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
||||||
headers = {}
|
headers = {}
|
||||||
|
|
||||||
out.append({
|
out.append({
|
||||||
|
|
||||||
"id": s.id,
|
"id": s.id,
|
||||||
|
|
||||||
"name": s.name,
|
"name": s.name,
|
||||||
|
|
||||||
"description": s.description or "",
|
"description": s.description or "",
|
||||||
|
|
||||||
"transport": s.transport_type or "streamable_http",
|
"transport": s.transport_type or "streamable_http",
|
||||||
|
|
||||||
"endpoint": s.url or "",
|
"endpoint": s.url or "",
|
||||||
|
|
||||||
"url": s.url or "",
|
"url": s.url or "",
|
||||||
|
|
||||||
"headers": headers,
|
"headers": headers,
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _list_enabled_mcp_servers(db: Session) -> list:
|
def _list_enabled_mcp_servers(db: Session) -> list:
|
||||||
"""返回平台所有已启用(is_enabled=True)的 MCP 服务清单,供 AI 准确回答"平台有哪些 MCP"。"""
|
"""返回平台所有已启用(is_enabled=True)的 MCP 服务清单,供 AI 准确回答"平台有哪些 MCP"。"""
|
||||||
servers = db.query(MCPServer).filter(MCPServer.is_enabled == True).all()
|
servers = db.query(MCPServer).filter(MCPServer.is_enabled == True).all()
|
||||||
out = []
|
out = []
|
||||||
for s in servers:
|
for s in servers:
|
||||||
try:
|
try:
|
||||||
headers = json.loads(s.headers) if isinstance(s.headers, str) else (s.headers or {})
|
headers = json.loads(s.headers) if isinstance(s.headers, str) else (s.headers or {})
|
||||||
except Exception:
|
except Exception:
|
||||||
headers = {}
|
headers = {}
|
||||||
out.append({
|
out.append({
|
||||||
"id": s.id,
|
"id": s.id,
|
||||||
"name": s.name,
|
"name": s.name,
|
||||||
"description": s.description or "",
|
"description": s.description or "",
|
||||||
"transport": s.transport_type or "streamable_http",
|
"transport": s.transport_type or "streamable_http",
|
||||||
"endpoint": s.url or "",
|
"endpoint": s.url or "",
|
||||||
"url": s.url or "",
|
"url": s.url or "",
|
||||||
"headers": headers,
|
"headers": headers,
|
||||||
})
|
})
|
||||||
return out
|
return out
|
||||||
@@ -3,7 +3,8 @@
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_, desc, asc, func
|
from sqlalchemy import and_, desc, asc, func, type_coerce
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
import uuid
|
import uuid
|
||||||
@@ -839,6 +840,86 @@ async def _agnes_post_json(api_url: str, headers: dict, payload: dict, timeout)
|
|||||||
|
|
||||||
return None, last_err
|
return None, last_err
|
||||||
|
|
||||||
|
|
||||||
|
def _media_api_url(ai_model, provider, media_kind: str) -> str:
|
||||||
|
"""推导图像/视频生成地址,避免把 chat/completions 端点误用作媒体端点。
|
||||||
|
|
||||||
|
- 若模型 endpoint 已是对应的媒体端点(含 /images/generations 或 /videos),直接使用;
|
||||||
|
- 否则从 chat endpoint 反推 base,再拼 /v1/images|videos/generations;
|
||||||
|
- 若 endpoint 为空,则回退供应商 api_base_url + 媒体路径。
|
||||||
|
"""
|
||||||
|
suffix = "/v1/images/generations" if media_kind == "image" else "/v1/videos"
|
||||||
|
chat_suffixes = ["/v1/chat/completions", "/chat/completions"]
|
||||||
|
ep = (ai_model.endpoint or "").strip()
|
||||||
|
if ep:
|
||||||
|
if suffix in ep:
|
||||||
|
return ep
|
||||||
|
base = ep
|
||||||
|
for cs in chat_suffixes:
|
||||||
|
if base.endswith(cs):
|
||||||
|
base = base[: -len(cs)]
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
if "/v1" in base:
|
||||||
|
base = base.rsplit("/v1", 1)[0]
|
||||||
|
return f"{base.rstrip('/')}{suffix}"
|
||||||
|
if provider and provider.api_base_url:
|
||||||
|
return f"{provider.api_base_url.rstrip('/')}{suffix}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def _build_media_route(db, capability: str, preferred_id: str = None):
|
||||||
|
"""构造媒体生成模型路由顺序:
|
||||||
|
1) 按能力默认模型(后台"能力默认模型"或全局默认) 作为第一顺位
|
||||||
|
2) 调用方显式指定的模型(若不同于默认) 次位
|
||||||
|
3) 其余启用且具备该能力的模型,按 is_default 降序、created_at 升序 排列
|
||||||
|
去重后返回 AIModel 列表。
|
||||||
|
"""
|
||||||
|
from ..models import AIModel as _AM
|
||||||
|
|
||||||
|
selected = []
|
||||||
|
seen = set()
|
||||||
|
|
||||||
|
def _add(m):
|
||||||
|
if m and m.id not in seen:
|
||||||
|
selected.append(m)
|
||||||
|
seen.add(m.id)
|
||||||
|
|
||||||
|
default_model = resolve_auto_model(capability, db)
|
||||||
|
if default_model:
|
||||||
|
_add(default_model)
|
||||||
|
|
||||||
|
if preferred_id:
|
||||||
|
pref = db.query(_AM).filter(_AM.id == preferred_id, _AM.is_enabled == True).first()
|
||||||
|
_add(pref)
|
||||||
|
|
||||||
|
others = db.query(_AM).filter(
|
||||||
|
_AM.is_enabled == True,
|
||||||
|
_AM.capabilities.cast(JSONB).contains(type_coerce([capability], JSONB)),
|
||||||
|
).order_by(_AM.is_default.desc(), _AM.created_at.asc()).all()
|
||||||
|
for m in others:
|
||||||
|
_add(m)
|
||||||
|
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_media_route(db, route, prompt, user_id, media_kind):
|
||||||
|
"""依次尝试路由中的模型生成媒体;首个成功(非 ⚠️ 开头)即返回,否则尝试下一个。"""
|
||||||
|
last_err = None
|
||||||
|
for idx, m in enumerate(route, 1):
|
||||||
|
logger.info(f"[_run_media_route] ({idx}/{len(route)}) 尝试模型 {m.name} ({m.id})")
|
||||||
|
try:
|
||||||
|
res = await _generate_media(db, m, prompt, user_id)
|
||||||
|
except Exception as e:
|
||||||
|
last_err = f"模型 {m.name} 异常: {str(e)[:160]}"
|
||||||
|
logger.warning(f"[_run_media_route] 模型 {m.name} 异常: {e}")
|
||||||
|
continue
|
||||||
|
if res and not res.startswith("⚠️"):
|
||||||
|
return res
|
||||||
|
last_err = res
|
||||||
|
logger.warning(f"[_run_media_route] 模型 {m.name} 失败: {str(res)[:160]}")
|
||||||
|
return last_err or "⚠️ 所有模型均生成失败"
|
||||||
|
|
||||||
|
|
||||||
async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str:
|
async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str:
|
||||||
|
|
||||||
|
|
||||||
@@ -880,6 +961,9 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
timeout = ai_model.timeout or 120
|
timeout = ai_model.timeout or 120
|
||||||
|
# 单次媒体调用超时封顶:避免单个供应商长时间挂起拖垮整条生成链路;
|
||||||
|
# 多模型 failover 由 _generate_media_task 外层循环保证
|
||||||
|
call_timeout = min(timeout, 300 if "video" in caps else 180)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -895,15 +979,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
api_url = ai_model.endpoint
|
api_url = _media_api_url(ai_model, provider, "image")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if not api_url:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
api_url = f"{provider.api_base_url.rstrip('/')}/v1/images/generations" if provider else ""
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -951,7 +1027,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
"size": "1024x768",
|
"size": "1024x1024",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -960,7 +1036,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
async with span("media.agnes_call"):
|
async with span("media.agnes_call"):
|
||||||
resp, err = await _agnes_post_json(api_url, headers, payload, timeout)
|
resp, err = await _agnes_post_json(api_url, headers, payload, call_timeout)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -992,7 +1068,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
resp2, _ = await _agnes_post_json(api_url, headers, payload, timeout)
|
resp2, _ = await _agnes_post_json(api_url, headers, payload, call_timeout)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1092,15 +1168,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
api_url = ai_model.endpoint
|
api_url = _media_api_url(ai_model, provider, "video")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if not api_url:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
api_url = f"{provider.api_base_url.rstrip('/')}/v1/videos" if provider else ""
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1169,7 +1237,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
async with span("media.agnes_call"):
|
async with span("media.agnes_call"):
|
||||||
resp, err = await _agnes_post_json(api_url, headers, payload, timeout)
|
resp, err = await _agnes_post_json(api_url, headers, payload, call_timeout)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1197,7 +1265,7 @@ async def _generate_media(db, ai_model, prompt: str, user_id: str = None) -> str
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
resp2, _ = await _agnes_post_json(api_url, headers, payload, timeout)
|
resp2, _ = await _agnes_post_json(api_url, headers, payload, call_timeout)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1430,22 +1498,27 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
|
|||||||
logger.info(f"[_generate_media_task] 启动 media 生成 msg={ai_msg_id} model={ai_model_id} prompt={prompt[:60]!r}")
|
logger.info(f"[_generate_media_task] 启动 media 生成 msg={ai_msg_id} model={ai_model_id} prompt={prompt[:60]!r}")
|
||||||
caps = [c.lower() for c in (ai_model.capabilities or [])]
|
caps = [c.lower() for c in (ai_model.capabilities or [])]
|
||||||
is_video = "video" in caps
|
is_video = "video" in caps
|
||||||
timeout_seconds = 300 if is_video else 90
|
media_kind = "video" if is_video else "image"
|
||||||
try:
|
|
||||||
result = await asyncio.wait_for(
|
|
||||||
_generate_media(db, ai_model, prompt, user_id),
|
|
||||||
timeout=timeout_seconds
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# 构造模型路由:默认模型第一顺位,之后按路由策略逐一尝试
|
||||||
|
route = _build_media_route(db, media_kind, ai_model_id)
|
||||||
except asyncio.TimeoutError:
|
if not route:
|
||||||
logger.warning(f"[_generate_media_task] media 生成超时 msg={ai_msg_id} is_video={is_video} timeout={timeout_seconds}s")
|
result = f"⚠️ 未找到可用的{'视频' if is_video else '图像'}模型,请在后台「大模型库」中启用具备该能力的模型。"
|
||||||
|
else:
|
||||||
_media_name = "视频" if is_video else "图像"
|
_media_name = "视频" if is_video else "图像"
|
||||||
result = f"⚠️ 媒体生成超时:{_media_name}生成耗时超过 {timeout_seconds} 秒,请稍后重试。"
|
per_call = 300 if is_video else 180
|
||||||
except Exception as e:
|
route_timeout = min(per_call * len(route) + 30, 900 if is_video else 600)
|
||||||
logger.warning(f"[_generate_media_task] media 生成异常 msg={ai_msg_id}: {e}", exc_info=True)
|
try:
|
||||||
result = f"⚠️ 媒体生成失败:{str(e)[:200]}"
|
result = await asyncio.wait_for(
|
||||||
|
_run_media_route(db, route, prompt, user_id, media_kind),
|
||||||
|
timeout=route_timeout,
|
||||||
|
)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
logger.warning(f"[_generate_media_task] media 路由全部超时 msg={ai_msg_id} is_video={is_video} timeout={route_timeout}s")
|
||||||
|
result = f"⚠️ {_media_name}生成超时:已依次尝试 {len(route)} 个模型仍失败,请稍后重试。"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[_generate_media_task] media 路由异常 msg={ai_msg_id}: {e}", exc_info=True)
|
||||||
|
result = f"⚠️ {_media_name}生成失败:{str(e)[:200]}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1494,11 +1567,16 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
|
|||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
logger.warning(f"[_generate_media_task] 后台生成异常: {e}", exc_info=True)
|
||||||
|
# 兜底回写:任何意外异常都不能让消息永久停在「⏳ 生成中…」
|
||||||
|
try:
|
||||||
logger.warning(f"[_generate_media_task] 后台生成异常: {e}")
|
db.rollback()
|
||||||
|
_err = db.query(Message).filter(Message.id == ai_msg_id).first()
|
||||||
|
if _err and str(_err.content or "").startswith("⏳"):
|
||||||
|
_err.content = "⚠️ 媒体生成失败,请稍后重试"
|
||||||
|
db.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
+8600
-2113
File diff suppressed because it is too large.
Load diff
+1742
-1595
File diff suppressed because it is too large.
Load diff
@@ -1,378 +1,387 @@
|
|||||||
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
||||||
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_, desc, asc, func
|
from sqlalchemy import and_, desc, asc, func
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone, timedelta
|
from datetime import datetime, timezone, timedelta
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
import httpx
|
import httpx
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
from ..database import get_db, SessionLocal
|
from ..database import get_db, SessionLocal
|
||||||
from ..models import (
|
from ..models import (
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MCPServer,
|
MCPServer,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
gen_uuid
|
gen_uuid
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
)
|
)
|
||||||
from ..auth import get_current_user
|
from ..auth import get_current_user
|
||||||
from ..platform_knowledge import get_platform_knowledge
|
from ..platform_knowledge import get_platform_knowledge
|
||||||
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
||||||
from ..middleware.log_service import LogService
|
from ..middleware.log_service import LogService
|
||||||
from ..capability_registry import resolve_auto_model
|
from ..capability_registry import resolve_auto_model
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
CST_TZ = timezone(timedelta(hours=8))
|
CST_TZ = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
def cst_now():
|
def cst_now():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""Get current time in CST timezone"""
|
"""Get current time in CST timezone"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return datetime.now(CST_TZ)
|
return datetime.now(CST_TZ)
|
||||||
|
|
||||||
def _html_escape(s: str) -> str:
|
def _html_escape(s: str) -> str:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
.replace('"', """).replace("'", "'"))
|
.replace('"', """).replace("'", "'"))
|
||||||
|
|
||||||
def _outbound_proxy() -> str:
|
def _outbound_proxy() -> str:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""出网代理地址(兜底)。默认经 172.18.0.1:7890 智能路由代理;
|
"""出网代理地址(兜底)。默认经 172.18.0.1:7890 智能路由代理;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
运行时若未注入代理环境变量则回退到该地址。"""
|
运行时若未注入代理环境变量则回退到该地址。"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
||||||
|
|
||||||
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
||||||
|
|
||||||
def _proxy_for_url(url: str) -> str | None:
|
def _proxy_for_url(url: str) -> str | None:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""按目标域名选择是否走代理。
|
"""按目标域名选择是否走代理。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
2026-07-15 调整:AGNES(apihub.agnes-ai.com / platform-outputs.agnes-ai.space)
|
2026-07-15 调整:AGNES(apihub.agnes-ai.com / platform-outputs.agnes-ai.space)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
经用户实测走香港代理 103.242.14.208:11495 延迟更低、更稳定,故改为走 HK 代理
|
经用户实测走香港代理 103.242.14.208:11495 延迟更低、更稳定,故改为走 HK 代理
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
(带鉴权),不再直连,也不经智能路由代理(172.18.0.1:7890 对 AGNES 返 502)。
|
(带鉴权),不再直连,也不经智能路由代理(172.18.0.1:7890 对 AGNES 返 502)。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
其余国内/平台域名直连,真正的境外域名走 _outbound_proxy()。
|
其余国内/平台域名直连,真正的境外域名走 _outbound_proxy()。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
注意:httpx 默认 trust_env=True 会忽略 proxy 参数而改用环境变量 HTTP_PROXY,
|
注意:httpx 默认 trust_env=True 会忽略 proxy 参数而改用环境变量 HTTP_PROXY,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
故调用方必须同时传 trust_env=False 才能真正走此处指定的代理。
|
故调用方必须同时传 trust_env=False 才能真正走此处指定的代理。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
host = (urlparse(url).hostname or "").lower()
|
host = (urlparse(url).hostname or "").lower()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
# 文生图 / 视频生成走直连:智能路由代理(172.18.0.1:7890)与 HK 代理对这类长耗时、
|
||||||
|
# 大响应体的生成连接会偶发重置(Server disconnected),而各图像/视频供应商均为公网
|
||||||
|
# API,直连更稳定(已实测 gpt-image-2 / agnes 直连均返回 200)。故媒体端点统一直连。
|
||||||
|
_lower = (url or "").lower()
|
||||||
return _HK_PROXY
|
if "/images/" in _lower or "/videos/" in _lower or "/v1/images" in _lower or "/v1/videos" in _lower:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
# 平台自有域名(含自建 Dify/n8n 等)必须直连,不经出网代理。
|
|
||||||
|
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
||||||
|
|
||||||
|
|
||||||
if "qihuyun.com" in host:
|
|
||||||
|
return _HK_PROXY
|
||||||
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
# 平台自有域名(含自建 Dify/n8n 等)必须直连,不经出网代理。
|
||||||
|
|
||||||
|
|
||||||
# 尊重 NO_PROXY:国内域名(硅基流动/DeepSeek/小米MoE 等)直连更稳定,
|
|
||||||
|
if "qihuyun.com" in host:
|
||||||
|
|
||||||
|
|
||||||
# 避免经易波动的智能路由代理 172.18.0.1:7890(对国内域名偶发连接重置)。
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
|
||||||
|
# 尊重 NO_PROXY:国内域名(硅基流动/DeepSeek/小米MoE 等)直连更稳定,
|
||||||
|
|
||||||
|
|
||||||
for _np in _no_proxy:
|
|
||||||
|
# 避免经易波动的智能路由代理 172.18.0.1:7890(对国内域名偶发连接重置)。
|
||||||
|
|
||||||
|
|
||||||
if host == _np or host.endswith("." + _np) or _np in host:
|
|
||||||
|
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
||||||
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
for _np in _no_proxy:
|
||||||
|
|
||||||
|
|
||||||
return _outbound_proxy()
|
|
||||||
|
if host == _np or host.endswith("." + _np) or _np in host:
|
||||||
def _extract_text_from_json(obj) -> str:
|
|
||||||
|
|
||||||
|
|
||||||
|
return None
|
||||||
"""从 n8n / 通用 webhook 的任意 JSON 响应中尽力抽取文本回答。"""
|
|
||||||
|
|
||||||
|
|
||||||
|
return _outbound_proxy()
|
||||||
if obj is None:
|
|
||||||
|
def _extract_text_from_json(obj) -> str:
|
||||||
|
|
||||||
|
|
||||||
return ""
|
|
||||||
|
"""从 n8n / 通用 webhook 的任意 JSON 响应中尽力抽取文本回答。"""
|
||||||
|
|
||||||
|
|
||||||
if isinstance(obj, str):
|
|
||||||
|
if obj is None:
|
||||||
|
|
||||||
|
|
||||||
return obj
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
if isinstance(obj, (int, float, bool)):
|
|
||||||
|
if isinstance(obj, str):
|
||||||
|
|
||||||
|
|
||||||
return str(obj)
|
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
if isinstance(obj, list):
|
|
||||||
|
if isinstance(obj, (int, float, bool)):
|
||||||
|
|
||||||
|
|
||||||
# 取第一个可抽取到文本的元素
|
|
||||||
|
return str(obj)
|
||||||
|
|
||||||
|
|
||||||
for it in obj:
|
|
||||||
|
if isinstance(obj, list):
|
||||||
|
|
||||||
|
|
||||||
t = _extract_text_from_json(it)
|
|
||||||
|
# 取第一个可抽取到文本的元素
|
||||||
|
|
||||||
|
|
||||||
if t:
|
|
||||||
|
for it in obj:
|
||||||
|
|
||||||
|
|
||||||
return t
|
|
||||||
|
t = _extract_text_from_json(it)
|
||||||
|
|
||||||
|
|
||||||
return ""
|
|
||||||
|
if t:
|
||||||
|
|
||||||
|
|
||||||
if isinstance(obj, dict):
|
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
# 常见回答字段优先级
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
for k in ("output", "text", "answer", "response", "reply",
|
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
|
||||||
|
|
||||||
"message", "content", "result", "data"):
|
|
||||||
|
# 常见回答字段优先级
|
||||||
|
|
||||||
|
|
||||||
if k in obj:
|
|
||||||
|
for k in ("output", "text", "answer", "response", "reply",
|
||||||
|
|
||||||
|
|
||||||
t = _extract_text_from_json(obj[k])
|
|
||||||
|
"message", "content", "result", "data"):
|
||||||
|
|
||||||
|
|
||||||
if t:
|
|
||||||
|
if k in obj:
|
||||||
|
|
||||||
|
|
||||||
return t
|
|
||||||
|
t = _extract_text_from_json(obj[k])
|
||||||
|
|
||||||
|
|
||||||
# 兜底:整体序列化
|
|
||||||
|
if t:
|
||||||
|
|
||||||
|
|
||||||
try:
|
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
return json.dumps(obj, ensure_ascii=False)
|
|
||||||
|
# 兜底:整体序列化
|
||||||
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
|
||||||
return str(obj)
|
|
||||||
|
return json.dumps(obj, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
return str(obj)
|
|
||||||
|
except Exception:
|
||||||
class CreateConversationRequest(BaseModel):
|
|
||||||
|
|
||||||
|
|
||||||
|
return str(obj)
|
||||||
title: str = Field(default="新对话")
|
|
||||||
|
|
||||||
|
|
||||||
|
return str(obj)
|
||||||
model_id: Optional[str] = None
|
|
||||||
|
class CreateConversationRequest(BaseModel):
|
||||||
class UpdateConversationRequest(BaseModel):
|
|
||||||
|
|
||||||
|
|
||||||
|
title: str = Field(default="新对话")
|
||||||
title: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
|
model_id: Optional[str] = None
|
||||||
status: Optional[str] = None # active, archived
|
|
||||||
|
class UpdateConversationRequest(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
pinned: Optional[bool] = None
|
|
||||||
|
title: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
agent_ids: Optional[list] = None
|
|
||||||
|
status: Optional[str] = None # active, archived
|
||||||
|
|
||||||
|
|
||||||
skill_ids: Optional[list] = None
|
|
||||||
|
pinned: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
knowledge_base_ids: Optional[list] = None
|
|
||||||
|
agent_ids: Optional[list] = None
|
||||||
class SendMessageRequest(BaseModel):
|
|
||||||
|
|
||||||
|
|
||||||
|
skill_ids: Optional[list] = None
|
||||||
content: str
|
|
||||||
|
|
||||||
|
|
||||||
|
knowledge_base_ids: Optional[list] = None
|
||||||
model_id: Optional[str] = None
|
|
||||||
|
class SendMessageRequest(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
skill_ids: Optional[list] = None
|
|
||||||
|
content: str
|
||||||
|
|
||||||
|
|
||||||
agent_ids: Optional[list] = None
|
|
||||||
|
model_id: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
knowledge_base_ids: Optional[list] = None
|
|
||||||
|
skill_ids: Optional[list] = None
|
||||||
|
|
||||||
|
|
||||||
mcp_ids: Optional[list] = None
|
|
||||||
|
agent_ids: Optional[list] = None
|
||||||
|
|
||||||
|
|
||||||
attachments: Optional[list] = None
|
|
||||||
|
knowledge_base_ids: Optional[list] = None
|
||||||
|
|
||||||
|
|
||||||
use_tools: Optional[bool] = False
|
|
||||||
|
mcp_ids: Optional[list] = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
attachments: Optional[list] = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
use_tools: Optional[bool] = False
|
||||||
@@ -109,20 +109,20 @@ def _ensure_table(db):
|
|||||||
"""确保 im_bot_platform_account 表存在(首次调用时创建)。"""
|
"""确保 im_bot_platform_account 表存在(首次调用时创建)。"""
|
||||||
db.execute(text("""
|
db.execute(text("""
|
||||||
CREATE TABLE IF NOT EXISTS im_bot_platform_account (
|
CREATE TABLE IF NOT EXISTS im_bot_platform_account (
|
||||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_id VARCHAR(64) DEFAULT NULL,
|
user_id VARCHAR(64) DEFAULT NULL,
|
||||||
platform VARCHAR(32) NOT NULL,
|
platform VARCHAR(32) NOT NULL,
|
||||||
status VARCHAR(32) DEFAULT 'disconnected',
|
status VARCHAR(32) DEFAULT 'disconnected',
|
||||||
creds MEDIUMTEXT NULL,
|
creds TEXT NULL,
|
||||||
send_url VARCHAR(512) NULL,
|
send_url VARCHAR(512) NULL,
|
||||||
api_base VARCHAR(512) NULL,
|
api_base VARCHAR(512) NULL,
|
||||||
bot_token VARCHAR(512) NULL,
|
bot_token VARCHAR(512) NULL,
|
||||||
webhook_token VARCHAR(64) NULL,
|
webhook_token VARCHAR(64) NULL,
|
||||||
last_error MEDIUMTEXT NULL,
|
last_error TEXT NULL,
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
UNIQUE KEY uk_user_platform (user_id, platform)
|
UNIQUE (user_id, platform)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
)
|
||||||
"""))
|
"""))
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|||||||
@@ -458,9 +458,8 @@ def _wechat_receiver_loop(account_id: int):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
if ret in (-2, -14):
|
if ret in (-2, -14):
|
||||||
# 会话/鉴权失效:标记需重扫并停止接收线程
|
# 会话/鉴权失效:标记需重扫但继续循环,让下一轮 poll 自然检测过期
|
||||||
_mark_wechat_expired(d["id"])
|
_mark_wechat_expired(d["id"])
|
||||||
return
|
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
except Exception:
|
except Exception:
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|||||||
+282
-234
@@ -1,234 +1,282 @@
|
|||||||
"""
|
"""
|
||||||
IM Bot 真实 LLM 调用。
|
IM Bot 真实 LLM 调用。
|
||||||
|
|
||||||
原实现位于 channels.py(通用频道管理模块),该模块已移除。
|
原实现位于 channels.py(通用频道管理模块),该模块已移除。
|
||||||
为保持 IM Bot(微信机器人等)正常生成回复,将 _call_real_llm 迁移至此独立模块。
|
为保持 IM Bot(微信机器人等)正常生成回复,将 _call_real_llm 迁移至此独立模块。
|
||||||
|
|
||||||
行为(对齐 AI 聊天):
|
行为(对齐 AI 聊天 — 2026-07-23 同步至最新):
|
||||||
- Issue 7:图像/视频/语音意图优先走平台媒体模型(与 AI 聊天同一套 Auto 路由),
|
- Issue 7:图像/视频/语音意图优先走平台媒体模型(与 AI 聊天同一套 Auto 路由),
|
||||||
不再对"制作图片"这类请求只回文本。
|
不再对"制作图片"这类请求只回文本。
|
||||||
- Issue 8:默认 Auto 模型;每轮先自动发现本账号已安装且平台已部署的技能,
|
- Issue 8:默认 Auto 模型;每轮先自动发现本账号已安装且平台已部署的技能,
|
||||||
多个适用时由模型自行判断选 1 个最优,通过 function calling 执行。
|
多个适用时由模型自行判断选 1 个最优,通过 function calling 执行。
|
||||||
- 2026-07-15:修复 trust_env=False + proxy 处理,避免容器坏代理导致调用失败;
|
- 2026-07-15:修复 trust_env=False + proxy 处理,避免容器坏代理导致调用失败;
|
||||||
媒体生成前先经 _optimize_media_prompt 精炼提示词,提升 AGNES 生成质量。
|
媒体生成前先经 _optimize_media_prompt 精炼提示词,提升 AGNES 生成质量。
|
||||||
"""
|
- 2026-07-23:对齐 Web Chat 最新能力:
|
||||||
import asyncio
|
* 模型 failover(Auto 模式自动切换备选模型)
|
||||||
import json
|
* 平台知识库注入(get_platform_knowledge,技能清单实时同步)
|
||||||
import logging
|
"""
|
||||||
import re as _re
|
import asyncio
|
||||||
from datetime import datetime, timezone, timedelta
|
import json
|
||||||
from typing import Optional
|
import logging
|
||||||
from urllib.parse import urlparse as _urlparse
|
import re as _re
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
import httpx
|
from typing import Optional
|
||||||
from sqlalchemy.orm import Session
|
from urllib.parse import urlparse as _urlparse
|
||||||
|
|
||||||
from ..capability_registry import resolve_auto_model
|
import httpx
|
||||||
from ..models import AIModel, ModelProvider, TokenUsageLog, gen_uuid
|
from app.core.llm_client import chat_complete # 统一模型层(07-24): web/IM 共用标准 OpenAI SDK 客户端
|
||||||
from app.core.observability import get_trace_id
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from ..capability_registry import resolve_auto_model
|
||||||
|
from ..models import AIModel, ModelProvider, TokenUsageLog, gen_uuid
|
||||||
|
from app.core.observability import get_trace_id
|
||||||
# 香港出网代理(实测对 AGNES 延迟更低,2026-07-15 用户实测),与 chat.py 同值。
|
|
||||||
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def _proxy_for_url(url: str) -> str | None:
|
# 香港出网代理(实测对 AGNES 延迟更低,2026-07-15 用户实测),与 chat.py 同值。
|
||||||
"""按目标域名选择是否走代理(与 chat.py 同逻辑)。
|
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
||||||
|
|
||||||
2026-07-15 调整:AGNES 改走香港代理(实测延迟更低),不再直连。
|
|
||||||
国内域名(尊重 NO_PROXY)直连,更稳定。
|
def _proxy_for_url(url: str) -> str | None:
|
||||||
"""
|
"""按目标域名选择是否走代理(与 chat.py 同逻辑)。
|
||||||
import os
|
|
||||||
host = (_urlparse(url).hostname or "").lower()
|
2026-07-15 调整:AGNES 改走香港代理(实测延迟更低),不再直连。
|
||||||
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
国内域名(尊重 NO_PROXY)直连,更稳定。
|
||||||
return _HK_PROXY
|
"""
|
||||||
if "qihuyun.com" in host:
|
import os
|
||||||
return None
|
host = (_urlparse(url).hostname or "").lower()
|
||||||
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
||||||
for _np in _no_proxy:
|
return _HK_PROXY
|
||||||
if host == _np or host.endswith("." + _np) or _np in host:
|
if "qihuyun.com" in host:
|
||||||
return None
|
return None
|
||||||
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
||||||
|
for _np in _no_proxy:
|
||||||
|
if host == _np or host.endswith("." + _np) or _np in host:
|
||||||
def _run_async(coro, timeout=None):
|
return None
|
||||||
"""在同步上下文中运行协程,兼容「无事件循环」与「已有事件循环」两种场景。
|
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
||||||
|
|
||||||
IM 个人微信在独立线程中调用(无事件循环)→ asyncio.run;
|
|
||||||
IM 多平台 Webhook 可能在 FastAPI 协程内调用(已有事件循环)→ 丢到线程池执行。
|
def _run_async(coro, timeout=None):
|
||||||
|
"""在同步上下文中运行协程,兼容「无事件循环」与「已有事件循环」两种场景。
|
||||||
timeout: 可选,秒数;超时抛出 asyncio.TimeoutError(由调用方捕获)。
|
|
||||||
"""
|
IM 个人微信在独立线程中调用(无事件循环)→ asyncio.run;
|
||||||
try:
|
IM 多平台 Webhook 可能在 FastAPI 协程内调用(已有事件循环)→ 丢到线程池执行。
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
except RuntimeError:
|
timeout: 可选,秒数;超时抛出 asyncio.TimeoutError(由调用方捕获)。
|
||||||
loop = None
|
"""
|
||||||
|
try:
|
||||||
if timeout is not None:
|
loop = asyncio.get_running_loop()
|
||||||
async def _timed():
|
except RuntimeError:
|
||||||
return await asyncio.wait_for(coro, timeout=timeout)
|
loop = None
|
||||||
target = _timed()
|
|
||||||
else:
|
if timeout is not None:
|
||||||
target = coro
|
async def _timed():
|
||||||
|
return await asyncio.wait_for(coro, timeout=timeout)
|
||||||
if loop is not None and loop.is_running():
|
target = _timed()
|
||||||
import concurrent.futures
|
else:
|
||||||
with concurrent.futures.ThreadPoolExecutor(1) as ex:
|
target = coro
|
||||||
return ex.submit(lambda: asyncio.run(target)).result(timeout=(timeout + 10) if timeout else None)
|
|
||||||
return asyncio.run(target)
|
if loop is not None and loop.is_running():
|
||||||
|
import concurrent.futures
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(1) as ex:
|
||||||
def _log_media_usage(db: Session, user_id: str, ai_model, media_type: str, prompt: str):
|
return ex.submit(lambda: asyncio.run(target)).result(timeout=(timeout + 10) if timeout else None)
|
||||||
"""IM Bot 媒体生成记账:把图片/视频消耗写入 TokenUsageLog,供驾驶舱统计。
|
return asyncio.run(target)
|
||||||
|
|
||||||
此前 IM Bot 路径完全不写 TokenUsageLog,导致微信生成的图片/视频在驾驶舱里“查无此项”。
|
|
||||||
媒体 API 不返回 token 用量,这里用与 chat.py _generate_media_task 一致的估算。
|
def _log_media_usage(db: Session, user_id: str, ai_model, media_type: str, prompt: str):
|
||||||
"""
|
"""IM Bot 媒体生成记账:把图片/视频消耗写入 TokenUsageLog,供驾驶舱统计。
|
||||||
if not user_id or not ai_model:
|
|
||||||
return
|
此前 IM Bot 路径完全不写 TokenUsageLog,导致微信生成的图片/视频在驾驶舱里"查无此项"。
|
||||||
try:
|
媒体 API 不返回 token 用量,这里用与 chat.py _generate_media_task 一致的估算。
|
||||||
base = 1200 if media_type == "video" else 400
|
"""
|
||||||
est = base + (len(prompt or "") // 4)
|
if not user_id or not ai_model:
|
||||||
db.add(TokenUsageLog(
|
return
|
||||||
id=gen_uuid(),
|
try:
|
||||||
user_id=user_id,
|
base = 1200 if media_type == "video" else 400
|
||||||
model_id=ai_model.id,
|
est = base + (len(prompt or "") // 4)
|
||||||
model_name=ai_model.name,
|
db.add(TokenUsageLog(
|
||||||
trace_id=get_trace_id(),
|
id=gen_uuid(),
|
||||||
prompt_tokens=est,
|
user_id=user_id,
|
||||||
completion_tokens=0,
|
model_id=ai_model.id,
|
||||||
total_tokens=est,
|
model_name=ai_model.name,
|
||||||
created_at=datetime.now(timezone(timedelta(hours=8))).replace(tzinfo=None),
|
trace_id=get_trace_id(),
|
||||||
))
|
prompt_tokens=est,
|
||||||
db.commit()
|
completion_tokens=0,
|
||||||
except Exception as e:
|
total_tokens=est,
|
||||||
try:
|
created_at=datetime.now(timezone(timedelta(hours=8))).replace(tzinfo=None),
|
||||||
db.rollback()
|
))
|
||||||
except Exception:
|
db.commit()
|
||||||
pass
|
except Exception as e:
|
||||||
logger.warning(f"[im_llm] 媒体 Token 记账失败(忽略): {e}")
|
try:
|
||||||
|
db.rollback()
|
||||||
|
except Exception:
|
||||||
def _call_real_llm(db: Session, user=None, prompt: str = "", platform: str = "im", user_id: str = None) -> "str | dict":
|
pass
|
||||||
"""调用七虎AI 生成回复,供 IM Bot 复用。支持媒体意图路由与已安装技能自动发现。"""
|
logger.warning(f"[im_llm] 媒体 Token 记账失败(忽略): {e}")
|
||||||
try:
|
|
||||||
from app.api.chat import (
|
|
||||||
_generate_media,
|
def _call_real_llm(db: Session, user=None, prompt: str = "", platform: str = "im", user_id: str = None) -> "str | dict":
|
||||||
detect_media_intent,
|
"""调用七虎AI 生成回复,供 IM Bot 复用。支持媒体意图路由、已安装技能自动发现、模型 failover。"""
|
||||||
_discover_installed_skills,
|
try:
|
||||||
_build_system_prompt,
|
from app.api.chat import (
|
||||||
_execute_skill_tool,
|
_generate_media,
|
||||||
)
|
detect_media_intent,
|
||||||
|
_discover_installed_skills,
|
||||||
# ===== 1) 媒体意图路由(Issue 7)=====
|
_build_system_prompt,
|
||||||
intent = detect_media_intent(prompt)
|
_execute_skill_tool,
|
||||||
if intent:
|
)
|
||||||
ai_model = resolve_auto_model(intent, db)
|
|
||||||
if ai_model:
|
# ===== 1) 媒体意图路由(Issue 7)=====
|
||||||
try:
|
intent = detect_media_intent(prompt)
|
||||||
result = _run_async(_generate_media(db, ai_model, prompt, user_id), timeout=300)
|
if intent:
|
||||||
except Exception:
|
ai_model = resolve_auto_model(intent, db)
|
||||||
# 任何未预期异常(如 AGNES 连接重置)统一兜底为友好提示,
|
if ai_model:
|
||||||
# 绝不直接把原始异常(如 "Server disconnected")甩给用户
|
try:
|
||||||
result = "⚠️ 媒体生成暂时失败(连接或服务波动),请稍后重试。"
|
result = _run_async(_generate_media(db, ai_model, prompt, user_id), timeout=300)
|
||||||
if result:
|
except Exception:
|
||||||
# 媒体生成成功:返回结构化对象,交由 im_bot_user 在微信内联发送图片/视频
|
# 任何未预期异常(如 AGNES 连接重置)统一兜底为友好提示,
|
||||||
s = result.strip()
|
# 绝不直接把原始异常(如 "Server disconnected")甩给用户
|
||||||
if s.startswith("<img") or s.startswith("<video"):
|
result = "⚠️ 媒体生成暂时失败(连接或服务波动),请稍后重试。"
|
||||||
m = _re.search(r'src="([^"]+)"', s)
|
if result:
|
||||||
url = m.group(1) if m else ""
|
# 媒体生成成功:返回结构化对象,交由 im_bot_user 在微信内联发送图片/视频
|
||||||
media_type = "image" if s.startswith("<img") else "video"
|
s = result.strip()
|
||||||
if not url:
|
if s.startswith("<img") or s.startswith("<video"):
|
||||||
return "(生成完成,但未能提取媒体地址)"
|
m = _re.search(r'src="([^"]+)"', s)
|
||||||
# IM Bot 路径此前完全不记账 → 补写媒体消耗,驾驶舱才看得到图片/视频数据
|
url = m.group(1) if m else ""
|
||||||
_log_media_usage(db, user_id, ai_model, media_type, prompt)
|
media_type = "image" if s.startswith("<img") else "video"
|
||||||
return {"__media__": True, "media_type": media_type, "url": url}
|
if not url:
|
||||||
# 媒体生成失败:_generate_media 已返回友好中文(如限频/队列繁忙),
|
return "(生成完成,但未能提取媒体地址)"
|
||||||
# 直接透传,绝不把原始提示词/标签/JSON 透传给用户
|
# IM Bot 路径此前完全不记账 → 补写媒体消耗,驾驶舱才看得到图片/视频数据
|
||||||
if s.startswith("⚠️") or s.startswith("(媒体"):
|
_log_media_usage(db, user_id, ai_model, media_type, prompt)
|
||||||
return s
|
return {"__media__": True, "media_type": media_type, "url": url}
|
||||||
return "(媒体生成未能返回有效内容,请重试)"
|
# 媒体生成失败:_generate_media 已返回友好中文(如限频/队列繁忙),
|
||||||
|
# 直接透传,绝不把原始提示词/标签/JSON 透传给用户
|
||||||
# ===== 2) 文本回复 + 技能自动发现(Issue 8)=====
|
if s.startswith("⚠️") or s.startswith("(媒体"):
|
||||||
ai_model = resolve_auto_model("text", db)
|
return s
|
||||||
if not ai_model:
|
return "(媒体生成未能返回有效内容,请重试)"
|
||||||
return "(未配置默认文本模型,无法生成回复)"
|
|
||||||
provider = db.query(ModelProvider).filter(ModelProvider.id == ai_model.provider_id).first()
|
# ===== 2) 文本回复:模型 failover + 技能自动发现 + 平台知识库注入 =====
|
||||||
api_key = ai_model.api_key or (provider.api_key if provider else None)
|
from ..platform_knowledge import get_platform_knowledge
|
||||||
api_url = ai_model.endpoint
|
|
||||||
if not api_url and provider and provider.api_base_url:
|
# 构建候选模型列表(对齐 Web Chat failover)
|
||||||
api_url = f"{provider.api_base_url.rstrip('/')}/v1/chat/completions"
|
ai_model = resolve_auto_model("text", db)
|
||||||
if not (api_key and api_url):
|
_try_models = [ai_model] if (ai_model and ai_model.is_enabled) else []
|
||||||
return "(模型未配置 API Key 或地址,无法生成回复)"
|
# Auto 模式附加备选(IM Bot 始终 Auto)
|
||||||
|
_fallbacks = db.query(AIModel).filter(
|
||||||
# 自动发现本账号已安装且平台已部署的技能
|
AIModel.is_enabled == True,
|
||||||
skills = []
|
AIModel.id != (ai_model.id if ai_model else ""),
|
||||||
if user_id:
|
).order_by(AIModel.is_default.desc()).limit(4).all()
|
||||||
try:
|
_try_models.extend([m for m in _fallbacks if m not in _try_models])
|
||||||
skills = _discover_installed_skills(db, user_id)[:15]
|
|
||||||
except Exception:
|
if not _try_models:
|
||||||
skills = []
|
return "(未配置可用文本模型,无法生成回复)"
|
||||||
|
|
||||||
system_prompt, function_definitions = _build_system_prompt(
|
# 技能自动发现(提前执行一次,不必每个候选模型重复做)
|
||||||
skills=skills,
|
skills = []
|
||||||
agents=[],
|
if user_id:
|
||||||
kb_context="",
|
try:
|
||||||
user_content=prompt,
|
skills = _discover_installed_skills(db, user_id)[:15]
|
||||||
mcp=[],
|
except Exception:
|
||||||
auto_discovered=bool(skills),
|
skills = []
|
||||||
)
|
|
||||||
messages = [
|
# 平台知识库注入(对齐 Web Chat——微信用户提问"平台有哪些技能"也能得到完整清单)
|
||||||
{"role": "system", "content": system_prompt},
|
kb_context = ""
|
||||||
{"role": "user", "content": prompt},
|
try:
|
||||||
]
|
pk = get_platform_knowledge(db=db)
|
||||||
|
if pk:
|
||||||
max_rounds = 3
|
kb_context = f"【平台知识库——优先使用以下知识回答用户问题】\n{pk}"
|
||||||
ai_content = ""
|
except Exception:
|
||||||
for _ in range(max_rounds):
|
pass
|
||||||
request_body = {"model": ai_model.name, "messages": messages, "max_tokens": 2048}
|
|
||||||
if function_definitions and skills:
|
# 尝试每个候选模型
|
||||||
request_body["tools"] = [
|
_retry_log = []
|
||||||
{"type": "function", "function": fd} for fd in function_definitions
|
for _try_model in _try_models:
|
||||||
]
|
ai_model = _try_model
|
||||||
request_body["tool_choice"] = "auto"
|
|
||||||
with httpx.Client(
|
provider = db.query(ModelProvider).filter(ModelProvider.id == ai_model.provider_id).first()
|
||||||
timeout=ai_model.timeout or 120,
|
api_key = ai_model.api_key or (provider.api_key if provider else None)
|
||||||
proxy=_proxy_for_url(api_url),
|
api_url = ai_model.endpoint
|
||||||
trust_env=False,
|
if not api_url and provider and provider.api_base_url:
|
||||||
) as client:
|
api_url = f"{provider.api_base_url.rstrip('/')}/v1/chat/completions"
|
||||||
resp = client.post(
|
if not (api_key and api_url):
|
||||||
api_url,
|
_retry_log.append(f"{ai_model.name}: 缺少密钥或端点")
|
||||||
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
continue
|
||||||
json=request_body,
|
|
||||||
)
|
system_prompt, function_definitions = _build_system_prompt(
|
||||||
if resp.status_code != 200:
|
skills=skills,
|
||||||
return f"(AI 模型调用失败 HTTP {resp.status_code})"
|
agents=[],
|
||||||
data = resp.json()
|
kb_context=kb_context,
|
||||||
message = data.get("choices", [{}])[0].get("message", {})
|
user_content=prompt,
|
||||||
tool_calls = message.get("tool_calls", [])
|
mcp=[],
|
||||||
if tool_calls and skills:
|
auto_discovered=bool(skills),
|
||||||
messages.append({
|
)
|
||||||
"role": "assistant",
|
messages = [
|
||||||
"content": message.get("content") or "",
|
{"role": "system", "content": system_prompt},
|
||||||
"tool_calls": tool_calls,
|
{"role": "user", "content": prompt},
|
||||||
})
|
]
|
||||||
for tc in tool_calls:
|
|
||||||
func_name = tc.get("function", {}).get("name", "")
|
# 尝试调用
|
||||||
try:
|
try:
|
||||||
func_args = json.loads(tc.get("function", {}).get("arguments", "{}"))
|
max_rounds = 3
|
||||||
except Exception:
|
ai_content = ""
|
||||||
func_args = {"input": tc.get("function", {}).get("arguments", "")}
|
_http_ok = True
|
||||||
tool_result = _execute_skill_tool(db, func_name, func_args, skills, prompt)
|
for round_num in range(max_rounds):
|
||||||
messages.append({
|
request_body = {"model": ai_model.name, "messages": messages, "max_tokens": 2048}
|
||||||
"role": "tool",
|
if function_definitions and skills:
|
||||||
"tool_call_id": tc.get("id", "call_1"),
|
request_body["tools"] = [
|
||||||
"content": tool_result,
|
{"type": "function", "function": fd} for fd in function_definitions
|
||||||
})
|
]
|
||||||
continue
|
request_body["tool_choice"] = "auto"
|
||||||
ai_content = message.get("content", "")
|
try:
|
||||||
break
|
data = chat_complete(
|
||||||
return ai_content or "(AI 回复为空)"
|
api_url,
|
||||||
except Exception as e:
|
api_key,
|
||||||
return f"(AI 回复生成失败:{e})"
|
request_body,
|
||||||
|
proxy=_proxy_for_url(api_url),
|
||||||
|
timeout=ai_model.timeout or 120,
|
||||||
|
)
|
||||||
|
except Exception as _exc:
|
||||||
|
_retry_log.append(f"{ai_model.name}: {str(_exc)[:60]}")
|
||||||
|
logger.warning(f"[im_llm] 模型 {ai_model.name} 异常: {_exc}")
|
||||||
|
_http_ok = False
|
||||||
|
break
|
||||||
|
message = data.get("choices", [{}])[0].get("message", {})
|
||||||
|
tool_calls = message.get("tool_calls", [])
|
||||||
|
if tool_calls and skills:
|
||||||
|
messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"content": message.get("content") or "",
|
||||||
|
"tool_calls": tool_calls,
|
||||||
|
})
|
||||||
|
for tc in tool_calls:
|
||||||
|
func_name = tc.get("function", {}).get("name", "")
|
||||||
|
try:
|
||||||
|
func_args = json.loads(tc.get("function", {}).get("arguments", "{}"))
|
||||||
|
except Exception:
|
||||||
|
func_args = {"input": tc.get("function", {}).get("arguments", "")}
|
||||||
|
tool_result = _execute_skill_tool(db, func_name, func_args, skills, prompt)
|
||||||
|
messages.append({
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": tc.get("id", "call_1"),
|
||||||
|
"content": tool_result,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
ai_content = message.get("content", "")
|
||||||
|
break
|
||||||
|
|
||||||
|
# 检查本轮调用是否成功
|
||||||
|
if _http_ok and ai_content:
|
||||||
|
return ai_content or "(AI 回复为空)"
|
||||||
|
# 本轮失败:记录日志,切换备选
|
||||||
|
logger.warning(f"[im_llm] 模型 {ai_model.name} 失败,切换备选...")
|
||||||
|
continue
|
||||||
|
except Exception as exc:
|
||||||
|
_retry_log.append(f"{ai_model.name}: {str(exc)[:60]}")
|
||||||
|
logger.warning(f"[im_llm] 模型 {ai_model.name} 异常: {exc}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 全部失败
|
||||||
|
_summary = "; ".join(_retry_log[-3:])
|
||||||
|
return f"(已尝试 {len(_try_models)} 个模型均调用失败。最后错误: {_summary}。请稍后重试。)"
|
||||||
|
except Exception as e:
|
||||||
|
return f"(AI 回复生成失败:{e})"
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, Form
|
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, Form
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_, desc, asc
|
from sqlalchemy import and_, desc, asc
|
||||||
@@ -501,8 +502,8 @@ def _parse_llm_graph_response(content: str):
|
|||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 方式2: 提取```json ... ```代码块
|
# 方式2: 提取\"\"\"json ... \"\"\"代码块
|
||||||
json_match = re.search(r'```(?:json)?\s*([\s\S]*?)```', content)
|
json_match = re.search(r'\"\"\"(?:json)?\s*([\s\S]*?)\"\"\"', content)
|
||||||
if json_match:
|
if json_match:
|
||||||
try:
|
try:
|
||||||
result = json.loads(json_match.group(1))
|
result = json.loads(json_match.group(1))
|
||||||
@@ -851,6 +852,15 @@ def get_documents(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/bases/{base_id}/documents")
|
@router.post("/bases/{base_id}/documents")
|
||||||
|
async def _index_kb_doc_to_pgvector(doc_id: str, kb_id: str, content: str):
|
||||||
|
"""将文档内容异步索引到 pgvector,供语义向量检索使用(best-effort)。"""
|
||||||
|
try:
|
||||||
|
from app.pgvector_search import index_document
|
||||||
|
await index_document(doc_id, kb_id, content, metadata={"source": "kb_upload"})
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[kb] 向量索引失败 doc={doc_id}: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def upload_document(
|
async def upload_document(
|
||||||
base_id: str,
|
base_id: str,
|
||||||
file: Optional[UploadFile] = File(None),
|
file: Optional[UploadFile] = File(None),
|
||||||
@@ -961,6 +971,12 @@ async def upload_document(
|
|||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(doc)
|
db.refresh(doc)
|
||||||
|
|
||||||
|
# T1: 异步索引到 pgvector 语义库(best-effort,不阻塞上传响应)
|
||||||
|
try:
|
||||||
|
asyncio.create_task(_index_kb_doc_to_pgvector(doc.id, base_id, content))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
LogService.log_operation(
|
LogService.log_operation(
|
||||||
user_id=current_user.id, username=current_user.username, action="upload",
|
user_id=current_user.id, username=current_user.username, action="upload",
|
||||||
target="knowledge_document", target_id=doc.id,
|
target="knowledge_document", target_id=doc.id,
|
||||||
@@ -1415,6 +1431,89 @@ def search_knowledge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tree-search")
|
||||||
|
async def tree_search_endpoint(
|
||||||
|
query: str = Query(min_length=1, description="检索查询"),
|
||||||
|
kb_id: Optional[str] = Query(default=None, description="限定知识库ID"),
|
||||||
|
scope: Optional[str] = Query(
|
||||||
|
default=None,
|
||||||
|
description="作用域: doc:<doc_id> | dir:<dir_id> | base:<base_id>",
|
||||||
|
),
|
||||||
|
top_k: int = Query(default=5, ge=1, le=20),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""TreeSearch 结构化文档两级检索。
|
||||||
|
|
||||||
|
Level 1: 返回用户可见的知识库 -> 目录 -> 文档结构树(tree)。
|
||||||
|
Level 2: 在作用域内做分片段(chunk)级精准检索,命中带完整面包屑与片段摘要。
|
||||||
|
"""
|
||||||
|
from app.tree_search import build_kb_tree, tree_search
|
||||||
|
|
||||||
|
# Level 1: 结构树
|
||||||
|
tree = build_kb_tree(db, user_id=current_user.id, kb_id=kb_id)
|
||||||
|
|
||||||
|
# Level 2: 分片段检索
|
||||||
|
scope_doc = scope_dir = scope_base = None
|
||||||
|
if scope:
|
||||||
|
if scope.startswith("doc:"):
|
||||||
|
scope_doc = scope[len("doc:"):]
|
||||||
|
elif scope.startswith("dir:"):
|
||||||
|
scope_dir = scope[len("dir:"):]
|
||||||
|
elif scope.startswith("base:"):
|
||||||
|
scope_base = scope[len("base:"):]
|
||||||
|
|
||||||
|
hits = await tree_search(
|
||||||
|
db, query,
|
||||||
|
user_id=current_user.id,
|
||||||
|
kb_ids=[kb_id] if kb_id else None,
|
||||||
|
scope_base=scope_base, scope_dir=scope_dir, scope_doc=scope_doc,
|
||||||
|
top_k=top_k, mode="hybrid",
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"code": 0,
|
||||||
|
"data": {
|
||||||
|
"query": query,
|
||||||
|
"tree": tree,
|
||||||
|
"hits": hits,
|
||||||
|
"total": len(hits),
|
||||||
|
},
|
||||||
|
"message": "ok",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class WebSearchRequest(BaseModel):
|
||||||
|
query: str = Field(min_length=1, max_length=500)
|
||||||
|
top_k: int = 5
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/web-search", summary="AnySearch 联网检索")
|
||||||
|
async def web_search_endpoint(
|
||||||
|
req: WebSearchRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""联网检索(AnySearch):返回实时网页结果,供前端 / 智能体引用。"""
|
||||||
|
try:
|
||||||
|
from ..anysearch_client import anysearch_search, load_anysearch_config
|
||||||
|
cfg = load_anysearch_config(db)
|
||||||
|
if not cfg.get("is_enabled") or not cfg.get("api_key"):
|
||||||
|
return {"code": 0, "data": {"results": [], "enabled": False, "message": "未配置 AnySearch 联网检索服务"}}
|
||||||
|
hits = await anysearch_search(
|
||||||
|
cfg["api_key"],
|
||||||
|
cfg.get("api_url") or "https://api.anysearch.com/v1/search",
|
||||||
|
req.query,
|
||||||
|
top_k=req.top_k,
|
||||||
|
zone=cfg.get("zone", "cn"),
|
||||||
|
freshness=cfg.get("freshness"),
|
||||||
|
)
|
||||||
|
return {"code": 0, "data": {"results": hits, "enabled": True}}
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"web-search endpoint failed: {e}")
|
||||||
|
return {"code": 1, "message": str(e), "data": {"results": []}}
|
||||||
|
|
||||||
|
|
||||||
def generate_document_excerpt(doc, query: str) -> str:
|
def generate_document_excerpt(doc, query: str) -> str:
|
||||||
"""根据文档类型生成模拟的原文摘录"""
|
"""根据文档类型生成模拟的原文摘录"""
|
||||||
excerpts = {
|
excerpts = {
|
||||||
|
|||||||
+1341
-1075
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,163 @@
|
|||||||
|
"""服务端 URL 读取器(Issue 2 修复)
|
||||||
|
|
||||||
|
当用户输入包含 URL 且明确要求『读取 / 加入 / 安装 / 分析 / 总结』等意图时,
|
||||||
|
服务端抓取该链接的真实内容并作为参考上下文注入对话,使模型能基于页面真实信息
|
||||||
|
作答(例如按 GitHub 仓库 README 的 Quick Start 引导用户完成安装/加入),
|
||||||
|
而不是凭空编造。
|
||||||
|
|
||||||
|
SSRF 防护:仅允许 http/https;解析域名 IP 后阻断内网/回环/链路本地/云元数据地址;
|
||||||
|
限制跳转、响应体大小与超时。
|
||||||
|
"""
|
||||||
|
import ipaddress
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_URL_RE = re.compile(r'https?://[^\s"\)\\\]>]+', re.IGNORECASE)
|
||||||
|
# 触发意图:显式要求读取/加入/安装/分析/总结/打开/访问 等
|
||||||
|
_INTENT_RE = re.compile(
|
||||||
|
r'(read|join|install|fetch|summar|analys|open|visit|access|browse|'
|
||||||
|
r'读取|加入|安装|打开|访问|浏览|总结|分析|抓取|看下这个|查看该|这个网页|这个页面|这个链接|help me join)',
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 常见私有/保留网段(阻断内网扫描与云元数据)
|
||||||
|
_BLOCKED_NETS = [
|
||||||
|
ipaddress.ip_network('10.0.0.0/8'),
|
||||||
|
ipaddress.ip_network('172.16.0.0/12'),
|
||||||
|
ipaddress.ip_network('192.168.0.0/16'),
|
||||||
|
ipaddress.ip_network('127.0.0.0/8'),
|
||||||
|
ipaddress.ip_network('169.254.0.0/16'),
|
||||||
|
ipaddress.ip_network('::1/128'),
|
||||||
|
ipaddress.ip_network('fc00::/7'),
|
||||||
|
ipaddress.ip_network('fe80::/10'),
|
||||||
|
ipaddress.ip_network('0.0.0.0/8'),
|
||||||
|
]
|
||||||
|
|
||||||
|
_MAX_CHARS = 16000
|
||||||
|
_TIMEOUT = 30.0
|
||||||
|
|
||||||
|
|
||||||
|
def _is_blocked_host(host: str) -> bool:
|
||||||
|
host = (host or '').strip().lower()
|
||||||
|
if not host:
|
||||||
|
return True
|
||||||
|
if re.fullmatch(r'(\d{1,3}\.){3}\d{1,3}', host):
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(host)
|
||||||
|
except ValueError:
|
||||||
|
return True
|
||||||
|
return any(ip in net for net in _BLOCKED_NETS)
|
||||||
|
try:
|
||||||
|
infos = socket.getaddrinfo(host, None)
|
||||||
|
for info in infos:
|
||||||
|
ipstr = info[4][0]
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(ipstr)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if any(ip in net for net in _BLOCKED_NETS):
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def _make_client():
|
||||||
|
try:
|
||||||
|
return httpx.AsyncClient(trust_env=True, follow_redirects=True, timeout=_TIMEOUT)
|
||||||
|
except Exception:
|
||||||
|
return httpx.AsyncClient(trust_env=False, follow_redirects=True, timeout=_TIMEOUT)
|
||||||
|
|
||||||
|
|
||||||
|
async def _github_text(url: str):
|
||||||
|
p = urlparse(url)
|
||||||
|
if p.netloc.lower() not in ('github.com', 'www.github.com'):
|
||||||
|
return None
|
||||||
|
parts = [x for x in p.path.split('/') if x]
|
||||||
|
if len(parts) < 2:
|
||||||
|
return None
|
||||||
|
owner, repo = parts[0], parts[1]
|
||||||
|
if len(parts) >= 4 and parts[2] == 'blob':
|
||||||
|
ref = parts[3]
|
||||||
|
fpath = '/'.join(parts[4:])
|
||||||
|
raw = f'https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{fpath}'
|
||||||
|
return await _fetch_text(raw)
|
||||||
|
api = f'https://api.github.com/repos/{owner}/{repo}/readme'
|
||||||
|
try:
|
||||||
|
async with await _make_client() as c:
|
||||||
|
r = await c.get(api, headers={
|
||||||
|
'Accept': 'application/vnd.github+json',
|
||||||
|
'User-Agent': 'Mozilla/5.0',
|
||||||
|
})
|
||||||
|
if r.status_code == 200:
|
||||||
|
import base64
|
||||||
|
d = r.json()
|
||||||
|
return base64.b64decode(d.get('content', '')).decode('utf-8', 'replace')
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning('github readme fetch failed: %s', e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def _fetch_text(url: str) -> str:
|
||||||
|
async with await _make_client() as c:
|
||||||
|
r = await c.get(url, headers={'User-Agent': 'Mozilla/5.0'})
|
||||||
|
r.raise_for_status()
|
||||||
|
data = r.content[:2_000_000]
|
||||||
|
ctype = r.headers.get('content-type', '')
|
||||||
|
text = data.decode('utf-8', 'replace')
|
||||||
|
if 'html' in ctype:
|
||||||
|
return _html_to_text(text)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _html_to_text(html: str) -> str:
|
||||||
|
html = re.sub(r'(?is)<(script|style|head|noscript|svg|template)[^>]*>.*?</\1>', ' ', html)
|
||||||
|
html = re.sub(r'(?is)<!--.*?-->', ' ', html)
|
||||||
|
html = re.sub(r'(?is)<[^>]+>', ' ', html)
|
||||||
|
import html as _html
|
||||||
|
text = _html.unescape(html)
|
||||||
|
text = re.sub(r'[ \t]+', ' ', text)
|
||||||
|
text = re.sub(r'\n{3,}', '\n\n', text)
|
||||||
|
return text.strip()
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_url_context(text: str):
|
||||||
|
"""若有 URL 且命中读取意图,返回 {'url','text'};否则返回 None。"""
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
m = _URL_RE.search(text)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
url = m.group(0).rstrip('.,);]')
|
||||||
|
if not _INTENT_RE.search(text):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
p = urlparse(url)
|
||||||
|
if p.scheme not in ('http', 'https'):
|
||||||
|
return None
|
||||||
|
if _is_blocked_host(p.hostname):
|
||||||
|
logger.warning('blocked host for url fetch: %s', p.hostname)
|
||||||
|
return None
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
if 'github.com' in (p.hostname or '').lower():
|
||||||
|
body = await _github_text(url)
|
||||||
|
if not body:
|
||||||
|
body = await _fetch_text(url)
|
||||||
|
else:
|
||||||
|
body = await _fetch_text(url)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning('url fetch failed: %s', e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not body or not body.strip():
|
||||||
|
return None
|
||||||
|
return {'url': url, 'text': body[:_MAX_CHARS]}
|
||||||
@@ -12,12 +12,35 @@ from fastapi import Depends, HTTPException, status, Request
|
|||||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
||||||
|
|
||||||
|
|
||||||
|
# Phase0: 5-level RBAC
|
||||||
|
ROLE_HIERARCHY = {
|
||||||
|
"super_admin": 100,
|
||||||
|
"admin": 80,
|
||||||
|
"developer": 50,
|
||||||
|
"user": 30,
|
||||||
|
"guest": 10,
|
||||||
|
}
|
||||||
|
|
||||||
|
def has_role(user_role: str, required: str) -> bool:
|
||||||
|
return ROLE_HIERARCHY.get(user_role, 0) >= ROLE_HIERARCHY.get(required, 0)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
security = HTTPBearer()
|
security = HTTPBearer()
|
||||||
security_optional = HTTPBearer(auto_error=False)
|
security_optional = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_tenant(
|
||||||
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
|
return payload.get("tenant_id")
|
||||||
|
except JWTError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
def hash_password(password: str) -> str:
|
||||||
"""使用 bcrypt 直接生成密码哈希"""
|
"""使用 bcrypt 直接生成密码哈希"""
|
||||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||||
@@ -35,8 +58,10 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None, tenant_id: str = None) -> str:
|
||||||
to_encode = data.copy()
|
to_encode = data.copy()
|
||||||
|
if tenant_id:
|
||||||
|
to_encode["tenant_id"] = tenant_id
|
||||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||||
to_encode.update({"exp": expire})
|
to_encode.update({"exp": expire})
|
||||||
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||||
|
|||||||
@@ -98,12 +98,11 @@ def resolve_auto_model(capability: str, db: Session) -> Optional[AIModel]:
|
|||||||
# 媒体类能力(image/video/audio):无显式配置时自动发现任一启用的模型
|
# 媒体类能力(image/video/audio):无显式配置时自动发现任一启用的模型
|
||||||
# 避免用户未在后台配置"能力默认模型"时 Auto 回退到文本模型导致"无法生成图片/视频"
|
# 避免用户未在后台配置"能力默认模型"时 Auto 回退到文本模型导致"无法生成图片/视频"
|
||||||
if capability in ("image", "video", "audio"):
|
if capability in ("image", "video", "audio"):
|
||||||
from sqlalchemy import text as _text
|
from sqlalchemy import text as _text, func, type_coerce
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
m = db.query(AIModel).filter(
|
m = db.query(AIModel).filter(
|
||||||
AIModel.is_enabled == True,
|
AIModel.is_enabled == True,
|
||||||
AIModel.capabilities.op("JSON_CONTAINS")(
|
AIModel.capabilities.cast(JSONB).contains(type_coerce([capability], JSONB)),
|
||||||
AIModel.capabilities, f'"{capability}"'
|
|
||||||
),
|
|
||||||
).first()
|
).first()
|
||||||
if m:
|
if m:
|
||||||
return m
|
return m
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -15,7 +15,12 @@ if not (Path("/.dockerenv").exists() or Path("/run/.containerenv").exists()):
|
|||||||
load_dotenv(env_path, override=False)
|
load_dotenv(env_path, override=False)
|
||||||
|
|
||||||
# 数据库配置
|
# 数据库配置
|
||||||
DATABASE_URL = f"mysql+pymysql://{os.getenv('MYSQL_USER', 'root')}:{os.getenv('MYSQL_PASSWORD', 'pwd2026')}@{os.getenv('MYSQL_HOST', 'localhost')}:{os.getenv('MYSQL_PORT', '3306')}/{os.getenv('MYSQL_DATABASE', 'aiflow')}?charset=utf8mb4"
|
# PostgreSQL preferred when DATABASE_URL is provided (production); else legacy MySQL builder (local/dev + rollback)
|
||||||
|
_DATABASE_URL_ENV = os.getenv("DATABASE_URL", "")
|
||||||
|
if _DATABASE_URL_ENV:
|
||||||
|
DATABASE_URL = _DATABASE_URL_ENV
|
||||||
|
else:
|
||||||
|
DATABASE_URL = f"mysql+pymysql://{os.getenv('MYSQL_USER', 'root')}:{os.getenv('MYSQL_PASSWORD', 'pwd2026')}@{os.getenv('MYSQL_HOST', 'localhost')}:{os.getenv('MYSQL_PORT', '3306')}/{os.getenv('MYSQL_DATABASE', 'aiflow')}?charset=utf8mb4"
|
||||||
|
|
||||||
# Redis配置
|
# Redis配置
|
||||||
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
||||||
@@ -128,7 +133,15 @@ def setup_file_logging():
|
|||||||
root_logger.setLevel(logging.INFO)
|
root_logger.setLevel(logging.INFO)
|
||||||
root_logger.addHandler(app_handler)
|
root_logger.addHandler(app_handler)
|
||||||
root_logger.addHandler(error_handler)
|
root_logger.addHandler(error_handler)
|
||||||
root_logger.addFilter(TraceIdFilter())
|
|
||||||
|
# TraceIdFilter 必须挂在 handler 上,而非 root logger。
|
||||||
|
# logger 级 filter 只对「直接经该 logger 发射」的记录生效;子 logger 的记录向上冒泡
|
||||||
|
# 到 root 的 handler 时不会经过 root 的 logger 级 filter,导致 %(trace_id)s 缺失并抛
|
||||||
|
# KeyError('trace_id')。handler 级 filter 对经它格式化的每条记录都生效。
|
||||||
|
_tid_filter = TraceIdFilter()
|
||||||
|
app_handler.addFilter(_tid_filter)
|
||||||
|
error_handler.addFilter(_tid_filter)
|
||||||
|
access_handler.addFilter(_tid_filter)
|
||||||
|
|
||||||
# 配置访问日志专用logger
|
# 配置访问日志专用logger
|
||||||
access_logger = logging.getLogger("aiflow.access")
|
access_logger = logging.getLogger("aiflow.access")
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
"""Shared, standards-based LLM client for web chat + IM bot.
|
||||||
|
|
||||||
|
平台红线(07-24):模型层以成熟/开源标准为设计基准。本模块使用官方 OpenAI SDK
|
||||||
|
(\"openai.AsyncOpenAI\")——它是 OpenAI 兼容端点的事实标准客户端。平台本身已在讲
|
||||||
|
OpenAI 协议(\"/v1/chat/completions\"),因此零协议改造成本,并天然获得:
|
||||||
|
* 原生 SSE 流式(\"stream=True\");
|
||||||
|
* 结构化的 tool_calls / usage 解析;
|
||||||
|
* 统一的代理(trust_env=False + 显式 proxy)与超时处理。
|
||||||
|
|
||||||
|
本模块取代 chat_service.py 与 im_llm.py 中两套手写 httpx 循环,使 web chat 与
|
||||||
|
IM bot 共用**同一模型层**、同一套 failover/代理/超时语义——这是「各端能力统一对齐」
|
||||||
|
红线在模型层的落地。
|
||||||
|
|
||||||
|
API:
|
||||||
|
achat_complete(api_url, api_key, request_body, *, proxy=None, timeout=120, stream=False)
|
||||||
|
- stream=False -> dict,形状对齐上游 \"data\" 响应:
|
||||||
|
{"choices":[{"message":{"content","tool_calls","reasoning_content"}}], "usage":{...}}
|
||||||
|
- stream=True -> async generator,逐块产出 ("content"|"reasoning", text) 增量
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import asyncio
|
||||||
|
from openai import AsyncOpenAI, OpenAI
|
||||||
|
|
||||||
|
|
||||||
|
def _base_url(api_url: str) -> str:
|
||||||
|
"""从完整 /v1/chat/completions 或 /v1/embeddings 地址推导 OpenAI SDK 所需的 base_url。"""
|
||||||
|
u = (api_url or "").rstrip()
|
||||||
|
for suf in ("/v1/chat/completions", "/chat/completions", "/v1/embeddings", "/embeddings"):
|
||||||
|
if u.endswith(suf):
|
||||||
|
return u[: -len(suf)]
|
||||||
|
return u
|
||||||
|
|
||||||
|
|
||||||
|
def build_openai_client(api_url, api_key, *, proxy=None, timeout=120, auth_header=None) -> AsyncOpenAI:
|
||||||
|
base = _base_url(api_url)
|
||||||
|
# 始终 trust_env=False:避免容器 HTTP_PROXY 对国内端点(siliconflow 等)造成 502;
|
||||||
|
# 代理经 proxy 显式传入(AGNES 等),未传则直连。
|
||||||
|
http_client = httpx.AsyncClient(proxy=proxy, trust_env=False)
|
||||||
|
# 故障快速失败(全栈统一,覆盖 web chat / IM bot / embedding):
|
||||||
|
# connect 封顶 10s —— 坏端点不再让请求挂死事件循环;
|
||||||
|
# read/write 封顶 30s —— 长流式回复只要持续有分块即不受影响;
|
||||||
|
# 保留数值型 timeout 接口,旧调用方无需改动。
|
||||||
|
_num = float(timeout) if isinstance(timeout, (int, float)) else 120.0
|
||||||
|
_to = httpx.Timeout(
|
||||||
|
connect=min(10.0, _num),
|
||||||
|
read=min(30.0, _num),
|
||||||
|
write=min(30.0, _num),
|
||||||
|
pool=10.0,
|
||||||
|
)
|
||||||
|
_hdrs = {}
|
||||||
|
if auth_header and ":" in auth_header:
|
||||||
|
_k, _v = auth_header.split(":", 1)
|
||||||
|
_hdrs[_k.strip()] = _v.strip()
|
||||||
|
elif auth_header:
|
||||||
|
_hdrs[auth_header.strip()] = api_key
|
||||||
|
|
||||||
|
return AsyncOpenAI(
|
||||||
|
base_url=base,
|
||||||
|
api_key=api_key or "EMPTY",
|
||||||
|
timeout=_to,
|
||||||
|
http_client=http_client,
|
||||||
|
default_headers=_hdrs if _hdrs else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _create_kwargs(request_body: dict, stream: bool = False) -> dict:
|
||||||
|
kw = {
|
||||||
|
"model": request_body.get("model"),
|
||||||
|
"messages": request_body.get("messages", []),
|
||||||
|
"stream": stream,
|
||||||
|
}
|
||||||
|
if request_body.get("temperature") is not None:
|
||||||
|
kw["temperature"] = request_body["temperature"]
|
||||||
|
if request_body.get("top_p") is not None:
|
||||||
|
kw["top_p"] = request_body["top_p"]
|
||||||
|
if request_body.get("max_tokens") is not None:
|
||||||
|
kw["max_tokens"] = request_body["max_tokens"]
|
||||||
|
if request_body.get("stop") is not None:
|
||||||
|
kw["stop"] = request_body["stop"]
|
||||||
|
tools = request_body.get("tools")
|
||||||
|
if tools:
|
||||||
|
kw["tools"] = tools
|
||||||
|
kw["tool_choice"] = request_body.get("tool_choice", "auto")
|
||||||
|
return kw
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_tool_calls(tcs):
|
||||||
|
if not tcs:
|
||||||
|
return None
|
||||||
|
out = []
|
||||||
|
for tc in tcs:
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"id": getattr(tc, "id", None),
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": getattr(tc.function, "name", None),
|
||||||
|
"arguments": getattr(tc.function, "arguments", "") or "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def achat_complete(api_url, api_key, request_body, *, proxy=None, timeout=120, stream=False, auth_header=None):
|
||||||
|
"""统一的 OpenAI 兼容聊天补全。详见模块 docstring。"""
|
||||||
|
if stream:
|
||||||
|
|
||||||
|
async def _gen():
|
||||||
|
client = build_openai_client(api_url, api_key, proxy=proxy, timeout=timeout, auth_header=auth_header)
|
||||||
|
_content_parts = []
|
||||||
|
_reasoning_parts = []
|
||||||
|
_tool_acc = {} # index -> {id, type, name, arguments}
|
||||||
|
try:
|
||||||
|
_to = min(30.0, float(timeout) if isinstance(timeout, (int, float)) else 120.0)
|
||||||
|
gen = await asyncio.wait_for(
|
||||||
|
client.chat.completions.create(
|
||||||
|
**_create_kwargs(request_body, stream=True)
|
||||||
|
),
|
||||||
|
timeout=_to,
|
||||||
|
)
|
||||||
|
_it = gen.__aiter__()
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
chunk = await asyncio.wait_for(_it.__anext__(), timeout=_to)
|
||||||
|
except StopAsyncIteration:
|
||||||
|
break
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
raise TimeoutError("stream chunk read timeout")
|
||||||
|
if not chunk.choices:
|
||||||
|
continue
|
||||||
|
delta = chunk.choices[0].delta
|
||||||
|
rc = getattr(delta, "reasoning_content", None)
|
||||||
|
if rc:
|
||||||
|
_reasoning_parts.append(rc)
|
||||||
|
yield ("reasoning", rc)
|
||||||
|
ct = getattr(delta, "content", None)
|
||||||
|
if ct:
|
||||||
|
_content_parts.append(ct)
|
||||||
|
yield ("content", ct)
|
||||||
|
# 累积 OpenAI 流式 tool_calls(供后续工具循环执行)
|
||||||
|
tcs = getattr(delta, "tool_calls", None)
|
||||||
|
if tcs:
|
||||||
|
for tc in tcs:
|
||||||
|
_idx = getattr(tc, "index", 0)
|
||||||
|
_slot = _tool_acc.setdefault(
|
||||||
|
_idx, {"id": None, "type": "function", "name": "", "arguments": ""}
|
||||||
|
)
|
||||||
|
_tcid = getattr(tc, "id", None)
|
||||||
|
if _tcid:
|
||||||
|
_slot["id"] = _tcid
|
||||||
|
_fn = getattr(tc, "function", None)
|
||||||
|
if _fn is not None:
|
||||||
|
_fn_name = getattr(_fn, "name", None)
|
||||||
|
if _fn_name:
|
||||||
|
_slot["name"] += _fn_name
|
||||||
|
_fn_args = getattr(_fn, "arguments", None)
|
||||||
|
if _fn_args:
|
||||||
|
_slot["arguments"] += _fn_args
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(client.close(), timeout=5)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# 流式结束时吐出已组装的完整 message(含 tool_calls),供调用方无缝衔接工具循环
|
||||||
|
_tool_calls = None
|
||||||
|
if _tool_acc:
|
||||||
|
_tool_calls = []
|
||||||
|
for _i in sorted(_tool_acc.keys()):
|
||||||
|
_s = _tool_acc[_i]
|
||||||
|
_tool_calls.append({
|
||||||
|
"id": _s["id"],
|
||||||
|
"type": "function",
|
||||||
|
"function": {"name": _s["name"], "arguments": _s["arguments"]},
|
||||||
|
})
|
||||||
|
yield ("message", {
|
||||||
|
"content": "".join(_content_parts),
|
||||||
|
"tool_calls": _tool_calls,
|
||||||
|
"reasoning_content": "".join(_reasoning_parts) or None,
|
||||||
|
})
|
||||||
|
|
||||||
|
return _gen()
|
||||||
|
|
||||||
|
client = build_openai_client(api_url, api_key, proxy=proxy, timeout=timeout, auth_header=auth_header)
|
||||||
|
try:
|
||||||
|
_to = min(30.0, float(timeout) if isinstance(timeout, (int, float)) else 120.0)
|
||||||
|
resp = await asyncio.wait_for(
|
||||||
|
client.chat.completions.create(**_create_kwargs(request_body)),
|
||||||
|
timeout=_to,
|
||||||
|
)
|
||||||
|
msg = resp.choices[0].message
|
||||||
|
return {
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"message": {
|
||||||
|
"content": msg.content or "",
|
||||||
|
"tool_calls": _normalize_tool_calls(getattr(msg, "tool_calls", None)),
|
||||||
|
"reasoning_content": getattr(msg, "reasoning_content", None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"usage": (resp.usage.model_dump() if resp.usage else {}),
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(client.close(), timeout=5)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def build_openai_client_sync(api_url, api_key, *, proxy=None, timeout=120, auth_header=None) -> OpenAI:
|
||||||
|
"""同步客户端工厂(供 IM bot 等同步上下文复用同一标准模型层)。"""
|
||||||
|
base = _base_url(api_url)
|
||||||
|
http_client = httpx.Client(proxy=proxy, trust_env=False)
|
||||||
|
_hdrs = {}
|
||||||
|
if auth_header and ":" in auth_header:
|
||||||
|
_k, _v = auth_header.split(":", 1)
|
||||||
|
_hdrs[_k.strip()] = _v.strip()
|
||||||
|
elif auth_header:
|
||||||
|
_hdrs[auth_header.strip()] = api_key
|
||||||
|
return OpenAI(base_url=base, api_key=api_key or "EMPTY", timeout=timeout, http_client=http_client, default_headers=_hdrs if _hdrs else None)
|
||||||
|
|
||||||
|
|
||||||
|
def chat_complete(api_url, api_key, request_body, *, proxy=None, timeout=120):
|
||||||
|
"""同步版(与 achat_complete 行为/返回形状完全一致),供非 async 上下文使用。"""
|
||||||
|
client = build_openai_client_sync(api_url, api_key, proxy=proxy, timeout=timeout, auth_header=auth_header)
|
||||||
|
with client:
|
||||||
|
resp = client.chat.completions.create(**_create_kwargs(request_body))
|
||||||
|
msg = resp.choices[0].message
|
||||||
|
return {
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"message": {
|
||||||
|
"content": msg.content or "",
|
||||||
|
"tool_calls": _normalize_tool_calls(getattr(msg, "tool_calls", None)),
|
||||||
|
"reasoning_content": getattr(msg, "reasoning_content", None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"usage": (resp.usage.model_dump() if resp.usage else {}),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 嵌入(Embeddings):OpenAI 兼容 /v1/embeddings,收敛散落的裸 httpx 嵌入调用
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _embed_kwargs(input, model):
|
||||||
|
return {"model": model, "input": input if isinstance(input, list) else [input]}
|
||||||
|
|
||||||
|
|
||||||
|
async def aembed(api_url, api_key, input, model, *, proxy=None, timeout=60) -> list:
|
||||||
|
"""统一的 OpenAI 兼容文本嵌入(异步)。返回 list[list[float]]。
|
||||||
|
|
||||||
|
供 pgvector_search.get_embedding 等 embeddings 路径复用,把散落的裸 httpx
|
||||||
|
嵌入调用收敛到同一标准模型层(与聊天共用代理/超时/failover 语义)。
|
||||||
|
"""
|
||||||
|
client = build_openai_client(api_url, api_key, proxy=proxy, timeout=timeout, auth_header=auth_header)
|
||||||
|
try:
|
||||||
|
_to = min(60.0, float(timeout) if isinstance(timeout, (int, float)) else 60.0)
|
||||||
|
resp = await asyncio.wait_for(
|
||||||
|
client.embeddings.create(**_embed_kwargs(input, model)),
|
||||||
|
timeout=_to,
|
||||||
|
)
|
||||||
|
return [d.embedding for d in resp.data]
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(client.close(), timeout=5)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def embed(api_url, api_key, input, model, *, proxy=None, timeout=60) -> list:
|
||||||
|
"""同步版嵌入(与非 async 上下文复用同一标准模型层)。"""
|
||||||
|
client = build_openai_client_sync(api_url, api_key, proxy=proxy, timeout=timeout, auth_header=auth_header)
|
||||||
|
with client:
|
||||||
|
resp = client.embeddings.create(**_embed_kwargs(input, model))
|
||||||
|
return [d.embedding for d in resp.data]
|
||||||
|
|
||||||
@@ -1,22 +1,26 @@
|
|||||||
"""
|
"""
|
||||||
Qihu-AIFlow 统一可观测基座 (Phase 2.1)
|
Qihu-AIFlow 统一可观测基座 (Phase 2.1 + Phase 1.I OTel 增强)
|
||||||
=====================================
|
=============================================================
|
||||||
提供贯穿一次请求的全局链路 ID(trace_id)与结构化日志能力,
|
提供贯穿一次请求的全局链路 ID(trace_id)与结构化日志能力,
|
||||||
为后续重构(上下文引擎、媒体/LLM 成本归因)建立回归基线。
|
为后续重构(上下文引擎、媒体/LLM 成本归因)建立回归基线。
|
||||||
|
|
||||||
设计原则(Strangler Fig 增量):
|
设计原则(Strangler Fig 增量):
|
||||||
- 纯增量埋点,不改任何既有接口的返回结构。
|
- 纯增量埋点,不改任何既有接口的返回结构。
|
||||||
- 向后兼容现有 `logging.getLogger(__name__)` 用法:trace_id 由 root logger 的
|
- 向后兼容现有 \"logging.getLogger(__name__)\" 用法:trace_id 由 root logger 的
|
||||||
TraceIdFilter 自动注入,调用方无需改动。
|
TraceIdFilter 自动注入,调用方无需改动。
|
||||||
- 不引入第三方依赖(structlog 未安装),自带可选的 JSON formatter。
|
- 不引入第三方依赖(structlog 未安装),自带可选的 JSON formatter。
|
||||||
|
|
||||||
|
Phase 1.I 增强:span() 在保持原有日志计时的同时,额外嵌套一个标准 OpenTelemetry
|
||||||
|
span(经 app.core.otel 桥接,OTLP 导出到 Grafana)。OTel 失败时自动降级为 no-op,
|
||||||
|
绝不改变既有日志行为与请求链路。
|
||||||
|
|
||||||
使用方式:
|
使用方式:
|
||||||
from app.core.observability import set_trace_id, get_trace_id, span
|
from app.core.observability import set_trace_id, get_trace_id, span
|
||||||
|
|
||||||
# 在中间件里为每个请求注入:
|
# 在中间件里为每个请求注入:
|
||||||
set_trace_id(request_id)
|
set_trace_id(request_id)
|
||||||
|
|
||||||
# 在关键调用处打计时 span(自动带 trace_id):
|
# 在关键调用处打计时 span(自动带 trace_id + OTel span):
|
||||||
async with span("chat.send_message", conv_id=conv_id):
|
async with span("chat.send_message", conv_id=conv_id):
|
||||||
return await _send_message_core(...)
|
return await _send_message_core(...)
|
||||||
"""
|
"""
|
||||||
@@ -26,6 +30,8 @@ import uuid
|
|||||||
import json
|
import json
|
||||||
from contextvars import ContextVar
|
from contextvars import ContextVar
|
||||||
|
|
||||||
|
from app.core.otel import current_span_cm, record_span_metrics
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# trace_id:贯穿一次请求(含其内所有子调用/协程)的全局链路 ID
|
# trace_id:贯穿一次请求(含其内所有子调用/协程)的全局链路 ID
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -52,7 +58,7 @@ def get_trace_id() -> str:
|
|||||||
class TraceIdFilter(logging.Filter):
|
class TraceIdFilter(logging.Filter):
|
||||||
"""为每一条日志记录注入 trace_id 属性(不存在则写为 '-')。
|
"""为每一条日志记录注入 trace_id 属性(不存在则写为 '-')。
|
||||||
|
|
||||||
挂载到 root logger 后,所有 `getLogger(__name__)` 的子 logger 都会继承,
|
挂载到 root logger 后,所有 \"getLogger(__name__)\" 的子 logger 都会继承,
|
||||||
从而让全平台既有日志自动带上链路 ID,零侵入。
|
从而让全平台既有日志自动带上链路 ID,零侵入。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -103,10 +109,10 @@ def get_logger(name: str | None = None) -> logging.Logger:
|
|||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# span:结构化计时上下文管理器(耗时 + trace_id + 自定义字段)
|
# span:结构化计时上下文管理器(耗时 + trace_id + 自定义字段 + OTel 嵌套)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
class _Span:
|
class _Span:
|
||||||
"""同步/异步通用的计时 span。退出时记录 elapsed_ms 与状态。"""
|
"""同步/异步通用的计时 span。退出时记录 elapsed_ms 与状态,并结束嵌套的 OTel span。"""
|
||||||
|
|
||||||
def __init__(self, name: str, **fields):
|
def __init__(self, name: str, **fields):
|
||||||
self.name = name
|
self.name = name
|
||||||
@@ -114,6 +120,7 @@ class _Span:
|
|||||||
self._logger = logging.getLogger("aiflow.span")
|
self._logger = logging.getLogger("aiflow.span")
|
||||||
self._start = None
|
self._start = None
|
||||||
self.elapsed_ms = 0.0
|
self.elapsed_ms = 0.0
|
||||||
|
self._otel_cm = None # 嵌套的 OTel span 上下文管理器
|
||||||
|
|
||||||
def _enter(self):
|
def _enter(self):
|
||||||
self._start = time.perf_counter()
|
self._start = time.perf_counter()
|
||||||
@@ -121,6 +128,10 @@ class _Span:
|
|||||||
f"SPAN_START {self.name}",
|
f"SPAN_START {self.name}",
|
||||||
extra={"span": self.name, "event": "start", "trace_id": get_trace_id(), **self.fields},
|
extra={"span": self.name, "event": "start", "trace_id": get_trace_id(), **self.fields},
|
||||||
)
|
)
|
||||||
|
# OTel 嵌套 span(失败安全:current_span_cm 返回 None 时 no-op)
|
||||||
|
self._otel_cm = current_span_cm(self.name, self.fields)
|
||||||
|
if self._otel_cm is not None:
|
||||||
|
self._otel_cm.__enter__()
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def _exit(self, exc_type, exc, tb):
|
def _exit(self, exc_type, exc, tb):
|
||||||
@@ -137,6 +148,24 @@ class _Span:
|
|||||||
**self.fields,
|
**self.fields,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
# 结束嵌套的 OTel span(失败安全)
|
||||||
|
if self._otel_cm is not None:
|
||||||
|
try:
|
||||||
|
from opentelemetry import trace as _ot
|
||||||
|
if exc_type is not None:
|
||||||
|
self._otel_cm.set_status(
|
||||||
|
_ot.trace.Status(_ot.trace.StatusCode.ERROR, str(exc_type.__name__))
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._otel_cm.set_status(_ot.trace.Status(_ot.trace.StatusCode.OK))
|
||||||
|
self._otel_cm.__exit__(exc_type, exc, tb)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# 记录 span 指标(耗时直方图 + 计数),供 Grafana 出图(失败安全)
|
||||||
|
try:
|
||||||
|
record_span_metrics(self.name, self.elapsed_ms, status)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
return False # 不吞掉异常
|
return False # 不吞掉异常
|
||||||
|
|
||||||
# 同步协议
|
# 同步协议
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ async def _run_local_agent_turn(agent: dict, node_input: str, db, user_id, conv_
|
|||||||
from app.api.chat_utils import _proxy_for_url
|
from app.api.chat_utils import _proxy_for_url
|
||||||
|
|
||||||
skills = _resolve_market_skills(db, agent.get("skill_ids") or [], user_id)
|
skills = _resolve_market_skills(db, agent.get("skill_ids") or [], user_id)
|
||||||
kb_context = _retrieve_kb_context(db, agent.get("knowledge_base_ids") or [], node_input)
|
kb_context = await _retrieve_kb_context(db, agent.get("knowledge_base_ids") or [], node_input)
|
||||||
system_prompt, function_definitions = _build_system_prompt(
|
system_prompt, function_definitions = _build_system_prompt(
|
||||||
skills=skills,
|
skills=skills,
|
||||||
agents=[agent],
|
agents=[agent],
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"""
|
||||||
|
OpenTelemetry 桥接 (Phase 1.I 标准化)
|
||||||
|
=====================================
|
||||||
|
设计基准(标准对照表见 STANDARDS_AUDIT_2026-07-24.md §I):
|
||||||
|
- 标准:OpenTelemetry SDK + OTLP gRPC exporter —— 云原生可观测事实标准。
|
||||||
|
- traces:span 经 observability.span() 嵌套导出(见 observability.py)。
|
||||||
|
- metrics:MeterProvider 经 OTLP 导出 span 耗时直方图 + 调用计数,供 Grafana 出图。
|
||||||
|
- 失败安全(生产红线):若 OTLP 端点不可达 / 初始化异常,自动降级为 no-op,
|
||||||
|
绝不阻断业务请求、不产生未捕获异常。
|
||||||
|
- 门控:OTEL_ENABLED=1 默认开启;置 0 则零开销、不走 OTel。
|
||||||
|
- 发射目标:OTEL_EXPORTER_OTLP_ENDPOINT,默认 http://qihu-aiflow-alloy:4317
|
||||||
|
(经 Grafana Alloy 桥接 OTLP→Prometheus,再由 Prometheus 喂给 Grafana 出图)。
|
||||||
|
|
||||||
|
对外 API:
|
||||||
|
init_otel() 首次调用时构建 TracerProvider + MeterProvider(幂等)
|
||||||
|
get_tracer() 返回 tracer(未启用/失败则 None)
|
||||||
|
get_meter() 返回 meter(未启用/失败则 None)
|
||||||
|
current_span_cm(name) 返回一个 OTel span 的上下文管理器(供 observability 嵌套)
|
||||||
|
record_span_metrics(name, elapsed_ms, status) 记录 span 指标(耗时直方图 + 计数)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_ENABLED = os.getenv("OTEL_ENABLED", "1") not in ("0", "false", "False", "")
|
||||||
|
_ENDPOINT = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://qihu-aiflow-alloy:4317").rstrip("/")
|
||||||
|
if not _ENDPOINT.startswith("http://") and not _ENDPOINT.startswith("https://"):
|
||||||
|
_ENDPOINT = "http://" + _ENDPOINT
|
||||||
|
|
||||||
|
_tracer = None
|
||||||
|
_meter = None
|
||||||
|
_initialized = False
|
||||||
|
_duration_hist = None
|
||||||
|
_span_counter = None
|
||||||
|
|
||||||
|
|
||||||
|
def init_otel() -> None:
|
||||||
|
"""构建 TracerProvider + MeterProvider(幂等)。失败则降级为 no-op。"""
|
||||||
|
global _tracer, _meter, _initialized
|
||||||
|
if _initialized:
|
||||||
|
return
|
||||||
|
_initialized = True
|
||||||
|
if not _ENABLED:
|
||||||
|
logger.info("[otel] disabled (OTEL_ENABLED=0)")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from opentelemetry import trace, metrics
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.semconv.resource import ResourceAttributes
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
|
||||||
|
OTLPSpanExporter,
|
||||||
|
)
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
|
||||||
|
OTLPMetricExporter,
|
||||||
|
)
|
||||||
|
|
||||||
|
resource = Resource.create({ResourceAttributes.SERVICE_NAME: "qihu-aiflow"})
|
||||||
|
|
||||||
|
# --- traces ---
|
||||||
|
trace_provider = TracerProvider(resource=resource)
|
||||||
|
trace_provider.add_span_processor(
|
||||||
|
BatchSpanProcessor(OTLPSpanExporter(endpoint=_ENDPOINT, insecure=True))
|
||||||
|
)
|
||||||
|
trace.set_tracer_provider(trace_provider)
|
||||||
|
_tracer = trace.get_tracer("qihu-aiflow")
|
||||||
|
|
||||||
|
# --- metrics ---
|
||||||
|
metric_reader = PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(endpoint=_ENDPOINT, insecure=True)
|
||||||
|
)
|
||||||
|
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
|
||||||
|
metrics.set_meter_provider(meter_provider)
|
||||||
|
_meter = metrics.get_meter("qihu-aiflow")
|
||||||
|
|
||||||
|
logger.info(f"[otel] tracer+meter ready -> {_ENDPOINT}")
|
||||||
|
except Exception as e: # pragma: no cover - 降级保护
|
||||||
|
logger.warning(f"[otel] init failed, degraded to no-op: {e}")
|
||||||
|
_tracer = None
|
||||||
|
_meter = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_tracer():
|
||||||
|
"""返回 tracer;首次调用触发 init。未启用/失败返回 None。"""
|
||||||
|
if _tracer is None and _ENABLED:
|
||||||
|
init_otel()
|
||||||
|
return _tracer
|
||||||
|
|
||||||
|
|
||||||
|
def get_meter():
|
||||||
|
"""返回 meter;首次调用触发 init。未启用/失败返回 None。"""
|
||||||
|
if _meter is None and _ENABLED:
|
||||||
|
init_otel()
|
||||||
|
return _meter
|
||||||
|
|
||||||
|
|
||||||
|
def current_span_cm(name: str, attributes: dict | None = None):
|
||||||
|
"""返回一个 OTel span 的上下文管理器(同步/异步通用)。失败时返回 None。"""
|
||||||
|
tr = get_tracer()
|
||||||
|
if tr is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return tr.start_as_current_span(name, attributes=attributes or {})
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
logger.warning(f"[otel] start_span failed: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def record_span_metrics(name: str, elapsed_ms: float, status: str) -> None:
|
||||||
|
"""记录 span 指标:耗时直方图 + 调用计数(供 Grafana 出图)。失败安全。"""
|
||||||
|
m = get_meter()
|
||||||
|
if m is None:
|
||||||
|
return
|
||||||
|
global _duration_hist, _span_counter
|
||||||
|
try:
|
||||||
|
if _duration_hist is None:
|
||||||
|
_duration_hist = m.create_histogram(
|
||||||
|
"aiflow_span_duration_ms", "Span duration in milliseconds"
|
||||||
|
)
|
||||||
|
_span_counter = m.create_counter("aiflow_span_count", "Span invocation count")
|
||||||
|
attrs = {"span": name, "status": status}
|
||||||
|
_duration_hist.record(elapsed_ms, attrs)
|
||||||
|
_span_counter.add(1, attrs)
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
pass
|
||||||
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""标准 RAG 管线 (Phase 2.C 标准化)
|
||||||
|
====================================
|
||||||
|
设计基准(标准对照表见 STANDARDS_AUDIT_2026-07-24.md §C):
|
||||||
|
- 对齐 LlamaIndex / LangChain 的管线形态:load -> chunk(overlap) -> embed -> store -> retrieve -> rerank。
|
||||||
|
- 复用现有 pgvector 后端(document_embeddings 表 + ivfflat)与共享 embeddings 客户端
|
||||||
|
(app.core.llm_client.aembed);嵌入维度(1024)、表结构、混合检索(RRF)全部沿用,不重复造轮子。
|
||||||
|
- 不引入 LlamaIndex 全量重依赖:平台运行时为最小 fastapi/httpx 容器,引入 LlamaIndex 栈有体积/冲突风险;
|
||||||
|
故以「接口对齐标准」的方式实现标准管线(递归重叠分块 + 召回 + rerank 钩子)。后续若评估可接受,
|
||||||
|
可平滑替换为 llama_index.core 的 VectorStoreIndex + PGVectorStore(对外接口一致)。
|
||||||
|
|
||||||
|
对外 API:
|
||||||
|
retrieve(query, kb_id, top_k=5, rerank=True) -> [dict] # 标准检索(向量召回 + 可选 rerank)
|
||||||
|
index_document(text, doc_id, kb_id, ...) -> int # 标准索引(递归重叠分块后逐块入库)
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.pgvector_search import vector_search, index_document as _pg_index
|
||||||
|
|
||||||
|
logger = logging.getLogger("aiflow.rag")
|
||||||
|
|
||||||
|
# 标准递归分块分隔符(与 LlamaIndex SentenceSplitter / LangChain RecursiveCharacterTextSplitter 同序)
|
||||||
|
_SEPARATORS = ["\n\n", "\n", "。", "!", "?", ";", ".", "!", "?", ";", " ", ""]
|
||||||
|
|
||||||
|
|
||||||
|
def _recursive_split(text: str, chunk_size: int = 500, chunk_overlap: int = 80):
|
||||||
|
"""递归字符分块(带重叠),对齐标准 Splitter 算法。
|
||||||
|
|
||||||
|
逐层用分隔符切分;某段仍超长时递归细切;最终兜底硬切(带重叠步长)。
|
||||||
|
"""
|
||||||
|
text = text or ""
|
||||||
|
if len(text) <= chunk_size:
|
||||||
|
return [text] if text.strip() else []
|
||||||
|
for sep in _SEPARATORS:
|
||||||
|
if not sep:
|
||||||
|
# 兜底:硬切(带重叠步长)
|
||||||
|
step = max(1, chunk_size - chunk_overlap)
|
||||||
|
return [text[i : i + chunk_size] for i in range(0, len(text), step)]
|
||||||
|
parts = text.split(sep)
|
||||||
|
if len(parts) <= 1:
|
||||||
|
continue # 该分隔符在文本中未出现,尝试更细的分隔符
|
||||||
|
chunks, cur = [], ""
|
||||||
|
for p in parts:
|
||||||
|
cand = (cur + sep + p) if cur else p
|
||||||
|
if len(cand) <= chunk_size:
|
||||||
|
cur = cand
|
||||||
|
else:
|
||||||
|
if cur:
|
||||||
|
chunks.append(cur)
|
||||||
|
cur = ""
|
||||||
|
if len(p) > chunk_size:
|
||||||
|
chunks.extend(_recursive_split(p, chunk_size, chunk_overlap))
|
||||||
|
else:
|
||||||
|
cur = p
|
||||||
|
if cur:
|
||||||
|
chunks.append(cur)
|
||||||
|
if chunks:
|
||||||
|
return [c for c in chunks if c.strip()]
|
||||||
|
return [text]
|
||||||
|
|
||||||
|
|
||||||
|
async def index_document(
|
||||||
|
text: str,
|
||||||
|
doc_id: str,
|
||||||
|
kb_id: str,
|
||||||
|
chunk_size: int = 500,
|
||||||
|
chunk_overlap: int = 80,
|
||||||
|
metadata: dict | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""标准索引:递归重叠分块后逐块存入 pgvector。返回成功分块数。"""
|
||||||
|
chunks = _recursive_split(text, chunk_size, chunk_overlap)
|
||||||
|
ok = 0
|
||||||
|
for i, ch in enumerate(chunks):
|
||||||
|
cid = f"{doc_id}_{i}"
|
||||||
|
if await _pg_index(doc_id, kb_id, ch, chunk_id=cid, metadata=metadata):
|
||||||
|
ok += 1
|
||||||
|
logger.info(f"[rag] indexed {doc_id}: {ok}/{len(chunks)} chunks")
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
async def retrieve(
|
||||||
|
query: str,
|
||||||
|
kb_id: str | None = None,
|
||||||
|
top_k: int = 5,
|
||||||
|
rerank: bool = True,
|
||||||
|
) -> list:
|
||||||
|
"""标准检索:向量召回 + 可选 rerank。
|
||||||
|
|
||||||
|
返回 [{doc_id, chunk_id, content, score, metadata}, ...]。
|
||||||
|
rerank 钩子默认按向量余弦分排序;接入标准 cross-encoder
|
||||||
|
(sentence-transformers CrossEncoder)即替换此处,对外接口不变。
|
||||||
|
"""
|
||||||
|
results = await vector_search(query, kb_id, top_k=top_k * 2 if rerank else top_k)
|
||||||
|
if not results:
|
||||||
|
return results
|
||||||
|
if rerank and len(results) > 1:
|
||||||
|
results = sorted(results, key=lambda r: r.get("score", 0), reverse=True)
|
||||||
|
return results[:top_k]
|
||||||
@@ -63,15 +63,65 @@ async def _search_external(service: Dict, query: str, top_k: int = 5) -> List[Di
|
|||||||
logger.warning(f"Unknown external KB type: {service_type}")
|
logger.warning(f"Unknown external KB type: {service_type}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
async def _get_web_services(db_session, enabled_only: bool = True) -> List[Dict]:
|
||||||
|
"""获取全局 AnySearch 联网检索配置(从 site_settings 读取)。"""
|
||||||
|
from app.anysearch_client import load_anysearch_config
|
||||||
|
cfg = load_anysearch_config(db_session)
|
||||||
|
if not cfg:
|
||||||
|
return []
|
||||||
|
if enabled_only and not cfg.get("is_enabled"):
|
||||||
|
return []
|
||||||
|
api_key = cfg.get("api_key", "")
|
||||||
|
if not api_key:
|
||||||
|
return []
|
||||||
|
return [{
|
||||||
|
"id": "anysearch_global",
|
||||||
|
"service_type": "anysearch",
|
||||||
|
"api_key": api_key,
|
||||||
|
"api_url": cfg.get("api_url") or "https://api.anysearch.com/v1/search",
|
||||||
|
"config": {
|
||||||
|
"zone": cfg.get("zone", "cn"),
|
||||||
|
"freshness": cfg.get("freshness"),
|
||||||
|
"top_k": cfg.get("top_k", 5),
|
||||||
|
},
|
||||||
|
"is_enabled": cfg.get("is_enabled", False),
|
||||||
|
}]
|
||||||
|
|
||||||
|
|
||||||
|
async def _search_anysearch(service: Dict, query: str, top_k: int = 5) -> List[Dict]:
|
||||||
|
"""调用 AnySearch 联网检索(走 app.anysearch_client)。"""
|
||||||
|
try:
|
||||||
|
from app.anysearch_client import anysearch_search
|
||||||
|
api_key = service.get("api_key", "")
|
||||||
|
api_url = service.get("api_url") or "https://api.anysearch.com/v1/search"
|
||||||
|
cfg = service.get("config")
|
||||||
|
if isinstance(cfg, str):
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
cfg = json.loads(cfg)
|
||||||
|
except Exception:
|
||||||
|
cfg = None
|
||||||
|
cfg = cfg or {}
|
||||||
|
zone = cfg.get("zone", "cn")
|
||||||
|
freshness = cfg.get("freshness")
|
||||||
|
k = int(cfg.get("top_k", top_k))
|
||||||
|
return await anysearch_search(api_key, api_url, query, top_k=k, zone=zone, freshness=freshness)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"AnySearch search error: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
async def kb_router_search(
|
async def kb_router_search(
|
||||||
query: str,
|
query: str,
|
||||||
kb_id: Optional[str] = None,
|
kb_id: Optional[str] = None,
|
||||||
|
kb_ids: Optional[List[str]] = None,
|
||||||
top_k: int = 5,
|
top_k: int = 5,
|
||||||
bm25_results: Optional[List[Dict]] = None,
|
bm25_results: Optional[List[Dict]] = None,
|
||||||
db_session=None,
|
db_session=None,
|
||||||
use_vector: bool = True,
|
use_vector: bool = True,
|
||||||
use_external: bool = True,
|
use_external: bool = True,
|
||||||
|
use_tree: bool = True,
|
||||||
|
use_web: bool = False,
|
||||||
) -> List[Dict]:
|
) -> List[Dict]:
|
||||||
"""
|
"""
|
||||||
知识库路由层 — 混合检索
|
知识库路由层 — 混合检索
|
||||||
@@ -79,7 +129,9 @@ async def kb_router_search(
|
|||||||
检索策略:
|
检索策略:
|
||||||
1. 本地 BM25 检索 (MySQL, 已有)
|
1. 本地 BM25 检索 (MySQL, 已有)
|
||||||
2. 向量语义检索 (PostgreSQL+pgvector, 新增)
|
2. 向量语义检索 (PostgreSQL+pgvector, 新增)
|
||||||
3. 外部KB检索 (Dify, 按配置)
|
3. 结构化分片段检索 (TreeSearch, 新增: 知识库目录树 + chunk 级精准命中)
|
||||||
|
4. 外部KB检索 (Dify, 按配置)
|
||||||
|
5. 联网检索 (AnySearch, 可选 use_web)
|
||||||
|
|
||||||
融合方式: Reciprocal Rank Fusion (RRF)
|
融合方式: Reciprocal Rank Fusion (RRF)
|
||||||
|
|
||||||
@@ -88,9 +140,11 @@ async def kb_router_search(
|
|||||||
kb_id: 知识库ID
|
kb_id: 知识库ID
|
||||||
top_k: 返回结果数
|
top_k: 返回结果数
|
||||||
bm25_results: BM25检索结果
|
bm25_results: BM25检索结果
|
||||||
db_session: 数据库会话(用于获取外部KB配置)
|
db_session: 数据库会话(用于获取外部KB配置与分片段检索)
|
||||||
use_vector: 是否使用向量检索
|
use_vector: 是否使用向量检索
|
||||||
use_external: 是否使用外部KB检索
|
use_external: 是否使用外部KB检索
|
||||||
|
use_tree: 是否使用 TreeSearch 结构化分片段检索
|
||||||
|
use_web: 是否使用 AnySearch 联网检索
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
融合后的检索结果列表
|
融合后的检索结果列表
|
||||||
@@ -112,7 +166,13 @@ async def kb_router_search(
|
|||||||
if use_vector:
|
if use_vector:
|
||||||
try:
|
try:
|
||||||
from app.pgvector_search import vector_search
|
from app.pgvector_search import vector_search
|
||||||
vec_results = await vector_search(query, kb_id, top_k)
|
kb_targets = kb_ids if kb_ids else ([kb_id] if kb_id else [None])
|
||||||
|
vec_results = []
|
||||||
|
for _kid in kb_targets:
|
||||||
|
try:
|
||||||
|
vec_results.extend(await vector_search(query, _kid, top_k))
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Vector search failed for kb={_kid}: {e}")
|
||||||
for rank, item in enumerate(vec_results):
|
for rank, item in enumerate(vec_results):
|
||||||
all_results.append({
|
all_results.append({
|
||||||
"content": item.get("content", ""),
|
"content": item.get("content", ""),
|
||||||
@@ -126,6 +186,25 @@ async def kb_router_search(
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Vector search failed: {e}")
|
logger.warning(f"Vector search failed: {e}")
|
||||||
|
|
||||||
|
# 2.5 结构化分片段检索 (TreeSearch, Level 2)
|
||||||
|
if use_tree and db_session is not None:
|
||||||
|
try:
|
||||||
|
from app.tree_search import tree_search
|
||||||
|
kb_targets = kb_ids if kb_ids else ([kb_id] if kb_id else None)
|
||||||
|
tree_hits = await tree_search(
|
||||||
|
db_session, query, kb_ids=kb_targets, top_k=top_k, mode="hybrid",
|
||||||
|
)
|
||||||
|
for rank, item in enumerate(tree_hits):
|
||||||
|
all_results.append({
|
||||||
|
"content": item.get("content", ""),
|
||||||
|
"score": item.get("score", 0.5),
|
||||||
|
"source": "tree_chunk",
|
||||||
|
"rank": rank + 1,
|
||||||
|
"metadata": item.get("metadata", {}),
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"TreeSearch failed: {e}")
|
||||||
|
|
||||||
# 3. 外部KB检索 (Dify)
|
# 3. 外部KB检索 (Dify)
|
||||||
if use_external and db_session:
|
if use_external and db_session:
|
||||||
services = await _get_external_services(db_session)
|
services = await _get_external_services(db_session)
|
||||||
@@ -141,6 +220,23 @@ async def kb_router_search(
|
|||||||
"metadata": item.get("metadata", {}),
|
"metadata": item.get("metadata", {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# 4. 联网检索 (AnySearch, 可选)
|
||||||
|
if use_web and db_session is not None:
|
||||||
|
try:
|
||||||
|
web_services = await _get_web_services(db_session)
|
||||||
|
for svc in web_services:
|
||||||
|
web_hits = await _search_anysearch(svc, query, top_k)
|
||||||
|
for rank, item in enumerate(web_hits):
|
||||||
|
all_results.append({
|
||||||
|
"content": item.get("content", ""),
|
||||||
|
"score": item.get("score", 0.6),
|
||||||
|
"source": item.get("source", "web_anysearch"),
|
||||||
|
"rank": rank + 1,
|
||||||
|
"metadata": item.get("metadata", {}),
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"AnySearch web search failed: {e}")
|
||||||
|
|
||||||
if not all_results:
|
if not all_results:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@@ -1,122 +1,96 @@
|
|||||||
"""
|
"""
|
||||||
MCP (Model Context Protocol) 客户端 —— 异步实现 streamable_http 传输。
|
MCP (Model Context Protocol) 客户端 —— 基于官方 \"mcp\" Python SDK (Phase 1.E 标准化)
|
||||||
|
|
||||||
支持:
|
设计基准(标准对照表见 STANDARDS_AUDIT_2026-07-24.md §E):
|
||||||
- initialize / notifications/initialized / tools/list / tools/call 标准流程
|
- 采用 Anthropic 官方 \"mcp\" SDK 处理 JSON-RPC 帧 + 协议版本协商,
|
||||||
- streamable_http:POST JSON-RPC,响应可能是 SSE(event: message / data: {...})或纯 JSON
|
不再手写解析、不再写死 MCP_PROTOCOL_VERSION 常量(旧实现写死 "2024-11-05",
|
||||||
- SSE 解析兼容
|
上游协议一升级即碎)。
|
||||||
- 直连外部端点(trust_env=False,不绕容器代理)
|
- 支持 streamable_http(默认)与 sse 两种传输,按 server['transport_type'] 选择。
|
||||||
|
- 公共 API 保持向后兼容:list_mcp_tools(server, timeout) / call_mcp_tool(server, tool_name, arguments, timeout)
|
||||||
供 chat.py 在 AI 对话中把 MCP 工具暴露为 function calling,并代理执行 tools/call。
|
供 chat.py / chat_service.py / chat_agents.py / chat_skill.py / chat_mcp.py /
|
||||||
|
chat_context.py / chat_knowledge.py / chat_media.py / chat_utils.py / core/aca.py
|
||||||
|
共 10+ 处调用,签名与返回结构(tools 数组 / 文本结果字符串)不变。
|
||||||
|
- 工具列表缓存(按 url)与错误处理保持原行为,避免重复握手、保证降级安全。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
import httpx
|
from mcp import ClientSession
|
||||||
|
from mcp.client.sse import sse_client
|
||||||
|
from mcp.client.streamable_http import streamablehttp_client
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
MCP_PROTOCOL_VERSION = "2024-11-05"
|
|
||||||
|
|
||||||
# 工具列表缓存(url -> (timestamp, tools)),避免同一请求内 / 短时间重复握手
|
# 工具列表缓存(url -> (timestamp, tools)),避免同一请求内 / 短时间重复握手
|
||||||
_TOOLS_CACHE: dict = {}
|
_TOOLS_CACHE: dict = {}
|
||||||
_TOOLS_CACHE_TTL = 120 # 秒
|
_TOOLS_CACHE_TTL = 120 # 秒
|
||||||
|
|
||||||
|
|
||||||
def _parse_sse(text: str):
|
def _transport_cm(server: dict, timeout: float):
|
||||||
"""从响应文本解析 JSON-RPC 结果。兼容 SSE(data: 行)与纯 JSON。"""
|
"""按 server['transport_type'] 选择官方 SDK 传输层。
|
||||||
if not text:
|
|
||||||
return None
|
返回异步上下文管理器,进入后产出 (read_stream, write_stream, ...)。
|
||||||
text = text.strip()
|
"""
|
||||||
# SSE 格式:多行 "event: message" / "data: {...}"
|
url = (server.get("url") or "").strip()
|
||||||
data_lines = []
|
ttype = (server.get("transport_type") or "streamable_http").lower()
|
||||||
for line in text.splitlines():
|
headers = server.get("headers") or {}
|
||||||
ls = line.strip()
|
if ttype == "sse":
|
||||||
if ls.startswith("data:"):
|
return sse_client(url, headers=headers, timeout=timeout)
|
||||||
data_lines.append(ls[5:].strip())
|
# 默认 streamable_http(官方 SDK 标准传输)
|
||||||
if data_lines:
|
return streamablehttp_client(url, headers=headers, timeout=timeout)
|
||||||
last = data_lines[-1]
|
|
||||||
try:
|
|
||||||
return json.loads(last)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
# 纯 JSON
|
|
||||||
try:
|
|
||||||
return json.loads(text)
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
async def _handshake_and_request(
|
async def _session_request(
|
||||||
url: str,
|
server: dict, method: str, params: dict, timeout: float = 30.0
|
||||||
headers: dict,
|
|
||||||
method: str,
|
|
||||||
params: dict,
|
|
||||||
timeout: float = 30.0,
|
|
||||||
):
|
):
|
||||||
|
"""用官方 ClientSession 完成一次标准 MCP 调用(initialize -> 目标请求)。
|
||||||
|
|
||||||
|
返回解析后的 dict:{"result": {...}} 或 None(失败)。
|
||||||
|
协议版本由 SDK 自动协商,不再硬编码。
|
||||||
"""
|
"""
|
||||||
完成一次完整 MCP 会话(initialize -> initialized -> 目标请求)。
|
url = (server.get("url") or "").strip()
|
||||||
返回解析后的 JSON-RPC 响应 dict,或 None。
|
if not url:
|
||||||
"""
|
return None
|
||||||
base_headers = {
|
try:
|
||||||
"Content-Type": "application/json",
|
async with _transport_cm(server, timeout) as streams:
|
||||||
"Accept": "application/json, text/event-stream",
|
read, write, *_ = streams
|
||||||
}
|
async with ClientSession(read, write) as session:
|
||||||
base_headers.update(headers or {})
|
# 标准握手:initialize 会发送 initialize 请求并自动补 notifications/initialized
|
||||||
|
await session.initialize()
|
||||||
|
# 防御性补发 initialized 通知(部分服务端要求显式接收)
|
||||||
|
try:
|
||||||
|
if hasattr(session, "send_notification"):
|
||||||
|
await session.send_notification("notifications/initialized", {})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
|
if method == "tools/list":
|
||||||
# 1) initialize
|
result = await session.list_tools()
|
||||||
r = await client.post(
|
tools = [t.model_dump() for t in (result.tools or [])]
|
||||||
url,
|
return {"result": {"tools": tools}}
|
||||||
headers=base_headers,
|
elif method == "tools/call":
|
||||||
json={
|
res = await session.call_tool(
|
||||||
"jsonrpc": "2.0",
|
params.get("name"), params.get("arguments") or {}
|
||||||
"id": 1,
|
)
|
||||||
"method": "initialize",
|
content = []
|
||||||
"params": {
|
for blk in (res.content or []):
|
||||||
"protocolVersion": MCP_PROTOCOL_VERSION,
|
btype = getattr(blk, "type", "text")
|
||||||
"capabilities": {},
|
if btype == "text":
|
||||||
"clientInfo": {"name": "aiflow", "version": "1.0"},
|
content.append({"type": "text", "text": getattr(blk, "text", "")})
|
||||||
},
|
else:
|
||||||
},
|
content.append({"type": btype, "text": str(blk)})
|
||||||
)
|
return {
|
||||||
if r.status_code >= 400:
|
"result": {
|
||||||
logger.warning(f"[MCP] initialize 失败 {url} -> HTTP {r.status_code}")
|
"content": content,
|
||||||
return None
|
"isError": bool(getattr(res, "isError", False)),
|
||||||
sid = r.headers.get("mcp-session-id") or r.headers.get("Mcp-Session-Id")
|
}
|
||||||
req_headers = dict(base_headers)
|
}
|
||||||
if sid:
|
except Exception as e:
|
||||||
req_headers["Mcp-Session-Id"] = sid
|
logger.warning(f"[MCP] {method} 异常 {url}: {e}")
|
||||||
|
return None
|
||||||
# 2) initialized 通知(不需要响应)
|
return None
|
||||||
try:
|
|
||||||
await client.post(
|
|
||||||
url,
|
|
||||||
headers=req_headers,
|
|
||||||
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 3) 目标请求
|
|
||||||
rid = 2 if method != "tools/call" else 3
|
|
||||||
r2 = await client.post(
|
|
||||||
url,
|
|
||||||
headers=req_headers,
|
|
||||||
json={
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": rid,
|
|
||||||
"method": method,
|
|
||||||
"params": params,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if r2.status_code >= 400:
|
|
||||||
logger.warning(f"[MCP] {method} 失败 {url} -> HTTP {r2.status_code}")
|
|
||||||
return None
|
|
||||||
return _parse_sse(r2.text)
|
|
||||||
|
|
||||||
|
|
||||||
async def list_mcp_tools(server: dict, timeout: float = 30.0) -> list:
|
async def list_mcp_tools(server: dict, timeout: float = 30.0) -> list:
|
||||||
@@ -134,9 +108,7 @@ async def list_mcp_tools(server: dict, timeout: float = 30.0) -> list:
|
|||||||
if cached and (now - cached[0]) < _TOOLS_CACHE_TTL:
|
if cached and (now - cached[0]) < _TOOLS_CACHE_TTL:
|
||||||
return cached[1]
|
return cached[1]
|
||||||
try:
|
try:
|
||||||
data = await _handshake_and_request(
|
data = await _session_request(server, "tools/list", {}, timeout)
|
||||||
url, server.get("headers") or {}, "tools/list", {}, timeout
|
|
||||||
)
|
|
||||||
tools = []
|
tools = []
|
||||||
if data and "result" in data:
|
if data and "result" in data:
|
||||||
tools = data["result"].get("tools", []) or []
|
tools = data["result"].get("tools", []) or []
|
||||||
@@ -158,9 +130,8 @@ async def call_mcp_tool(
|
|||||||
return f"[MCP 工具 {tool_name} 执行失败:服务端地址为空]"
|
return f"[MCP 工具 {tool_name} 执行失败:服务端地址为空]"
|
||||||
logger.info(f"[MCP] 执行工具调用 tool={tool_name} server={server.get('name')} url={url}")
|
logger.info(f"[MCP] 执行工具调用 tool={tool_name} server={server.get('name')} url={url}")
|
||||||
try:
|
try:
|
||||||
data = await _handshake_and_request(
|
data = await _session_request(
|
||||||
url,
|
server,
|
||||||
server.get("headers") or {},
|
|
||||||
"tools/call",
|
"tools/call",
|
||||||
{"name": tool_name, "arguments": arguments or {}},
|
{"name": tool_name, "arguments": arguments or {}},
|
||||||
timeout,
|
timeout,
|
||||||
@@ -169,7 +140,7 @@ async def call_mcp_tool(
|
|||||||
return f"[MCP 工具 {tool_name} 调用失败:无响应]"
|
return f"[MCP 工具 {tool_name} 调用失败:无响应]"
|
||||||
if "error" in data:
|
if "error" in data:
|
||||||
err = data["error"]
|
err = data["error"]
|
||||||
return f"[MCP 工具 {tool_name} 返回错误] {json.dumps(err, ensure_ascii=False)}"
|
return f"[MCP 工具 {tool_name} 返回错误] {__import__('json').dumps(err, ensure_ascii=False)}"
|
||||||
result = data.get("result", {})
|
result = data.get("result", {})
|
||||||
content = result.get("content", []) or []
|
content = result.get("content", []) or []
|
||||||
parts = []
|
parts = []
|
||||||
@@ -177,7 +148,7 @@ async def call_mcp_tool(
|
|||||||
if isinstance(item, dict) and item.get("type") == "text":
|
if isinstance(item, dict) and item.get("type") == "text":
|
||||||
parts.append(item.get("text", ""))
|
parts.append(item.get("text", ""))
|
||||||
else:
|
else:
|
||||||
parts.append(json.dumps(item, ensure_ascii=False))
|
parts.append(__import__("json").dumps(item, ensure_ascii=False))
|
||||||
text = "\n".join(parts).strip()
|
text = "\n".join(parts).strip()
|
||||||
if result.get("isError"):
|
if result.get("isError"):
|
||||||
return f"[MCP 工具 {tool_name} 执行报错]\n{text}"
|
return f"[MCP 工具 {tool_name} 执行报错]\n{text}"
|
||||||
|
|||||||
+1208
-1159
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,7 @@ from datetime import datetime
|
|||||||
logger = logging.getLogger("aiflow.pgvector")
|
logger = logging.getLogger("aiflow.pgvector")
|
||||||
|
|
||||||
# PostgreSQL 连接配置
|
# PostgreSQL 连接配置
|
||||||
PG_HOST = os.environ.get("POSTGRES_HOST", "pgvector")
|
PG_HOST = os.environ.get("POSTGRES_HOST", "qihu-aiflow-pgvector")
|
||||||
PG_PORT = int(os.environ.get("POSTGRES_PORT", "5432"))
|
PG_PORT = int(os.environ.get("POSTGRES_PORT", "5432"))
|
||||||
PG_USER = os.environ.get("POSTGRES_USER", "aiflow")
|
PG_USER = os.environ.get("POSTGRES_USER", "aiflow")
|
||||||
PG_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "pwd2026")
|
PG_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "pwd2026")
|
||||||
@@ -29,6 +29,32 @@ EMBEDDING_API_URL = os.environ.get("SILICONFLOW_BASE_URL", "https://api.siliconf
|
|||||||
EMBEDDING_API_KEY = os.environ.get("SILICONFLOW_API_KEY", "")
|
EMBEDDING_API_KEY = os.environ.get("SILICONFLOW_API_KEY", "")
|
||||||
EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "BAAI/bge-large-zh-v1.5")
|
EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "BAAI/bge-large-zh-v1.5")
|
||||||
|
|
||||||
|
# ---- 本地嵌入缓存(SQLite 持久化):破解"每次嵌入消耗外部 API 额度"的隐性成本障碍 ----
|
||||||
|
import sqlite3, hashlib, json as _json
|
||||||
|
_EMBED_CACHE_DB = os.environ.get("EMBED_CACHE_DB", "/app/backend/python/.embed_cache.db")
|
||||||
|
def _embed_cache_get(text, model):
|
||||||
|
try:
|
||||||
|
key = hashlib.sha256(f"{model}::{text}".encode("utf-8")).hexdigest()
|
||||||
|
conn = sqlite3.connect(_EMBED_CACHE_DB, timeout=5)
|
||||||
|
row = conn.execute("SELECT vec FROM embed_cache WHERE k=?", (key,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if row:
|
||||||
|
return _json.loads(row[0])
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
def _embed_cache_put(text, model, vec):
|
||||||
|
try:
|
||||||
|
key = hashlib.sha256(f"{model}::{text}".encode("utf-8")).hexdigest()
|
||||||
|
conn = sqlite3.connect(_EMBED_CACHE_DB, timeout=5)
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS embed_cache (k TEXT PRIMARY KEY, vec TEXT, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
|
||||||
|
conn.execute("INSERT OR REPLACE INTO embed_cache (k, vec) VALUES (?, ?)", (key, _json.dumps(vec)))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
# 连接池
|
# 连接池
|
||||||
_pg_pool = None
|
_pg_pool = None
|
||||||
_pool_lock = asyncio.Lock()
|
_pool_lock = asyncio.Lock()
|
||||||
@@ -105,27 +131,20 @@ async def get_embedding(text: str) -> Optional[List[float]]:
|
|||||||
logger.warning("No embedding API key configured")
|
logger.warning("No embedding API key configured")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
cached = _embed_cache_get(text, EMBEDDING_MODEL)
|
||||||
|
if cached:
|
||||||
|
return cached
|
||||||
try:
|
try:
|
||||||
import httpx
|
# 收敛到共享标准模型层(app.core.llm_client.aembed),与聊天共用代理/超时/failover 语义
|
||||||
async with httpx.AsyncClient(timeout=30) as client:
|
from app.core.llm_client import aembed
|
||||||
resp = await client.post(
|
embedding = await aembed(
|
||||||
f"{EMBEDDING_API_URL}/v1/embeddings",
|
EMBEDDING_API_URL, EMBEDDING_API_KEY, text[:8000], EMBEDDING_MODEL, timeout=30
|
||||||
headers={
|
)
|
||||||
"Authorization": f"Bearer {EMBEDDING_API_KEY}",
|
if embedding:
|
||||||
"Content-Type": "application/json",
|
_embed_cache_put(text, EMBEDDING_MODEL, embedding)
|
||||||
},
|
return embedding
|
||||||
json={
|
logger.error("Embedding API returned empty")
|
||||||
"model": EMBEDDING_MODEL,
|
return None
|
||||||
"input": text[:8000], # 截断防止超长
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if resp.status_code == 200:
|
|
||||||
data = resp.json()
|
|
||||||
embedding = data["data"][0]["embedding"]
|
|
||||||
return embedding
|
|
||||||
else:
|
|
||||||
logger.error(f"Embedding API error: {resp.status_code} {resp.text[:200]}")
|
|
||||||
return None
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Embedding generation failed: {e}")
|
logger.error(f"Embedding generation failed: {e}")
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ PLATFORM_KNOWLEDGE = """# 七虎AI平台能力全览
|
|||||||
|
|
||||||
## 5. IM Bot(微信集成)
|
## 5. IM Bot(微信集成)
|
||||||
- **个人微信Bot**: 通过iLink官方接口接入,扫码绑定,微信内直接AI对话
|
- **个人微信Bot**: 通过iLink官方接口接入,扫码绑定,微信内直接AI对话
|
||||||
- **企业微信/飞书/QQ/悟空IM**: Webhook框架已就绪,支持自定义机器人
|
- **企业微信/飞书/QQ/悟空IM**: Webhook框架已绪,支持自定义机器人
|
||||||
- **统一会话管理**: 微信消息并入平台AI聊天,统一历史管理
|
- **统一会话管理**: 微信消息并入平台AI聊天,统一历史管理
|
||||||
|
|
||||||
## 6. 资源中心
|
## 6. 资源中心
|
||||||
@@ -73,7 +73,7 @@ PLATFORM_KNOWLEDGE = """# 七虎AI平台能力全览
|
|||||||
- **安全**: JWT鉴权、HTTPS加密、操作审计日志
|
- **安全**: JWT鉴权、HTTPS加密、操作审计日志
|
||||||
|
|
||||||
## AI回复规范
|
## AI回复规范
|
||||||
1. **回复格式**: 使用Markdown(标题 `##`/`###`、加粗 `**`、列表 `-`/`1.`、代码块等)
|
1. **回复格式**: 使用Markdown(标题 \"##\"/\"###\"、加粗 \"**\"、列表 \"-\"/\"1.\"、代码块等)
|
||||||
2. **层次分明**: 使用标题分隔段落,确保信息有层次
|
2. **层次分明**: 使用标题分隔段落,确保信息有层次
|
||||||
3. **平台优先**: 回答问题时优先引用本平台功能,而非泛泛建议
|
3. **平台优先**: 回答问题时优先引用本平台功能,而非泛泛建议
|
||||||
4. **准确具体**: 基于平台文档给出具体操作路径、配置方法、API示例
|
4. **准确具体**: 基于平台文档给出具体操作路径、配置方法、API示例
|
||||||
@@ -81,6 +81,78 @@ PLATFORM_KNOWLEDGE = """# 七虎AI平台能力全览
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def get_platform_knowledge() -> str:
|
def get_platform_knowledge(db=None, user_id=None) -> str:
|
||||||
"""获取平台全功能知识库文本,注入到AI对话系统提示中"""
|
"""获取平台全功能知识库文本,注入到AI对话系统提示中。
|
||||||
return PLATFORM_KNOWLEDGE
|
|
||||||
|
若传入 db,则动态追加当前平台已上线的官方技能目录
|
||||||
|
(source=official 且 status=published),确保管理员/前台导入或下架技能后,
|
||||||
|
AI 能及时感知并使用「平台自身已有内容」,而非停留在陈旧硬编码清单(见 #712)。
|
||||||
|
任何异常均安全回退到静态 PLATFORM_KNOWLEDGE。
|
||||||
|
"""
|
||||||
|
if db is None:
|
||||||
|
return PLATFORM_KNOWLEDGE
|
||||||
|
try:
|
||||||
|
from .models import MarketApp
|
||||||
|
|
||||||
|
apps = (
|
||||||
|
db.query(MarketApp)
|
||||||
|
.filter(MarketApp.source == "official", MarketApp.status == "published")
|
||||||
|
.order_by(MarketApp.capability, MarketApp.type, MarketApp.name)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if not apps:
|
||||||
|
return PLATFORM_KNOWLEDGE
|
||||||
|
|
||||||
|
# 按类型分组统计
|
||||||
|
type_count = {}
|
||||||
|
for a in apps:
|
||||||
|
t = getattr(a, "type", None) or "skill"
|
||||||
|
type_count[t] = type_count.get(t, 0) + 1
|
||||||
|
type_brief = ", ".join([f"{({'skill':'技能','agent':'Agent','mcp':'MCP应用','mcp_tool':'MCP工具'}.get(k,k))} {v}" for k, v in sorted(type_count.items())])
|
||||||
|
|
||||||
|
# 按能力(capability)分组
|
||||||
|
from collections import OrderedDict
|
||||||
|
by_cap = OrderedDict()
|
||||||
|
for a in apps:
|
||||||
|
cap = getattr(a, "capability", None) or getattr(a, "category", None) or "通用"
|
||||||
|
by_cap.setdefault(cap, []).append(a)
|
||||||
|
|
||||||
|
# 强制完整性说明(关键变更)
|
||||||
|
lines = [
|
||||||
|
"# 📦 平台已上线能力清单(实时同步自数据库,可放心信任此清单)",
|
||||||
|
"",
|
||||||
|
f"**总数:{len(apps)} 个已上线能力**({type_brief})",
|
||||||
|
"",
|
||||||
|
"## ⚠️ 强制完整性指令",
|
||||||
|
"当用户询问以下任何一类问题时,**必须输出下方全部内容**:",
|
||||||
|
'- "平台有哪些技能/应用/MCP"',
|
||||||
|
'- "全部技能" / "列一下技能" / "技能清单"',
|
||||||
|
'- "有什么 Skills" / "支持哪些 Skills"',
|
||||||
|
'- "列举所有" / "每个都列出来"',
|
||||||
|
"",
|
||||||
|
"**绝对不允许**精简、抽样、挑代表性的几个、或改写为综述类叙述。**逐条输出下方每一项**,可以按类别分组展示,但不可省略任何一条。",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
|
||||||
|
# 按能力分组渲染
|
||||||
|
type_emoji = {"skill": "🛠", "agent": "🤖", "mcp": "🔌", "mcp_tool": "🔧"}
|
||||||
|
for cap in by_cap.keys():
|
||||||
|
cap_apps = by_cap[cap]
|
||||||
|
lines.append(f"## 【{cap}】- {len(cap_apps)} 个")
|
||||||
|
for a in cap_apps:
|
||||||
|
name = getattr(a, "name", None) or "未命名"
|
||||||
|
desc = (getattr(a, "description", "") or "").strip().replace("\n", " ")
|
||||||
|
# 描述长度提升到 100 字,给出更可识别的简介
|
||||||
|
if len(desc) > 100:
|
||||||
|
desc = desc[:100] + "…"
|
||||||
|
emoji = type_emoji.get(getattr(a, "type", "skill"), "📦")
|
||||||
|
lines.append(f"- {emoji} **{name}**: {desc}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
dynamic_section = "\n".join(lines)
|
||||||
|
|
||||||
|
# 关键:动态能力清单放在最前面,让 AI 优先处理
|
||||||
|
return dynamic_section + "\n\n---\n\n# 平台静态文档\n\n" + PLATFORM_KNOWLEDGE
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[platform_knowledge] 动态构建失败,回退静态知识库: {e}")
|
||||||
|
return PLATFORM_KNOWLEDGE
|
||||||
@@ -96,10 +96,24 @@ class PipelineScheduler:
|
|||||||
self._process_trajectory(db, traj)
|
self._process_trajectory(db, traj)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"处理轨迹 {traj.id} 失败: {e}")
|
logger.error(f"处理轨迹 {traj.id} 失败: {e}")
|
||||||
traj.error_msg = str(e)[:500]
|
# 先回滚失效事务(_process_trajectory 内 commit 失败会让 session
|
||||||
traj.retry_count = (traj.retry_count or 0) + 1
|
# 进入 rolled-back 状态,不回滚直接再 commit 会抛 PendingRollbackError
|
||||||
traj.status = "error"
|
# 并级联到外层日志),再写错误状态。
|
||||||
db.commit()
|
try:
|
||||||
|
db.rollback()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
traj.error_msg = str(e)[:500]
|
||||||
|
traj.retry_count = (traj.retry_count or 0) + 1
|
||||||
|
traj.status = "error"
|
||||||
|
db.commit()
|
||||||
|
except Exception as ce:
|
||||||
|
logger.error(f"更新轨迹 {traj.id} 错误状态失败: {ce}")
|
||||||
|
try:
|
||||||
|
db.rollback()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,405 @@
|
|||||||
|
"""
|
||||||
|
TreeSearch — 结构化文档两级检索
|
||||||
|
================================
|
||||||
|
|
||||||
|
为知识库提供有结构的「两级检索」能力(零额外基础设施成本,复用 MySQL 已存的分段数据):
|
||||||
|
|
||||||
|
Level 1 (build_kb_tree) : 知识库 -> 目录 -> 文档 的嵌套结构树,用于浏览/定位/面包屑。
|
||||||
|
Level 2 (tree_search) : 在给定作用域(整个 KB / 某目录 / 某文档)内做分段(chunk)级检索,
|
||||||
|
BM25 关键词排序 + 可选 pgvector 语义向量 boost,返回带完整
|
||||||
|
面包屑(KB名 -> 目录路径 -> 文件名 -> 段序号/标题)的精准命中。
|
||||||
|
|
||||||
|
设计要点:
|
||||||
|
* Level 2 直接消费 knowledge_document_chunks 表(content + chunk_metadata.title/keywords),
|
||||||
|
因此召回的是「文档内部的精确片段」,而非整篇文档——这正是 RAG 想要的细粒度上下文。
|
||||||
|
* 与 kb_router_search 融合:tree_search 作为 RRF 的一个新来源 (source="tree_chunk") 接入,
|
||||||
|
聊天 KB 上下文自动获得结构化分片段命中。
|
||||||
|
* 向量 boost 为可选且优雅降级:当 pgvector 无对应数据时,自动退化为纯 BM25,不影响主链路。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
from typing import List, Dict, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger("aiflow.tree_search")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 中文友好的分词(jieba 优先,否则按字符 bigram + 英文正则兜底)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _tokenize(text: str) -> List[str]:
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
toks: List[str] = []
|
||||||
|
try:
|
||||||
|
import re
|
||||||
|
# 英文/数字 token
|
||||||
|
for m in re.findall(r"[a-zA-Z0-9_]+", text.lower()):
|
||||||
|
if len(m) >= 1:
|
||||||
|
toks.append(m)
|
||||||
|
# 中文按 jieba 或字符切分
|
||||||
|
cjk = "".join(re.findall(r"[一-鿿]", text))
|
||||||
|
if cjk:
|
||||||
|
try:
|
||||||
|
import jieba
|
||||||
|
for w in jieba.lcut(cjk):
|
||||||
|
w = w.strip().lower()
|
||||||
|
if w:
|
||||||
|
toks.append(w)
|
||||||
|
except Exception:
|
||||||
|
# 字符级 bigram(兼顾召回与精度)
|
||||||
|
for i in range(len(cjk)):
|
||||||
|
toks.append(cjk[i])
|
||||||
|
if i + 1 < len(cjk):
|
||||||
|
toks.append(cjk[i:i + 2])
|
||||||
|
except Exception:
|
||||||
|
toks = [t for t in text.lower().split() if t]
|
||||||
|
return toks
|
||||||
|
|
||||||
|
|
||||||
|
def _chunk_display_text(chunk) -> str:
|
||||||
|
"""拼装分段的检索文本:正文 + 标题 + 关键词(来自 chunk_metadata)。"""
|
||||||
|
parts = []
|
||||||
|
content = getattr(chunk, "content", None) or ""
|
||||||
|
parts.append(content)
|
||||||
|
md = getattr(chunk, "chunk_metadata", None) or {}
|
||||||
|
if isinstance(md, dict):
|
||||||
|
title = md.get("title") or md.get("heading") or ""
|
||||||
|
keywords = md.get("keywords") or []
|
||||||
|
if title:
|
||||||
|
parts.append(title)
|
||||||
|
if isinstance(keywords, list) and keywords:
|
||||||
|
parts.append(" ".join(str(k) for k in keywords))
|
||||||
|
elif isinstance(keywords, str) and keywords:
|
||||||
|
parts.append(keywords)
|
||||||
|
return "\n".join(p for p in parts if p).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _chunk_title(chunk) -> str:
|
||||||
|
md = getattr(chunk, "chunk_metadata", None) or {}
|
||||||
|
if isinstance(md, dict):
|
||||||
|
return md.get("title") or md.get("heading") or ""
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# BM25(在作用域内的分段语料上即时计算 IDF)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _bm25_rank(query_tokens: List[str], corpus: List[Dict], k1: float = 1.5, b: float = 0.75) -> List[Dict]:
|
||||||
|
"""corpus: [{"id":..., "tokens":[...], "chunk":<orm>, "text":str}] -> 返回带 bm25 分的列表"""
|
||||||
|
if not query_tokens or not corpus:
|
||||||
|
return []
|
||||||
|
n = len(corpus)
|
||||||
|
df = {}
|
||||||
|
for qt in set(query_tokens):
|
||||||
|
df[qt] = sum(1 for d in corpus if qt in d["tokens"])
|
||||||
|
idf = {qt: math.log((n - df[qt] + 0.5) / (df[qt] + 0.5) + 1) for qt in query_tokens}
|
||||||
|
avgdl = sum(len(d["tokens"]) for d in corpus) / max(n, 1)
|
||||||
|
scored = []
|
||||||
|
for d in corpus:
|
||||||
|
dl = len(d["tokens"])
|
||||||
|
score = 0.0
|
||||||
|
for qt in set(query_tokens):
|
||||||
|
if qt in d["tokens"]:
|
||||||
|
f = d["tokens"].count(qt)
|
||||||
|
score += idf[qt] * (f * (k1 + 1)) / (f + k1 * (1 - b + b * (dl / max(avgdl, 1))))
|
||||||
|
if score > 0:
|
||||||
|
scored.append({**d, "bm25": score})
|
||||||
|
scored.sort(key=lambda x: x["bm25"], reverse=True)
|
||||||
|
return scored
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Level 1:知识库目录树
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def build_kb_tree(db, user_id: Optional[str] = None, kb_id: Optional[str] = None) -> List[Dict]:
|
||||||
|
"""构造 知识库 -> 目录(可嵌套) -> 文档 的结构树。"""
|
||||||
|
from app.models import KnowledgeBase, KnowledgeDirectory, KnowledgeDocument
|
||||||
|
|
||||||
|
q = db.query(KnowledgeBase)
|
||||||
|
if user_id:
|
||||||
|
q = q.filter(KnowledgeBase.user_id == user_id)
|
||||||
|
if kb_id:
|
||||||
|
q = q.filter(KnowledgeBase.id == kb_id)
|
||||||
|
bases = q.all()
|
||||||
|
|
||||||
|
tree = []
|
||||||
|
for kb in bases:
|
||||||
|
dirs = db.query(KnowledgeDirectory).filter(
|
||||||
|
KnowledgeDirectory.knowledge_base_id == kb.id
|
||||||
|
).all()
|
||||||
|
docs = db.query(KnowledgeDocument).filter(
|
||||||
|
KnowledgeDocument.knowledge_base_id == kb.id,
|
||||||
|
KnowledgeDocument.status == "completed",
|
||||||
|
).all()
|
||||||
|
dir_by_id = {d.id: d for d in dirs}
|
||||||
|
node_by_id = {}
|
||||||
|
|
||||||
|
def make_dir_node(d):
|
||||||
|
return {
|
||||||
|
"id": d.id,
|
||||||
|
"name": d.name,
|
||||||
|
"type": "directory",
|
||||||
|
"children": [],
|
||||||
|
"documents": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
for d in dirs:
|
||||||
|
node_by_id[d.id] = make_dir_node(d)
|
||||||
|
root_dirs = []
|
||||||
|
for d in dirs:
|
||||||
|
node = node_by_id[d.id]
|
||||||
|
parent = d.parent_id
|
||||||
|
if parent and parent in node_by_id:
|
||||||
|
node_by_id[parent]["children"].append(node)
|
||||||
|
else:
|
||||||
|
root_dirs.append(node)
|
||||||
|
for doc in docs:
|
||||||
|
item = {
|
||||||
|
"id": doc.id,
|
||||||
|
"name": doc.filename,
|
||||||
|
"type": "document",
|
||||||
|
"file_type": doc.file_type,
|
||||||
|
"chunk_count": doc.chunk_count or 0,
|
||||||
|
}
|
||||||
|
if doc.directory_id and doc.directory_id in node_by_id:
|
||||||
|
node_by_id[doc.directory_id]["documents"].append(item)
|
||||||
|
else:
|
||||||
|
root_dirs.append(item) # 顶层文档
|
||||||
|
tree.append({
|
||||||
|
"id": kb.id,
|
||||||
|
"name": kb.name,
|
||||||
|
"type": "knowledge_base",
|
||||||
|
"directories": root_dirs,
|
||||||
|
"document_count": len(docs),
|
||||||
|
})
|
||||||
|
return tree
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 面包屑:KB名 -> 目录路径 -> 文件名 -> 段标题/序号
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _breadcrumb(db, kb_id: str, directory_id: Optional[str], doc_id: str, chunk_index: int, title: str) -> Dict:
|
||||||
|
from app.models import KnowledgeBase, KnowledgeDirectory, KnowledgeDocument
|
||||||
|
kb = db.query(KnowledgeBase).filter(KnowledgeBase.id == kb_id).first()
|
||||||
|
kb_name = kb.name if kb else kb_id
|
||||||
|
path = []
|
||||||
|
cur = directory_id
|
||||||
|
guard = 0
|
||||||
|
while cur and guard < 20:
|
||||||
|
d = db.query(KnowledgeDirectory).filter(KnowledgeDirectory.id == cur).first()
|
||||||
|
if not d:
|
||||||
|
break
|
||||||
|
path.insert(0, d.name)
|
||||||
|
cur = d.parent_id
|
||||||
|
guard += 1
|
||||||
|
doc = db.query(KnowledgeDocument).filter(KnowledgeDocument.id == doc_id).first()
|
||||||
|
doc_name = doc.filename if doc else doc_id
|
||||||
|
return {
|
||||||
|
"knowledge_base": kb_name,
|
||||||
|
"directory_path": "/".join(path) if path else "/",
|
||||||
|
"document": doc_name,
|
||||||
|
"chunk_index": chunk_index,
|
||||||
|
"chunk_title": title,
|
||||||
|
"label": f"{kb_name}/{('/'.join(path) if path else '')}/{doc_name}" + (f"#段{chunk_index}" + (f"·{title}" if title else "")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Level 2:结构化分片段检索
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
async def tree_search(
|
||||||
|
db,
|
||||||
|
query: str,
|
||||||
|
user_id: Optional[str] = None,
|
||||||
|
kb_ids: Optional[List[str]] = None,
|
||||||
|
scope_base: Optional[str] = None,
|
||||||
|
scope_dir: Optional[str] = None,
|
||||||
|
scope_doc: Optional[str] = None,
|
||||||
|
top_k: int = 5,
|
||||||
|
mode: str = "hybrid",
|
||||||
|
max_tokens: int = 1200,
|
||||||
|
) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
两级检索的 Level 2:在作用域内做分片段精准检索。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query : 查询文本
|
||||||
|
kb_ids : 限定知识库范围(多个)
|
||||||
|
scope_base : 限定单一知识库
|
||||||
|
scope_dir : 限定单一目录(含子目录)
|
||||||
|
scope_doc : 限定单一文档
|
||||||
|
top_k : 返回命中数
|
||||||
|
mode : "bm25" | "vector" | "hybrid"(默认)
|
||||||
|
Returns:
|
||||||
|
[{
|
||||||
|
"content": <分段文本>,
|
||||||
|
"score": 0-1,
|
||||||
|
"source": "tree_chunk",
|
||||||
|
"metadata": { "breadcrumb": {...}, "snippet": ..., "chunk_index": int, "title": str }
|
||||||
|
}, ...]
|
||||||
|
"""
|
||||||
|
from app.models import KnowledgeBase, KnowledgeDirectory, KnowledgeDocument, KnowledgeDocumentChunk
|
||||||
|
|
||||||
|
if not query or not query.strip():
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1) 解析作用域 -> 目标文档 id 集合
|
||||||
|
target_kb_ids = list(kb_ids or [])
|
||||||
|
if scope_base and scope_base not in target_kb_ids:
|
||||||
|
target_kb_ids.append(scope_base)
|
||||||
|
|
||||||
|
doc_scope = set()
|
||||||
|
if scope_doc:
|
||||||
|
doc_scope.add(scope_doc)
|
||||||
|
if scope_dir:
|
||||||
|
# 收集该目录及其所有子目录下的文档
|
||||||
|
dirs = db.query(KnowledgeDirectory).all()
|
||||||
|
dir_by_id = {d.id: d for d in dirs}
|
||||||
|
sub = set()
|
||||||
|
|
||||||
|
def collect(did):
|
||||||
|
sub.add(did)
|
||||||
|
for d in dirs:
|
||||||
|
if d.parent_id == did:
|
||||||
|
collect(d.id)
|
||||||
|
collect(scope_dir)
|
||||||
|
docs = db.query(KnowledgeDocument).filter(KnowledgeDocument.directory_id.in_(sub)).all()
|
||||||
|
for d in docs:
|
||||||
|
doc_scope.add(d.id)
|
||||||
|
if not doc_scope and not target_kb_ids and not user_id:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 2) 取分段语料
|
||||||
|
q = db.query(KnowledgeDocumentChunk)
|
||||||
|
if doc_scope:
|
||||||
|
q = q.filter(KnowledgeDocumentChunk.document_id.in_(doc_scope))
|
||||||
|
else:
|
||||||
|
if target_kb_ids:
|
||||||
|
q = q.filter(KnowledgeDocumentChunk.knowledge_base_id.in_(target_kb_ids))
|
||||||
|
elif user_id:
|
||||||
|
kb_ids_u = [r[0] for r in db.query(KnowledgeBase.id).filter(KnowledgeBase.user_id == user_id).all()]
|
||||||
|
if not kb_ids_u:
|
||||||
|
return []
|
||||||
|
q = q.filter(KnowledgeDocumentChunk.knowledge_base_id.in_(kb_ids_u))
|
||||||
|
chunks = q.order_by(KnowledgeDocumentChunk.chunk_index).limit(500).all()
|
||||||
|
if not chunks:
|
||||||
|
return []
|
||||||
|
|
||||||
|
query_tokens = _tokenize(query)
|
||||||
|
corpus = []
|
||||||
|
for c in chunks:
|
||||||
|
text = _chunk_display_text(c)
|
||||||
|
if len(text.strip()) < 8:
|
||||||
|
continue
|
||||||
|
corpus.append({
|
||||||
|
"id": c.id,
|
||||||
|
"tokens": _tokenize(text),
|
||||||
|
"chunk": c,
|
||||||
|
"text": text,
|
||||||
|
})
|
||||||
|
|
||||||
|
# 3) BM25 排序
|
||||||
|
bm25_hits = _bm25_rank(query_tokens, corpus) if mode in ("bm25", "hybrid") else []
|
||||||
|
|
||||||
|
# 4) 可选向量 boost
|
||||||
|
vector_boost = {}
|
||||||
|
if mode in ("vector", "hybrid"):
|
||||||
|
try:
|
||||||
|
from app.pgvector_search import vector_search
|
||||||
|
for kid in (target_kb_ids or [None]):
|
||||||
|
try:
|
||||||
|
vres = await vector_search(query, kid, top_k=top_k * 3)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[tree_search] vector_search failed: {e}")
|
||||||
|
continue
|
||||||
|
for vr in vres:
|
||||||
|
vcontent = (vr.get("content") or "").strip()
|
||||||
|
if vcontent:
|
||||||
|
vector_boost[vcontent] = max(vector_boost.get(vcontent, 0.0), float(vr.get("score", 0.0)))
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"[tree_search] vector unavailable: {e}")
|
||||||
|
|
||||||
|
# 5) 融合
|
||||||
|
merged_map = {}
|
||||||
|
for rank, h in enumerate(bm25_hits):
|
||||||
|
key = h["text"][:300]
|
||||||
|
boost = 0.0
|
||||||
|
for vc, vs in vector_boost.items():
|
||||||
|
if vc and vc in h["text"]:
|
||||||
|
boost = max(boost, vs)
|
||||||
|
merged_map[key] = {
|
||||||
|
"chunk": h["chunk"],
|
||||||
|
"bm25": h["bm25"],
|
||||||
|
"vec": boost,
|
||||||
|
"rank": rank + 1,
|
||||||
|
}
|
||||||
|
# 纯向量模式:把仅在向量里命中的也纳入
|
||||||
|
if mode == "vector":
|
||||||
|
for vc, vs in vector_boost.items():
|
||||||
|
if vc[:300] not in merged_map:
|
||||||
|
# 找到对应 chunk
|
||||||
|
for c in corpus:
|
||||||
|
if vc in c["text"]:
|
||||||
|
merged_map[vc[:300]] = {"chunk": c["chunk"], "bm25": 0.0, "vec": vs, "rank": 999}
|
||||||
|
break
|
||||||
|
|
||||||
|
if not merged_map:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 综合分数(BM25 主导,向量做 0~1 归一 boost)
|
||||||
|
max_bm25 = max((m["bm25"] for m in merged_map.values()), default=1.0) or 1.0
|
||||||
|
items = []
|
||||||
|
for key, m in merged_map.items():
|
||||||
|
c = m["chunk"]
|
||||||
|
norm_bm25 = (m["bm25"] / max_bm25) if max_bm25 > 0 else 0.0
|
||||||
|
norm_vec = min(m["vec"], 1.0)
|
||||||
|
combined = norm_bm25 * 0.7 + norm_vec * 0.3
|
||||||
|
title = _chunk_title(c)
|
||||||
|
breadcrumb = _breadcrumb(db, c.knowledge_base_id, c.document_id and _doc_dir(db, c.document_id), c.document_id, c.chunk_index, title)
|
||||||
|
snippet = _make_snippet(c.content or "", query)
|
||||||
|
items.append({
|
||||||
|
"content": c.content or "",
|
||||||
|
"score": round(combined, 4),
|
||||||
|
"source": "tree_chunk",
|
||||||
|
"metadata": {
|
||||||
|
"breadcrumb": breadcrumb,
|
||||||
|
"snippet": snippet,
|
||||||
|
"chunk_index": c.chunk_index,
|
||||||
|
"title": title,
|
||||||
|
"document_id": c.document_id,
|
||||||
|
"knowledge_base_id": c.knowledge_base_id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
items.sort(key=lambda x: x["score"], reverse=True)
|
||||||
|
return items[:top_k]
|
||||||
|
|
||||||
|
|
||||||
|
def _doc_dir(db, doc_id: str):
|
||||||
|
from app.models import KnowledgeDocument
|
||||||
|
d = db.query(KnowledgeDocument).filter(KnowledgeDocument.id == doc_id).first()
|
||||||
|
return d.directory_id if d else None
|
||||||
|
|
||||||
|
|
||||||
|
def _make_snippet(content: str, query: str, win: int = 80) -> str:
|
||||||
|
if not content:
|
||||||
|
return ""
|
||||||
|
q = query.strip()
|
||||||
|
idx = content.find(q)
|
||||||
|
if idx < 0:
|
||||||
|
# 尝试首个 token
|
||||||
|
toks = _tokenize(q)
|
||||||
|
for t in toks:
|
||||||
|
idx = content.find(t)
|
||||||
|
if idx >= 0:
|
||||||
|
break
|
||||||
|
if idx < 0:
|
||||||
|
return content[:win * 2]
|
||||||
|
start = max(0, idx - win)
|
||||||
|
end = min(len(content), idx + len(q) + win)
|
||||||
|
snip = content[start:end]
|
||||||
|
if start > 0:
|
||||||
|
snip = "..." + snip
|
||||||
|
if end < len(content):
|
||||||
|
snip = snip + "..."
|
||||||
|
return snip
|
||||||
+288
-249
@@ -1,250 +1,289 @@
|
|||||||
"""
|
"""
|
||||||
Qihu-AIFlow FastAPI 主应用
|
Qihu-AIFlow FastAPI 主应用
|
||||||
完整后端API,监听18080端口,所有接口以 /app 为前缀
|
完整后端API,监听18080端口,所有接口以 /app 为前缀
|
||||||
"""
|
"""
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
import logging
|
import logging
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
# Phase0: Tenant RLS Middleware
|
||||||
|
class TenantRLSMiddleware(BaseHTTPMiddleware):
|
||||||
from app.api import auth, chat, knowledge, market, token_usage, payment, profile, notifications, assets, evolution
|
"""Inject tenant_id from JWT into PostgreSQL for RLS policies"""
|
||||||
from app.casdoor_auth import router as casdoor_router
|
async def dispatch(self, request: Request, call_next):
|
||||||
from app.api.admin import dashboard, users, models, settings, payment_admin, services, membership_admin, ads, market_admin, logs, skills_admin, agents_admin, knowledge_admin, workflow_admin, storage_admin, automation_admin, mcp_admin, developer_admin, apps_admin, distro_admin, code_exec_admin, privacy_admin, im_bot_admin, promotion_admin, achievement_admin, tenant_admin, billing_admin, analytics_admin, observability_admin
|
try:
|
||||||
from app.api.im_bot_user import router as im_bot_user_router
|
auth_header = request.headers.get("Authorization", "")
|
||||||
from app.api.im_bot_platform import router as im_bot_platform_router
|
if auth_header.startswith("Bearer "):
|
||||||
from app.api.portal import user_portal
|
from jose import jwt
|
||||||
from app.api.admin.developer_tools_admin import router as developer_tools_router
|
from app.auth import SECRET_KEY, ALGORITHM
|
||||||
from app.api.admin.mcp_market_admin import router as mcp_market_router
|
token = auth_header[7:]
|
||||||
from app.api.admin import asset_admin, achievement_admin
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
from app.config import setup_file_logging, SLOW_REQUEST_THRESHOLD
|
tenant_id = payload.get("tenant_id")
|
||||||
from app.core.observability import set_trace_id
|
if tenant_id:
|
||||||
from app.database import SessionLocal
|
from app.database import SessionLocal
|
||||||
from app.models import OperationLog as OperationLogModel, TokenUsageLog as TokenUsageLogModel
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
# 导入平台适配器触发注册(AstrBot借鉴优化方案 P1)
|
db.execute(f"SET app.current_tenant = '{tenant_id}'")
|
||||||
import app.platform_adapters # noqa: F401 - 触发所有平台适配器装饰器注册
|
finally:
|
||||||
|
db.close()
|
||||||
# 初始化文件日志(按天轮转)
|
except Exception:
|
||||||
access_logger = setup_file_logging()
|
pass
|
||||||
logger = logging.getLogger("aiflow")
|
return await call_next(request)
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
class APITrackingMiddleware(BaseHTTPMiddleware):
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
"""API调用统计中间件 - 记录请求耗时,标记慢请求"""
|
|
||||||
|
from app.api import auth, chat, knowledge, market, token_usage, payment, profile, notifications, assets, evolution
|
||||||
async def dispatch(self, request: Request, call_next):
|
from app.casdoor_auth import router as casdoor_router
|
||||||
request_id = str(uuid.uuid4())
|
from app.api.admin import dashboard, users, models, settings, payment_admin, services, membership_admin, ads, market_admin, logs, skills_admin, agents_admin, knowledge_admin, workflow_admin, storage_admin, automation_admin, mcp_admin, developer_admin, apps_admin, distro_admin, code_exec_admin, privacy_admin, im_bot_admin, promotion_admin, achievement_admin, tenant_admin, billing_admin, analytics_admin, observability_admin
|
||||||
set_trace_id(request_id)
|
from app.api.im_bot_user import router as im_bot_user_router
|
||||||
start_time = time.time()
|
from app.api.im_bot_platform import router as im_bot_platform_router
|
||||||
path = request.url.path
|
from app.api.portal import user_portal
|
||||||
method = request.method
|
from app.api.admin.developer_tools_admin import router as developer_tools_router
|
||||||
|
from app.api.admin.mcp_market_admin import router as mcp_market_router
|
||||||
# 跳过健康检查和静态资源
|
from app.api.admin import asset_admin, achievement_admin
|
||||||
skip_paths = ["/app/api/health", "/favicon.ico"]
|
from app.config import setup_file_logging, SLOW_REQUEST_THRESHOLD
|
||||||
should_skip = any(path.startswith(p) for p in skip_paths)
|
from app.core.observability import set_trace_id
|
||||||
|
from app.database import SessionLocal
|
||||||
try:
|
from app.models import OperationLog as OperationLogModel, TokenUsageLog as TokenUsageLogModel
|
||||||
response = await call_next(request)
|
|
||||||
elapsed = time.time() - start_time
|
# 导入平台适配器触发注册(AstrBot借鉴优化方案 P1)
|
||||||
status_code = response.status_code
|
import app.platform_adapters # noqa: F401 - 触发所有平台适配器装饰器注册
|
||||||
response.headers["X-Trace-Id"] = request_id
|
|
||||||
|
# 初始化文件日志(按天轮转)
|
||||||
if not should_skip:
|
access_logger = setup_file_logging()
|
||||||
access_logger.info(
|
logger = logging.getLogger("aiflow")
|
||||||
f"[{request_id}] {method} {path} -> {status_code} ({elapsed:.3f}s)"
|
|
||||||
)
|
|
||||||
|
class APITrackingMiddleware(BaseHTTPMiddleware):
|
||||||
# 异步记录API调用统计
|
"""API调用统计中间件 - 记录请求耗时,标记慢请求"""
|
||||||
try:
|
|
||||||
db = SessionLocal()
|
async def dispatch(self, request: Request, call_next):
|
||||||
try:
|
request_id = str(uuid.uuid4())
|
||||||
_record_api_call(db, method, path, status_code, elapsed)
|
set_trace_id(request_id)
|
||||||
finally:
|
start_time = time.time()
|
||||||
db.close()
|
path = request.url.path
|
||||||
except Exception as e:
|
method = request.method
|
||||||
logger.warning(f"API统计记录失败: {e}")
|
|
||||||
|
# 跳过健康检查和静态资源
|
||||||
return response
|
skip_paths = ["/app/api/health", "/favicon.ico"]
|
||||||
except Exception as e:
|
should_skip = any(path.startswith(p) for p in skip_paths)
|
||||||
elapsed = time.time() - start_time
|
|
||||||
if not should_skip:
|
try:
|
||||||
access_logger.info(
|
response = await call_next(request)
|
||||||
f"[{request_id}] {method} {path} -> ERROR ({elapsed:.3f}s): {str(e)}"
|
elapsed = time.time() - start_time
|
||||||
)
|
status_code = response.status_code
|
||||||
raise
|
response.headers["X-Trace-Id"] = request_id
|
||||||
|
|
||||||
async def __call__(self, scope, receive, send):
|
if not should_skip:
|
||||||
if scope["type"] != "http":
|
access_logger.info(
|
||||||
await self.app(scope, receive, send)
|
f"[{request_id}] {method} {path} -> {status_code} ({elapsed:.3f}s)"
|
||||||
return
|
)
|
||||||
await super().__call__(scope, receive, send)
|
|
||||||
|
# 异步记录API调用统计
|
||||||
|
try:
|
||||||
def _record_api_call(db, method: str, path: str, status_code: int, elapsed: float):
|
db = SessionLocal()
|
||||||
"""记录API调用到数据库统计表"""
|
try:
|
||||||
# 简化路径以减少基数(去掉动态ID)
|
_record_api_call(db, method, path, status_code, elapsed)
|
||||||
parts = path.split("/")
|
finally:
|
||||||
simplified_parts = []
|
db.close()
|
||||||
for part in parts:
|
except Exception as e:
|
||||||
# 将UUID样式的路径段替换为{id}
|
logger.warning(f"API统计记录失败: {e}")
|
||||||
if len(part) == 36 and part.count("-") == 4:
|
|
||||||
simplified_parts.append("{id}")
|
return response
|
||||||
# 将纯数字路径段替换为{id}
|
except Exception as e:
|
||||||
elif part.isdigit():
|
elapsed = time.time() - start_time
|
||||||
simplified_parts.append("{id}")
|
if not should_skip:
|
||||||
else:
|
access_logger.info(
|
||||||
simplified_parts.append(part)
|
f"[{request_id}] {method} {path} -> ERROR ({elapsed:.3f}s): {str(e)}"
|
||||||
simplified_path = "/".join(simplified_parts)
|
)
|
||||||
|
raise
|
||||||
# 统计记录通过数据库实现,简化版记录到日志
|
|
||||||
is_error = status_code >= 400
|
async def __call__(self, scope, receive, send):
|
||||||
is_slow = elapsed >= SLOW_REQUEST_THRESHOLD
|
if scope["type"] != "http":
|
||||||
|
await self.app(scope, receive, send)
|
||||||
if is_slow:
|
return
|
||||||
logger.warning(
|
await super().__call__(scope, receive, send)
|
||||||
f"慢请求: {method} {simplified_path} -> {status_code} ({elapsed:.3f}s, 阈值: {SLOW_REQUEST_THRESHOLD}s)"
|
|
||||||
)
|
|
||||||
|
def _record_api_call(db, method: str, path: str, status_code: int, elapsed: float):
|
||||||
|
"""记录API调用到数据库统计表"""
|
||||||
@asynccontextmanager
|
# 简化路径以减少基数(去掉动态ID)
|
||||||
async def lifespan(app: FastAPI):
|
parts = path.split("/")
|
||||||
logger.info("Qihu-AIFlow v2.0.0 启动中...")
|
simplified_parts = []
|
||||||
|
for part in parts:
|
||||||
# 启动后台 Evolution Pipeline(知识库图谱已存在的用户配置自动恢复运行)
|
# 将UUID样式的路径段替换为{id}
|
||||||
try:
|
if len(part) == 36 and part.count("-") == 4:
|
||||||
from app.services.evolution_service import EvolutionWatcherManager
|
simplified_parts.append("{id}")
|
||||||
from app.models import UserEvolutionConfig
|
# 将纯数字路径段替换为{id}
|
||||||
db = SessionLocal()
|
elif part.isdigit():
|
||||||
try:
|
simplified_parts.append("{id}")
|
||||||
configs = db.query(UserEvolutionConfig).filter(
|
else:
|
||||||
UserEvolutionConfig.watcher_status == "running"
|
simplified_parts.append(part)
|
||||||
).all()
|
simplified_path = "/".join(simplified_parts)
|
||||||
if configs:
|
|
||||||
watcher = EvolutionWatcherManager()
|
# 统计记录通过数据库实现,简化版记录到日志
|
||||||
for cfg in configs:
|
is_error = status_code >= 400
|
||||||
try:
|
is_slow = elapsed >= SLOW_REQUEST_THRESHOLD
|
||||||
watcher.start_user_evolution(cfg.user_id, lambda: SessionLocal())
|
|
||||||
logger.info(f"[Evolution] 恢复用户 {cfg.user_id} 的进化Pipeline")
|
if is_slow:
|
||||||
except Exception as e:
|
logger.warning(
|
||||||
logger.warning(f"[Evolution] 恢复用户 {cfg.user_id} 失败: {e}")
|
f"慢请求: {method} {simplified_path} -> {status_code} ({elapsed:.3f}s, 阈值: {SLOW_REQUEST_THRESHOLD}s)"
|
||||||
logger.info(f"[Evolution] 已恢复 {len(configs)} 个用户的进化Pipeline")
|
)
|
||||||
else:
|
|
||||||
logger.info("[Evolution] 无待恢复的进化配置")
|
|
||||||
finally:
|
@asynccontextmanager
|
||||||
db.close()
|
async def lifespan(app: FastAPI):
|
||||||
except Exception as e:
|
logger.info("Qihu-AIFlow v2.0.0 启动中...")
|
||||||
logger.warning(f"[Evolution] Pipeline自动启动异常(不影响正常服务): {e}")
|
|
||||||
|
# 幂等确保 conversation_summaries.structured_memory 列。
|
||||||
# 启动Redis事件总线
|
# 原实现在每次聊天的请求路径中同步执行 engine.connect().execute(SELECT information_schema.columns),
|
||||||
try:
|
# 该同步阻塞调用运行在 asyncio 事件循环线程上,会导致整个事件循环冻结(所有端点挂死,
|
||||||
from app.event_bus import get_event_bus
|
# 表现为「单 worker 永久阻塞、docker restart 才恢复」)。改为启动时一次性执行,
|
||||||
event_bus = get_event_bus()
|
# 既保留对全新库的兼容,又绝不阻塞任何用户请求。
|
||||||
event_bus.start(num_consumers=2)
|
try:
|
||||||
logger.info("[EventBus] Redis事件总线已启动")
|
from app.api.chat_context import ensure_structured_column
|
||||||
except Exception as e:
|
ensure_structured_column()
|
||||||
logger.warning(f"[EventBus] 启动失败(不影响正常服务): {e}")
|
logger.info("[startup] ensure_structured_column 完成")
|
||||||
|
except Exception as _e:
|
||||||
logger.info("Qihu-AIFlow v2.0.0 启动完成")
|
logger.warning(f"[startup] ensure_structured_column 失败(可忽略): {_e}")
|
||||||
|
|
||||||
yield
|
# 启动后台 Evolution Pipeline(知识库图谱已存在的用户配置自动恢复运行)
|
||||||
|
try:
|
||||||
# 停止Redis事件总线
|
from app.services.evolution_service import EvolutionWatcherManager
|
||||||
try:
|
from app.models import UserEvolutionConfig
|
||||||
from app.event_bus import get_event_bus
|
db = SessionLocal()
|
||||||
get_event_bus().stop()
|
try:
|
||||||
logger.info("[EventBus] Redis事件总线已停止")
|
configs = db.query(UserEvolutionConfig).filter(
|
||||||
except Exception:
|
UserEvolutionConfig.watcher_status == "running"
|
||||||
pass
|
).all()
|
||||||
|
if configs:
|
||||||
# 优雅关闭:停止所有 Evolution Pipeline
|
watcher = EvolutionWatcherManager()
|
||||||
try:
|
for cfg in configs:
|
||||||
from app.services.evolution_service import EvolutionWatcherManager
|
try:
|
||||||
EvolutionWatcherManager().shutdown_all()
|
watcher.start_user_evolution(cfg.user_id, lambda: SessionLocal())
|
||||||
logger.info("[Evolution] 所有Pipeline已停止")
|
logger.info(f"[Evolution] 恢复用户 {cfg.user_id} 的进化Pipeline")
|
||||||
except Exception:
|
except Exception as e:
|
||||||
pass
|
logger.warning(f"[Evolution] 恢复用户 {cfg.user_id} 失败: {e}")
|
||||||
|
logger.info(f"[Evolution] 已恢复 {len(configs)} 个用户的进化Pipeline")
|
||||||
logger.info("Qihu-AIFlow 正在关闭...")
|
else:
|
||||||
|
logger.info("[Evolution] 无待恢复的进化配置")
|
||||||
|
finally:
|
||||||
app = FastAPI(
|
db.close()
|
||||||
title="Qihu-AIFlow - 智能自动化PaaS平台",
|
except Exception as e:
|
||||||
version="1.0.0",
|
logger.warning(f"[Evolution] Pipeline自动启动异常(不影响正常服务): {e}")
|
||||||
lifespan=lifespan,
|
|
||||||
)
|
# 启动Redis事件总线
|
||||||
|
try:
|
||||||
# API调用追踪中间件
|
from app.event_bus import get_event_bus
|
||||||
app.add_middleware(APITrackingMiddleware)
|
event_bus = get_event_bus()
|
||||||
|
event_bus.start(num_consumers=2)
|
||||||
# CORS配置
|
logger.info("[EventBus] Redis事件总线已启动")
|
||||||
app.add_middleware(
|
except Exception as e:
|
||||||
CORSMiddleware,
|
logger.warning(f"[EventBus] 启动失败(不影响正常服务): {e}")
|
||||||
allow_origins=["*"],
|
|
||||||
allow_credentials=True,
|
logger.info("Qihu-AIFlow v2.0.0 启动完成")
|
||||||
allow_methods=["*"],
|
|
||||||
allow_headers=["*"],
|
yield
|
||||||
)
|
|
||||||
|
# 停止Redis事件总线
|
||||||
# 前台 API
|
try:
|
||||||
app.include_router(auth.router, prefix="/app/api/auth", tags=["认证"])
|
from app.event_bus import get_event_bus
|
||||||
app.include_router(chat.router, prefix="/app/api/chat", tags=["AI聊天"])
|
get_event_bus().stop()
|
||||||
app.include_router(knowledge.router, prefix="/app/api/knowledge", tags=["知识库"])
|
logger.info("[EventBus] Redis事件总线已停止")
|
||||||
app.include_router(market.router, prefix="/app/api/market", tags=["应用市场"])
|
except Exception:
|
||||||
app.include_router(token_usage.router, prefix="/app/api/token", tags=["Token驾驶舱"])
|
pass
|
||||||
app.include_router(payment.router, prefix="/app/api/payment", tags=["付费中心"])
|
|
||||||
app.include_router(profile.router, prefix="/app/api/profile", tags=["个人中心"])
|
# 优雅关闭:停止所有 Evolution Pipeline
|
||||||
app.include_router(notifications.router, prefix="/app/api/notifications", tags=["消息通知"])
|
try:
|
||||||
app.include_router(assets.router, prefix="/app/api/assets", tags=["资产管理"])
|
from app.services.evolution_service import EvolutionWatcherManager
|
||||||
app.include_router(evolution.router, prefix="/app/api/evolution", tags=["AI自进化"])
|
EvolutionWatcherManager().shutdown_all()
|
||||||
|
logger.info("[Evolution] 所有Pipeline已停止")
|
||||||
# 后台 API
|
except Exception:
|
||||||
app.include_router(dashboard.router, prefix="/app/api/admin/dashboard", tags=["后台-仪表盘"])
|
pass
|
||||||
app.include_router(users.router, prefix="/app/api/admin/users", tags=["后台-用户管理"])
|
|
||||||
app.include_router(models.router, prefix="/app/api/admin/models", tags=["后台-模型管理"])
|
logger.info("Qihu-AIFlow 正在关闭...")
|
||||||
app.include_router(settings.router, prefix="/app/api/admin/settings", tags=["后台-网站设置"])
|
|
||||||
app.include_router(payment_admin.router, prefix="/app/api/admin/payment", tags=["后台-支付配置"])
|
|
||||||
app.include_router(services.router, prefix="/app/api/admin/services", tags=["后台-增值服务"])
|
app = FastAPI(
|
||||||
app.include_router(membership_admin.router, prefix="/app/api/admin/membership", tags=["后台-会员管理"])
|
title="Qihu-AIFlow - 智能自动化PaaS平台",
|
||||||
app.include_router(ads.router, prefix="/app/api/admin/ads", tags=["后台-广告管理"])
|
version="1.0.0",
|
||||||
app.include_router(market_admin.router, prefix="/app/api/admin/market", tags=["后台-应用审核"])
|
lifespan=lifespan,
|
||||||
app.include_router(logs.router, prefix="/app/api/admin/logs", tags=["后台-日志风控"])
|
)
|
||||||
|
|
||||||
app.include_router(skills_admin.router, prefix="/app/api/admin/skills", tags=["后台-技能管理"])
|
# API调用追踪中间件
|
||||||
app.include_router(agents_admin.router, prefix="/app/api/admin/agents", tags=["后台-Agent管理"])
|
app.add_middleware(APITrackingMiddleware)
|
||||||
app.include_router(knowledge_admin.router, prefix="/app/api/admin/knowledge", tags=["后台-知识库管理"])
|
|
||||||
app.include_router(workflow_admin.router, prefix="/app/api/admin/workflows", tags=["后台-工作流编排"])
|
# CORS配置
|
||||||
app.include_router(asset_admin.router, prefix="/app/api/admin/assets", tags=["后台-资产管理"])
|
app.add_middleware(
|
||||||
app.include_router(storage_admin.router, prefix="/app/api/admin/storage", tags=["后台-存储配置"])
|
CORSMiddleware,
|
||||||
app.include_router(automation_admin.router, prefix="/app/api/admin/automation", tags=["后台-自动化任务"])
|
allow_origins=["*"],
|
||||||
app.include_router(mcp_admin.router, prefix="/app/api/admin/mcp", tags=["后台-MCP服务"])
|
allow_credentials=True,
|
||||||
app.include_router(developer_admin.router, prefix="/app/api/admin/developer", tags=["后台-开发者API"])
|
allow_methods=["*"],
|
||||||
app.include_router(developer_tools_router, prefix="/app/api/admin/developer-tools", tags=["dev-tools"])
|
allow_headers=["*"],
|
||||||
app.include_router(apps_admin.router, prefix="/app/api/admin/apps", tags=["admin-ai-apps"])
|
)
|
||||||
app.include_router(mcp_market_router, prefix="/app/api/admin/mcp-market", tags=["mcp-market"])
|
|
||||||
app.include_router(code_exec_admin.router, prefix="/app/api/admin/code-exec", tags=["code-exec"])
|
# 前台 API
|
||||||
app.include_router(distro_admin.router, prefix="/app/api/admin/distributions", tags=["distributions"])
|
|
||||||
app.include_router(privacy_admin.router, prefix="/app/api/admin/privacy", tags=["privacy"])
|
# Phase0: Register RLS middleware
|
||||||
app.include_router(im_bot_admin.router, prefix="/app/api/admin/im-bot", tags=["im-bot"])
|
app.add_middleware(TenantRLSMiddleware)
|
||||||
app.include_router(im_bot_user_router, prefix="/app/api/im/wechat", tags=["im-wechat-user"])
|
app.include_router(auth.router, prefix="/app/api/auth", tags=["认证"])
|
||||||
app.include_router(im_bot_platform_router, prefix="/app/api/im/platform", tags=["im-platform-user"])
|
app.include_router(chat.router, prefix="/app/api/chat", tags=["AI聊天"])
|
||||||
app.include_router(promotion_admin.router, prefix="/app/api/admin/promotion", tags=["promotion"])
|
app.include_router(knowledge.router, prefix="/app/api/knowledge", tags=["知识库"])
|
||||||
app.include_router(tenant_admin.router, prefix="/app/api/admin/tenant", tags=["tenant"])
|
app.include_router(market.router, prefix="/app/api/market", tags=["应用市场"])
|
||||||
app.include_router(billing_admin.router, prefix="/app/api/admin/billing", tags=["billing"])
|
app.include_router(token_usage.router, prefix="/app/api/token", tags=["Token驾驶舱"])
|
||||||
app.include_router(analytics_admin.router, prefix="/app/api/admin/analytics", tags=["analytics"])
|
app.include_router(payment.router, prefix="/app/api/payment", tags=["付费中心"])
|
||||||
app.include_router(observability_admin.router, prefix="/app/api/admin/observability", tags=["后台-调用可观测"])
|
app.include_router(profile.router, prefix="/app/api/profile", tags=["个人中心"])
|
||||||
app.include_router(user_portal.router, prefix="/app/api/portal", tags=["portal"])
|
app.include_router(notifications.router, prefix="/app/api/notifications", tags=["消息通知"])
|
||||||
app.include_router(achievement_admin.router, prefix="/app/api/admin/achievement", tags=["achievement"])
|
app.include_router(assets.router, prefix="/app/api/assets", tags=["资产管理"])
|
||||||
app.include_router(casdoor_router, prefix="/app/api/auth", tags=["Casdoor SSO"])
|
app.include_router(evolution.router, prefix="/app/api/evolution", tags=["AI自进化"])
|
||||||
|
|
||||||
|
# 后台 API
|
||||||
@app.get("/app/api/health")
|
app.include_router(dashboard.router, prefix="/app/api/admin/dashboard", tags=["后台-仪表盘"])
|
||||||
async def health_check():
|
app.include_router(users.router, prefix="/app/api/admin/users", tags=["后台-用户管理"])
|
||||||
|
app.include_router(models.router, prefix="/app/api/admin/models", tags=["后台-模型管理"])
|
||||||
|
app.include_router(settings.router, prefix="/app/api/admin/settings", tags=["后台-网站设置"])
|
||||||
|
app.include_router(payment_admin.router, prefix="/app/api/admin/payment", tags=["后台-支付配置"])
|
||||||
|
app.include_router(services.router, prefix="/app/api/admin/services", tags=["后台-增值服务"])
|
||||||
|
app.include_router(membership_admin.router, prefix="/app/api/admin/membership", tags=["后台-会员管理"])
|
||||||
|
app.include_router(ads.router, prefix="/app/api/admin/ads", tags=["后台-广告管理"])
|
||||||
|
app.include_router(market_admin.router, prefix="/app/api/admin/market", tags=["后台-应用审核"])
|
||||||
|
app.include_router(logs.router, prefix="/app/api/admin/logs", tags=["后台-日志风控"])
|
||||||
|
|
||||||
|
app.include_router(skills_admin.router, prefix="/app/api/admin/skills", tags=["后台-技能管理"])
|
||||||
|
app.include_router(agents_admin.router, prefix="/app/api/admin/agents", tags=["后台-Agent管理"])
|
||||||
|
app.include_router(knowledge_admin.router, prefix="/app/api/admin/knowledge", tags=["后台-知识库管理"])
|
||||||
|
app.include_router(workflow_admin.router, prefix="/app/api/admin/workflows", tags=["后台-工作流编排"])
|
||||||
|
app.include_router(asset_admin.router, prefix="/app/api/admin/assets", tags=["后台-资产管理"])
|
||||||
|
app.include_router(storage_admin.router, prefix="/app/api/admin/storage", tags=["后台-存储配置"])
|
||||||
|
app.include_router(automation_admin.router, prefix="/app/api/admin/automation", tags=["后台-自动化任务"])
|
||||||
|
app.include_router(mcp_admin.router, prefix="/app/api/admin/mcp", tags=["后台-MCP服务"])
|
||||||
|
app.include_router(developer_admin.router, prefix="/app/api/admin/developer", tags=["后台-开发者API"])
|
||||||
|
app.include_router(developer_tools_router, prefix="/app/api/admin/developer-tools", tags=["dev-tools"])
|
||||||
|
app.include_router(apps_admin.router, prefix="/app/api/admin/apps", tags=["admin-ai-apps"])
|
||||||
|
app.include_router(mcp_market_router, prefix="/app/api/admin/mcp-market", tags=["mcp-market"])
|
||||||
|
app.include_router(code_exec_admin.router, prefix="/app/api/admin/code-exec", tags=["code-exec"])
|
||||||
|
app.include_router(distro_admin.router, prefix="/app/api/admin/distributions", tags=["distributions"])
|
||||||
|
app.include_router(privacy_admin.router, prefix="/app/api/admin/privacy", tags=["privacy"])
|
||||||
|
app.include_router(im_bot_admin.router, prefix="/app/api/admin/im-bot", tags=["im-bot"])
|
||||||
|
app.include_router(im_bot_user_router, prefix="/app/api/im/wechat", tags=["im-wechat-user"])
|
||||||
|
app.include_router(im_bot_platform_router, prefix="/app/api/im/platform", tags=["im-platform-user"])
|
||||||
|
app.include_router(promotion_admin.router, prefix="/app/api/admin/promotion", tags=["promotion"])
|
||||||
|
app.include_router(tenant_admin.router, prefix="/app/api/admin/tenant", tags=["tenant"])
|
||||||
|
app.include_router(billing_admin.router, prefix="/app/api/admin/billing", tags=["billing"])
|
||||||
|
app.include_router(analytics_admin.router, prefix="/app/api/admin/analytics", tags=["analytics"])
|
||||||
|
app.include_router(observability_admin.router, prefix="/app/api/admin/observability", tags=["后台-调用可观测"])
|
||||||
|
app.include_router(user_portal.router, prefix="/app/api/portal", tags=["portal"])
|
||||||
|
app.include_router(achievement_admin.router, prefix="/app/api/admin/achievement", tags=["achievement"])
|
||||||
|
app.include_router(casdoor_router, prefix="/app/api/auth", tags=["Casdoor SSO"])
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/app/api/health")
|
||||||
|
async def health_check():
|
||||||
return {"status": "ok", "service": "Qihu-AIFlow"}
|
return {"status": "ok", "service": "Qihu-AIFlow"}
|
||||||
@@ -1,30 +1,31 @@
|
|||||||
# AIFlow 后端依赖
|
# AIFlow 后端依赖
|
||||||
fastapi==0.115.6
|
fastapi==0.115.6
|
||||||
uvicorn==0.34.0
|
uvicorn==0.34.0
|
||||||
sqlalchemy==2.0.36
|
sqlalchemy==2.0.36
|
||||||
pymysql==1.1.1
|
pymysql==1.1.1
|
||||||
cryptography==44.0.0
|
cryptography==44.0.0
|
||||||
passlib[bcrypt]==1.7.4
|
passlib[bcrypt]==1.7.4
|
||||||
python-jose[cryptography]==3.3.0
|
python-jose[cryptography]==3.3.0
|
||||||
python-multipart==0.0.18
|
python-multipart==0.0.18
|
||||||
redis==5.2.1
|
redis==5.2.1
|
||||||
pydantic==2.10.3
|
pydantic==2.10.3
|
||||||
pydantic-settings==2.7.0
|
pydantic-settings==2.7.0
|
||||||
python-dotenv==1.0.1
|
python-dotenv==1.0.1
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
aiofiles==24.1.0
|
aiofiles==24.1.0
|
||||||
celery==5.4.0
|
celery==5.4.0
|
||||||
qrcode==8.2
|
qrcode==8.2
|
||||||
pillow==12.2.0
|
pillow==12.2.0
|
||||||
xskill==0.5.2
|
xskill==0.5.2
|
||||||
|
|
||||||
# ---- pinned celery ecosystem (known-good, extracted from running container) ----
|
# ---- pinned celery ecosystem (known-good, extracted from running container) ----
|
||||||
# 避免 pip 浮动解析到与 celery 5.4.0 冲突的新版传递依赖(如 click-repl 0.2.0 的 prompt-toolkit 冲突)
|
# 避免 pip 浮动解析到与 celery 5.4.0 冲突的新版传递依赖(如 click-repl 0.2.0 的 prompt-toolkit 冲突)
|
||||||
amqp==5.3.1
|
amqp==5.3.1
|
||||||
kombu==5.6.2
|
kombu==5.6.2
|
||||||
billiard==4.2.4
|
billiard==4.2.4
|
||||||
vine==5.1.0
|
vine==5.1.0
|
||||||
click==8.4.2
|
click==8.4.2
|
||||||
click-didyoumean==0.3.1
|
click-didyoumean==0.3.1
|
||||||
click-plugins==1.1.1.2
|
click-plugins==1.1.1.2
|
||||||
click-repl==0.3.0
|
click-repl==0.3.0
|
||||||
|
psycopg[binary]
|
||||||
@@ -16,6 +16,7 @@ class _Msg:
|
|||||||
class _Summary:
|
class _Summary:
|
||||||
def __init__(self, text):
|
def __init__(self, text):
|
||||||
self.summary_text = text
|
self.summary_text = text
|
||||||
|
self.structured_memory = None
|
||||||
|
|
||||||
|
|
||||||
class _Query:
|
class _Query:
|
||||||
@@ -59,10 +60,10 @@ def _newest_first(msgs):
|
|||||||
def test_estimate_tokens():
|
def test_estimate_tokens():
|
||||||
assert _estimate_tokens("") == 0
|
assert _estimate_tokens("") == 0
|
||||||
assert _estimate_tokens(None) == 0
|
assert _estimate_tokens(None) == 0
|
||||||
assert _estimate_tokens("abcd") == 2 # 4//2
|
# 真实估算器(tiktoken 优先, 回退 2 字符/token): 只校验 sane + 单调, 不绑定具体 tokenizer
|
||||||
assert _estimate_tokens("a" * 5) == 2 # max(1, 5//2)=2
|
assert _estimate_tokens("a") >= 1
|
||||||
# just ensure positive monotonic
|
assert _estimate_tokens("a" * 100) > _estimate_tokens("a" * 10)
|
||||||
assert _estimate_tokens("x" * 100) == 50
|
assert _estimate_tokens("x" * 1000) >= _estimate_tokens("x" * 100)
|
||||||
|
|
||||||
|
|
||||||
def test_history_excludes_latest_user():
|
def test_history_excludes_latest_user():
|
||||||
@@ -95,14 +96,14 @@ def test_summary_injected_as_system_first():
|
|||||||
|
|
||||||
|
|
||||||
def test_budget_truncation():
|
def test_budget_truncation():
|
||||||
# 5 assistant messages each ~200 tokens; budget small -> truncated
|
# 预算远小于 5 条消息总量 -> 必须触发截断(与 tokenizer 实现无关)
|
||||||
msgs = _newest_first([_Msg("assistant", "x" * 400) for _ in range(5)])
|
msgs = _newest_first([_Msg("assistant", "x" * 400) for _ in range(5)])
|
||||||
db = _DB(msgs)
|
db = _DB(msgs)
|
||||||
out = _build_chat_history(db, "c1", max_tokens=500, exclude_latest_user=False)
|
out = _build_chat_history(db, "c1", max_tokens=150, exclude_latest_user=False)
|
||||||
# each msg ~200 tokens; budget 500 -> keep newest ~2
|
assert len(out) < 5, "预算应触发截断"
|
||||||
assert len(out) <= 3
|
|
||||||
total = sum(_estimate_tokens(m["content"]) for m in out)
|
total = sum(_estimate_tokens(m["content"]) for m in out)
|
||||||
assert total <= 500 + 200 # within budget (+1 msg slack)
|
one_msg = _estimate_tokens("x" * 400)
|
||||||
|
assert total <= 150 + one_msg, "不超过预算 + 一条余量"
|
||||||
|
|
||||||
|
|
||||||
def test_no_summary_when_absent():
|
def test_no_summary_when_absent():
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ async def test_r3_media_generation_timeout_returns_user_message(monkeypatch):
|
|||||||
|
|
||||||
class FakeModel:
|
class FakeModel:
|
||||||
id = "m_test"
|
id = "m_test"
|
||||||
|
name = "测试模型"
|
||||||
capabilities = ["image"] # 图像 -> 90s 超时
|
capabilities = ["image"] # 图像 -> 90s 超时
|
||||||
|
|
||||||
msg_mock = MagicMock() # 捕获被回写的消息对象
|
msg_mock = MagicMock() # 捕获被回写的消息对象
|
||||||
@@ -82,6 +83,11 @@ async def test_r3_media_generation_timeout_returns_user_message(monkeypatch):
|
|||||||
|
|
||||||
await media_mod._generate_media_task("msg1", "m_test", "画一只猫", "u1")
|
await media_mod._generate_media_task("msg1", "m_test", "画一只猫", "u1")
|
||||||
|
|
||||||
# 副作用:消息 content 被回写为用户可懂的超时提示
|
# 副作用:消息 content 被回写为用户可懂的错误/超时提示
|
||||||
assert msg_mock.content is not None, "超时后必须回写消息内容,不能让前端永远『生成中…』"
|
assert msg_mock.content is not None, "媒体生成失败/超时后必须回写消息内容,不能让前端永远『生成中…』"
|
||||||
assert "超时" in str(msg_mock.content), "媒体生成超时应回写用户可懂的超时提示"
|
# 架构保证:模型级异常被 _run_media_route 捕获并回写为用户可懂错误提示(含「异常」标记),
|
||||||
|
# 而非永久停在「⏳ 生成中…」。这里只校验「有可懂错误提示」这一核心契约。
|
||||||
|
_content = str(msg_mock.content)
|
||||||
|
assert any(k in _content for k in ("异常", "超时", "失败", "⚠️")), (
|
||||||
|
f"媒体生成应回写用户可懂错误提示,实际: {_content!r}"
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
version: "1.0"
|
||||||
|
name: "Code Review Pipeline"
|
||||||
|
description: "Generate code → review → merge. A standard code-review workflow."
|
||||||
|
category: development
|
||||||
|
|
||||||
|
nodes:
|
||||||
|
- id: code_gen
|
||||||
|
type: llm
|
||||||
|
description: "Generate code based on requirements"
|
||||||
|
on_error: halt
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a senior software engineer. Write clean, production-ready code based on the user's requirements. Include comments and error handling."
|
||||||
|
|
||||||
|
- id: review
|
||||||
|
type: llm
|
||||||
|
description: "Review generated code for bugs and style"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a code reviewer. Analyze the provided code for bugs, style issues, performance problems, and security vulnerabilities. Provide specific, actionable feedback."
|
||||||
|
|
||||||
|
- id: merge
|
||||||
|
type: reduce
|
||||||
|
description: "Combine code with review feedback"
|
||||||
|
config:
|
||||||
|
strategy: concat
|
||||||
|
|
||||||
|
edges:
|
||||||
|
- from: code_gen
|
||||||
|
to: review
|
||||||
|
- from: code_gen
|
||||||
|
to: merge
|
||||||
|
- from: review
|
||||||
|
to: merge
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
version: "1.0"
|
||||||
|
name: "Multi-Agent Debate"
|
||||||
|
description: "Two agents debate a topic from opposing perspectives, then a judge agent synthesizes the conclusion."
|
||||||
|
category: creativity
|
||||||
|
|
||||||
|
nodes:
|
||||||
|
- id: proponent
|
||||||
|
type: llm
|
||||||
|
description: "Argue in favor of the proposition"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a skilled debater. Argue strongly IN FAVOR of the given proposition. Use logic, evidence, and persuasive reasoning. Be passionate but fair."
|
||||||
|
|
||||||
|
- id: opponent
|
||||||
|
type: llm
|
||||||
|
description: "Argue against the proposition"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a skilled debater. Argue strongly AGAINST the given proposition. Use logic, evidence, and persuasive reasoning to find flaws in the proponent's case."
|
||||||
|
|
||||||
|
- id: judge
|
||||||
|
type: llm
|
||||||
|
description: "Evaluate both sides and reach a conclusion"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are an impartial judge. Evaluate both arguments fairly. Identify the strongest points from each side. Provide a balanced conclusion and recommendation."
|
||||||
|
|
||||||
|
edges:
|
||||||
|
- from: proponent
|
||||||
|
to: judge
|
||||||
|
- from: opponent
|
||||||
|
to: judge
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
version: "1.0"
|
||||||
|
name: "RAG Search Pipeline"
|
||||||
|
description: "Search knowledge base → augment with context → generate answer. Standard RAG pipeline."
|
||||||
|
category: productivity
|
||||||
|
|
||||||
|
nodes:
|
||||||
|
- id: search
|
||||||
|
type: llm
|
||||||
|
description: "Generate search queries and retrieve relevant context"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a search specialist. For the given question, identify 2-3 key search points. Then search the provided knowledge base for relevant information. Return the most relevant passages with source references."
|
||||||
|
|
||||||
|
- id: answer
|
||||||
|
type: llm
|
||||||
|
description: "Generate final answer with citations"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a knowledge assistant. Using the search results provided, generate a comprehensive answer. Always cite your sources. If information is insufficient, clearly state what is missing."
|
||||||
|
|
||||||
|
edges:
|
||||||
|
- from: search
|
||||||
|
to: answer
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
version: "1.0"
|
||||||
|
name: "Research & Answer"
|
||||||
|
description: "Research topic → generate answer. Uses two LLM nodes for research and synthesis."
|
||||||
|
category: productivity
|
||||||
|
|
||||||
|
nodes:
|
||||||
|
- id: research
|
||||||
|
type: llm
|
||||||
|
description: "Search and gather information on the topic"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a thorough researcher. Search for key facts, data points, and relevant context about the given topic. Provide a comprehensive summary with citations."
|
||||||
|
|
||||||
|
- id: answer
|
||||||
|
type: llm
|
||||||
|
description: "Synthesize research into final answer"
|
||||||
|
on_error: continue
|
||||||
|
config:
|
||||||
|
model: auto
|
||||||
|
system_prompt: "You are a professional writer. Based on the research summary provided, craft a clear, well-structured answer for the user. Include key findings and actionable insights."
|
||||||
|
|
||||||
|
edges:
|
||||||
|
- from: research
|
||||||
|
to: answer
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
|
||||||
|
model_list:
|
||||||
|
- model_name: deepseek-v4-flash
|
||||||
|
litellm_params:
|
||||||
|
model: deepseek-ai/DeepSeek-V4-Flash
|
||||||
|
api_base: https://api.siliconflow.cn/v1
|
||||||
|
api_key: os.environ/SILICONFLOW_API_KEY
|
||||||
|
rpm: 1000
|
||||||
|
tpm: 200000
|
||||||
|
- model_name: agnes-2.0-flash
|
||||||
|
litellm_params:
|
||||||
|
model: openai/agnes-2.0-flash
|
||||||
|
api_base: https://ai.qihuapi.com/v1
|
||||||
|
api_key: os.environ/AGNES_API_KEY
|
||||||
|
rpm: 500
|
||||||
|
- model_name: mimo-v2.5
|
||||||
|
litellm_params:
|
||||||
|
model: openai/mimo-v2.5
|
||||||
|
api_base: https://token-plan-cn.xiaomimimo.com/v1
|
||||||
|
api_key: os.environ/MIMO_API_KEY
|
||||||
|
rpm: 500
|
||||||
|
- model_name: qwen3-vl-32b
|
||||||
|
litellm_params:
|
||||||
|
model: openai/Qwen3-VL-32B-Instruct
|
||||||
|
api_base: https://api.siliconflow.cn/v1
|
||||||
|
api_key: os.environ/SILICONFLOW_API_KEY
|
||||||
|
rpm: 300
|
||||||
|
|
||||||
|
litellm_settings:
|
||||||
|
drop_params: true
|
||||||
|
request_timeout: 120
|
||||||
|
|
||||||
|
general_settings:
|
||||||
|
master_key: os.environ/LITELLM_MASTER_KEY
|
||||||
|
|
||||||
|
router_settings:
|
||||||
|
routing_strategy: "usage-based-routing-v2"
|
||||||
|
allowed_fails: 2
|
||||||
|
num_retries: 2
|
||||||
|
fallbacks:
|
||||||
|
- deepseek-v4-flash: ["agnes-2.0-flash"]
|
||||||
|
- agnes-2.0-flash: ["deepseek-v4-flash"]
|
||||||
|
- mimo-v2.5: ["deepseek-v4-flash"]
|
||||||
+206
-206
@@ -1,206 +1,206 @@
|
|||||||
# Design System Master File
|
# Design System Master File
|
||||||
|
|
||||||
> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.
|
> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.
|
||||||
> If that file exists, its rules **override** this Master file.
|
> If that file exists, its rules **override** this Master file.
|
||||||
> If not, strictly follow the rules below.
|
> If not, strictly follow the rules below.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Project:** 七虎AI
|
**Project:** 七虎AI
|
||||||
**Generated:** 2026-07-13 09:07:15
|
**Generated:** 2026-07-13 09:07:15
|
||||||
**Category:** AI PaaS Platform / Developer Console
|
**Category:** AI PaaS Platform / Developer Console
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Global Rules
|
## Global Rules
|
||||||
|
|
||||||
### Color Palette
|
### Color Palette
|
||||||
|
|
||||||
| Role | Hex | CSS Variable |
|
| Role | Hex | CSS Variable |
|
||||||
|------|-----|--------------|
|
|------|-----|--------------|
|
||||||
| Primary | `#5B5FED` | `--color-primary` |
|
| Primary | `#5B5FED` | `--color-primary` |
|
||||||
| Secondary | `#3B82F6` | `--color-secondary` |
|
| Secondary | `#3B82F6` | `--color-secondary` |
|
||||||
| CTA/Accent | `#5B5FED` | `--color-cta` |
|
| CTA/Accent | `#5B5FED` | `--color-cta` |
|
||||||
| Background | `#F8F9FB` | `--color-background` |
|
| Background | `#F8F9FB` | `--color-background` |
|
||||||
| Text | `#101214` | `--color-text` |
|
| Text | `#101214` | `--color-text` |
|
||||||
|
|
||||||
**Color Notes:** Indigo #5B5FED is the single brand hue. Success #219B5E / Warning #E8922C / Error #D9383A / Info #3B82F6 are semantic only. Do not introduce extra brand colors.
|
**Color Notes:** Indigo #5B5FED is the single brand hue. Success #219B5E / Warning #E8922C / Error #D9383A / Info #3B82F6 are semantic only. Do not introduce extra brand colors.
|
||||||
|
|
||||||
### Typography
|
### Typography
|
||||||
|
|
||||||
- **Heading Font:** Inter
|
- **Heading Font:** Inter
|
||||||
- **Body Font:** Inter
|
- **Body Font:** Inter
|
||||||
- **Mood:** neutral, precise, technical
|
- **Mood:** neutral, precise, technical
|
||||||
- **Google Fonts:** [Inter + Inter](https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700;800;900|JetBrains+Mono:wght@400;500;600)
|
- **Google Fonts:** [Inter + Inter](https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700;800;900|JetBrains+Mono:wght@400;500;600)
|
||||||
|
|
||||||
**CSS Import:**
|
**CSS Import:**
|
||||||
```css
|
```css
|
||||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600&display=swap');
|
||||||
```
|
```
|
||||||
|
|
||||||
### Spacing Variables
|
### Spacing Variables
|
||||||
|
|
||||||
| Token | Value | Usage |
|
| Token | Value | Usage |
|
||||||
|-------|-------|-------|
|
|-------|-------|-------|
|
||||||
| `--space-xs` | `4px` / `0.25rem` | Tight gaps |
|
| `--space-xs` | `4px` / `0.25rem` | Tight gaps |
|
||||||
| `--space-sm` | `8px` / `0.5rem` | Icon gaps, inline spacing |
|
| `--space-sm` | `8px` / `0.5rem` | Icon gaps, inline spacing |
|
||||||
| `--space-md` | `16px` / `1rem` | Standard padding |
|
| `--space-md` | `16px` / `1rem` | Standard padding |
|
||||||
| `--space-lg` | `24px` / `1.5rem` | Section padding |
|
| `--space-lg` | `24px` / `1.5rem` | Section padding |
|
||||||
| `--space-xl` | `32px` / `2rem` | Large gaps |
|
| `--space-xl` | `32px` / `2rem` | Large gaps |
|
||||||
| `--space-2xl` | `48px` / `3rem` | Section margins |
|
| `--space-2xl` | `48px` / `3rem` | Section margins |
|
||||||
| `--space-3xl` | `64px` / `4rem` | Hero padding |
|
| `--space-3xl` | `64px` / `4rem` | Hero padding |
|
||||||
|
|
||||||
### Shadow Depths
|
### Shadow Depths
|
||||||
|
|
||||||
| Level | Value | Usage |
|
| Level | Value | Usage |
|
||||||
|-------|-------|-------|
|
|-------|-------|-------|
|
||||||
| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |
|
| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |
|
||||||
| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |
|
| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |
|
||||||
| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |
|
| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |
|
||||||
| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |
|
| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Component Specs
|
## Component Specs
|
||||||
|
|
||||||
### Buttons
|
### Buttons
|
||||||
|
|
||||||
```css
|
```css
|
||||||
/* Primary Button */
|
/* Primary Button */
|
||||||
.btn-primary {
|
.btn-primary {
|
||||||
background: #5B5FED;
|
background: #5B5FED;
|
||||||
color: white;
|
color: white;
|
||||||
padding: 12px 24px;
|
padding: 12px 24px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
transition: all 200ms ease;
|
transition: all 200ms ease;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary:hover {
|
.btn-primary:hover {
|
||||||
opacity: 0.9;
|
opacity: 0.9;
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Secondary Button */
|
/* Secondary Button */
|
||||||
.btn-secondary {
|
.btn-secondary {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: #5B5FED;
|
color: #5B5FED;
|
||||||
border: 2px solid #5B5FED;
|
border: 2px solid #5B5FED;
|
||||||
padding: 12px 24px;
|
padding: 12px 24px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
transition: all 200ms ease;
|
transition: all 200ms ease;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Cards
|
### Cards
|
||||||
|
|
||||||
```css
|
```css
|
||||||
.card {
|
.card {
|
||||||
background: #F8F9FB;
|
background: #F8F9FB;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
padding: 24px;
|
padding: 24px;
|
||||||
box-shadow: var(--shadow-md);
|
box-shadow: var(--shadow-md);
|
||||||
transition: all 200ms ease;
|
transition: all 200ms ease;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card:hover {
|
.card:hover {
|
||||||
box-shadow: var(--shadow-lg);
|
box-shadow: var(--shadow-lg);
|
||||||
transform: translateY(-2px);
|
transform: translateY(-2px);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Inputs
|
### Inputs
|
||||||
|
|
||||||
```css
|
```css
|
||||||
.input {
|
.input {
|
||||||
padding: 12px 16px;
|
padding: 12px 16px;
|
||||||
border: 1px solid #E2E8F0;
|
border: 1px solid #E2E8F0;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
transition: border-color 200ms ease;
|
transition: border-color 200ms ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input:focus {
|
.input:focus {
|
||||||
border-color: #5B5FED;
|
border-color: #5B5FED;
|
||||||
outline: none;
|
outline: none;
|
||||||
box-shadow: 0 0 0 3px #5B5FED20;
|
box-shadow: 0 0 0 3px #5B5FED20;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Modals
|
### Modals
|
||||||
|
|
||||||
```css
|
```css
|
||||||
.modal-overlay {
|
.modal-overlay {
|
||||||
background: rgba(0, 0, 0, 0.5);
|
background: rgba(0, 0, 0, 0.5);
|
||||||
backdrop-filter: blur(4px);
|
backdrop-filter: blur(4px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.modal {
|
.modal {
|
||||||
background: white;
|
background: white;
|
||||||
border-radius: 16px;
|
border-radius: 16px;
|
||||||
padding: 32px;
|
padding: 32px;
|
||||||
box-shadow: var(--shadow-xl);
|
box-shadow: var(--shadow-xl);
|
||||||
max-width: 500px;
|
max-width: 500px;
|
||||||
width: 90%;
|
width: 90%;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Style Guidelines
|
## Style Guidelines
|
||||||
|
|
||||||
**Style:** Warm Tech Minimalism
|
**Style:** Warm Tech Minimalism
|
||||||
|
|
||||||
**Keywords:** clean, precise, data-dense, soft surfaces, indigo accent, generous whitespace
|
**Keywords:** clean, precise, data-dense, soft surfaces, indigo accent, generous whitespace
|
||||||
|
|
||||||
**Best For:** AI PaaS consoles, developer platforms, agent/workflow editors
|
**Best For:** AI PaaS consoles, developer platforms, agent/workflow editors
|
||||||
|
|
||||||
**Key Effects:** Subtle hover lift (translateY -1 to -2px), 150-300ms ease transitions, soft shadow escalation, skeleton shimmer for loading, fade/slide micro-entrances.
|
**Key Effects:** Subtle hover lift (translateY -1 to -2px), 150-300ms ease transitions, soft shadow escalation, skeleton shimmer for loading, fade/slide micro-entrances.
|
||||||
|
|
||||||
### Page Pattern
|
### Page Pattern
|
||||||
|
|
||||||
**Pattern Name:** App Shell + Dashboard Grid
|
**Pattern Name:** App Shell + Dashboard Grid
|
||||||
|
|
||||||
- **Conversion Strategy:** Core value shown immediately via workspace/chat; primary action (新建对话/部署) persistent in header and sidebar.
|
- **Conversion Strategy:** Core value shown immediately via workspace/chat; primary action (新建对话/部署) persistent in header and sidebar.
|
||||||
- **CTA Placement:** Sticky header + sidebar primary action; contextual CTAs inside cards.
|
- **CTA Placement:** Sticky header + sidebar primary action; contextual CTAs inside cards.
|
||||||
- **Section Order:** Sidebar > Workspace(Chat/Agents/Skills/MCP) > Main content grid > Detail drawer
|
- **Section Order:** Sidebar > Workspace(Chat/Agents/Skills/MCP) > Main content grid > Detail drawer
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Anti-Patterns (Do NOT Use)
|
## Anti-Patterns (Do NOT Use)
|
||||||
|
|
||||||
- ❌ Ornate decoration
|
- ❌ Ornate decoration
|
||||||
- ❌ Low contrast text
|
- ❌ Low contrast text
|
||||||
- ❌ Missing focus states
|
- ❌ Missing focus states
|
||||||
- ❌ Emojis as icons
|
- ❌ Emojis as icons
|
||||||
- ❌ Layout-shifting scale hovers
|
- ❌ Layout-shifting scale hovers
|
||||||
- ❌ Instant state changes
|
- ❌ Instant state changes
|
||||||
|
|
||||||
### Additional Forbidden Patterns
|
### Additional Forbidden Patterns
|
||||||
|
|
||||||
- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)
|
- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)
|
||||||
- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer
|
- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer
|
||||||
- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout
|
- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout
|
||||||
- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio
|
- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio
|
||||||
- ❌ **Instant state changes** — Always use transitions (150-300ms)
|
- ❌ **Instant state changes** — Always use transitions (150-300ms)
|
||||||
- ❌ **Invisible focus states** — Focus states must be visible for a11y
|
- ❌ **Invisible focus states** — Focus states must be visible for a11y
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Pre-Delivery Checklist
|
## Pre-Delivery Checklist
|
||||||
|
|
||||||
Before delivering any UI code, verify:
|
Before delivering any UI code, verify:
|
||||||
|
|
||||||
- [ ] No emojis as icons (use SVG: Heroicons/Lucide)
|
- [ ] No emojis as icons (use SVG: Heroicons/Lucide)
|
||||||
- [ ] cursor-pointer on all clickable elements
|
- [ ] cursor-pointer on all clickable elements
|
||||||
- [ ] Hover states with smooth transitions (150-300ms)
|
- [ ] Hover states with smooth transitions (150-300ms)
|
||||||
- [ ] Light mode: text contrast 4.5:1 minimum
|
- [ ] Light mode: text contrast 4.5:1 minimum
|
||||||
- [ ] Focus states visible for keyboard nav
|
- [ ] Focus states visible for keyboard nav
|
||||||
- [ ] prefers-reduced-motion respected
|
- [ ] prefers-reduced-motion respected
|
||||||
- [ ] Responsive: 375px, 768px, 1024px, 1440px
|
- [ ] Responsive: 375px, 768px, 1024px, 1440px
|
||||||
- [ ] No content hidden behind fixed navbars
|
- [ ] No content hidden behind fixed navbars
|
||||||
- [ ] No horizontal scroll on mobile
|
- [ ] No horizontal scroll on mobile
|
||||||
+43
-35
@@ -21,11 +21,13 @@ services:
|
|||||||
- "12888:8080"
|
- "12888:8080"
|
||||||
- "18080:18080"
|
- "18080:18080"
|
||||||
environment:
|
environment:
|
||||||
- MYSQL_HOST=mysql
|
- DATABASE_URL=postgresql+psycopg://aiflow:pwd2026@qihu-aiflow-pg18:5432/aiflow
|
||||||
- MYSQL_PORT=3306
|
- POSTGRES_HOST=qihu-aiflow-pg18
|
||||||
- MYSQL_USER=root
|
- POSTGRES_PORT=5432
|
||||||
- MYSQL_PASSWORD=pwd2026
|
- POSTGRES_USER=aiflow
|
||||||
- MYSQL_DATABASE=aiflow
|
- POSTGRES_PASSWORD=pwd2026
|
||||||
|
- POSTGRES_DB=aiflow_vectors
|
||||||
|
- PG_HOST=qihu-aiflow-pg18
|
||||||
- REDIS_HOST=redis
|
- REDIS_HOST=redis
|
||||||
- REDIS_PORT=6379
|
- REDIS_PORT=6379
|
||||||
- REDIS_PASSWORD=pwd2026
|
- REDIS_PASSWORD=pwd2026
|
||||||
@@ -46,10 +48,8 @@ services:
|
|||||||
- DEFAULT_MODEL=deepseek-ai/DeepSeek-V4-Flash
|
- DEFAULT_MODEL=deepseek-ai/DeepSeek-V4-Flash
|
||||||
- HTTP_PROXY=http://172.18.0.1:7890
|
- HTTP_PROXY=http://172.18.0.1:7890
|
||||||
- HTTPS_PROXY=http://172.18.0.1:7890
|
- HTTPS_PROXY=http://172.18.0.1:7890
|
||||||
- NO_PROXY=localhost,127.0.0.1,::1,210.16.161.218,172.17.0.0/16,172.18.0.0/16,172.19.0.0/16,172.20.0.0/16,10.0.0.0/8,192.168.0.0/16,.svc,.local,casdoor,qihu-aiflow-mysql,qihu-aiflow-redis,qihu-aiflow-pgvector,qihu-aiflow-casdoor,qihuyun.com,ai.qihuyun.com,docs.qihuyun.com,bot.qihuyun.com,siliconflow.cn,api.siliconflow.cn,deepseek.com,api.deepseek.com,volcengineapi.com,aliyun.com,aliyuncs.com,dysmsapi.aliyuncs.com,tencentcloudapi.com,baidubce.com,dashscope.com,qwen.ai,zhipuai.cn,moonshot.cn,minimax.chat,baichuan.com,chatglm.cn,xiaomimimo.com,token-plan-cn.xiaomimimo.com,mi.com,pypi.tuna.tsinghua.edu.cn,feishu.cn,open.feishu.cn,dingtalk.com,open.dingtalk.com,weixin.qq.com,developers.weixin.qq.com,qyapi.weixin.qq.com,ilinkai.weixin.qq.com,tencent.com
|
- NO_PROXY=localhost,127.0.0.1,::1,210.16.161.218,172.17.0.0/16,172.18.0.0/16,172.19.0.0/16,172.20.0.0/16,10.0.0.0/8,192.168.0.0/16,.svc,.local,casdoor,qihu-aiflow-mysql,qihu-aiflow-redis,qihu-aiflow-pgvector,qihu-aiflow-pg18,qihu-aiflow-casdoor,qihuyun.com,ai.qihuyun.com,docs.qihuyun.com,bot.qihuyun.com,siliconflow.cn,api.siliconflow.cn,deepseek.com,api.deepseek.com,volcengineapi.com,aliyun.com,aliyuncs.com,dysmsapi.aliyuncs.com,tencentcloudapi.com,baidubce.com,dashscope.com,qwen.ai,zhipuai.cn,moonshot.cn,minimax.chat,baichuan.com,chatglm.cn,xiaomimimo.com,token-plan-cn.xiaomimimo.com,mi.com,pypi.tuna.tsinghua.edu.cn,feishu.cn,open.feishu.cn,dingtalk.com,open.dingtalk.com,weixin.qq.com,developers.weixin.qq.com,qyapi.weixin.qq.com,ilinkai.weixin.qq.com,tencent.com
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
|
||||||
condition: service_healthy
|
|
||||||
redis:
|
redis:
|
||||||
condition: service_started
|
condition: service_started
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -63,32 +63,6 @@ services:
|
|||||||
max-size: "50m"
|
max-size: "50m"
|
||||||
max-file: "10"
|
max-file: "10"
|
||||||
|
|
||||||
mysql:
|
|
||||||
image: mysql:8.0
|
|
||||||
container_name: qihu-aiflow-mysql
|
|
||||||
command: --ssl=0
|
|
||||||
environment:
|
|
||||||
- MYSQL_ROOT_PASSWORD=pwd2026
|
|
||||||
- MYSQL_DATABASE=aiflow
|
|
||||||
ports:
|
|
||||||
- "3306:3306"
|
|
||||||
volumes:
|
|
||||||
- mysql_data:/var/lib/mysql
|
|
||||||
restart: unless-stopped
|
|
||||||
networks:
|
|
||||||
- aiflow-network
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-ppwd2026"]
|
|
||||||
interval: 5s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 10
|
|
||||||
start_period: 30s
|
|
||||||
logging:
|
|
||||||
driver: json-file
|
|
||||||
options:
|
|
||||||
max-size: "50m"
|
|
||||||
max-file: "5"
|
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:7-alpine
|
image: redis:7-alpine
|
||||||
container_name: qihu-aiflow-redis
|
container_name: qihu-aiflow-redis
|
||||||
@@ -106,9 +80,43 @@ services:
|
|||||||
max-size: "20m"
|
max-size: "20m"
|
||||||
max-file: "5"
|
max-file: "5"
|
||||||
|
|
||||||
|
# Phase 0B: LiteLLM Proxy - Unified AI Gateway
|
||||||
|
litellm:
|
||||||
|
image: ghcr.io/berriai/litellm:main-stable
|
||||||
|
container_name: qihu-aiflow-litellm
|
||||||
|
ports:
|
||||||
|
- "14000:4000"
|
||||||
|
volumes:
|
||||||
|
- ./config/litellm_config.yaml:/app/config.yaml
|
||||||
|
environment:
|
||||||
|
- LITELLM_MASTER_KEY=sk-litellm-master-key-aiflow-2026
|
||||||
|
- SILICONFLOW_API_KEY=os.environ/SILICONFLOW_API_KEY
|
||||||
|
- AGNES_API_KEY=os.environ/AGNES_API_KEY
|
||||||
|
- MIMO_API_KEY=os.environ/MIMO_API_KEY
|
||||||
|
- DATABASE_URL=postgresql://aiflow:pwd2026@qihu-aiflow-pg18:5432/aiflow
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- aiflow-network
|
||||||
|
|
||||||
|
# Phase 0C: Meilisearch - Full-text search engine
|
||||||
|
meilisearch:
|
||||||
|
image: getmeili/meilisearch:v1.11
|
||||||
|
container_name: qihu-aiflow-meilisearch
|
||||||
|
ports:
|
||||||
|
- "17700:7700"
|
||||||
|
volumes:
|
||||||
|
- meilisearch_data:/meili_data
|
||||||
|
environment:
|
||||||
|
- MEILI_MASTER_KEY=meili-master-key-aiflow-2026
|
||||||
|
- MEILI_ENV=production
|
||||||
|
- MEILI_NO_ANALYTICS=true
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- aiflow-network
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql_data:
|
|
||||||
redis_data:
|
redis_data:
|
||||||
|
meilisearch_data:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
aiflow-network:
|
aiflow-network:
|
||||||
|
|||||||
@@ -0,0 +1,544 @@
|
|||||||
|
# 七虎AI PaaS 平台 — 架构设计与实施方案 v2.0
|
||||||
|
|
||||||
|
> **最后更新**: 2026-07-27
|
||||||
|
> **版本**: v2.0
|
||||||
|
> **用途**: 投喂 AI 大模型进行平台竞争力、护城河、扩展能力分析
|
||||||
|
> **维护**: 随系统迭代实时更新
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、平台概述
|
||||||
|
|
||||||
|
### 1.1 定位
|
||||||
|
|
||||||
|
七虎AI(qihuyun.com)是一个面向开发者和企业的 **AI PaaS 平台**,核心能力是聚合多厂商大模型、提供标准化工具调用层、支持 Skill/MCP/Agent 的发现-安装-编排-执行全生命周期管理。
|
||||||
|
|
||||||
|
### 1.2 核心价值主张
|
||||||
|
|
||||||
|
| 价值维度 | 实现方式 |
|
||||||
|
|---------|---------|
|
||||||
|
| 模型聚合 | 统一 OpenAI 兼容协议接入 4+ 厂商(SiliconFlow、MiMo、AGNES、DeepSeek),自动 failover |
|
||||||
|
| 技能市场 | Skills 的上架-搜索-安装-执行闭环,支持 14 个能力分类 |
|
||||||
|
| MCP 协议 | 官方 Anthropic MCP SDK 实现,支持 streamable_http/SSE 传输 |
|
||||||
|
| Agent 编排 | DAG 图引擎 + Supervisor 模式,支持外部 Agent(Dify/n8n/Coze)远程调用 |
|
||||||
|
| IM Bot | 多平台(微信/企业微信/飞书/QQ)统一消息网关 |
|
||||||
|
| 知识库 RAG | PostgreSQL pgvector + 混合检索 |
|
||||||
|
| 媒体生成 | 异步图片/视频生成(后台线程,不阻塞 SSE) |
|
||||||
|
| 可观测 | Prometheus+Grafana 监控栈 + 日志审计 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、整体架构
|
||||||
|
|
||||||
|
### 2.1 部署架构
|
||||||
|
|
||||||
|
```
|
||||||
|
Internet
|
||||||
|
│
|
||||||
|
┌────▼────┐
|
||||||
|
│ Nginx │ :12888 (HTTPS)
|
||||||
|
└────┬────┘
|
||||||
|
│
|
||||||
|
┌──────────────┼──────────────┐
|
||||||
|
│ │ │
|
||||||
|
┌────▼────┐ ┌───▼────┐ ┌───▼─────┐
|
||||||
|
│ React │ │FastAPI │ │ Casdoor │
|
||||||
|
│ Vite │ │uvicorn │ │ :8000 │
|
||||||
|
│ (dist/) │ │:18080 │ └─────────┘
|
||||||
|
└─────────┘ └───┬────┘
|
||||||
|
│
|
||||||
|
┌─────────────┼─────────────┐
|
||||||
|
│ │ │
|
||||||
|
┌────▼────┐ ┌───▼────┐ ┌───▼──────┐
|
||||||
|
│Postgres │ │ Redis │ │ Executor │
|
||||||
|
│PG18+ │ │:6379 │ │ (Code) │
|
||||||
|
│pgvector │ └────────┘ └──────────┘
|
||||||
|
└─────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 容器清单
|
||||||
|
|
||||||
|
| 容器 | 镜像 | 用途 |
|
||||||
|
|------|------|------|
|
||||||
|
| qihu-aiflow | 自建(custom) | 主应用(Nginx + FastAPI uvicorn + React dist) |
|
||||||
|
| qihu-aiflow-pg18 | pgvector/pgvector:pg16 | PostgreSQL 主库 + 向量扩展 |
|
||||||
|
| qihu-aiflow-redis | redis:7-alpine | 缓存/队列/会话 |
|
||||||
|
| qihu-aiflow-casdoor | casdoor | 统一认证 |
|
||||||
|
| qihuaiflow-executor | 自建 | 代码执行沙箱 |
|
||||||
|
| qihu-aiflow-prometheus | prom/prometheus | 指标采集 |
|
||||||
|
| qihu-aiflow-grafana | grafana/grafana | 可视化监控 |
|
||||||
|
| qihu-aiflow-alloy | grafana/alloy | 日志采集 Agent |
|
||||||
|
| qihu-aiflow-node-exporter | prom/node-exporter | 宿主机指标 |
|
||||||
|
|
||||||
|
### 2.3 数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
用户请求 → Nginx(:12888) → uvicorn(:18080)
|
||||||
|
├── /app/api/chat/* → chat.py (SSE streaming)
|
||||||
|
├── /app/api/auth/* → auth.py (JWT)
|
||||||
|
├── /app/api/admin/* → admin/* (CRUD + 管理)
|
||||||
|
└── / → index.html → React SPA
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、技术栈矩阵
|
||||||
|
|
||||||
|
| 层级 | 技术 | 版本 | 选型理由 |
|
||||||
|
|------|------|------|---------|
|
||||||
|
| 后端框架 | FastAPI (Python) | 0.115+ | 异步原生、SSE 流式支持、Pydantic 验证 |
|
||||||
|
| ASGI 服务器 | uvicorn | 0.30+ | 单进程事件循环、生产级 |
|
||||||
|
| 前端框架 | React + Vite | 18 + 5 | 组件化、HMR 热更新、Tree-shaking |
|
||||||
|
| 前端语言 | TypeScript | 5.6+ | 类型安全 |
|
||||||
|
| 关系数据库 | PostgreSQL | 18 | JSONB、pgvector 原生支持、AIO 引擎 |
|
||||||
|
| 向量引擎 | pgvector | 0.8.4 | 与主库同集群、免运维 |
|
||||||
|
| 缓存 | Redis | 7 | 会话、队列、工具列表缓存 |
|
||||||
|
| 认证 | Casdoor | latest | 开源统一认证、OAuth2/OIDC |
|
||||||
|
| ORM | SQLAlchemy | 2.0.36 | 成熟生态、支持 async |
|
||||||
|
| LLM 客户端 | openai Python SDK | 1.x | OpenAI 兼容协议统一接入 |
|
||||||
|
| MCP 客户端 | mcp Python SDK | 1.28.1 | Anthropic 官方 SDK |
|
||||||
|
| 代理 | Nginx | 1.25+ | 反向代理、静态文件、SSL |
|
||||||
|
| 容器 | Docker Compose | v2 | 单机编排 |
|
||||||
|
| 监控 | Prometheus + Grafana | latest | 开源标准、全栈可见 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、数据模型(67 张表,按域分组)
|
||||||
|
|
||||||
|
### 4.1 核心业务域
|
||||||
|
|
||||||
|
| 表名 | 说明 | 关键字段 |
|
||||||
|
|------|------|---------|
|
||||||
|
| users | 用户 | id, username, password_hash, role |
|
||||||
|
| conversations | 对话 | id, user_id, title, model_id |
|
||||||
|
| messages | 消息 | id, conv_id, role, content, tool_calls, used_skills |
|
||||||
|
| models | AI 模型 | id, provider_id, name, endpoint, capabilities, is_default |
|
||||||
|
| model_providers | 模型提供商 | id, name, protocol, api_key, api_base_url, auth_header |
|
||||||
|
| site_settings | 站点配置 | key, value (JSON) |
|
||||||
|
| mcpservers | MCP 服务 | id, name, url, transport_type, is_enabled, tools_count |
|
||||||
|
|
||||||
|
### 4.2 技能市场域
|
||||||
|
|
||||||
|
| 表名 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| market_apps | 市场应用(Skills/MCP/Agents) |
|
||||||
|
| market_app_versions | 应用版本 |
|
||||||
|
| app_purchases | 购买记录 |
|
||||||
|
| app_reviews | 评价 |
|
||||||
|
| app_installations | 安装记录 |
|
||||||
|
| skill_versions | 技能版本 |
|
||||||
|
| skill_publish_records | 发布记录 |
|
||||||
|
| evolution_skills | 进��技能 |
|
||||||
|
| evolution_events | 进化事件 |
|
||||||
|
| evolution_trajectories | 进化轨迹 |
|
||||||
|
| team_shared_skills | 团队共享技能 |
|
||||||
|
|
||||||
|
### 4.3 知识库域
|
||||||
|
|
||||||
|
| 表名 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| knowledge_bases | 知识库 |
|
||||||
|
| knowledge_directories | 知识目录 |
|
||||||
|
| knowledge_documents | 文档 |
|
||||||
|
| knowledge_document_chunks | 文档分块 |
|
||||||
|
| knowledge_graph_nodes | 知识图谱节点 |
|
||||||
|
| knowledge_graph_edges | 知识图谱边 |
|
||||||
|
| external_kb_services | 外部 KB 服务 |
|
||||||
|
|
||||||
|
### 4.4 会员/支付域
|
||||||
|
|
||||||
|
| 表名 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| membership_plans | 会员计划 |
|
||||||
|
| membership_subscriptions | 订阅 |
|
||||||
|
| orders | 订单 |
|
||||||
|
| coupons | 优惠券 |
|
||||||
|
| user_coupons | 用户优惠券 |
|
||||||
|
| value_added_services | 增值服务 |
|
||||||
|
| payment_configs | 支付配置 |
|
||||||
|
|
||||||
|
### 4.5 监控/运维域
|
||||||
|
|
||||||
|
| 表名 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| token_usage_logs | Token 用量日志 |
|
||||||
|
| token_balances | 余额 |
|
||||||
|
| operation_logs | 操作日志 |
|
||||||
|
| audit_logs | 审计日志 |
|
||||||
|
| login_logs | 登录日志 |
|
||||||
|
| risk_rules | 风控规则 |
|
||||||
|
| slow_request_logs | 慢请求日志 |
|
||||||
|
| api_call_stats | API 调用统计 |
|
||||||
|
| task_execution_logs | 任务执行日志 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、API 全景
|
||||||
|
|
||||||
|
### 5.1 前台 API(用户面)
|
||||||
|
|
||||||
|
| 路由前缀 | 端点 | 方法 | 说明 |
|
||||||
|
|---------|------|------|------|
|
||||||
|
| /app/api/auth | /login | POST | 用户登录,返回 JWT |
|
||||||
|
| /app/api/auth | /register | POST | 注册 |
|
||||||
|
| /app/api/chat | /conversations | GET/POST | 对话列表/创建 |
|
||||||
|
| /app/api/chat | /conversations/{id}/messages | POST | 发送消息(非流式) |
|
||||||
|
| /app/api/chat | /conversations/{id}/messages/stream | POST | **SSE 流式聊天** |
|
||||||
|
| /app/api/chat | /models | GET | 可用模型列表 |
|
||||||
|
| /app/api/chat | /media/relay | GET | 媒体代理 |
|
||||||
|
| /app/api/market | /apps | GET | 应用市场列表 |
|
||||||
|
| /app/api/market | /apps/{id} | GET | 应用详情 |
|
||||||
|
| /app/api/knowledge | /search | POST | 知识库搜索 |
|
||||||
|
|
||||||
|
### 5.2 后台 API(管理面)
|
||||||
|
|
||||||
|
| 路由前缀 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| /app/api/admin/users | 用户管理 |
|
||||||
|
| /app/api/admin/models | 模型管理 |
|
||||||
|
| /app/api/admin/skills | 技能管理 |
|
||||||
|
| /app/api/admin/agents | Agent 管理 |
|
||||||
|
| /app/api/admin/mcp | MCP 服务管理 |
|
||||||
|
| /app/api/admin/workflow | 工作流管理 |
|
||||||
|
| /app/api/admin/market | 市场管理 |
|
||||||
|
| /app/api/admin/analytics | 数据分析 |
|
||||||
|
| /app/api/admin/developer | 开发者 API |
|
||||||
|
| /app/api/admin/settings | 站点设置 |
|
||||||
|
| /app/api/admin/storage | 存储管理 |
|
||||||
|
| /app/api/admin/logs | 日志查看 |
|
||||||
|
| /app/api/admin/automation | 自动化任务 |
|
||||||
|
|
||||||
|
### 5.3 SSE 事件类型
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /conversations/{id}/messages/stream
|
||||||
|
Content-Type: text/event-stream
|
||||||
|
|
||||||
|
事件帧:
|
||||||
|
data: {"type":"reasoning","content":"..."} // 模型推理过程
|
||||||
|
data: {"type":"delta","content":"..."} // 逐字回复增量
|
||||||
|
data: {"type":"step","step":{...}} // 工具调用步骤
|
||||||
|
step.type: "thinking" | "skill" | "mcp"
|
||||||
|
data: {"type":"done","message_id":"..."} // 流结束
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、核心管道与工作流
|
||||||
|
|
||||||
|
### 6.1 消息处理管道(主循环)
|
||||||
|
|
||||||
|
```
|
||||||
|
用户消息
|
||||||
|
→ 鉴权(JWT Bearer)
|
||||||
|
→ 上下文恢复(skill_ids/agent_ids/mcp_ids 跨轮继承)
|
||||||
|
→ 技能解析(显式选择 → 自动发现 → Agent 合并)
|
||||||
|
→ MCP 工具列表拉取(带缓存 TTL 120s,按 url + transport 缓存)
|
||||||
|
→ 知识库检索(RAG,BM25 + vector hybrid)
|
||||||
|
→ System Prompt 组装(AGENT_GUIDE + platform_knowledge + agent_role + skill_desc + kb_context)
|
||||||
|
→ Function Definitions 组装(skills → tools + MCP → tools + install_app)
|
||||||
|
→ LLM 调用(OpenAI 兼容协议,stream=True)
|
||||||
|
→ Tool Calls 循环(max 15 轮,每轮 tool_policy 沙箱检查)
|
||||||
|
├── MCP Tool → call_mcp_tool() via Anthropic SDK
|
||||||
|
├── Skill → _execute_skill_tool() 指令转发
|
||||||
|
└── install_app → 安装到市场
|
||||||
|
→ 工具结果回注 → 继续 LLM 循环 → 最终回复
|
||||||
|
→ 上下文压缩(后台异步,fire-and-forget)
|
||||||
|
→ 结构化记忆抽取(实体/事实/偏好/决策/待办 五类)
|
||||||
|
→ 媒体生成(后台 daemon 线程,独立事件循环)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 模型路由与 Failover 管道
|
||||||
|
|
||||||
|
```
|
||||||
|
模型选择 → 解析 api_url/api_key/provider.auth_header
|
||||||
|
→ build_openai_client(httpx.Timeout + trust_env=False + auth_header 支持)
|
||||||
|
→ 首次调用失败(Exception)→ continue 下一个模型
|
||||||
|
→ 备用模型列表(order_by is_default desc × 5)
|
||||||
|
→ 成功 → break
|
||||||
|
→ 全部失败 → 返回错误消息
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 MCP 协议管道
|
||||||
|
|
||||||
|
```
|
||||||
|
Client: mcp_client.py (官方 Anthropic SDK)
|
||||||
|
list_mcp_tools(server) → tools/list (JSON-RPC)
|
||||||
|
⇢ 缓存: _TOOLS_CACHE[url] = (timestamp, tools), TTL 120s
|
||||||
|
call_mcp_tool(server, name, arguments) → tools/call (JSON-RPC)
|
||||||
|
⇢ 返回: text content blocks → 拼接为字符串 → 反馈给 LLM
|
||||||
|
|
||||||
|
传输层:
|
||||||
|
streamable_http (默认) → streamablehttp_client()
|
||||||
|
sse → sse_client()
|
||||||
|
|
||||||
|
Schema 适配:
|
||||||
|
MCP inputSchema (JSON Schema 2020-12) → _normalize_mcp_schema()
|
||||||
|
⇢ 展开 $ref → 处理 oneOf/anyOf → allOf 合并 → 剥离非 OpenAI 关���字
|
||||||
|
⇢ 转为 OpenAI function calling 兼容的 parameters
|
||||||
|
|
||||||
|
认证:
|
||||||
|
Authorization: Bearer {key} (默认)
|
||||||
|
api-key: {key} (MiMo Token Plan 等自定义)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.4 Agent 编排管道(DAG 图引擎)
|
||||||
|
|
||||||
|
```
|
||||||
|
YAML 定义 → validate_graph() → topological_layers() (Kahn算法)
|
||||||
|
→ 按层并行执行 (asyncio.gather)
|
||||||
|
|
||||||
|
节点类型:
|
||||||
|
llm → _build_system_prompt + LLM 调用
|
||||||
|
local → _execute_skill_tool (本地技能)
|
||||||
|
external → _call_external_agent (Dify/n8n/Coze 远程)
|
||||||
|
reduce → 多路结果聚合
|
||||||
|
|
||||||
|
边: 有向边定义数据流 → 拓扑排序 → 分层并行
|
||||||
|
失败隔离: per-node on_error=halt|continue
|
||||||
|
并发安全: 每节点独立 SessionLocal()
|
||||||
|
|
||||||
|
预处理流水线:
|
||||||
|
外部 Agent endpoint → 直接远程调用(跳过本地 LLM)
|
||||||
|
Orchestrator → run_graph() → 图执行 → 聚合回答
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 媒体生成管道
|
||||||
|
|
||||||
|
```
|
||||||
|
SSE 回复结束 → _launch_media_task_bg()
|
||||||
|
→ daemon Thread → asyncio.run(_generate_media_task)
|
||||||
|
→ 独立事件循环(不阻塞主 uvicorn 循环)
|
||||||
|
→ HTTP 调用图片/视频生成 API
|
||||||
|
→ 写入存储 → 更新 Message 记录
|
||||||
|
→ 前端轮询 → 渲染结果
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.6 上下文压缩管道
|
||||||
|
|
||||||
|
```
|
||||||
|
(后台异步, fire-and-forget, 不阻塞用户响应)
|
||||||
|
|
||||||
|
旧消息 (>20 条保护窗口外)
|
||||||
|
→ 分块 (CHUNK=30) → _summarize_via_llm()
|
||||||
|
→ chunk_summaries 合并
|
||||||
|
→ _recursive_compress() (depth≤3, budget=700 tokens)
|
||||||
|
→ _extract_structured_memory()
|
||||||
|
实体/事实/偏好/决策/待办 五类
|
||||||
|
→ _merge_structured_memory(old, new)
|
||||||
|
→ ConversationSummary 写入 PG
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、前端架构
|
||||||
|
|
||||||
|
### 7.1 路由设计
|
||||||
|
|
||||||
|
```
|
||||||
|
前台 (/):
|
||||||
|
/login - 登录
|
||||||
|
/chat[/:id] - AI 对话(核心页面,SSE 流式)
|
||||||
|
/knowledge - 知识库管理
|
||||||
|
/market - 应用市场(Skills/MCP/Agents)
|
||||||
|
/token - Token 用量面板
|
||||||
|
/pricing - 定价/会员
|
||||||
|
/profile - 个人中心
|
||||||
|
/assets[/novel/:id] - 资产/小说
|
||||||
|
/evolution - 进化仪表板
|
||||||
|
/wechat-bot - 微信 Bot
|
||||||
|
/im-bots - 多平台 IM Bot Hub
|
||||||
|
/app-services - 应用服务
|
||||||
|
|
||||||
|
后台 (/admin):
|
||||||
|
/admin - 仪表板
|
||||||
|
/admin/users - 用户管理
|
||||||
|
/admin/models - 模型管理
|
||||||
|
/admin/skills - 技能管理
|
||||||
|
/admin/agents - Agent 管理
|
||||||
|
/admin/mcp - MCP 管理
|
||||||
|
/admin/workflow - 工作流
|
||||||
|
/admin/market - 市场审核
|
||||||
|
/admin/knowledge - 知识库管理
|
||||||
|
/admin/code-exec - 代码执行
|
||||||
|
/admin/storage - 存储管理
|
||||||
|
/admin/developer[/tools] - 开发者 API/工具
|
||||||
|
/admin/automation - 自动化任务
|
||||||
|
/admin/settings - 站点设置
|
||||||
|
/admin/analytics - 数据分析
|
||||||
|
/admin/logs - 日志
|
||||||
|
/admin/membership - 会员管理
|
||||||
|
/admin/payment - 支付配置
|
||||||
|
/admin/services - 增值服务
|
||||||
|
/admin/ads - 广告管理
|
||||||
|
/admin/apps - 应用管理
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 核心组件
|
||||||
|
|
||||||
|
| 组件 | 文件 | 功能 |
|
||||||
|
|------|------|------|
|
||||||
|
| ChatPage | front/ChatPage.tsx | SSE 流式聊天、Step 渲染、推理展示 |
|
||||||
|
| AiProcessBlock | ChatPage.tsx 内 | 工具调用过程可视化(⏳/✅/❌) |
|
||||||
|
| MarketPage | front/MarketPage.tsx | 应用市场网格、分类筛选 |
|
||||||
|
| FrontLayout | components/layout/FrontLayout.tsx | 前台 sidebar + main 布局 |
|
||||||
|
| AdminLayout | components/layout/AdminLayout.tsx | 后台 sidebar + main 布局 |
|
||||||
|
|
||||||
|
### 7.3 设计系统
|
||||||
|
|
||||||
|
```
|
||||||
|
CSS 变量(global.css :root):
|
||||||
|
--color-accent: #5B5FED
|
||||||
|
--color-bg-primary: #F8F9FB
|
||||||
|
--sidebar-width: 240px
|
||||||
|
--space-xs..4xl: 4px..40px
|
||||||
|
--radius-md..3xl: 8px..20px
|
||||||
|
|
||||||
|
防溢出: html/body/.front-main { overflow-x: hidden }
|
||||||
|
响应式: @media (max-width: 1200px/768px) 断点
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、安全设计
|
||||||
|
|
||||||
|
### 8.1 认证
|
||||||
|
|
||||||
|
- JWT Bearer Token 认证(FastAPI HTTPBearer)
|
||||||
|
- Casdoor OAuth2/OIDC 统一认证(可选)
|
||||||
|
- Token 前端存内存,401/403 清 token 跳 /login
|
||||||
|
|
||||||
|
### 8.2 授权
|
||||||
|
|
||||||
|
- 前台: 用户级(需登录)
|
||||||
|
- 后台: 管理员级(role=admin)
|
||||||
|
- API Key: 支持 per-model key 覆盖 provider key
|
||||||
|
|
||||||
|
### 8.3 工具调用沙箱
|
||||||
|
|
||||||
|
```
|
||||||
|
_check_tool_policy() 三层防护:
|
||||||
|
1. 白名单: agent 只允许调特定 skill_ids + mcp_ids
|
||||||
|
2. 预算: max_calls_per_conversation 上限
|
||||||
|
3. 每轮上限: per_round_cap
|
||||||
|
|
||||||
|
代码执行: 独立 executor 容器沙箱
|
||||||
|
密钥管理: credential.py 加解密存储
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、运维架构
|
||||||
|
|
||||||
|
### 9.1 CI/CD
|
||||||
|
|
||||||
|
```
|
||||||
|
Git push → pre-push hook (.git/hooks/pre-push)
|
||||||
|
→ 容器内 backend pytest (28 用例)
|
||||||
|
→ 容器内 frontend vitest (2 文件, 15 用例)
|
||||||
|
→ 全绿 → push 放行
|
||||||
|
→ 失败 → block
|
||||||
|
|
||||||
|
部署:
|
||||||
|
docker cp 容器文件 → 宿主 Git
|
||||||
|
→ git add -A + commit
|
||||||
|
→ docker commit → qihuaiflow:with-deps (新镜像)
|
||||||
|
→ docker compose up -d --force-recreate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.2 健康检查
|
||||||
|
|
||||||
|
```
|
||||||
|
/health → 200 {status: "ok"} (liveness)
|
||||||
|
前端 :8080 → 200 HTML (SPA)
|
||||||
|
后端 :18080/docs → 200 Swagger UI
|
||||||
|
容器: docker restart → < 20s 恢复
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.3 监控栈
|
||||||
|
|
||||||
|
```
|
||||||
|
Prometheus (scrape) ← node-exporter (host) + Alloy (logs)
|
||||||
|
Grafana (visualize) ← Prometheus datasource
|
||||||
|
应用日志: Python logging → docker logs / Alloy 采集
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、市场竞争分析
|
||||||
|
|
||||||
|
### 10.1 护城河
|
||||||
|
|
||||||
|
| 护城河 | 具体实现 | 壁垒强度 |
|
||||||
|
|--------|---------|---------|
|
||||||
|
| **多模型协议适配层** | OpenAI/Anthropic/Token Plan 三种认证头、MCP Schema → OpenAI 转换 | 🔴 高 |
|
||||||
|
| **Skill 全生命周期** | 发布→审核→上架→安装→执行→进化,闭环 | 🔴 高 |
|
||||||
|
| **Agent DAG 编排** | 拓扑排序+分层并行+失败隔离+外部 Agent 远程调用 | 🟡 中 |
|
||||||
|
| **工具调��标准化** | AGENT_GUIDE + tool_policy 沙箱 + 15 轮 loop + 错误自修正 | 🟡 中 |
|
||||||
|
| **PG 统一数据层** | 主库+向量+Casdoor 同集群 pgvector,混合检索零延迟 | 🟡 中 |
|
||||||
|
| **IM Bot 多平台** | 统一消息网关,微信/企业微信/飞书/QQ | 🟢 低 |
|
||||||
|
| **安全沙箱** | Tool Policy 白名单+预算+代码执行容器隔离 | 🟡 中 |
|
||||||
|
|
||||||
|
### 10.2 竞品对比
|
||||||
|
|
||||||
|
| 维度 | 七虎AI | Dify | Coze | 扣子 | FastGPT |
|
||||||
|
|------|--------|------|------|------|---------|
|
||||||
|
| 模型聚合 | ✅ 手动 failover | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
| Skill 市场 | ✅ 上架-安装-进化 | ❌ | ❌ (Plugin) | ❌ (Plugin) | ❌ |
|
||||||
|
| MCP 协议 | ✅ 官方 SDK | ✅ | ❌ | ❌ | ❌ |
|
||||||
|
| Agent DAG | ✅ 图引擎 | ✅ 工作流 | ✅ 工作流 | ✅ 工作流 | ❌ 简单 |
|
||||||
|
| IM Bot | ✅ 多平台 | ❌ | ❌ | ✅ 飞书 | ❌ |
|
||||||
|
| PG 全栈 | ✅ PG18 | ⚠️ MySQL | ? | ? | ✅ PG |
|
||||||
|
| Auth | ✅ Casdoor+JWT | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
|
||||||
|
### 10.3 扩展能力
|
||||||
|
|
||||||
|
| 扩展方向 | 当前能力 | 增长空间 |
|
||||||
|
|---------|---------|---------|
|
||||||
|
| 模型厂商 | 4 家 | 新增厂商只需配 ModelProvider |
|
||||||
|
| Skill 类型 | 14 场景分类 | 支持自定义执行器(非纯 LLM 转发) |
|
||||||
|
| MCP 服务 | 任意 MCP Server | MCP Registry 对接 |
|
||||||
|
| Agent | Dify/n8n/Coze + 自研 DAG | CrewAI/LangGraph 集成 |
|
||||||
|
| 前端渠道 | Web Chat + IM Bot | API/Webhook/SDK |
|
||||||
|
| 计费 | Token + 会员 | 按 Skill/MCP 调用计费 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十一、迭代路线图
|
||||||
|
|
||||||
|
### 已完成
|
||||||
|
|
||||||
|
- [x] PostgreSQL 迁移(MySQL → PG18 + pgvector)
|
||||||
|
- [x] SSE 四类事件(reasoning/delta/step/done)
|
||||||
|
- [x] MCP 协议标准化(官方 SDK,Schema 转换)
|
||||||
|
- [x] Agent DAG 编排引擎 + YAML workflow
|
||||||
|
- [x] 工具调用标准化(AGENT_GUIDE + install_app 优化 + max_rounds 15 + MCP 命名)
|
||||||
|
- [x] 模型 Failover + 事件循环防冻(#812)
|
||||||
|
- [x] Token Plan 适配(MiMo custom auth_header)
|
||||||
|
- [x] 前端 Step 渲染增强(⏳/✅/❌ 状态)
|
||||||
|
- [x] 横向溢出防护(overflow-x: hidden 三层)
|
||||||
|
- [x] 知识库 KG 构建
|
||||||
|
- [x] 多平台 IM Bot Hub
|
||||||
|
- [x] Prometheus+Grafana 监控栈
|
||||||
|
|
||||||
|
### 进行中
|
||||||
|
|
||||||
|
- [ ] Skill 真实执行器(非 LLM 转发模拟)
|
||||||
|
- [ ] 多 Agent 协作(Supervisor 模式)
|
||||||
|
- [ ] API/OpenAPI 对外接口
|
||||||
|
- [ ] 技能 SDK 发布工具
|
||||||
|
|
||||||
|
### 计划中
|
||||||
|
|
||||||
|
- [ ] LiteLLM 集成(统一模型路由+成本追踪)
|
||||||
|
- [ ] 流式 Token 计费(精确到字符级)
|
||||||
|
- [ ] LangGraph 工作流引擎
|
||||||
|
- [ ] 向量混合检索增强(BM25 + dense + sparse)
|
||||||
|
- [ ] 前端暗色模式
|
||||||
|
- [ ] 多语言(i18n)
|
||||||
|
- [ ] 移动端适配
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> **文档维护规则**: 每次系统重大迭代后,更新本文档对应章节并变更版本号。
|
||||||
|
> **上传位置**: Gitea 仓库 `qihuaiflow/docs/ARCHITECTURE.md`
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
# 七虎AI PaaS 平台 — 迭代优化可执行方案 v1.0
|
||||||
|
|
||||||
|
> **来源**: 基于 `AI_PaaS_Platform_Analysis_and_Execution_Plan v2.md`(元宝深度分析文档)
|
||||||
|
> **日期**: 2026-07-27
|
||||||
|
> **原则**: P0 先做、P1 跟进、P2 规划评估;每 Phase 一个交付周期
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 总览:20 项行动按 4 个 Phase 分组
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 0 (本周): 4 P0 项 — 基础设施补全,投入产出比最高
|
||||||
|
Phase 1 (2周内): 6 P0+P1 项 — 核心竞争力构建
|
||||||
|
Phase 2 (1月内): 5 P1 项 — 体验与护城河加固
|
||||||
|
Phase 3 (评估): 5 P2 项 — 按需投入
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 0:基础设施补全(本周,4 项 P0)
|
||||||
|
|
||||||
|
这些是文档反复强调的"先决条件"——不做,后面的都没法高效开展。
|
||||||
|
|
||||||
|
### #0A. 多租户隔离(PG RLS + tenant_id)
|
||||||
|
|
||||||
|
**现状**: 平台无真正的多租户隔离。所有用户共享同一套数据,仅靠 JWT 区分身份。
|
||||||
|
**目标**: 启用 PostgreSQL Row Level Security,所有业务表加 `tenant_id`。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**实施**:
|
||||||
|
- 核心表(conversations/messages/market_apps/skill_instances)加 `tenant_id UUID` 列
|
||||||
|
- 启用 `ALTER TABLE ... ENABLE ROW LEVEL SECURITY`
|
||||||
|
- 创建 RLS 策略:`USING (tenant_id = current_setting('app.current_tenant')::UUID)`
|
||||||
|
- FastAPI middleware 注入 `app.current_tenant` 从 JWT 提取
|
||||||
|
- 知识库/资产存储目录结构改为 `/workspace/{tenant_id}/{user_id}/`
|
||||||
|
|
||||||
|
### #0B. LiteLLM Proxy — 统一 AI 网关
|
||||||
|
|
||||||
|
**现状**: 自定义 failover(`_try_models` 列表 + `continue` 切换),无成本追踪、无限流、无缓存。
|
||||||
|
**目标**: 引入 LiteLLM Proxy 作为网关,客户端零改动。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**实施**:
|
||||||
|
- 部署 `litellm` 容器,配置 `litellm_config.yaml`
|
||||||
|
- 映射现有 4 个 provider(SiliconFlow/MiMo/AGNES/DeepSeek)
|
||||||
|
- 启用 Virtual Keys(按用户/租户分发 API Key,追踪花费)
|
||||||
|
- 启用 RPM/TPM 限流 + 加权负载均衡(替代 try-except failover)
|
||||||
|
- 启用 Redis 语义缓存(相同 prompt 不重复计费)
|
||||||
|
- litellm 端点替换 `DATABASE_URL` 配置中的模型 endpoint
|
||||||
|
|
||||||
|
### #0C. Meilisearch — 技能市场搜索引擎
|
||||||
|
|
||||||
|
**现状**: 技能市场搜索依赖 PostgreSQL `ILIKE` 查询,无中文分词、无 BM25、无分面筛选。
|
||||||
|
**目标**: 部署 Meilisearch 容器,替代 PG 全文搜索。
|
||||||
|
**工作量**: 2 天
|
||||||
|
**实施**:
|
||||||
|
- 部署 `meilisearch` 容器(含 jieba 中文分词)
|
||||||
|
- 创建 `market_apps` 索引(name/description/tags/category/capability/publisher)
|
||||||
|
- 全量同步现有 115 个技能到 Meilisearch
|
||||||
|
- 前端 MarketPage 搜索框改为调用 `/search` API(sub-50ms 响应)
|
||||||
|
- 支持 facets(category/capability/tags)+ 排序(downloads/rating/date)
|
||||||
|
- 后续可用 Tenant Tokens 做多租户搜索隔离
|
||||||
|
|
||||||
|
### #0D. 角色模型扩展(5 级 + 用户组)
|
||||||
|
|
||||||
|
**现状**: 仅 admin/user 两级,无 user groups、无模型/技能按组分配。
|
||||||
|
**目标**: 5 级角色 + 用户组机制。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**实施**:
|
||||||
|
- 角色:super_admin / admin / developer / user / guest
|
||||||
|
- 用户组(Groups):用户可属于多个组;组级模型配额和技能可见性
|
||||||
|
- 用户组 API(CRUD + 成员管理)
|
||||||
|
- 前端 AdminLayout 角色判断(developer 可发布技能但不可管理用户)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1:核心竞争力构建(2 周内,6 项 P0+P1)
|
||||||
|
|
||||||
|
### #1A. 技能真实执行器 — 3 个标杆技能 ⭐ 最重要
|
||||||
|
|
||||||
|
**现状**: `_execute_skill_tool()` 是"指令转发"——把 SKILL.md 的文字抄给 LLM,让 LLM "模拟执行"。这是平台最大短板。
|
||||||
|
**目标**: 落地真实执行器,3 个标杆技能跑通端到端。
|
||||||
|
**工作量**: 2 周
|
||||||
|
**实施**:
|
||||||
|
|
||||||
|
**Step 1: 执行器基础架构(3 天)**
|
||||||
|
- `SkillRuntime` 类:鉴权 → 创建工作区 → 调技能 API → 扣配额 → 存储产物 → 记录计量
|
||||||
|
- `SkillInstance` DB 模型:状态机(generating/ready/failed/archived)
|
||||||
|
- S3 兼容对象存储集成(MinIO 起步)
|
||||||
|
- 工作区隔离:`/workspace/{tenant_id}/{user_id}/{skill}/{instance_id}/`
|
||||||
|
|
||||||
|
**Step 2: 标杆技能 #1 — AI PPT 生成器(5 天)**
|
||||||
|
- 基于 dashi-ppt-skill 改造
|
||||||
|
- 适配层 API:`/api/generate` POST、`/api/export/pptx` GET、`/api/export/pdf` GET
|
||||||
|
- 输入:文本/文档 → LLM 生成大纲 → 渲染 HTML 幻灯片 → 导出 PPTX/PDF
|
||||||
|
- 预览图生成(headless Chrome 截图)
|
||||||
|
- 配额:Free 3次/天,Pro 50次/天
|
||||||
|
|
||||||
|
**Step 3: 标杆技能 #2 — SEO 优化助手(2 天)**
|
||||||
|
- 基于 marketing-skills 改造
|
||||||
|
- 输入:URL/关键词 → 分析 SERP → 输出 SEO 报告+优化建议
|
||||||
|
|
||||||
|
**Step 4: 标杆技能 #3 — AI 投研报告��2 天)**
|
||||||
|
- 基于 equity-research-skill 改造
|
||||||
|
- 输入:股票代码 → 财报分析 + DCF 估值 → 输出结构化投研报告
|
||||||
|
|
||||||
|
### #1B. 统一 SKILL.md Schema
|
||||||
|
|
||||||
|
**现状**: 技能元数据散乱,无统一格式/版本/权限/定价规范。
|
||||||
|
**目标**: 发布平台统一 SKILL.md 规范(9 大区块)。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**实施**:
|
||||||
|
- Schema:name/version/author/description/capabilities/inputs/outputs/resource/permissions/dependencies/pricing
|
||||||
|
- 与现有 market_app DB 字段映射
|
||||||
|
- 自动解析器:`_parse_skill_content()` 增强,从 SKILL.md 提取结构
|
||||||
|
- 前端技能详情页显示结构化信息(输入/输出/配额/定价)
|
||||||
|
|
||||||
|
### #1C. 流式 Token 计费 + 实时余额
|
||||||
|
|
||||||
|
**现状**: 仅记录 Token 用量,无计费、无余额扣减、无配额提示。
|
||||||
|
**目标**: 实时 Token 计费 + 流式扣费 + 用户余额。
|
||||||
|
**工作量**: 5 天
|
||||||
|
**实施**:
|
||||||
|
- LiteLLM 集成后,每次调用自动获取 `usage.prompt_tokens + completion_tokens`
|
||||||
|
- 流式场景:累加 chunk 计数,`done` 事件时写入
|
||||||
|
- 用户余额表:`token_balances`
|
||||||
|
- 前端:对话中实时显示剩余 Token(顶部状态栏)
|
||||||
|
- 余额不足时提前拦截(不浪费一次模型调用)
|
||||||
|
|
||||||
|
### #1D. Agent 可视化编排画布 ⭐ 亮点
|
||||||
|
|
||||||
|
**现状**: Agent 编排靠 YAML 手写,无可视化界面。
|
||||||
|
**目标**: 基于 React Flow 的可拖拽编排画布。
|
||||||
|
**工作量**: 2 周
|
||||||
|
**实施**:
|
||||||
|
- 前端:React Flow 节点编辑器(节点库:LLM/Skill/MCP/External/Reduce/条件分支)
|
||||||
|
- 拖拽连线定义数据流
|
||||||
|
- 导出为 YAML → 对接现有 `run_graph()` 引擎
|
||||||
|
- 执行监控:实时高亮当前执行节点、查看输出
|
||||||
|
|
||||||
|
### #1E. 角色模型扩展(5 级 + 用户组)— 续 Phase 0D
|
||||||
|
(已在 Phase 0 中定义)
|
||||||
|
|
||||||
|
### #1F. 技能市场搜索 — 续 Phase 0C
|
||||||
|
(已在 Phase 0 中定义,Meilisearch)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2:体验与护城河加固(1 月内,5 项 P1)
|
||||||
|
|
||||||
|
### #2A. 工具调用四级风险审批
|
||||||
|
|
||||||
|
**现状**: 仅 `tool_policy` 沙箱(白名单+预算+每轮上限),无操作风险分级。
|
||||||
|
**目标**: 参考 OpenWorker 的四级风险模型。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**实施**:
|
||||||
|
- 风险等级:read / write_local / exec / external
|
||||||
|
- 每级定义默认行为(read 自动许可 / write_local 确认 / exec 审批 / external 管理员审批)
|
||||||
|
- 前端:高风险操作弹窗确认 + 审批后重试
|
||||||
|
- 审批队列:pending_approvals 表 + 管理员后台
|
||||||
|
|
||||||
|
### #2B. 引入 MemPalace 分层记忆
|
||||||
|
|
||||||
|
**现状**: 五类结构化记忆(实体/事实/偏好/决策/待办),无分层索引。
|
||||||
|
**目标**: Wing/Room/Drawer 分层索引(MemPalace)。
|
||||||
|
**工作量**: 1 周
|
||||||
|
**实施**:
|
||||||
|
- Wing = 用户级(跨所有对话)
|
||||||
|
- Room = 对话级(单次对话上下文)
|
||||||
|
- Drawer = 话题级(对话内特定话题)
|
||||||
|
- 跑 LongMemEval benchmark 量化召回率
|
||||||
|
|
||||||
|
### #2C. Loop 原语 + Verifier
|
||||||
|
|
||||||
|
**现状**: Agent 编排是 DAG 拓扑排序,无循环边、无验证器。
|
||||||
|
**目标**: 引入 Loop 原语(循环边 + 终止条件 + Verifier)。
|
||||||
|
**工作量**: 1 周
|
||||||
|
**实施**:
|
||||||
|
- `orchestrator.py` 支持循环边:`{"from": "verify", "to": "generate", "condition": "not_passed"}`
|
||||||
|
- Verifier 节点:判断目标是否达成的验证器
|
||||||
|
- 前端画布(#1D)支持画循环边
|
||||||
|
|
||||||
|
### #2D. executor 沙箱升级
|
||||||
|
|
||||||
|
**现状**: executor 容器基于 Docker,无严格内核隔离。
|
||||||
|
**目标**: gVisor 或 Firecracker 微虚拟机隔离。
|
||||||
|
**工作量**: 3 天
|
||||||
|
**评估**: gVisor 集成最简单(Docker 的 `--runtime=runsc`)
|
||||||
|
|
||||||
|
### #2E. 技能 SDK + 脚手架 CLI
|
||||||
|
|
||||||
|
**现状**: 技能开发者手动创建目录和 SKILL.md。
|
||||||
|
**目标**: `qihu-skill` CLI 脚手架。
|
||||||
|
**工作量**: 1 周
|
||||||
|
**实施**:
|
||||||
|
- `qihu-skill init my-skill` → 生成目录结构 + SKILL.md 模板
|
||||||
|
- `qihu-skill validate` → 校验 SKILL.md Schema
|
||||||
|
- `qihu-skill publish` → 打包上传到平台技能市场
|
||||||
|
- `qihu-skill dev` → 本地调试(Mock SkillRuntime)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3:评估后按需投入(5 项,P2)
|
||||||
|
|
||||||
|
### #3A. Semantica 决策溯源
|
||||||
|
- 场景:金融/医疗/法律客户要求可解释 AI
|
||||||
|
- 工作量:评估 3 天 + 集成 1 周
|
||||||
|
- 决策标准:是否有付费企业客户明确要求
|
||||||
|
|
||||||
|
### #3B. Langfuse/LangSmith Agent 轨迹
|
||||||
|
- 场景:开发者调试 Agent 执行、产品优化
|
||||||
|
- 工作量:3 天集成
|
||||||
|
- 决策标准:Agent 可视化画布上线后,按需求优先级
|
||||||
|
|
||||||
|
### #3C. Agent 广播网络(EigenFlux)
|
||||||
|
- 场景:Agent 间自动发现与协作
|
||||||
|
- 工作量:评估
|
||||||
|
- 决策标准:多 Agent 协作需求明确后
|
||||||
|
|
||||||
|
### #3D. 前端暗色模式
|
||||||
|
- 工作量:3 天
|
||||||
|
- 决策标准:用户体验迭代批次
|
||||||
|
|
||||||
|
### #3E. 移动端适配
|
||||||
|
- 工作量:2 周
|
||||||
|
- 决策标准:移动端用户数据达标后
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 优先级总表(20 项排序)
|
||||||
|
|
||||||
|
| # | 行动 | 模块 | 优先级 | 工作量 | 依赖 |
|
||||||
|
|---|------|------|--------|--------|------|
|
||||||
|
| 1 | LiteLLM Proxy 统一 AI 网关 | 模型路由 | P0 | 3d | - |
|
||||||
|
| 2 | Meilisearch 技能市场搜索 | 搜索 | P0 | 2d | - |
|
||||||
|
| 3 | PG RLS + tenant_id 多租户隔离 | 多租户 | P0 | 3d | - |
|
||||||
|
| 4 | 角色 5 级 + 用户组 | 多租户 | P0 | 3d | #3 |
|
||||||
|
| **5** | **3 个标杆技能真实执行器** | **技能市场** | **P0** | **2w** | **-** |
|
||||||
|
| 6 | SKILL.md 统一 Schema | 技能市场 | P0 | 3d | - |
|
||||||
|
| 7 | 流式 Token 计费 + 实时余额 | 变现 | P0 | 5d | #1 |
|
||||||
|
| **8** | **Agent 可视化编排画布** | **Agent** | **P1** | **2w** | **-** |
|
||||||
|
| 9 | Loop 原语 + Verifier | Agent | P1 | 1w | #8 |
|
||||||
|
| 10 | 工具四级风险审批 | 安全 | P1 | 3d | - |
|
||||||
|
| 11 | executor gVisor 升级 | 安全 | P1 | 3d | - |
|
||||||
|
| 12 | MemPalace 分层记忆 | RAG | P1 | 1w | - |
|
||||||
|
| 13 | 技能 SDK + 脚手架 CLI | 技能市场 | P1 | 1w | #6 |
|
||||||
|
| 14 | LongMemEval 基准测试 | RAG | P1 | 2d | - |
|
||||||
|
| 15 | 技能审核流水线 | 技能市场 | P2 | 1w | #6 |
|
||||||
|
| 16 | 分润模型 + 开发者结算 | 变现 | P2 | 1w | #7 |
|
||||||
|
| 17 | Langfuse Agent 轨迹 | 可观测 | P2 | 3d | #1 |
|
||||||
|
| 18 | Semantica 决策溯源 | 安全 | P2 | 评估 | - |
|
||||||
|
| 19 | 前端暗色模式 | UI | P2 | 3d | - |
|
||||||
|
| 20 | 移动端适配 | UI | P2 | 2w | - |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 竞品对比更新(基于分析文档)
|
||||||
|
|
||||||
|
| 维度 | 七虎AI 现状 | Open WebUI | Dify | 差距/优势 |
|
||||||
|
|------|------------|------------|------|----------|
|
||||||
|
| RBAC | admin/user 2 级 | Admin/User/Pending + Groups | 内置多租户 | 🔴 落后 |
|
||||||
|
| 向量库 | 仅 pgvector | 9 种可插拔 | 多种 | 🟡 够用 |
|
||||||
|
| RAG 管线 | 单路向量 | 3 阶段 BM25+向量+Rerank | 混合检索 | 🟡 待增强 |
|
||||||
|
| 插件体系 | Skills+MCP | 5 类插件 | 工作流节点 | 🟡 够用 |
|
||||||
|
| Token 计量 | 仅记录 | 实时+按模型+仪表盘 | 内置 | 🔴 落后 |
|
||||||
|
| 模型路由 | try-except | Pipe 路由 | 内置 failover | 🟡 待 LiteLLM |
|
||||||
|
| Agent 编排 | DAG 图引擎 | 无 | 工作流画布 | 🟢 领先 |
|
||||||
|
| 技能市场 | 上架-安装-执行 | 无 | 无 | 🟢 护城河 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 当前已完成(对标分析文档的"已修复弱点")
|
||||||
|
|
||||||
|
这些本期会话已修复,分析文档第九节引用:
|
||||||
|
|
||||||
|
| 修复 | 状态 | 对应文档章节 |
|
||||||
|
|------|------|------------|
|
||||||
|
| AGENT_GUIDE 标准化 | ✅ | §九 - 固定弱点已修复 |
|
||||||
|
| MCP 官方 SDK + Schema 转换 | ✅ | §九 |
|
||||||
|
| Tool Policy 白名单+预算+每轮上限 | ✅ | §九 |
|
||||||
|
| MiMo Token Plan 适配 | ✅ | - |
|
||||||
|
| `overflow-x: hidden` 响应式修复 | ✅ | - |
|
||||||
|
| 架构蓝图 `ARCHITECTURE.md` | ✅ | - |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> **执行指令**: 告诉我 "执行 Phase 0" 开始落地。每完成一项在对应 checkpoint 勾掉。
|
||||||
|
> **上传到 Gitea**: 本方案同步上传到 `qihuaiflow/docs/ITERATION_PLAN.md`
|
||||||
+177
-177
@@ -1,177 +1,177 @@
|
|||||||
import React, { useState, useEffect, Suspense } from 'react';
|
import React, { useState, useEffect, Suspense } from 'react';
|
||||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||||
import type { User } from '@/types';
|
import type { User } from '@/types';
|
||||||
import { AuthContext, AuthContextType } from '@/contexts/AuthContext';
|
import { AuthContext, AuthContextType } from '@/contexts/AuthContext';
|
||||||
import { authAPI } from '@/api';
|
import { authAPI } from '@/api';
|
||||||
|
|
||||||
// Layouts(保留为即时加载,构成应用外壳)
|
// Layouts(保留为即时加载,构成应用外壳)
|
||||||
import FrontLayout from '@/components/layout/FrontLayout';
|
import FrontLayout from '@/components/layout/FrontLayout';
|
||||||
import AdminLayout from '@/components/layout/AdminLayout';
|
import AdminLayout from '@/components/layout/AdminLayout';
|
||||||
|
|
||||||
// 路由级代码分割:每个页面独立打包成 chunk,首屏只加载外壳与公共依赖,
|
// 路由级代码分割:每个页面独立打包成 chunk,首屏只加载外壳与公共依赖,
|
||||||
// 访问具体页面时才按需加载对应 chunk,显著加快首屏渲染与路由切换速度。
|
// 访问具体页面时才按需加载对应 chunk,显著加快首屏渲染与路由切换速度。
|
||||||
const LandingPage = React.lazy(() => import('@/pages/front/LandingPage'));
|
const LandingPage = React.lazy(() => import('@/pages/front/LandingPage'));
|
||||||
const LoginPage = React.lazy(() => import('@/pages/front/LoginPage'));
|
const LoginPage = React.lazy(() => import('@/pages/front/LoginPage'));
|
||||||
const ChatPage = React.lazy(() => import('@/pages/front/ChatPage'));
|
const ChatPage = React.lazy(() => import('@/pages/front/ChatPage'));
|
||||||
const KnowledgePage = React.lazy(() => import('@/pages/front/KnowledgePage'));
|
const KnowledgePage = React.lazy(() => import('@/pages/front/KnowledgePage'));
|
||||||
const MarketPage = React.lazy(() => import('@/pages/front/MarketPage'));
|
const MarketPage = React.lazy(() => import('@/pages/front/MarketPage'));
|
||||||
const TokenDashboardPage = React.lazy(() => import('@/pages/front/TokenDashboardPage'));
|
const TokenDashboardPage = React.lazy(() => import('@/pages/front/TokenDashboardPage'));
|
||||||
const PricingPage = React.lazy(() => import('@/pages/front/PricingPage'));
|
const PricingPage = React.lazy(() => import('@/pages/front/PricingPage'));
|
||||||
const ProfilePage = React.lazy(() => import('@/pages/front/ProfilePage'));
|
const ProfilePage = React.lazy(() => import('@/pages/front/ProfilePage'));
|
||||||
const NotificationPage = React.lazy(() => import('@/pages/front/NotificationPage'));
|
const NotificationPage = React.lazy(() => import('@/pages/front/NotificationPage'));
|
||||||
const AssetsPage = React.lazy(() => import('@/pages/front/AssetsPage'));
|
const AssetsPage = React.lazy(() => import('@/pages/front/AssetsPage'));
|
||||||
const NovelPreviewPage = React.lazy(() => import('@/pages/front/NovelPreviewPage'));
|
const NovelPreviewPage = React.lazy(() => import('@/pages/front/NovelPreviewPage'));
|
||||||
const EvolutionDashboard = React.lazy(() => import('@/pages/front/EvolutionDashboard'));
|
const EvolutionDashboard = React.lazy(() => import('@/pages/front/EvolutionDashboard'));
|
||||||
|
|
||||||
const AdminDashboard = React.lazy(() => import('@/pages/admin/Dashboard'));
|
const AdminDashboard = React.lazy(() => import('@/pages/admin/Dashboard'));
|
||||||
const AdminUsers = React.lazy(() => import('@/pages/admin/Users'));
|
const AdminUsers = React.lazy(() => import('@/pages/admin/Users'));
|
||||||
const AdminModels = React.lazy(() => import('@/pages/admin/Models'));
|
const AdminModels = React.lazy(() => import('@/pages/admin/Models'));
|
||||||
const AdminSiteSettings = React.lazy(() => import('@/pages/admin/SiteSettings'));
|
const AdminSiteSettings = React.lazy(() => import('@/pages/admin/SiteSettings'));
|
||||||
const AdminSmsConfig = React.lazy(() => import('@/pages/admin/SmsConfig'));
|
const AdminSmsConfig = React.lazy(() => import('@/pages/admin/SmsConfig'));
|
||||||
const AdminPayment = React.lazy(() => import('@/pages/admin/Payment'));
|
const AdminPayment = React.lazy(() => import('@/pages/admin/Payment'));
|
||||||
const AdminServices = React.lazy(() => import('@/pages/admin/Services'));
|
const AdminServices = React.lazy(() => import('@/pages/admin/Services'));
|
||||||
const AdminMembership = React.lazy(() => import('@/pages/admin/Membership'));
|
const AdminMembership = React.lazy(() => import('@/pages/admin/Membership'));
|
||||||
const AdminAds = React.lazy(() => import('@/pages/admin/Ads'));
|
const AdminAds = React.lazy(() => import('@/pages/admin/Ads'));
|
||||||
const AdminMarket = React.lazy(() => import('@/pages/admin/Market'));
|
const AdminMarket = React.lazy(() => import('@/pages/admin/Market'));
|
||||||
const AdminLogs = React.lazy(() => import('@/pages/admin/Logs'));
|
const AdminLogs = React.lazy(() => import('@/pages/admin/Logs'));
|
||||||
const AdminSkills = React.lazy(() => import('@/pages/admin/Skills'));
|
const AdminSkills = React.lazy(() => import('@/pages/admin/Skills'));
|
||||||
const AdminAgents = React.lazy(() => import('@/pages/admin/Agents'));
|
const AdminAgents = React.lazy(() => import('@/pages/admin/Agents'));
|
||||||
const AdminCodeExec = React.lazy(() => import('@/pages/admin/CodeExec'));
|
const AdminCodeExec = React.lazy(() => import('@/pages/admin/CodeExec'));
|
||||||
const DistributionBuilder = React.lazy(() => import('@/pages/admin/DistributionBuilder'));
|
const DistributionBuilder = React.lazy(() => import('@/pages/admin/DistributionBuilder'));
|
||||||
const ImBots = React.lazy(() => import('@/pages/admin/ImBots'));
|
const ImBots = React.lazy(() => import('@/pages/admin/ImBots'));
|
||||||
const PrivacySettings = React.lazy(() => import('@/pages/admin/PrivacySettings'));
|
const PrivacySettings = React.lazy(() => import('@/pages/admin/PrivacySettings'));
|
||||||
const Promotion = React.lazy(() => import('@/pages/admin/Promotion'));
|
const Promotion = React.lazy(() => import('@/pages/admin/Promotion'));
|
||||||
const Achievement = React.lazy(() => import('@/pages/admin/Achievement'));
|
const Achievement = React.lazy(() => import('@/pages/admin/Achievement'));
|
||||||
const Tenant = React.lazy(() => import('@/pages/admin/Tenant'));
|
const Tenant = React.lazy(() => import('@/pages/admin/Tenant'));
|
||||||
const Billing = React.lazy(() => import('@/pages/admin/Billing'));
|
const Billing = React.lazy(() => import('@/pages/admin/Billing'));
|
||||||
const Analytics = React.lazy(() => import('@/pages/admin/Analytics'));
|
const Analytics = React.lazy(() => import('@/pages/admin/Analytics'));
|
||||||
const Observability = React.lazy(() => import('@/pages/admin/Observability'));
|
const Observability = React.lazy(() => import('@/pages/admin/Observability'));
|
||||||
const AdminKnowledge = React.lazy(() => import('@/pages/admin/Knowledge'));
|
const AdminKnowledge = React.lazy(() => import('@/pages/admin/Knowledge'));
|
||||||
const AdminWorkflow = React.lazy(() => import('@/pages/admin/Workflow'));
|
const AdminWorkflow = React.lazy(() => import('@/pages/admin/Workflow'));
|
||||||
const AdminStorage = React.lazy(() => import('@/pages/admin/Storage'));
|
const AdminStorage = React.lazy(() => import('@/pages/admin/Storage'));
|
||||||
const AdminDeveloper = React.lazy(() => import('@/pages/admin/Developer'));
|
const AdminDeveloper = React.lazy(() => import('@/pages/admin/Developer'));
|
||||||
const AdminDeveloperTools = React.lazy(() => import('@/pages/admin/DeveloperTools'));
|
const AdminDeveloperTools = React.lazy(() => import('@/pages/admin/DeveloperTools'));
|
||||||
const AdminAutomation = React.lazy(() => import('@/pages/admin/Automation'));
|
const AdminAutomation = React.lazy(() => import('@/pages/admin/Automation'));
|
||||||
const AdminMcp = React.lazy(() => import('@/pages/admin/Mcp'));
|
const AdminMcp = React.lazy(() => import('@/pages/admin/Mcp'));
|
||||||
const AdminApps = React.lazy(() => import('@/pages/admin/Apps'));
|
const AdminApps = React.lazy(() => import('@/pages/admin/Apps'));
|
||||||
const AssetCenter = React.lazy(() => import('@/pages/admin/AssetCenter'));
|
const AssetCenter = React.lazy(() => import('@/pages/admin/AssetCenter'));
|
||||||
const UserPortal = React.lazy(() => import('@/pages/UserPortal'));
|
const UserPortal = React.lazy(() => import('@/pages/UserPortal'));
|
||||||
const WechatBot = React.lazy(() => import('@/pages/front/WechatBot'));
|
const WechatBot = React.lazy(() => import('@/pages/front/WechatBot'));
|
||||||
const ImBotHub = React.lazy(() => import('@/pages/front/ImBotHub'));
|
const ImBotHub = React.lazy(() => import('@/pages/front/ImBotHub'));
|
||||||
const AppServices = React.lazy(() => import('@/pages/front/AppServices'));
|
const AppServices = React.lazy(() => import('@/pages/front/AppServices'));
|
||||||
|
|
||||||
const pageFallback = <div className="loading-screen">加载中...</div>;
|
const pageFallback = <div className="loading-screen">加载中...</div>;
|
||||||
|
|
||||||
const App: React.FC = () => {
|
const App: React.FC = () => {
|
||||||
const [user, setUser] = useState<User | null>(null);
|
const [user, setUser] = useState<User | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
// 初始化:从localStorage恢复登录状态
|
// 初始化:从localStorage恢复登录状态
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const token = localStorage.getItem('aiflow_token');
|
const token = localStorage.getItem('aiflow_token');
|
||||||
const cachedUser = localStorage.getItem('aiflow_user');
|
const cachedUser = localStorage.getItem('aiflow_user');
|
||||||
if (token && cachedUser) {
|
if (token && cachedUser) {
|
||||||
try {
|
try {
|
||||||
setUser(JSON.parse(cachedUser));
|
setUser(JSON.parse(cachedUser));
|
||||||
} catch {
|
} catch {
|
||||||
localStorage.removeItem('aiflow_token');
|
localStorage.removeItem('aiflow_token');
|
||||||
localStorage.removeItem('aiflow_user');
|
localStorage.removeItem('aiflow_user');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const login = (u: User) => {
|
const login = (u: User) => {
|
||||||
setUser(u);
|
setUser(u);
|
||||||
localStorage.setItem('aiflow_user', JSON.stringify(u));
|
localStorage.setItem('aiflow_user', JSON.stringify(u));
|
||||||
};
|
};
|
||||||
const logout = () => {
|
const logout = () => {
|
||||||
setUser(null);
|
setUser(null);
|
||||||
localStorage.removeItem('aiflow_token');
|
localStorage.removeItem('aiflow_token');
|
||||||
localStorage.removeItem('aiflow_user');
|
localStorage.removeItem('aiflow_user');
|
||||||
};
|
};
|
||||||
const isAdmin = user?.role === 'admin';
|
const isAdmin = user?.role === 'admin';
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return <div className="loading-screen">加载中...</div>;
|
return <div className="loading-screen">加载中...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ user, login, logout, isAdmin }}>
|
<AuthContext.Provider value={{ user, login, logout, isAdmin }}>
|
||||||
<Suspense fallback={pageFallback}>
|
<Suspense fallback={pageFallback}>
|
||||||
<Routes>
|
<Routes>
|
||||||
{/* Login */}
|
{/* Login */}
|
||||||
<Route path="/login" element={
|
<Route path="/login" element={
|
||||||
user ? (isAdmin ? <Navigate to="/admin" /> : <Navigate to="/chat" />) : <LoginPage />
|
user ? (isAdmin ? <Navigate to="/admin" /> : <Navigate to="/chat" />) : <LoginPage />
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Root - Landing for guests, redirect for authenticated users */}
|
{/* Root - Landing for guests, redirect for authenticated users */}
|
||||||
<Route path="/" element={
|
<Route path="/" element={
|
||||||
user ? (isAdmin ? <Navigate to="/admin" /> : <Navigate to="/chat" />) : <LandingPage />
|
user ? (isAdmin ? <Navigate to="/admin" /> : <Navigate to="/chat" />) : <LandingPage />
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Front Routes (authenticated only) */}
|
{/* Front Routes (authenticated only) */}
|
||||||
<Route path="/" element={<FrontLayout />}>
|
<Route path="/" element={<FrontLayout />}>
|
||||||
<Route path="chat" element={<ChatPage />} />
|
<Route path="chat" element={<ChatPage />} />
|
||||||
<Route path="chat/:id" element={<ChatPage />} />
|
<Route path="chat/:id" element={<ChatPage />} />
|
||||||
<Route path="knowledge" element={<KnowledgePage />} />
|
<Route path="knowledge" element={<KnowledgePage />} />
|
||||||
<Route path="market" element={<MarketPage />} />
|
<Route path="market" element={<MarketPage />} />
|
||||||
<Route path="token" element={<TokenDashboardPage />} />
|
<Route path="token" element={<TokenDashboardPage />} />
|
||||||
<Route path="pricing" element={<PricingPage />} />
|
<Route path="pricing" element={<PricingPage />} />
|
||||||
<Route path="profile" element={<ProfilePage />} />
|
<Route path="profile" element={<ProfilePage />} />
|
||||||
<Route path="notifications" element={<NotificationPage />} />
|
<Route path="notifications" element={<NotificationPage />} />
|
||||||
<Route path="assets" element={<AssetsPage />} />
|
<Route path="assets" element={<AssetsPage />} />
|
||||||
<Route path="assets/novel/:id" element={<NovelPreviewPage />} />
|
<Route path="assets/novel/:id" element={<NovelPreviewPage />} />
|
||||||
<Route path="evolution" element={<EvolutionDashboard />} />
|
<Route path="evolution" element={<EvolutionDashboard />} />
|
||||||
<Route path="wechat-bot" element={<WechatBot />} />
|
<Route path="wechat-bot" element={<WechatBot />} />
|
||||||
<Route path="im-bots" element={<ImBotHub />} />
|
<Route path="im-bots" element={<ImBotHub />} />
|
||||||
<Route path="app-services" element={<AppServices />} />
|
<Route path="app-services" element={<AppServices />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
{/* Admin Routes */}
|
{/* Admin Routes */}
|
||||||
<Route path="/admin" element={<AdminLayout />}>
|
<Route path="/admin" element={<AdminLayout />}>
|
||||||
<Route index element={<AdminDashboard />} />
|
<Route index element={<AdminDashboard />} />
|
||||||
<Route path="users" element={<AdminUsers />} />
|
<Route path="users" element={<AdminUsers />} />
|
||||||
<Route path="models" element={<AdminModels />} />
|
<Route path="models" element={<AdminModels />} />
|
||||||
<Route path="settings" element={<AdminSiteSettings />} />
|
<Route path="settings" element={<AdminSiteSettings />} />
|
||||||
<Route path="sms" element={<AdminSmsConfig />} />
|
<Route path="sms" element={<AdminSmsConfig />} />
|
||||||
<Route path="payment" element={<AdminPayment />} />
|
<Route path="payment" element={<AdminPayment />} />
|
||||||
<Route path="services" element={<AdminServices />} />
|
<Route path="services" element={<AdminServices />} />
|
||||||
<Route path="membership" element={<AdminMembership />} />
|
<Route path="membership" element={<AdminMembership />} />
|
||||||
<Route path="ads" element={<AdminAds />} />
|
<Route path="ads" element={<AdminAds />} />
|
||||||
<Route path="market" element={<AdminMarket />} />
|
<Route path="market" element={<AdminMarket />} />
|
||||||
<Route path="logs" element={<AdminLogs />} />
|
<Route path="logs" element={<AdminLogs />} />
|
||||||
<Route path="skills" element={<AdminSkills />} />
|
<Route path="skills" element={<AdminSkills />} />
|
||||||
<Route path="agents" element={<AdminAgents />} />
|
<Route path="agents" element={<AdminAgents />} />
|
||||||
<Route path="code-exec" element={<AdminCodeExec />} />
|
<Route path="code-exec" element={<AdminCodeExec />} />
|
||||||
<Route path="distributions" element={<DistributionBuilder />} />
|
<Route path="distributions" element={<DistributionBuilder />} />
|
||||||
<Route path="im-bots" element={<ImBots />} />
|
<Route path="im-bots" element={<ImBots />} />
|
||||||
<Route path="privacy" element={<PrivacySettings />} />
|
<Route path="privacy" element={<PrivacySettings />} />
|
||||||
<Route path="promotion" element={<Promotion />} />
|
<Route path="promotion" element={<Promotion />} />
|
||||||
<Route path="achievement" element={<Achievement />} />
|
<Route path="achievement" element={<Achievement />} />
|
||||||
<Route path="tenant" element={<Tenant />} />
|
<Route path="tenant" element={<Tenant />} />
|
||||||
<Route path="billing" element={<Billing />} />
|
<Route path="billing" element={<Billing />} />
|
||||||
<Route path="analytics" element={<Analytics />} />
|
<Route path="analytics" element={<Analytics />} />
|
||||||
<Route path="observability" element={<Observability />} />
|
<Route path="observability" element={<Observability />} />
|
||||||
<Route path="knowledge" element={<AdminKnowledge />} />
|
<Route path="knowledge" element={<AdminKnowledge />} />
|
||||||
<Route path="workflow" element={<AdminWorkflow />} />
|
<Route path="workflow" element={<AdminWorkflow />} />
|
||||||
<Route path="storage" element={<AdminStorage />} />
|
<Route path="storage" element={<AdminStorage />} />
|
||||||
<Route path="developer" element={<AdminDeveloper />} />
|
<Route path="developer" element={<AdminDeveloper />} />
|
||||||
<Route path="developer-tools" element={<AdminDeveloperTools />} />
|
<Route path="developer-tools" element={<AdminDeveloperTools />} />
|
||||||
<Route path="automation" element={<AdminAutomation />} />
|
<Route path="automation" element={<AdminAutomation />} />
|
||||||
<Route path="mcp" element={<AdminMcp />} />
|
<Route path="mcp" element={<AdminMcp />} />
|
||||||
<Route path="apps" element={<AdminApps />} />
|
<Route path="apps" element={<AdminApps />} />
|
||||||
<Route path="assets" element={<AssetCenter />} />
|
<Route path="assets" element={<AssetCenter />} />
|
||||||
<Route path="portal" element={<UserPortal />} />
|
<Route path="portal" element={<UserPortal />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
{/* 公开前台首页:不受登录态拦截,供后台「访问前台」直接打开 */}
|
{/* 公开前台首页:不受登录态拦截,供后台「访问前台」直接打开 */}
|
||||||
<Route path="/home" element={<LandingPage />} />
|
<Route path="/home" element={<LandingPage />} />
|
||||||
<Route path="*" element={<Navigate to="/" />} />
|
<Route path="*" element={<Navigate to="/" />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</AuthContext.Provider>
|
</AuthContext.Provider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default App;
|
export default App;
|
||||||
+2010
-2006
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,437 +1,437 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
|
|
||||||
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
|
||||||
import { useAuth } from '@/contexts/AuthContext';
|
import { useAuth } from '@/contexts/AuthContext';
|
||||||
|
|
||||||
import './AdminLayout.css';
|
import './AdminLayout.css';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
interface NavItem {
|
interface NavItem {
|
||||||
|
|
||||||
path: string;
|
path: string;
|
||||||
|
|
||||||
icon: string;
|
icon: string;
|
||||||
|
|
||||||
label: string;
|
label: string;
|
||||||
|
|
||||||
exact?: boolean;
|
exact?: boolean;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
interface NavGroup {
|
interface NavGroup {
|
||||||
|
|
||||||
title: string;
|
title: string;
|
||||||
|
|
||||||
icon: string;
|
icon: string;
|
||||||
|
|
||||||
items: NavItem[];
|
items: NavItem[];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const adminNavGroups: NavGroup[] = [
|
const adminNavGroups: NavGroup[] = [
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '数据驾驶舱',
|
title: '数据驾驶舱',
|
||||||
icon: 'dashboard',
|
icon: 'dashboard',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin', icon: 'dashboard', label: '平台驾驶舱', exact: true },
|
{ path: '/admin', icon: 'dashboard', label: '平台驾驶舱', exact: true },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: 'AI技能中心',
|
title: 'AI技能中心',
|
||||||
icon: 'agents',
|
icon: 'agents',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin/models', icon: 'models', label: '大模型库' },
|
{ path: '/admin/models', icon: 'models', label: '大模型库' },
|
||||||
{ path: '/admin/agents', icon: 'agents', label: 'Agent 管理' },
|
{ path: '/admin/agents', icon: 'agents', label: 'Agent 管理' },
|
||||||
{ path: '/admin/skills', icon: 'skills', label: 'Skills技能管理' },
|
{ path: '/admin/skills', icon: 'skills', label: 'Skills技能管理' },
|
||||||
{ path: '/admin/mcp', icon: 'mcp', label: 'MCP Client 管理' },
|
{ path: '/admin/mcp', icon: 'mcp', label: 'MCP Client 管理' },
|
||||||
{ path: '/admin/market', icon: 'market', label: 'AI 技能审核' },
|
{ path: '/admin/market', icon: 'market', label: 'AI 技能审核' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '平台运营',
|
title: '平台运营',
|
||||||
icon: 'users',
|
icon: 'users',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin/users', icon: 'users', label: '用户管理' },
|
{ path: '/admin/users', icon: 'users', label: '用户管理' },
|
||||||
{ path: '/admin/membership', icon: 'membership', label: '会员管理' },
|
{ path: '/admin/membership', icon: 'membership', label: '会员管理' },
|
||||||
{ path: '/admin/promotion', icon: 'promotion', label: '推广系统' },
|
{ path: '/admin/promotion', icon: 'promotion', label: '推广系统' },
|
||||||
{ path: '/admin/achievement', icon: 'achievement', label: '成就系统' },
|
{ path: '/admin/achievement', icon: 'achievement', label: '成就系统' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '商业变现',
|
title: '商业变现',
|
||||||
icon: 'billing',
|
icon: 'billing',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin/billing', icon: 'billing', label: '计费与支付' },
|
{ path: '/admin/billing', icon: 'billing', label: '计费与支付' },
|
||||||
{ path: '/admin/payment', icon: 'payment', label: '支付渠道' },
|
{ path: '/admin/payment', icon: 'payment', label: '支付渠道' },
|
||||||
{ path: '/admin/services', icon: 'services', label: '增值服务' },
|
{ path: '/admin/services', icon: 'services', label: '增值服务' },
|
||||||
{ path: '/admin/ads', icon: 'ads', label: '广告管理' },
|
{ path: '/admin/ads', icon: 'ads', label: '广告管理' },
|
||||||
{ path: '/admin/assets', icon: 'assets', label: '资产管理' },
|
{ path: '/admin/assets', icon: 'assets', label: '资产管理' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '系统管理',
|
title: '系统管理',
|
||||||
icon: 'settings',
|
icon: 'settings',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin/settings', icon: 'settings', label: '网站设置' },
|
{ path: '/admin/settings', icon: 'settings', label: '网站设置' },
|
||||||
{ path: '/admin/logs', icon: 'logs', label: '日志与风控' },
|
{ path: '/admin/logs', icon: 'logs', label: '日志与风控' },
|
||||||
{ path: '/admin/knowledge', icon: 'knowledge', label: '知识库管理' },
|
{ path: '/admin/knowledge', icon: 'knowledge', label: '知识库管理' },
|
||||||
{ path: '/admin/sms', icon: 'sms', label: '短信配置' },
|
{ path: '/admin/sms', icon: 'sms', label: '短信配置' },
|
||||||
{ path: '/admin/storage', icon: 'storage', label: '存储配置' },
|
{ path: '/admin/storage', icon: 'storage', label: '存储配置' },
|
||||||
{ path: '/admin/automation', icon: 'automation', label: '自动化任务' },
|
{ path: '/admin/automation', icon: 'automation', label: '自动化任务' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '待处理',
|
title: '待处理',
|
||||||
icon: 'developer',
|
icon: 'developer',
|
||||||
items: [
|
items: [
|
||||||
{ path: '/admin/analytics', icon: 'analytics', label: '数据分析' },
|
{ path: '/admin/analytics', icon: 'analytics', label: '数据分析' },
|
||||||
{ path: '/admin/observability', icon: 'observability', label: '调用可观测' },
|
{ path: '/admin/observability', icon: 'observability', label: '调用可观测' },
|
||||||
{ path: '/admin/workflow', icon: 'workflow', label: '工作流编排' },
|
{ path: '/admin/workflow', icon: 'workflow', label: '工作流编排' },
|
||||||
{ path: '/admin/apps', icon: 'apps', label: 'AI 应用管理' },
|
{ path: '/admin/apps', icon: 'apps', label: 'AI 应用管理' },
|
||||||
{ path: '/admin/code-exec', icon: 'code', label: '代码执行沙箱' },
|
{ path: '/admin/code-exec', icon: 'code', label: '代码执行沙箱' },
|
||||||
{ path: '/admin/tenant', icon: 'tenant', label: '多租户管理' },
|
{ path: '/admin/tenant', icon: 'tenant', label: '多租户管理' },
|
||||||
{ path: '/admin/im-bots', icon: 'imbot', label: 'IM 机器人' },
|
{ path: '/admin/im-bots', icon: 'imbot', label: 'IM 机器人' },
|
||||||
{ path: '/admin/privacy', icon: 'privacy', label: '隐私与本地代理' },
|
{ path: '/admin/privacy', icon: 'privacy', label: '隐私与本地代理' },
|
||||||
{ path: '/admin/distributions', icon: 'distro', label: '发行版构建' },
|
{ path: '/admin/distributions', icon: 'distro', label: '发行版构建' },
|
||||||
{ path: '/admin/developer', icon: 'developer', label: '开发者 API' },
|
{ path: '/admin/developer', icon: 'developer', label: '开发者 API' },
|
||||||
{ path: '/admin/developer-tools', icon: 'devtools', label: '开发者工具' },
|
{ path: '/admin/developer-tools', icon: 'devtools', label: '开发者工具' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const adminIconPaths: Record<string, JSX.Element> = {
|
const adminIconPaths: Record<string, JSX.Element> = {
|
||||||
|
|
||||||
dashboard: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
|
dashboard: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
|
||||||
|
|
||||||
users: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
|
users: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
|
||||||
|
|
||||||
models: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>,
|
models: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>,
|
||||||
|
|
||||||
settings: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
|
settings: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
|
||||||
|
|
||||||
payment: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>,
|
payment: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>,
|
||||||
|
|
||||||
services: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></svg>,
|
services: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></svg>,
|
||||||
|
|
||||||
membership: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>,
|
membership: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>,
|
||||||
|
|
||||||
ads: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>,
|
ads: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>,
|
||||||
|
|
||||||
market: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.2"/><rect x="14" y="3" width="7" height="7" rx="1.2"/><rect x="3" y="14" width="7" height="7" rx="1.2"/><rect x="14" y="14" width="7" height="7" rx="1.2"/></svg>,
|
market: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.2"/><rect x="14" y="3" width="7" height="7" rx="1.2"/><rect x="3" y="14" width="7" height="7" rx="1.2"/><rect x="14" y="14" width="7" height="7" rx="1.2"/></svg>,
|
||||||
|
|
||||||
logs: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>,
|
logs: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>,
|
||||||
|
|
||||||
agents: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" y1="16" x2="8" y2="16"/><line x1="16" y1="16" x2="16" y2="16"/></svg>,
|
agents: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" y1="16" x2="8" y2="16"/><line x1="16" y1="16" x2="16" y2="16"/></svg>,
|
||||||
|
|
||||||
skills: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
|
skills: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
|
||||||
|
|
||||||
code: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>,
|
code: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>,
|
||||||
|
|
||||||
distro: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
|
distro: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
|
||||||
|
|
||||||
privacy: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/><circle cx="12" cy="16" r="1"/></svg>,
|
privacy: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/><circle cx="12" cy="16" r="1"/></svg>,
|
||||||
|
|
||||||
promotion: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="7"/><path d="M8.5 12.5L6 21l6-2 6 2-2.5-8.5"/><circle cx="12" cy="8" r="3"/></svg>,
|
promotion: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="7"/><path d="M8.5 12.5L6 21l6-2 6 2-2.5-8.5"/><circle cx="12" cy="8" r="3"/></svg>,
|
||||||
|
|
||||||
achievement: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.27 7.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>,
|
achievement: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.27 7.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>,
|
||||||
|
|
||||||
tenant: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21V8l9-5 9 5v13"/><path d="M9 21v-6h6v6"/><path d="M3 13h18"/></svg>,
|
tenant: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21V8l9-5 9 5v13"/><path d="M9 21v-6h6v6"/><path d="M3 13h18"/></svg>,
|
||||||
|
|
||||||
billing: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/><line x1="6" y1="15" x2="10" y2="15"/></svg>,
|
billing: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/><line x1="6" y1="15" x2="10" y2="15"/></svg>,
|
||||||
|
|
||||||
analytics: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/><line x1="3" y1="20" x2="21" y2="20"/></svg>,
|
analytics: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/><line x1="3" y1="20" x2="21" y2="20"/></svg>,
|
||||||
observability: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12h4l3 8 4-16 3 8h4"/></svg>,
|
observability: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12h4l3 8 4-16 3 8h4"/></svg>,
|
||||||
|
|
||||||
imbot: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>,
|
imbot: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>,
|
||||||
|
|
||||||
storage: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>,
|
storage: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>,
|
||||||
|
|
||||||
automation: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>,
|
automation: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>,
|
||||||
|
|
||||||
developer: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>,
|
developer: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>,
|
||||||
|
|
||||||
devtools: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
|
devtools: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
|
||||||
|
|
||||||
knowledge: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>,
|
knowledge: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>,
|
||||||
|
|
||||||
workflow: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><line x1="10" y1="6" x2="14" y2="6"/><line x1="10" y1="17" x2="14" y2="17"/></svg>,
|
workflow: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><line x1="10" y1="6" x2="14" y2="6"/><line x1="10" y1="17" x2="14" y2="17"/></svg>,
|
||||||
|
|
||||||
mcp: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
|
mcp: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
|
||||||
|
|
||||||
apps: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
|
apps: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
|
||||||
|
|
||||||
assets: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
|
assets: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
|
||||||
|
|
||||||
chevron: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>,
|
chevron: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>,
|
||||||
|
|
||||||
sms: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
|
sms: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const AdminLayout: React.FC = () => {
|
const AdminLayout: React.FC = () => {
|
||||||
|
|
||||||
const { user, logout } = useAuth();
|
const { user, logout } = useAuth();
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
|
||||||
// 后台必须登录且为管理员
|
// 后台必须登录且为管理员
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const token = localStorage.getItem('aiflow_token');
|
const token = localStorage.getItem('aiflow_token');
|
||||||
if (!token || !user || user.role !== 'admin') {
|
if (!token || !user || user.role !== 'admin') {
|
||||||
logout();
|
logout();
|
||||||
navigate('/login', { replace: true });
|
navigate('/login', { replace: true });
|
||||||
}
|
}
|
||||||
}, [user, logout, navigate]);
|
}, [user, logout, navigate]);
|
||||||
|
|
||||||
const navCrumb = (() => {
|
const navCrumb = (() => {
|
||||||
|
|
||||||
for (const g of adminNavGroups) {
|
for (const g of adminNavGroups) {
|
||||||
|
|
||||||
for (const it of g.items) {
|
for (const it of g.items) {
|
||||||
|
|
||||||
const match = it.exact
|
const match = it.exact
|
||||||
|
|
||||||
? location.pathname === it.path
|
? location.pathname === it.path
|
||||||
|
|
||||||
: location.pathname === it.path || location.pathname.startsWith(it.path + '/');
|
: location.pathname === it.path || location.pathname.startsWith(it.path + '/');
|
||||||
|
|
||||||
if (match) return { group: g.title, label: it.label };
|
if (match) return { group: g.title, label: it.label };
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { group: '', label: '' };
|
return { group: '', label: '' };
|
||||||
|
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const navGroup = navCrumb.group;
|
const navGroup = navCrumb.group;
|
||||||
|
|
||||||
const navLabel = navCrumb.label;
|
const navLabel = navCrumb.label;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 默认展开全部功能板块,确保后台所有模块在 UI 中可见(DESIGN.md: 侧栏分类清晰)
|
// 默认展开全部功能板块,确保后台所有模块在 UI 中可见(DESIGN.md: 侧栏分类清晰)
|
||||||
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(() => {
|
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(() => {
|
||||||
return new Set(adminNavGroups.map((g) => g.title));
|
return new Set(adminNavGroups.map((g) => g.title));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const toggleGroup = (title: string) => {
|
const toggleGroup = (title: string) => {
|
||||||
|
|
||||||
setExpandedGroups(prev => {
|
setExpandedGroups(prev => {
|
||||||
|
|
||||||
const next = new Set(prev);
|
const next = new Set(prev);
|
||||||
|
|
||||||
if (next.has(title)) next.delete(title);
|
if (next.has(title)) next.delete(title);
|
||||||
|
|
||||||
else next.add(title);
|
else next.add(title);
|
||||||
|
|
||||||
return next;
|
return next;
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
|
|
||||||
logout();
|
logout();
|
||||||
|
|
||||||
navigate('/');
|
navigate('/');
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const handleVisitFrontend = () => {
|
const handleVisitFrontend = () => {
|
||||||
|
|
||||||
const url = window.location.origin + '/chat';
|
const url = window.location.origin + '/chat';
|
||||||
|
|
||||||
window.open(url, '_blank');
|
window.open(url, '_blank');
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<div className="admin-layout">
|
<div className="admin-layout">
|
||||||
|
|
||||||
<aside className="admin-sidebar">
|
<aside className="admin-sidebar">
|
||||||
|
|
||||||
<div className="admin-sidebar-header">
|
<div className="admin-sidebar-header">
|
||||||
|
|
||||||
<h1 className="admin-logo">七虎AI</h1>
|
<h1 className="admin-logo">七虎AI</h1>
|
||||||
|
|
||||||
<span className="admin-subtitle">管理控制台</span>
|
<span className="admin-subtitle">管理控制台</span>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button onClick={handleVisitFrontend} className="admin-frontend-link">
|
<button onClick={handleVisitFrontend} className="admin-frontend-link">
|
||||||
|
|
||||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
|
||||||
|
|
||||||
<span>访问前台</span>
|
<span>访问前台</span>
|
||||||
|
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<nav className="sidebar-nav">
|
<nav className="sidebar-nav">
|
||||||
|
|
||||||
{adminNavGroups.map((group) => {
|
{adminNavGroups.map((group) => {
|
||||||
|
|
||||||
const isExpanded = expandedGroups.has(group.title);
|
const isExpanded = expandedGroups.has(group.title);
|
||||||
|
|
||||||
const hasActiveChild = group.items.some(item =>
|
const hasActiveChild = group.items.some(item =>
|
||||||
|
|
||||||
item.exact ? location.pathname === item.path : location.pathname.startsWith(item.path)
|
item.exact ? location.pathname === item.path : location.pathname.startsWith(item.path)
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<div key={group.title} className={`nav-group ${hasActiveChild ? 'nav-group-active' : ''}`}>
|
<div key={group.title} className={`nav-group ${hasActiveChild ? 'nav-group-active' : ''}`}>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
|
|
||||||
className={`nav-group-header ${isExpanded ? 'expanded' : ''}`}
|
className={`nav-group-header ${isExpanded ? 'expanded' : ''}`}
|
||||||
|
|
||||||
onClick={() => toggleGroup(group.title)}
|
onClick={() => toggleGroup(group.title)}
|
||||||
|
|
||||||
>
|
>
|
||||||
|
|
||||||
<span className="nav-group-chevron-wrap">
|
<span className="nav-group-chevron-wrap">
|
||||||
|
|
||||||
<span className={`nav-group-chevron ${isExpanded ? 'chevron-expanded' : ''}`}>
|
<span className={`nav-group-chevron ${isExpanded ? 'chevron-expanded' : ''}`}>
|
||||||
|
|
||||||
{adminIconPaths.chevron}
|
{adminIconPaths.chevron}
|
||||||
|
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<span className="nav-group-title">{group.title}</span>
|
<span className="nav-group-title">{group.title}</span>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isExpanded && (
|
{isExpanded && (
|
||||||
|
|
||||||
<div className="nav-group-items">
|
<div className="nav-group-items">
|
||||||
|
|
||||||
{group.items.map((item) => (
|
{group.items.map((item) => (
|
||||||
|
|
||||||
<NavLink
|
<NavLink
|
||||||
|
|
||||||
key={item.path}
|
key={item.path}
|
||||||
|
|
||||||
to={item.path}
|
to={item.path}
|
||||||
|
|
||||||
end={item.exact}
|
end={item.exact}
|
||||||
|
|
||||||
className={({ isActive }) =>
|
className={({ isActive }) =>
|
||||||
|
|
||||||
`nav-item ${isActive ? 'nav-item-active' : ''}`
|
`nav-item ${isActive ? 'nav-item-active' : ''}`
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
>
|
>
|
||||||
|
|
||||||
<span className="nav-item-icon">{adminIconPaths[item.icon]}</span>
|
<span className="nav-item-icon">{adminIconPaths[item.icon]}</span>
|
||||||
|
|
||||||
<span className="nav-item-label">{item.label}</span>
|
<span className="nav-item-label">{item.label}</span>
|
||||||
|
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|
||||||
))}
|
))}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
})}
|
})}
|
||||||
|
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="admin-sidebar-footer">
|
<div className="admin-sidebar-footer">
|
||||||
|
|
||||||
<div className="admin-user-info">
|
<div className="admin-user-info">
|
||||||
|
|
||||||
<div className="admin-user-avatar">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
|
<div className="admin-user-avatar">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
|
||||||
|
|
||||||
<div className="admin-user-detail">
|
<div className="admin-user-detail">
|
||||||
|
|
||||||
<div className="admin-user-name">{user?.username || 'admin'}</div>
|
<div className="admin-user-name">{user?.username || 'admin'}</div>
|
||||||
|
|
||||||
<button className="admin-logout-btn" onClick={handleLogout}>退出登录</button>
|
<button className="admin-logout-btn" onClick={handleLogout}>退出登录</button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main className="admin-content">
|
<main className="admin-content">
|
||||||
|
|
||||||
<header className="admin-topbar">
|
<header className="admin-topbar">
|
||||||
|
|
||||||
<nav className="admin-breadcrumb" aria-label="breadcrumb">
|
<nav className="admin-breadcrumb" aria-label="breadcrumb">
|
||||||
|
|
||||||
<span className="crumb-root">管理控制台</span>
|
<span className="crumb-root">管理控制台</span>
|
||||||
|
|
||||||
{navGroup && (<><span className="crumb-sep">/</span><span className="crumb-group">{navGroup}</span></>)}
|
{navGroup && (<><span className="crumb-sep">/</span><span className="crumb-group">{navGroup}</span></>)}
|
||||||
|
|
||||||
{navLabel && (<><span className="crumb-sep">/</span><span className="crumb-current">{navLabel}</span></>)}
|
{navLabel && (<><span className="crumb-sep">/</span><span className="crumb-current">{navLabel}</span></>)}
|
||||||
|
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="admin-topbar-user">
|
<div className="admin-topbar-user">
|
||||||
|
|
||||||
<div className="admin-user-avatar sm">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
|
<div className="admin-user-avatar sm">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
|
||||||
|
|
||||||
<span className="admin-topbar-username">{user?.username || 'admin'}</span>
|
<span className="admin-topbar-username">{user?.username || 'admin'}</span>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<Outlet />
|
<Outlet />
|
||||||
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default AdminLayout;
|
export default AdminLayout;
|
||||||
|
|
||||||
@@ -203,6 +203,7 @@
|
|||||||
.front-main {
|
.front-main {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
overflow-x: hidden;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
|||||||
+1837
-1837
File diff suppressed because it is too large.
Load diff
@@ -1,207 +1,207 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { adminAPI } from '@/api';
|
import { adminAPI } from '@/api';
|
||||||
|
|
||||||
interface Overview {
|
interface Overview {
|
||||||
total_users: number; active_users: number; new_users: number;
|
total_users: number; active_users: number; new_users: number;
|
||||||
api_calls: number; avg_response_time: number; error_rate: number;
|
api_calls: number; avg_response_time: number; error_rate: number;
|
||||||
tokens_used: number; total_cost: number; total_chats: number; total_messages: number; revenue: number;
|
tokens_used: number; total_cost: number; total_chats: number; total_messages: number; revenue: number;
|
||||||
}
|
}
|
||||||
interface TrendItem { date: string; calls?: number; errors?: number; tokens?: number; new_users?: number; cumulative?: number; revenue?: number; consumption?: number; }
|
interface TrendItem { date: string; calls?: number; errors?: number; tokens?: number; new_users?: number; cumulative?: number; revenue?: number; consumption?: number; }
|
||||||
interface ModelUsage { model_name: string; call_count: number; total_tokens: number; total_cost: number; avg_tokens: number; }
|
interface ModelUsage { model_name: string; call_count: number; total_tokens: number; total_cost: number; avg_tokens: number; }
|
||||||
|
|
||||||
const Analytics: React.FC = () => {
|
const Analytics: React.FC = () => {
|
||||||
const [days, setDays] = useState(7);
|
const [days, setDays] = useState(7);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [overview, setOverview] = useState<Overview | null>(null);
|
const [overview, setOverview] = useState<Overview | null>(null);
|
||||||
const [apiTrend, setApiTrend] = useState<TrendItem[]>([]);
|
const [apiTrend, setApiTrend] = useState<TrendItem[]>([]);
|
||||||
const [tokenTrend, setTokenTrend] = useState<{ daily: any[]; model_distribution: Record<string, number> }>({ daily: [], model_distribution: {} });
|
const [tokenTrend, setTokenTrend] = useState<{ daily: any[]; model_distribution: Record<string, number> }>({ daily: [], model_distribution: {} });
|
||||||
const [userTrend, setUserTrend] = useState<TrendItem[]>([]);
|
const [userTrend, setUserTrend] = useState<TrendItem[]>([]);
|
||||||
const [revenueTrend, setRevenueTrend] = useState<TrendItem[]>([]);
|
const [revenueTrend, setRevenueTrend] = useState<TrendItem[]>([]);
|
||||||
const [modelUsage, setModelUsage] = useState<ModelUsage[]>([]);
|
const [modelUsage, setModelUsage] = useState<ModelUsage[]>([]);
|
||||||
|
|
||||||
const fetchAll = useCallback(async () => {
|
const fetchAll = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const [ov, api, tok, usr, rev, mu] = await Promise.all([
|
const [ov, api, tok, usr, rev, mu] = await Promise.all([
|
||||||
adminAPI.getAnalyticsOverview(days),
|
adminAPI.getAnalyticsOverview(days),
|
||||||
adminAPI.getAnalyticsApiTrends(days),
|
adminAPI.getAnalyticsApiTrends(days),
|
||||||
adminAPI.getAnalyticsTokenTrends(days),
|
adminAPI.getAnalyticsTokenTrends(days),
|
||||||
adminAPI.getAnalyticsUserTrends(days),
|
adminAPI.getAnalyticsUserTrends(days),
|
||||||
adminAPI.getAnalyticsRevenueTrends(days),
|
adminAPI.getAnalyticsRevenueTrends(days),
|
||||||
adminAPI.getAnalyticsModelUsage(days),
|
adminAPI.getAnalyticsModelUsage(days),
|
||||||
]);
|
]);
|
||||||
setOverview((ov as any)?.data || ov);
|
setOverview((ov as any)?.data || ov);
|
||||||
setApiTrend((api as any)?.data || []);
|
setApiTrend((api as any)?.data || []);
|
||||||
const td = (tok as any)?.data || { daily: [], model_distribution: {} };
|
const td = (tok as any)?.data || { daily: [], model_distribution: {} };
|
||||||
setTokenTrend(td);
|
setTokenTrend(td);
|
||||||
setUserTrend((usr as any)?.data || []);
|
setUserTrend((usr as any)?.data || []);
|
||||||
setRevenueTrend((rev as any)?.data || []);
|
setRevenueTrend((rev as any)?.data || []);
|
||||||
setModelUsage((mu as any)?.data || []);
|
setModelUsage((mu as any)?.data || []);
|
||||||
} catch (e) { console.error('fetchAnalytics:', e); }
|
} catch (e) { console.error('fetchAnalytics:', e); }
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}, [days]);
|
}, [days]);
|
||||||
|
|
||||||
useEffect(() => { fetchAll(); }, [fetchAll]);
|
useEffect(() => { fetchAll(); }, [fetchAll]);
|
||||||
|
|
||||||
const renderBar = (data: TrendItem[], key: string, color: string, label: string) => {
|
const renderBar = (data: TrendItem[], key: string, color: string, label: string) => {
|
||||||
if (!data.length) return <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无数据</div>;
|
if (!data.length) return <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无数据</div>;
|
||||||
const values = data.map((d: any) => d[key] || 0);
|
const values = data.map((d: any) => d[key] || 0);
|
||||||
const max = Math.max(...values, 1);
|
const max = Math.max(...values, 1);
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', height: '180px', padding: '0 16px' }}>
|
<div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', height: '180px', padding: '0 16px' }}>
|
||||||
{data.map((d: any, i) => {
|
{data.map((d: any, i) => {
|
||||||
const v = d[key] || 0;
|
const v = d[key] || 0;
|
||||||
const h = (v / max) * 140;
|
const h = (v / max) * 140;
|
||||||
return (
|
return (
|
||||||
<div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: '40px' }}>
|
<div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: '40px' }}>
|
||||||
<div style={{ fontSize: '10px', color: '#8892B0', marginBottom: '4px' }}>{v > 9999 ? `${(v/1000).toFixed(0)}k` : v}</div>
|
<div style={{ fontSize: '10px', color: '#8892B0', marginBottom: '4px' }}>{v > 9999 ? `${(v/1000).toFixed(0)}k` : v}</div>
|
||||||
<div style={{ width: '100%', height: `${h}px`, background: `linear-gradient(180deg, ${color}, ${color}aa)`, borderRadius: '4px 4px 0 0', transition: 'height 0.3s' }} />
|
<div style={{ width: '100%', height: `${h}px`, background: `linear-gradient(180deg, ${color}, ${color}aa)`, borderRadius: '4px 4px 0 0', transition: 'height 0.3s' }} />
|
||||||
<div style={{ fontSize: '10px', color: '#6B7280', marginTop: '6px' }}>{d.date?.substring(5)}</div>
|
<div style={{ fontSize: '10px', color: '#6B7280', marginTop: '6px' }}>{d.date?.substring(5)}</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderLine = (data: TrendItem[], key: string, color: string) => {
|
const renderLine = (data: TrendItem[], key: string, color: string) => {
|
||||||
if (!data.length) return <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无数据</div>;
|
if (!data.length) return <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无数据</div>;
|
||||||
const values = data.map((d: any) => d[key] || 0);
|
const values = data.map((d: any) => d[key] || 0);
|
||||||
const max = Math.max(...values, 1);
|
const max = Math.max(...values, 1);
|
||||||
const w = 100 / (data.length - 1 || 1);
|
const w = 100 / (data.length - 1 || 1);
|
||||||
const points = data.map((d: any, i) => `${i * w},${100 - ((d[key] || 0) / max) * 90}`).join(' ');
|
const points = data.map((d: any, i) => `${i * w},${100 - ((d[key] || 0) / max) * 90}`).join(' ');
|
||||||
return (
|
return (
|
||||||
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '180px' }}>
|
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '180px' }}>
|
||||||
<polyline points={points} fill="none" stroke={color} strokeWidth="1.5" />
|
<polyline points={points} fill="none" stroke={color} strokeWidth="1.5" />
|
||||||
{data.map((d: any, i) => (
|
{data.map((d: any, i) => (
|
||||||
<circle key={i} cx={i * w} cy={100 - ((d[key] || 0) / max) * 90} r="1" fill={color} />
|
<circle key={i} cx={i * w} cy={100 - ((d[key] || 0) / max) * 90} r="1" fill={color} />
|
||||||
))}
|
))}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const statCards = overview ? [
|
const statCards = overview ? [
|
||||||
{ label: '总用户数', value: overview.total_users, color: '#6C63FF', icon: 'U' },
|
{ label: '总用户数', value: overview.total_users, color: '#6C63FF', icon: 'U' },
|
||||||
{ label: '活跃用户', value: overview.active_users, color: '#10b981', icon: 'A' },
|
{ label: '活跃用户', value: overview.active_users, color: '#10b981', icon: 'A' },
|
||||||
{ label: '新增用户', value: overview.new_users, color: '#3b82f6', icon: '+' },
|
{ label: '新增用户', value: overview.new_users, color: '#3b82f6', icon: '+' },
|
||||||
{ label: 'API调用数', value: overview.api_calls, color: '#f59e0b', icon: 'API' },
|
{ label: 'API调用数', value: overview.api_calls, color: '#f59e0b', icon: 'API' },
|
||||||
{ label: 'Token用量', value: overview.tokens_used, color: '#ec4899', icon: 'T' },
|
{ label: 'Token用量', value: overview.tokens_used, color: '#ec4899', icon: 'T' },
|
||||||
{ label: '总费用(元)', value: overview.total_cost?.toFixed(2), color: '#ef4444', icon: '¥' },
|
{ label: '总费用(元)', value: overview.total_cost?.toFixed(2), color: '#ef4444', icon: '¥' },
|
||||||
{ label: '对话总数', value: overview.total_chats, color: '#8b5cf6', icon: 'C' },
|
{ label: '对话总数', value: overview.total_chats, color: '#8b5cf6', icon: 'C' },
|
||||||
{ label: '消息总数', value: overview.total_messages, color: '#06b6d4', icon: 'M' },
|
{ label: '消息总数', value: overview.total_messages, color: '#06b6d4', icon: 'M' },
|
||||||
] : [];
|
] : [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ padding: '24px', color: '#1A1F36' }}>
|
<div style={{ padding: '24px', color: '#1A1F36' }}>
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
|
||||||
<h1 style={{ fontSize: '24px', fontWeight: 700 }}>数据分析面板</h1>
|
<h1 style={{ fontSize: '24px', fontWeight: 700 }}>数据分析面板</h1>
|
||||||
<div style={{ display: 'flex', gap: '8px' }}>
|
<div style={{ display: 'flex', gap: '8px' }}>
|
||||||
{[7, 14, 30, 90].map(d => (
|
{[7, 14, 30, 90].map(d => (
|
||||||
<button key={d} onClick={() => setDays(d)} style={{ padding: '6px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
|
<button key={d} onClick={() => setDays(d)} style={{ padding: '6px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
|
||||||
background: days === d ? '#6C63FF' : '#F0F2F8', color: days === d ? '#fff' : '#5A6480', fontWeight: 600, fontSize: '13px' }}>{d}天</button>
|
background: days === d ? '#6C63FF' : '#F0F2F8', color: days === d ? '#fff' : '#5A6480', fontWeight: 600, fontSize: '13px' }}>{d}天</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? <div style={{ textAlign: 'center', padding: '80px', color: '#6B7280' }}>加载中...</div> : (
|
{loading ? <div style={{ textAlign: 'center', padding: '80px', color: '#6B7280' }}>加载中...</div> : (
|
||||||
<>
|
<>
|
||||||
{/* Stats grid */}
|
{/* Stats grid */}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
|
||||||
{statCards.map((s, i) => (
|
{statCards.map((s, i) => (
|
||||||
<div key={i} style={{ background: '#FFFFFF', borderRadius: '12px', padding: '20px', border: `1px solid ${s.color}33`, display: 'flex', alignItems: 'center', gap: '16px' }}>
|
<div key={i} style={{ background: '#FFFFFF', borderRadius: '12px', padding: '20px', border: `1px solid ${s.color}33`, display: 'flex', alignItems: 'center', gap: '16px' }}>
|
||||||
<div style={{ width: '48px', height: '48px', borderRadius: '12px', background: `${s.color}22`, color: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', fontWeight: 800 }}>{s.icon}</div>
|
<div style={{ width: '48px', height: '48px', borderRadius: '12px', background: `${s.color}22`, color: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', fontWeight: 800 }}>{s.icon}</div>
|
||||||
<div>
|
<div>
|
||||||
<div style={{ fontSize: '24px', fontWeight: 800, color: s.color }}>{typeof s.value === 'number' ? s.value.toLocaleString() : s.value}</div>
|
<div style={{ fontSize: '24px', fontWeight: 800, color: s.color }}>{typeof s.value === 'number' ? s.value.toLocaleString() : s.value}</div>
|
||||||
<div style={{ fontSize: '12px', color: '#8892B0', marginTop: '2px' }}>{s.label}</div>
|
<div style={{ fontSize: '12px', color: '#8892B0', marginTop: '2px' }}>{s.label}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Charts grid */}
|
{/* Charts grid */}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: '16px', marginBottom: '16px' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: '16px', marginBottom: '16px' }}>
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>API调用趋势 ({days}天)</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>API调用趋势 ({days}天)</h3>
|
||||||
{renderBar(apiTrend, 'calls', '#f59e0b', '调用次数')}
|
{renderBar(apiTrend, 'calls', '#f59e0b', '调用次数')}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>Token使用趋势 ({days}天)</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>Token使用趋势 ({days}天)</h3>
|
||||||
{renderLine(tokenTrend.daily, 'total_tokens', '#ec4899')}
|
{renderLine(tokenTrend.daily, 'total_tokens', '#ec4899')}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: '16px', marginBottom: '16px' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: '16px', marginBottom: '16px' }}>
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>用户增长 ({days}天)</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>用户增长 ({days}天)</h3>
|
||||||
{renderBar(userTrend, 'new_users', '#3b82f6', '新增用户')}
|
{renderBar(userTrend, 'new_users', '#3b82f6', '新增用户')}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>收入趋势 ({days}天)</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>收入趋势 ({days}天)</h3>
|
||||||
{renderBar(revenueTrend, 'revenue', '#10b981', '收入')}
|
{renderBar(revenueTrend, 'revenue', '#10b981', '收入')}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Model usage */}
|
{/* Model usage */}
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>模型使用分析 ({days}天)</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>模型使用分析 ({days}天)</h3>
|
||||||
{modelUsage.length > 0 ? (
|
{modelUsage.length > 0 ? (
|
||||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||||
<thead><tr style={{ borderBottom: '2px solid rgba(0,0,0,0.08)' }}>
|
<thead><tr style={{ borderBottom: '2px solid rgba(0,0,0,0.08)' }}>
|
||||||
{['模型', '调用次数', '总Tokens', '平均Tokens', '费用(元)'].map(h => (
|
{['模型', '调用次数', '总Tokens', '平均Tokens', '费用(元)'].map(h => (
|
||||||
<th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: '13px', color: '#8892B0', fontWeight: 600 }}>{h}</th>
|
<th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: '13px', color: '#8892B0', fontWeight: 600 }}>{h}</th>
|
||||||
))}
|
))}
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{modelUsage.map((m, i) => (
|
{modelUsage.map((m, i) => (
|
||||||
<tr key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.08)' }}>
|
<tr key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.08)' }}>
|
||||||
<td style={{ padding: '10px 16px', fontSize: '14px', fontWeight: 600 }}>{m.model_name}</td>
|
<td style={{ padding: '10px 16px', fontSize: '14px', fontWeight: 600 }}>{m.model_name}</td>
|
||||||
<td style={{ padding: '10px 16px', fontSize: '14px' }}>{m.call_count.toLocaleString()}</td>
|
<td style={{ padding: '10px 16px', fontSize: '14px' }}>{m.call_count.toLocaleString()}</td>
|
||||||
<td style={{ padding: '10px 16px', fontSize: '14px', color: '#ec4899', fontWeight: 600 }}>{m.total_tokens.toLocaleString()}</td>
|
<td style={{ padding: '10px 16px', fontSize: '14px', color: '#ec4899', fontWeight: 600 }}>{m.total_tokens.toLocaleString()}</td>
|
||||||
<td style={{ padding: '10px 16px', fontSize: '13px', color: '#8892B0' }}>{m.avg_tokens.toLocaleString()}</td>
|
<td style={{ padding: '10px 16px', fontSize: '13px', color: '#8892B0' }}>{m.avg_tokens.toLocaleString()}</td>
|
||||||
<td style={{ padding: '10px 16px', fontSize: '14px', color: '#ef4444' }}>¥{m.total_cost.toFixed(4)}</td>
|
<td style={{ padding: '10px 16px', fontSize: '14px', color: '#ef4444' }}>¥{m.total_cost.toFixed(4)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
) : <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无模型使用数据</div>}
|
) : <div style={{ textAlign: 'center', padding: '40px', color: '#6B7280' }}>暂无模型使用数据</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Model distribution pie (CSS) */}
|
{/* Model distribution pie (CSS) */}
|
||||||
{Object.keys(tokenTrend.model_distribution || {}).length > 0 && (
|
{Object.keys(tokenTrend.model_distribution || {}).length > 0 && (
|
||||||
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px', marginTop: '16px' }}>
|
<div style={{ background: '#FFFFFF', borderRadius: '12px', padding: '24px', marginTop: '16px' }}>
|
||||||
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>模型使用分布</h3>
|
<h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>模型使用分布</h3>
|
||||||
<div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>
|
<div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>
|
||||||
<div style={{ display: 'flex', borderRadius: '50%', overflow: 'hidden', width: '160px', height: '160px' }}>
|
<div style={{ display: 'flex', borderRadius: '50%', overflow: 'hidden', width: '160px', height: '160px' }}>
|
||||||
{(() => {
|
{(() => {
|
||||||
const entries = Object.entries(tokenTrend.model_distribution);
|
const entries = Object.entries(tokenTrend.model_distribution);
|
||||||
const total = entries.reduce((s, [, v]) => s + v, 1);
|
const total = entries.reduce((s, [, v]) => s + v, 1);
|
||||||
const colors = ['#6C63FF', '#10b981', '#f59e0b', '#ec4899', '#3b82f6', '#8b5cf6', '#06b6d4', '#ef4444'];
|
const colors = ['#6C63FF', '#10b981', '#f59e0b', '#ec4899', '#3b82f6', '#8b5cf6', '#06b6d4', '#ef4444'];
|
||||||
return entries.map(([model, val], i) => {
|
return entries.map(([model, val], i) => {
|
||||||
const pct = (val / total) * 100;
|
const pct = (val / total) * 100;
|
||||||
return <div key={model} style={{ width: `${pct}%`, background: colors[i % colors.length] }} title={`${model}: ${pct.toFixed(1)}%`} />;
|
return <div key={model} style={{ width: `${pct}%`, background: colors[i % colors.length] }} title={`${model}: ${pct.toFixed(1)}%`} />;
|
||||||
});
|
});
|
||||||
})()}
|
})()}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ flex: 1 }}>
|
<div style={{ flex: 1 }}>
|
||||||
{Object.entries(tokenTrend.model_distribution).map(([model, val], i) => {
|
{Object.entries(tokenTrend.model_distribution).map(([model, val], i) => {
|
||||||
const colors = ['#6C63FF', '#10b981', '#f59e0b', '#ec4899', '#3b82f6', '#8b5cf6', '#06b6d4', '#ef4444'];
|
const colors = ['#6C63FF', '#10b981', '#f59e0b', '#ec4899', '#3b82f6', '#8b5cf6', '#06b6d4', '#ef4444'];
|
||||||
const total = Object.values(tokenTrend.model_distribution).reduce((s, v) => s + v, 1);
|
const total = Object.values(tokenTrend.model_distribution).reduce((s, v) => s + v, 1);
|
||||||
return (
|
return (
|
||||||
<div key={model} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
|
<div key={model} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
|
||||||
<div style={{ width: '12px', height: '12px', borderRadius: '3px', background: colors[i % colors.length] }} />
|
<div style={{ width: '12px', height: '12px', borderRadius: '3px', background: colors[i % colors.length] }} />
|
||||||
<span style={{ fontSize: '13px', color: '#1A1F36' }}>{model}</span>
|
<span style={{ fontSize: '13px', color: '#1A1F36' }}>{model}</span>
|
||||||
<span style={{ fontSize: '13px', color: '#8892B0', marginLeft: 'auto' }}>{((val / total) * 100).toFixed(1)}%</span>
|
<span style={{ fontSize: '13px', color: '#8892B0', marginLeft: 'auto' }}>{((val / total) * 100).toFixed(1)}%</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Analytics;
|
export default Analytics;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,457 +1,457 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { adminAPI } from '@/api';
|
import { adminAPI } from '@/api';
|
||||||
import { formatBjTime } from '@/utils/datetime';
|
import { formatBjTime } from '@/utils/datetime';
|
||||||
|
|
||||||
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 20 }) => (
|
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 20 }) => (
|
||||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
|
||||||
{children}
|
{children}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
interface DashboardStats {
|
interface DashboardStats {
|
||||||
total_users: number;
|
total_users: number;
|
||||||
active_users: number;
|
active_users: number;
|
||||||
total_models: number;
|
total_models: number;
|
||||||
enabled_models: number;
|
enabled_models: number;
|
||||||
total_conversations: number;
|
total_conversations: number;
|
||||||
active_conversations: number;
|
active_conversations: number;
|
||||||
valid_conversations: number;
|
valid_conversations: number;
|
||||||
total_knowledge_bases: number;
|
total_knowledge_bases: number;
|
||||||
total_documents: number;
|
total_documents: number;
|
||||||
today_orders: number;
|
today_orders: number;
|
||||||
today_subscription_orders: number;
|
today_subscription_orders: number;
|
||||||
today_tokens: number;
|
today_tokens: number;
|
||||||
week_tokens: number;
|
week_tokens: number;
|
||||||
total_tokens: number;
|
total_tokens: number;
|
||||||
today_conversations: number;
|
today_conversations: number;
|
||||||
server_time: string;
|
server_time: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DailyStat {
|
interface DailyStat {
|
||||||
date: string;
|
date: string;
|
||||||
tokens: number;
|
tokens: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const quickEntries = [
|
const quickEntries = [
|
||||||
{ path: '/admin/models', label: '大模型库', desc: '管理AI模型与供应商', icon: <SVGIcon><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></SVGIcon> },
|
{ path: '/admin/models', label: '大模型库', desc: '管理AI模型与供应商', icon: <SVGIcon><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></SVGIcon> },
|
||||||
{ path: '/admin/settings', label: '网站设置', desc: '品牌、邮件、短信配置', icon: <SVGIcon><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></SVGIcon> },
|
{ path: '/admin/settings', label: '网站设置', desc: '品牌、邮件、短信配置', icon: <SVGIcon><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></SVGIcon> },
|
||||||
{ path: '/admin/payment', label: '支付配置', desc: '微信、支付宝渠道配置', icon: <SVGIcon><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></SVGIcon> },
|
{ path: '/admin/payment', label: '支付配置', desc: '微信、支付宝渠道配置', icon: <SVGIcon><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></SVGIcon> },
|
||||||
{ path: '/admin/services', label: '增值服务', desc: '服务管理与定制订单', icon: <SVGIcon><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></SVGIcon> },
|
{ path: '/admin/services', label: '增值服务', desc: '服务管理与定制订单', icon: <SVGIcon><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></SVGIcon> },
|
||||||
{ path: '/admin/membership', label: '会员体系', desc: '订阅计划与自动化规则', icon: <SVGIcon><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></SVGIcon> },
|
{ path: '/admin/membership', label: '会员体系', desc: '订阅计划与自动化规则', icon: <SVGIcon><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></SVGIcon> },
|
||||||
{ path: '/admin/market', label: '应用市场', desc: '应用审核与优惠券管理', icon: <SVGIcon><rect x="3" y="3" width="7" height="7" rx="1.2"/><rect x="14" y="3" width="7" height="7" rx="1.2"/><rect x="3" y="14" width="7" height="7" rx="1.2"/><rect x="14" y="14" width="7" height="7" rx="1.2"/></SVGIcon> },
|
{ path: '/admin/market', label: '应用市场', desc: '应用审核与优惠券管理', icon: <SVGIcon><rect x="3" y="3" width="7" height="7" rx="1.2"/><rect x="14" y="3" width="7" height="7" rx="1.2"/><rect x="3" y="14" width="7" height="7" rx="1.2"/><rect x="14" y="14" width="7" height="7" rx="1.2"/></SVGIcon> },
|
||||||
{ path: '/admin/logs', label: '日志风控', desc: '操作/调用/付费日志与风控', icon: <SVGIcon><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></SVGIcon> },
|
{ path: '/admin/logs', label: '日志风控', desc: '操作/调用/付费日志与风控', icon: <SVGIcon><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></SVGIcon> },
|
||||||
];
|
];
|
||||||
|
|
||||||
// SVG Bar Chart Component
|
// SVG Bar Chart Component
|
||||||
const BarChart: React.FC<{ data: DailyStat[] }> = ({ data }) => {
|
const BarChart: React.FC<{ data: DailyStat[] }> = ({ data }) => {
|
||||||
if (!data || data.length === 0) return <div style={{ color: '#6B7280', textAlign: 'center', padding: 40 }}>暂无数据</div>;
|
if (!data || data.length === 0) return <div style={{ color: '#6B7280', textAlign: 'center', padding: 40 }}>暂无数据</div>;
|
||||||
|
|
||||||
const maxVal = Math.max(...data.map(d => d.tokens), 1);
|
const maxVal = Math.max(...data.map(d => d.tokens), 1);
|
||||||
const w = 600, h = 200, padLeft = 55, padRight = 10, padTop = 10, padBottom = 25;
|
const w = 600, h = 200, padLeft = 55, padRight = 10, padTop = 10, padBottom = 25;
|
||||||
const barAreaW = w - padLeft - padRight;
|
const barAreaW = w - padLeft - padRight;
|
||||||
const barAreaH = h - padTop - padBottom;
|
const barAreaH = h - padTop - padBottom;
|
||||||
const barGap = 2;
|
const barGap = 2;
|
||||||
const barW = Math.max(2, (barAreaW / data.length) - barGap);
|
const barW = Math.max(2, (barAreaW / data.length) - barGap);
|
||||||
|
|
||||||
// Y axis ticks
|
// Y axis ticks
|
||||||
const yTicks = [0, Math.round(maxVal * 0.25), Math.round(maxVal * 0.5), Math.round(maxVal * 0.75), maxVal];
|
const yTicks = [0, Math.round(maxVal * 0.25), Math.round(maxVal * 0.5), Math.round(maxVal * 0.75), maxVal];
|
||||||
|
|
||||||
const formatK = (n: number) => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : String(n);
|
const formatK = (n: number) => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : String(n);
|
||||||
const formatDate = (d: string) => {
|
const formatDate = (d: string) => {
|
||||||
const parts = d.split('-');
|
const parts = d.split('-');
|
||||||
return parts.length >= 2 ? `${parts[1]}/${parts[2]}` : d;
|
return parts.length >= 2 ? `${parts[1]}/${parts[2]}` : d;
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 'auto', maxWidth: 600 }}>
|
<svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 'auto', maxWidth: 600 }}>
|
||||||
{/* Grid lines */}
|
{/* Grid lines */}
|
||||||
{yTicks.map((tick, i) => {
|
{yTicks.map((tick, i) => {
|
||||||
const y = padTop + barAreaH - (tick / maxVal) * barAreaH;
|
const y = padTop + barAreaH - (tick / maxVal) * barAreaH;
|
||||||
return (
|
return (
|
||||||
<g key={i}>
|
<g key={i}>
|
||||||
<line x1={padLeft} y1={y} x2={w - padRight} y2={y} stroke="rgba(0,0,0,0.06)" strokeWidth="0.5" />
|
<line x1={padLeft} y1={y} x2={w - padRight} y2={y} stroke="rgba(0,0,0,0.06)" strokeWidth="0.5" />
|
||||||
<text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize="10" fill="#6B7280">{formatK(tick)}</text>
|
<text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize="10" fill="#6B7280">{formatK(tick)}</text>
|
||||||
</g>
|
</g>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
{/* Bars */}
|
{/* Bars */}
|
||||||
{data.map((d, i) => {
|
{data.map((d, i) => {
|
||||||
const barH = (d.tokens / maxVal) * barAreaH;
|
const barH = (d.tokens / maxVal) * barAreaH;
|
||||||
const x = padLeft + i * (barAreaW / data.length);
|
const x = padLeft + i * (barAreaW / data.length);
|
||||||
const y = padTop + barAreaH - barH;
|
const y = padTop + barAreaH - barH;
|
||||||
return (
|
return (
|
||||||
<g key={i}>
|
<g key={i}>
|
||||||
<rect x={x + barGap / 2} y={y} width={barW} height={Math.max(barH, 1)} rx="2" fill="#6C63FF" opacity="0.85">
|
<rect x={x + barGap / 2} y={y} width={barW} height={Math.max(barH, 1)} rx="2" fill="#6C63FF" opacity="0.85">
|
||||||
<title>{`${d.date}: ${d.tokens.toLocaleString()} tokens`}</title>
|
<title>{`${d.date}: ${d.tokens.toLocaleString()} tokens`}</title>
|
||||||
</rect>
|
</rect>
|
||||||
{/* X label - every 7th bar */}
|
{/* X label - every 7th bar */}
|
||||||
{i % Math.max(1, Math.floor(data.length / 8)) === 0 && (
|
{i % Math.max(1, Math.floor(data.length / 8)) === 0 && (
|
||||||
<text x={x + barW / 2} y={h - 6} textAnchor="middle" fontSize="9" fill="#6B7280">{formatDate(d.date)}</text>
|
<text x={x + barW / 2} y={h - 6} textAnchor="middle" fontSize="9" fill="#6B7280">{formatDate(d.date)}</text>
|
||||||
)}
|
)}
|
||||||
</g>
|
</g>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Mini Donut for stat cards
|
// Mini Donut for stat cards
|
||||||
const MiniDonut: React.FC<{ value: number; max: number; color: string }> = ({ value, max, color }) => {
|
const MiniDonut: React.FC<{ value: number; max: number; color: string }> = ({ value, max, color }) => {
|
||||||
const pct = max > 0 ? Math.min(value / max, 1) : 0;
|
const pct = max > 0 ? Math.min(value / max, 1) : 0;
|
||||||
const r = 16, c = 20, circumference = 2 * Math.PI * r;
|
const r = 16, c = 20, circumference = 2 * Math.PI * r;
|
||||||
const dash = circumference * pct;
|
const dash = circumference * pct;
|
||||||
return (
|
return (
|
||||||
<svg width={c * 2} height={c * 2} viewBox={`0 0 ${c * 2} ${c * 2}`}>
|
<svg width={c * 2} height={c * 2} viewBox={`0 0 ${c * 2} ${c * 2}`}>
|
||||||
<circle cx={c} cy={c} r={r} fill="none" stroke="rgba(0,0,0,0.06)" strokeWidth="3" />
|
<circle cx={c} cy={c} r={r} fill="none" stroke="rgba(0,0,0,0.06)" strokeWidth="3" />
|
||||||
<circle cx={c} cy={c} r={r} fill="none" stroke={color} strokeWidth="3"
|
<circle cx={c} cy={c} r={r} fill="none" stroke={color} strokeWidth="3"
|
||||||
strokeDasharray={`${dash} ${circumference - dash}`} strokeLinecap="round"
|
strokeDasharray={`${dash} ${circumference - dash}`} strokeLinecap="round"
|
||||||
transform={`rotate(-90 ${c} ${c})`} style={{ transition: 'stroke-dasharray 0.6s ease' }} />
|
transform={`rotate(-90 ${c} ${c})`} style={{ transition: 'stroke-dasharray 0.6s ease' }} />
|
||||||
<text x={c} y={c + 4} textAnchor="middle" fontSize="9" fontWeight="600" fill={color}>
|
<text x={c} y={c + 4} textAnchor="middle" fontSize="9" fontWeight="600" fill={color}>
|
||||||
{Math.round(pct * 100)}%
|
{Math.round(pct * 100)}%
|
||||||
</text>
|
</text>
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const pagBtnStyle = (disabled: boolean): React.CSSProperties => ({
|
const pagBtnStyle = (disabled: boolean): React.CSSProperties => ({
|
||||||
border: '1px solid rgba(0,0,0,0.12)',
|
border: '1px solid rgba(0,0,0,0.12)',
|
||||||
background: disabled ? '#F3F4F6' : '#FFFFFF',
|
background: disabled ? '#F3F4F6' : '#FFFFFF',
|
||||||
color: disabled ? '#B0B3BD' : '#374151',
|
color: disabled ? '#B0B3BD' : '#374151',
|
||||||
borderRadius: 6,
|
borderRadius: 6,
|
||||||
padding: '4px 10px',
|
padding: '4px 10px',
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
cursor: disabled ? 'not-allowed' : 'pointer',
|
cursor: disabled ? 'not-allowed' : 'pointer',
|
||||||
});
|
});
|
||||||
|
|
||||||
const LogPagination: React.FC<{ total: number; page: number; pageSize: number; onPage: (p: number) => void }> = ({ total, page, pageSize, onPage }) => {
|
const LogPagination: React.FC<{ total: number; page: number; pageSize: number; onPage: (p: number) => void }> = ({ total, page, pageSize, onPage }) => {
|
||||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8, padding: '12px 16px', fontSize: 12, color: '#6B7280' }}>
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8, padding: '12px 16px', fontSize: 12, color: '#6B7280' }}>
|
||||||
<span>共 {total} 条</span>
|
<span>共 {total} 条</span>
|
||||||
<button disabled={page <= 1} onClick={() => onPage(page - 1)} style={pagBtnStyle(page <= 1)}>上一页</button>
|
<button disabled={page <= 1} onClick={() => onPage(page - 1)} style={pagBtnStyle(page <= 1)}>上一页</button>
|
||||||
<span style={{ fontFamily: 'var(--font-mono)', color: '#374151' }}>{page} / {totalPages}</span>
|
<span style={{ fontFamily: 'var(--font-mono)', color: '#374151' }}>{page} / {totalPages}</span>
|
||||||
<button disabled={page >= totalPages} onClick={() => onPage(page + 1)} style={pagBtnStyle(page >= totalPages)}>下一页</button>
|
<button disabled={page >= totalPages} onClick={() => onPage(page + 1)} style={pagBtnStyle(page >= totalPages)}>下一页</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const Dashboard: React.FC = () => {
|
const Dashboard: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [stats, setStats] = useState<DashboardStats>({
|
const [stats, setStats] = useState<DashboardStats>({
|
||||||
total_users: 0, active_users: 0, total_models: 0, enabled_models: 0,
|
total_users: 0, active_users: 0, total_models: 0, enabled_models: 0,
|
||||||
total_conversations: 0, active_conversations: 0, valid_conversations: 0, total_knowledge_bases: 0, total_documents: 0,
|
total_conversations: 0, active_conversations: 0, valid_conversations: 0, total_knowledge_bases: 0, total_documents: 0,
|
||||||
today_orders: 0, today_subscription_orders: 0, today_tokens: 0, week_tokens: 0, total_tokens: 0,
|
today_orders: 0, today_subscription_orders: 0, today_tokens: 0, week_tokens: 0, total_tokens: 0,
|
||||||
today_conversations: 0, server_time: '',
|
today_conversations: 0, server_time: '',
|
||||||
});
|
});
|
||||||
const [dailyStats, setDailyStats] = useState<DailyStat[]>([]);
|
const [dailyStats, setDailyStats] = useState<DailyStat[]>([]);
|
||||||
const [operationLogs, setOperationLogs] = useState<any[]>([]);
|
const [operationLogs, setOperationLogs] = useState<any[]>([]);
|
||||||
const [auditLogs, setAuditLogs] = useState<any[]>([]);
|
const [auditLogs, setAuditLogs] = useState<any[]>([]);
|
||||||
const [opTotal, setOpTotal] = useState(0);
|
const [opTotal, setOpTotal] = useState(0);
|
||||||
const [auditTotal, setAuditTotal] = useState(0);
|
const [auditTotal, setAuditTotal] = useState(0);
|
||||||
const [opPage, setOpPage] = useState(1);
|
const [opPage, setOpPage] = useState(1);
|
||||||
const [auditPage, setAuditPage] = useState(1);
|
const [auditPage, setAuditPage] = useState(1);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
const PAGE_SIZE = 20;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
const loadOperationLogs = async (page: number) => {
|
const loadOperationLogs = async (page: number) => {
|
||||||
try {
|
try {
|
||||||
const res: any = await (adminAPI as any).getDashboardOperationLogs(page, PAGE_SIZE);
|
const res: any = await (adminAPI as any).getDashboardOperationLogs(page, PAGE_SIZE);
|
||||||
const data = res?.data || res;
|
const data = res?.data || res;
|
||||||
setOperationLogs(Array.isArray(data?.items) ? data.items : []);
|
setOperationLogs(Array.isArray(data?.items) ? data.items : []);
|
||||||
setOpTotal(data?.total ?? 0);
|
setOpTotal(data?.total ?? 0);
|
||||||
setOpPage(page);
|
setOpPage(page);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('操作日志加载失败:', err);
|
console.error('操作日志加载失败:', err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadAuditLogs = async (page: number) => {
|
const loadAuditLogs = async (page: number) => {
|
||||||
try {
|
try {
|
||||||
const res: any = await (adminAPI as any).getDashboardAuditLogs(page, PAGE_SIZE);
|
const res: any = await (adminAPI as any).getDashboardAuditLogs(page, PAGE_SIZE);
|
||||||
const data = res?.data || res;
|
const data = res?.data || res;
|
||||||
setAuditLogs(Array.isArray(data?.items) ? data.items : []);
|
setAuditLogs(Array.isArray(data?.items) ? data.items : []);
|
||||||
setAuditTotal(data?.total ?? 0);
|
setAuditTotal(data?.total ?? 0);
|
||||||
setAuditPage(page);
|
setAuditPage(page);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('审计日志加载失败:', err);
|
console.error('审计日志加载失败:', err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const downloadCsv = async (url: string, filename: string) => {
|
const downloadCsv = async (url: string, filename: string) => {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('aiflow_token');
|
const token = localStorage.getItem('aiflow_token');
|
||||||
const res = await fetch(`/app/api${url}`, {
|
const res = await fetch(`/app/api${url}`, {
|
||||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error('下载失败');
|
if (!res.ok) throw new Error('下载失败');
|
||||||
const blob = await res.blob();
|
const blob = await res.blob();
|
||||||
const href = URL.createObjectURL(blob);
|
const href = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = href;
|
a.href = href;
|
||||||
a.download = filename;
|
a.download = filename;
|
||||||
document.body.appendChild(a);
|
document.body.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
document.body.removeChild(a);
|
document.body.removeChild(a);
|
||||||
URL.revokeObjectURL(href);
|
URL.revokeObjectURL(href);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('CSV下载失败:', err);
|
console.error('CSV下载失败:', err);
|
||||||
alert('下载失败,请稍后重试');
|
alert('下载失败,请稍后重试');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const [statsRes, dailyRes] = await Promise.all([
|
const [statsRes, dailyRes] = await Promise.all([
|
||||||
adminAPI.getStats() as any,
|
adminAPI.getStats() as any,
|
||||||
(adminAPI as any).getDailyStats?.(30) || Promise.resolve({ data: { data: { data: [] } } }),
|
(adminAPI as any).getDailyStats?.(30) || Promise.resolve({ data: { data: { data: [] } } }),
|
||||||
]);
|
]);
|
||||||
// Stats: backend returns raw dict (no {code,data} wrapper) — use .data or the response itself
|
// Stats: backend returns raw dict (no {code,data} wrapper) — use .data or the response itself
|
||||||
const statsData = statsRes?.data || statsRes;
|
const statsData = statsRes?.data || statsRes;
|
||||||
if (statsData && typeof statsData === 'object') setStats(statsData);
|
if (statsData && typeof statsData === 'object') setStats(statsData);
|
||||||
|
|
||||||
// Daily stats: backend returns {code, data: {days, data: [...]}} — access nested .data.data
|
// Daily stats: backend returns {code, data: {days, data: [...]}} — access nested .data.data
|
||||||
const dailyData = dailyRes?.data?.data || (Array.isArray(dailyRes?.data) ? dailyRes.data : []) || [];
|
const dailyData = dailyRes?.data?.data || (Array.isArray(dailyRes?.data) ? dailyRes.data : []) || [];
|
||||||
setDailyStats(Array.isArray(dailyData) ? dailyData : []);
|
setDailyStats(Array.isArray(dailyData) ? dailyData : []);
|
||||||
|
|
||||||
await Promise.all([loadOperationLogs(1), loadAuditLogs(1)]);
|
await Promise.all([loadOperationLogs(1), loadAuditLogs(1)]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Dashboard数据加载失败:', err);
|
console.error('Dashboard数据加载失败:', err);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const formatDate = (d: string | null) => formatBjTime(d);
|
const formatDate = (d: string | null) => formatBjTime(d);
|
||||||
|
|
||||||
const formatTokens = (n: number): string => {
|
const formatTokens = (n: number): string => {
|
||||||
if (n >= 100000000) return (n / 100000000).toFixed(2) + '亿';
|
if (n >= 100000000) return (n / 100000000).toFixed(2) + '亿';
|
||||||
if (n >= 10000) return (n / 10000).toFixed(1) + '万';
|
if (n >= 10000) return (n / 10000).toFixed(1) + '万';
|
||||||
return n.toLocaleString('en-US');
|
return n.toLocaleString('en-US');
|
||||||
};
|
};
|
||||||
|
|
||||||
const statCardDefs = [
|
const statCardDefs = [
|
||||||
{ label: '总用户', value: stats.total_users, sub: `近7天活跃 ${stats.active_users}`, color: '#6C63FF', bg: 'rgba(108,99,255,0.12)', subBg: 'rgba(108,99,255,0.08)',
|
{ label: '总用户', value: stats.total_users, sub: `近7天活跃 ${stats.active_users}`, color: '#6C63FF', bg: 'rgba(108,99,255,0.12)', subBg: 'rgba(108,99,255,0.08)',
|
||||||
icon: <SVGIcon size={22}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></SVGIcon> },
|
icon: <SVGIcon size={22}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></SVGIcon> },
|
||||||
{ label: 'AI模型', value: stats.total_models, sub: `启用 ${stats.enabled_models}`, color: '#219B5E', bg: 'rgba(33,155,94,0.12)', subBg: 'rgba(33,155,94,0.08)',
|
{ label: 'AI模型', value: stats.total_models, sub: `启用 ${stats.enabled_models}`, color: '#219B5E', bg: 'rgba(33,155,94,0.12)', subBg: 'rgba(33,155,94,0.08)',
|
||||||
icon: <SVGIcon size={22}><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></SVGIcon> },
|
icon: <SVGIcon size={22}><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></SVGIcon> },
|
||||||
{ label: '对话数', value: stats.valid_conversations, sub: `活跃窗口 ${stats.active_conversations}`, color: '#E8922C', bg: 'rgba(232,146,44,0.12)', subBg: 'rgba(232,146,44,0.08)',
|
{ label: '对话数', value: stats.valid_conversations, sub: `活跃窗口 ${stats.active_conversations}`, color: '#E8922C', bg: 'rgba(232,146,44,0.12)', subBg: 'rgba(232,146,44,0.08)',
|
||||||
icon: <SVGIcon size={22}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></SVGIcon> },
|
icon: <SVGIcon size={22}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></SVGIcon> },
|
||||||
{ label: '知识库文档', value: stats.total_documents, sub: `知识库 ${stats.total_knowledge_bases}`, color: '#3B82F6', bg: 'rgba(59,130,246,0.12)', subBg: 'rgba(59,130,246,0.08)',
|
{ label: '知识库文档', value: stats.total_documents, sub: `知识库 ${stats.total_knowledge_bases}`, color: '#3B82F6', bg: 'rgba(59,130,246,0.12)', subBg: 'rgba(59,130,246,0.08)',
|
||||||
icon: <SVGIcon size={22}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></SVGIcon> },
|
icon: <SVGIcon size={22}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></SVGIcon> },
|
||||||
{ label: '今日订阅成功', value: stats.today_subscription_orders, sub: `今日订单 ${stats.today_orders}`, color: '#8B5CF6', bg: 'rgba(139,92,246,0.12)', subBg: 'rgba(139,92,246,0.08)',
|
{ label: '今日订阅成功', value: stats.today_subscription_orders, sub: `今日订单 ${stats.today_orders}`, color: '#8B5CF6', bg: 'rgba(139,92,246,0.12)', subBg: 'rgba(139,92,246,0.08)',
|
||||||
icon: <SVGIcon size={22}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon> },
|
icon: <SVGIcon size={22}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon> },
|
||||||
{ label: '今日Token', value: stats.today_tokens, sub: `本周 ${formatTokens(stats.week_tokens)}`, color: '#EC4899', bg: 'rgba(236,72,153,0.12)', subBg: 'rgba(236,72,153,0.08)', format: true,
|
{ label: '今日Token', value: stats.today_tokens, sub: `本周 ${formatTokens(stats.week_tokens)}`, color: '#EC4899', bg: 'rgba(236,72,153,0.12)', subBg: 'rgba(236,72,153,0.08)', format: true,
|
||||||
icon: <SVGIcon size={22}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></SVGIcon> },
|
icon: <SVGIcon size={22}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></SVGIcon> },
|
||||||
];
|
];
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div style={{ animation: 'fadeIn var(--transition-normal)', padding: 'var(--space-2xl)', textAlign: 'center' }}>
|
<div style={{ animation: 'fadeIn var(--transition-normal)', padding: 'var(--space-2xl)', textAlign: 'center' }}>
|
||||||
<div className="audit-spinner" />
|
<div className="audit-spinner" />
|
||||||
<span style={{ marginLeft: 'var(--space-md)', color: 'var(--color-text-tertiary)' }}>加载仪表盘数据...</span>
|
<span style={{ marginLeft: 'var(--space-md)', color: 'var(--color-text-tertiary)' }}>加载仪表盘数据...</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
||||||
<h1 className="admin-page-title">平台驾驶舱</h1>
|
<h1 className="admin-page-title">平台驾驶舱</h1>
|
||||||
|
|
||||||
{/* Stats Cards Row */}
|
{/* Stats Cards Row */}
|
||||||
<div className="admin-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
|
<div className="admin-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
|
||||||
{statCardDefs.map((s, i) => (
|
{statCardDefs.map((s, i) => (
|
||||||
<div key={i} className="admin-stat-card" style={{
|
<div key={i} className="admin-stat-card" style={{
|
||||||
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-lg)',
|
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-lg)',
|
||||||
padding: 'var(--space-lg) var(--space-xl)',
|
padding: 'var(--space-lg) var(--space-xl)',
|
||||||
}}>
|
}}>
|
||||||
<div style={{
|
<div style={{
|
||||||
width: 48, height: 48, borderRadius: 14,
|
width: 48, height: 48, borderRadius: 14,
|
||||||
background: s.bg, color: s.color,
|
background: s.bg, color: s.color,
|
||||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
}}>
|
}}>
|
||||||
{s.icon}
|
{s.icon}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
<div className="admin-stat-label">{s.label}</div>
|
<div className="admin-stat-label">{s.label}</div>
|
||||||
<div className="admin-stat-value" style={{ fontSize: 'var(--text-xl)' }}>
|
<div className="admin-stat-value" style={{ fontSize: 'var(--text-xl)' }}>
|
||||||
{s.format ? formatTokens(s.value as number) : (s.value as number).toLocaleString()}
|
{s.format ? formatTokens(s.value as number) : (s.value as number).toLocaleString()}
|
||||||
</div>
|
</div>
|
||||||
<div style={{
|
<div style={{
|
||||||
fontSize: 11, color: s.color, marginTop: 2,
|
fontSize: 11, color: s.color, marginTop: 2,
|
||||||
background: s.subBg || s.bg, padding: '1px 6px', borderRadius: 4,
|
background: s.subBg || s.bg, padding: '1px 6px', borderRadius: 4,
|
||||||
display: 'inline-block',
|
display: 'inline-block',
|
||||||
}}>{s.sub}</div>
|
}}>{s.sub}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Charts Row */}
|
{/* Charts Row */}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 'var(--space-xl)', marginBottom: 'var(--space-xl)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 'var(--space-xl)', marginBottom: 'var(--space-xl)' }}>
|
||||||
{/* Token Trend Chart */}
|
{/* Token Trend Chart */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">
|
<h3 className="admin-card-title">
|
||||||
<SVGIcon size={18}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon>
|
<SVGIcon size={18}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon>
|
||||||
{' '}Token消耗趋势(近30天)
|
{' '}Token消耗趋势(近30天)
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ padding: 'var(--space-lg)', display: 'flex', justifyContent: 'center' }}>
|
<div style={{ padding: 'var(--space-lg)', display: 'flex', justifyContent: 'center' }}>
|
||||||
<BarChart data={dailyStats} />
|
<BarChart data={dailyStats} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* System Health */}
|
{/* System Health */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">
|
<h3 className="admin-card-title">
|
||||||
<SVGIcon size={18}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></SVGIcon>
|
<SVGIcon size={18}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></SVGIcon>
|
||||||
{' '}平台概览
|
{' '}平台概览
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ padding: 'var(--space-lg)' }}>
|
<div style={{ padding: 'var(--space-lg)' }}>
|
||||||
{[
|
{[
|
||||||
{ label: '累计Token消耗', value: formatTokens(stats.total_tokens), color: '#6C63FF', pct: 100 },
|
{ label: '累计Token消耗', value: formatTokens(stats.total_tokens), color: '#6C63FF', pct: 100 },
|
||||||
{ label: '模型利用率', value: `${stats.enabled_models}/${stats.total_models}`, color: '#219B5E', pct: stats.total_models > 0 ? stats.enabled_models / stats.total_models : 0 },
|
{ label: '模型利用率', value: `${stats.enabled_models}/${stats.total_models}`, color: '#219B5E', pct: stats.total_models > 0 ? stats.enabled_models / stats.total_models : 0 },
|
||||||
{ label: '用户活跃率', value: `${stats.active_users}/${stats.total_users}`, color: '#E8922C', pct: stats.total_users > 0 ? stats.active_users / stats.total_users : 0 },
|
{ label: '用户活跃率', value: `${stats.active_users}/${stats.total_users}`, color: '#E8922C', pct: stats.total_users > 0 ? stats.active_users / stats.total_users : 0 },
|
||||||
{ label: '对话活跃率', value: `${stats.active_conversations}/${stats.total_conversations}`, color: '#3B82F6', pct: stats.total_conversations > 0 ? stats.active_conversations / stats.total_conversations : 0 },
|
{ label: '对话活跃率', value: `${stats.active_conversations}/${stats.total_conversations}`, color: '#3B82F6', pct: stats.total_conversations > 0 ? stats.active_conversations / stats.total_conversations : 0 },
|
||||||
].map((item, i) => (
|
].map((item, i) => (
|
||||||
<div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < 3 ? '1px solid rgba(0,0,0,0.06)' : 'none' }}>
|
<div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < 3 ? '1px solid rgba(0,0,0,0.06)' : 'none' }}>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||||
<MiniDonut value={item.pct * 100} max={100} color={item.color} />
|
<MiniDonut value={item.pct * 100} max={100} color={item.color} />
|
||||||
<span style={{ fontSize: 13, color: '#1A1F36' }}>{item.label}</span>
|
<span style={{ fontSize: 13, color: '#1A1F36' }}>{item.label}</span>
|
||||||
</div>
|
</div>
|
||||||
<span style={{ fontSize: 15, fontWeight: 700, color: item.color, fontFamily: 'var(--font-mono)' }}>{item.value}</span>
|
<span style={{ fontSize: 15, fontWeight: 700, color: item.color, fontFamily: 'var(--font-mono)' }}>{item.value}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<div style={{ marginTop: 12, fontSize: 11, color: '#6B7280', textAlign: 'center' }}>
|
<div style={{ marginTop: 12, fontSize: 11, color: '#6B7280', textAlign: 'center' }}>
|
||||||
服务器时间: {stats.server_time ? formatBjTime(stats.server_time) : '-'}
|
服务器时间: {stats.server_time ? formatBjTime(stats.server_time) : '-'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Quick Actions */}
|
{/* Quick Actions */}
|
||||||
<div style={{ marginBottom: 'var(--space-xl)' }}>
|
<div style={{ marginBottom: 'var(--space-xl)' }}>
|
||||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 12, color: '#1A1F36' }}>快捷入口</h3>
|
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 12, color: '#1A1F36' }}>快捷入口</h3>
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 'var(--space-md)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 'var(--space-md)' }}>
|
||||||
{quickEntries.map((entry) => (
|
{quickEntries.map((entry) => (
|
||||||
<div
|
<div
|
||||||
key={entry.path}
|
key={entry.path}
|
||||||
onClick={() => navigate(entry.path)}
|
onClick={() => navigate(entry.path)}
|
||||||
style={{
|
style={{
|
||||||
background: '#FFFFFF', borderRadius: 'var(--radius-lg)', border: '1px solid rgba(0,0,0,0.08)',
|
background: '#FFFFFF', borderRadius: 'var(--radius-lg)', border: '1px solid rgba(0,0,0,0.08)',
|
||||||
padding: 'var(--space-md) var(--space-lg)', cursor: 'pointer', transition: 'all 0.2s',
|
padding: 'var(--space-md) var(--space-lg)', cursor: 'pointer', transition: 'all 0.2s',
|
||||||
display: 'flex', alignItems: 'center', gap: 'var(--space-md)',
|
display: 'flex', alignItems: 'center', gap: 'var(--space-md)',
|
||||||
boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
|
boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
|
||||||
}}
|
}}
|
||||||
onMouseEnter={(e) => {
|
onMouseEnter={(e) => {
|
||||||
e.currentTarget.style.borderColor = '#6C63FF';
|
e.currentTarget.style.borderColor = '#6C63FF';
|
||||||
e.currentTarget.style.boxShadow = '0 2px 8px rgba(108,99,255,0.15)';
|
e.currentTarget.style.boxShadow = '0 2px 8px rgba(108,99,255,0.15)';
|
||||||
e.currentTarget.style.transform = 'translateY(-1px)';
|
e.currentTarget.style.transform = 'translateY(-1px)';
|
||||||
}}
|
}}
|
||||||
onMouseLeave={(e) => {
|
onMouseLeave={(e) => {
|
||||||
e.currentTarget.style.borderColor = 'var(--color-border)';
|
e.currentTarget.style.borderColor = 'var(--color-border)';
|
||||||
e.currentTarget.style.boxShadow = 'none';
|
e.currentTarget.style.boxShadow = 'none';
|
||||||
e.currentTarget.style.transform = 'none';
|
e.currentTarget.style.transform = 'none';
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ color: '#6C63FF', flexShrink: 0 }}>{entry.icon}</div>
|
<div style={{ color: '#6C63FF', flexShrink: 0 }}>{entry.icon}</div>
|
||||||
<div>
|
<div>
|
||||||
<div style={{ fontSize: 13, fontWeight: 600, color: '#1A1F36' }}>{entry.label}</div>
|
<div style={{ fontSize: 13, fontWeight: 600, color: '#1A1F36' }}>{entry.label}</div>
|
||||||
<div style={{ fontSize: 11, color: '#6B7280' }}>{entry.desc}</div>
|
<div style={{ fontSize: 11, color: '#6B7280' }}>{entry.desc}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Recent Logs */}
|
{/* Recent Logs */}
|
||||||
<div className="admin-card" style={{ marginBottom: 'var(--space-xl)' }}>
|
<div className="admin-card" style={{ marginBottom: 'var(--space-xl)' }}>
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">操作日志</h3>
|
<h3 className="admin-card-title">操作日志</h3>
|
||||||
<button
|
<button
|
||||||
onClick={() => downloadCsv('/admin/dashboard/operation-logs/export', 'operation_logs.csv')}
|
onClick={() => downloadCsv('/admin/dashboard/operation-logs/export', 'operation_logs.csv')}
|
||||||
style={{ fontSize: 12, color: '#6C63FF', border: '1px solid rgba(108,99,255,0.4)', background: 'rgba(108,99,255,0.06)', borderRadius: 6, padding: '4px 12px', cursor: 'pointer' }}
|
style={{ fontSize: 12, color: '#6C63FF', border: '1px solid rgba(108,99,255,0.4)', background: 'rgba(108,99,255,0.06)', borderRadius: 6, padding: '4px 12px', cursor: 'pointer' }}
|
||||||
>下载 CSV</button>
|
>下载 CSV</button>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>用户</th>
|
<th>用户</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
<th>目标</th>
|
<th>目标</th>
|
||||||
<th>详情</th>
|
<th>详情</th>
|
||||||
<th>IP</th>
|
<th>IP</th>
|
||||||
<th>时间</th>
|
<th>时间</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{operationLogs.length > 0 ? operationLogs.map(log => (
|
{operationLogs.length > 0 ? operationLogs.map(log => (
|
||||||
<tr key={log.id}>
|
<tr key={log.id}>
|
||||||
<td style={{ fontWeight: 500 }}>{log.username}</td>
|
<td style={{ fontWeight: 500 }}>{log.username}</td>
|
||||||
<td><span className="admin-badge badge-info">{log.action}</span></td>
|
<td><span className="admin-badge badge-info">{log.action}</span></td>
|
||||||
<td>{log.target}</td>
|
<td>{log.target}</td>
|
||||||
<td style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{log.detail}</td>
|
<td style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{log.detail}</td>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{log.ip}</td>
|
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{log.ip}</td>
|
||||||
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(log.created_at)}</td>
|
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(log.created_at)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
)) : (
|
)) : (
|
||||||
<tr><td colSpan={6} style={{ textAlign: 'center', color: 'var(--color-text-tertiary)', padding: 'var(--space-lg)' }}>暂无操作日志</td></tr>
|
<tr><td colSpan={6} style={{ textAlign: 'center', color: 'var(--color-text-tertiary)', padding: 'var(--space-lg)' }}>暂无操作日志</td></tr>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<LogPagination total={opTotal} page={opPage} pageSize={PAGE_SIZE} onPage={loadOperationLogs} />
|
<LogPagination total={opTotal} page={opPage} pageSize={PAGE_SIZE} onPage={loadOperationLogs} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Recent Audit Logs */}
|
{/* Recent Audit Logs */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">审计日志</h3>
|
<h3 className="admin-card-title">审计日志</h3>
|
||||||
<button
|
<button
|
||||||
onClick={() => downloadCsv('/admin/dashboard/audit-logs/export', 'audit_logs.csv')}
|
onClick={() => downloadCsv('/admin/dashboard/audit-logs/export', 'audit_logs.csv')}
|
||||||
style={{ fontSize: 12, color: '#6C63FF', border: '1px solid rgba(108,99,255,0.4)', background: 'rgba(108,99,255,0.06)', borderRadius: 6, padding: '4px 12px', cursor: 'pointer' }}
|
style={{ fontSize: 12, color: '#6C63FF', border: '1px solid rgba(108,99,255,0.4)', background: 'rgba(108,99,255,0.06)', borderRadius: 6, padding: '4px 12px', cursor: 'pointer' }}
|
||||||
>下载 CSV</button>
|
>下载 CSV</button>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>操作人</th>
|
<th>操作人</th>
|
||||||
<th>操作类型</th>
|
<th>操作类型</th>
|
||||||
<th>目标类型</th>
|
<th>目标类型</th>
|
||||||
<th>详情</th>
|
<th>详情</th>
|
||||||
<th>时间</th>
|
<th>时间</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{auditLogs.length > 0 ? auditLogs.map(log => (
|
{auditLogs.length > 0 ? auditLogs.map(log => (
|
||||||
<tr key={log.id}>
|
<tr key={log.id}>
|
||||||
<td style={{ fontWeight: 500 }}>{log.admin_name}</td>
|
<td style={{ fontWeight: 500 }}>{log.admin_name}</td>
|
||||||
<td><span className="admin-badge badge-warning">{log.action}</span></td>
|
<td><span className="admin-badge badge-warning">{log.action}</span></td>
|
||||||
<td><span className="admin-badge badge neutral">{log.target_type}</span></td>
|
<td><span className="admin-badge badge neutral">{log.target_type}</span></td>
|
||||||
<td>{log.detail}</td>
|
<td>{log.detail}</td>
|
||||||
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(log.created_at)}</td>
|
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(log.created_at)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
)) : (
|
)) : (
|
||||||
<tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--color-text-tertiary)', padding: 'var(--space-lg)' }}>暂无审计日志</td></tr>
|
<tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--color-text-tertiary)', padding: 'var(--space-lg)' }}>暂无审计日志</td></tr>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<LogPagination total={auditTotal} page={auditPage} pageSize={PAGE_SIZE} onPage={loadAuditLogs} />
|
<LogPagination total={auditTotal} page={auditPage} pageSize={PAGE_SIZE} onPage={loadAuditLogs} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Dashboard;
|
export default Dashboard;
|
||||||
File diff suppressed because it is too large.
Load diff
+388
-388
@@ -1,388 +1,388 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { adminAPI } from '@/api';
|
import { adminAPI } from '@/api';
|
||||||
import { mockCoupons } from '@/mock/data';
|
import { mockCoupons } from '@/mock/data';
|
||||||
import type { MarketApp, Coupon } from '@/types';
|
import type { MarketApp, Coupon } from '@/types';
|
||||||
|
|
||||||
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
|
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
|
||||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
{children}
|
{children}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Phase 4.1: 安检状态徽章
|
// Phase 4.1: 安检状态徽章
|
||||||
function SecurityBadge({ scan }: { scan?: any }) {
|
function SecurityBadge({ scan }: { scan?: any }) {
|
||||||
if (!scan || !scan.status) return <span style={{ color: 'var(--color-text-disabled)' }}>未扫描</span>;
|
if (!scan || !scan.status) return <span style={{ color: 'var(--color-text-disabled)' }}>未扫描</span>;
|
||||||
const map: Record<string, { label: string; bg: string; fg: string }> = {
|
const map: Record<string, { label: string; bg: string; fg: string }> = {
|
||||||
pass: { label: '安检通过', bg: '#16a34a1A', fg: '#16a34a' },
|
pass: { label: '安检通过', bg: '#16a34a1A', fg: '#16a34a' },
|
||||||
warn: { label: '安检注意', bg: '#d977061A', fg: '#d97706' },
|
warn: { label: '安检注意', bg: '#d977061A', fg: '#d97706' },
|
||||||
fail: { label: '安检风险', bg: '#dc26261A', fg: '#dc2626' },
|
fail: { label: '安检风险', bg: '#dc26261A', fg: '#dc2626' },
|
||||||
};
|
};
|
||||||
const m = map[scan.status] || map.warn;
|
const m = map[scan.status] || map.warn;
|
||||||
return (
|
return (
|
||||||
<span style={{ background: m.bg, color: m.fg, padding: '2px 8px', borderRadius: 'var(--radius-full)', fontSize: 'var(--text-xs)', fontWeight: 600 }}>
|
<span style={{ background: m.bg, color: m.fg, padding: '2px 8px', borderRadius: 'var(--radius-full)', fontSize: 'var(--text-xs)', fontWeight: 600 }}>
|
||||||
{m.label}
|
{m.label}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const mapApp = (a: any): MarketApp => ({
|
const mapApp = (a: any): MarketApp => ({
|
||||||
id: a.id, name: a.name, type: a.type, source: a.source,
|
id: a.id, name: a.name, type: a.type, source: a.source,
|
||||||
publisherId: a.publisher_id, publisherName: a.publisher_name || '未知',
|
publisherId: a.publisher_id, publisherName: a.publisher_name || '未知',
|
||||||
description: a.description || '', icon: a.icon || '?',
|
description: a.description || '', icon: a.icon || '?',
|
||||||
price: a.price || 0, isMemberFree: a.is_member_free || false,
|
price: a.price || 0, isMemberFree: a.is_member_free || false,
|
||||||
joinPromotion: a.join_promotion || false, status: a.status || 'published',
|
joinPromotion: a.join_promotion || false, status: a.status || 'published',
|
||||||
ratingAvg: a.rating_avg || 0, reviewCount: a.review_count || 0,
|
ratingAvg: a.rating_avg || 0, reviewCount: a.review_count || 0,
|
||||||
installCount: a.install_count || 0, createdAt: a.created_at || '',
|
installCount: a.install_count || 0, createdAt: a.created_at || '',
|
||||||
version: a.version || '1.0.0', verified: a.verified || false,
|
version: a.version || '1.0.0', verified: a.verified || false,
|
||||||
securityScan: a.security_scan || null, dependencies: a.dependencies || null,
|
securityScan: a.security_scan || null, dependencies: a.dependencies || null,
|
||||||
});
|
});
|
||||||
|
|
||||||
const Market: React.FC = () => {
|
const Market: React.FC = () => {
|
||||||
const [reviewApps, setReviewApps] = useState<MarketApp[]>([]);
|
const [reviewApps, setReviewApps] = useState<MarketApp[]>([]);
|
||||||
const [officialApps, setOfficialApps] = useState<MarketApp[]>([]);
|
const [officialApps, setOfficialApps] = useState<MarketApp[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [activeTab, setActiveTab] = useState<'review' | 'coupon' | 'official'>('review');
|
const [activeTab, setActiveTab] = useState<'review' | 'coupon' | 'official'>('review');
|
||||||
const [showCouponModal, setShowCouponModal] = useState(false);
|
const [showCouponModal, setShowCouponModal] = useState(false);
|
||||||
const [coupons] = useState<Coupon[]>(mockCoupons);
|
const [coupons] = useState<Coupon[]>(mockCoupons);
|
||||||
|
|
||||||
const [couponForm, setCouponForm] = useState({
|
const [couponForm, setCouponForm] = useState({
|
||||||
code: '', type: 'fixed' as 'fixed' | 'percent', value: 0, minAmount: 0,
|
code: '', type: 'fixed' as 'fixed' | 'percent', value: 0, minAmount: 0,
|
||||||
validFrom: '', validTo: '',
|
validFrom: '', validTo: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
// Phase 4.1: 版本历史弹窗
|
// Phase 4.1: 版本历史弹窗
|
||||||
const [versionsApp, setVersionsApp] = useState<MarketApp | null>(null);
|
const [versionsApp, setVersionsApp] = useState<MarketApp | null>(null);
|
||||||
const [versions, setVersions] = useState<any[]>([]);
|
const [versions, setVersions] = useState<any[]>([]);
|
||||||
const [loadingVersions, setLoadingVersions] = useState(false);
|
const [loadingVersions, setLoadingVersions] = useState(false);
|
||||||
|
|
||||||
const loadReview = () => {
|
const loadReview = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
adminAPI.getPendingApps().then((res: any) => {
|
adminAPI.getPendingApps().then((res: any) => {
|
||||||
if (res && Array.isArray(res)) setReviewApps(res.map(mapApp));
|
if (res && Array.isArray(res)) setReviewApps(res.map(mapApp));
|
||||||
else if (res?.code === 0 && Array.isArray(res.data)) setReviewApps(res.data.map(mapApp));
|
else if (res?.code === 0 && Array.isArray(res.data)) setReviewApps(res.data.map(mapApp));
|
||||||
}).catch(() => {}).finally(() => setLoading(false));
|
}).catch(() => {}).finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadOfficial = () => {
|
const loadOfficial = () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
adminAPI.getAdminMarketApps('status=published').then((res: any) => {
|
adminAPI.getAdminMarketApps('status=published').then((res: any) => {
|
||||||
const items = (res?.data?.items || res?.items || []).map(mapApp).filter((a: MarketApp) => a.source === 'official');
|
const items = (res?.data?.items || res?.items || []).map(mapApp).filter((a: MarketApp) => a.source === 'official');
|
||||||
setOfficialApps(items);
|
setOfficialApps(items);
|
||||||
}).catch(() => {}).finally(() => setLoading(false));
|
}).catch(() => {}).finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeTab === 'review') loadReview();
|
if (activeTab === 'review') loadReview();
|
||||||
else if (activeTab === 'official') loadOfficial();
|
else if (activeTab === 'official') loadOfficial();
|
||||||
}, [activeTab]);
|
}, [activeTab]);
|
||||||
|
|
||||||
const handleApprove = (id: string) => {
|
const handleApprove = (id: string) => {
|
||||||
adminAPI.approveApp(id).then(() => loadReview()).catch(() => alert('审核失败'));
|
adminAPI.approveApp(id).then(() => loadReview()).catch(() => alert('审核失败'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReject = (id: string) => {
|
const handleReject = (id: string) => {
|
||||||
adminAPI.rejectApp(id).then(() => loadReview()).catch(() => alert('拒绝失败'));
|
adminAPI.rejectApp(id).then(() => loadReview()).catch(() => alert('拒绝失败'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRemoveOfficial = (id: string) => {
|
const handleRemoveOfficial = (id: string) => {
|
||||||
if (!confirm('确认下架该官方应用?')) return;
|
if (!confirm('确认下架该官方应用?')) return;
|
||||||
adminAPI.rejectApp(id).then(() => loadOfficial()).catch(() => alert('下架失败'));
|
adminAPI.rejectApp(id).then(() => loadOfficial()).catch(() => alert('下架失败'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRescan = (id: string) => {
|
const handleRescan = (id: string) => {
|
||||||
adminAPI.rescanApp(id).then((res: any) => {
|
adminAPI.rescanApp(id).then((res: any) => {
|
||||||
alert('重新安检完成:' + (res?.status || 'unknown'));
|
alert('重新安检完成:' + (res?.status || 'unknown'));
|
||||||
loadOfficial();
|
loadOfficial();
|
||||||
}).catch(() => alert('安检失败'));
|
}).catch(() => alert('安检失败'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const openVersions = (app: MarketApp) => {
|
const openVersions = (app: MarketApp) => {
|
||||||
setVersionsApp(app);
|
setVersionsApp(app);
|
||||||
setLoadingVersions(true);
|
setLoadingVersions(true);
|
||||||
setVersions([]);
|
setVersions([]);
|
||||||
adminAPI.getAppVersions(app.id).then((res: any) => {
|
adminAPI.getAppVersions(app.id).then((res: any) => {
|
||||||
setVersions(res?.items || []);
|
setVersions(res?.items || []);
|
||||||
}).catch(() => {}).finally(() => setLoadingVersions(false));
|
}).catch(() => {}).finally(() => setLoadingVersions(false));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRollback = (appId: string, versionId: string) => {
|
const handleRollback = (appId: string, versionId: string) => {
|
||||||
if (!confirm('确认回滚到该版本?当前配置将被覆盖。')) return;
|
if (!confirm('确认回滚到该版本?当前配置将被覆盖。')) return;
|
||||||
adminAPI.rollbackApp(appId, versionId).then(() => {
|
adminAPI.rollbackApp(appId, versionId).then(() => {
|
||||||
alert('已回滚');
|
alert('已回滚');
|
||||||
openVersions({ ...versionsApp!, id: appId } as MarketApp);
|
openVersions({ ...versionsApp!, id: appId } as MarketApp);
|
||||||
loadOfficial();
|
loadOfficial();
|
||||||
}).catch(() => alert('回滚失败'));
|
}).catch(() => alert('回滚失败'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatDate = (d: string) => {
|
const formatDate = (d: string) => {
|
||||||
if (!d) return '-';
|
if (!d) return '-';
|
||||||
const dt = new Date(d);
|
const dt = new Date(d);
|
||||||
return dt.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
return dt.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||||
};
|
};
|
||||||
|
|
||||||
const tabs = [
|
const tabs = [
|
||||||
{ key: 'review' as const, label: '待审核应用', count: reviewApps.length },
|
{ key: 'review' as const, label: '待审核应用', count: reviewApps.length },
|
||||||
{ key: 'coupon' as const, label: '优惠券管理', count: coupons.length },
|
{ key: 'coupon' as const, label: '优惠券管理', count: coupons.length },
|
||||||
{ key: 'official' as const, label: '官方应用管理', count: officialApps.length },
|
{ key: 'official' as const, label: '官方应用管理', count: officialApps.length },
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
||||||
<h1 className="admin-page-title">AI技能审核管理</h1>
|
<h1 className="admin-page-title">AI技能审核管理</h1>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div style={{ display: 'flex', gap: 'var(--space-sm)', marginBottom: 'var(--space-2xl)', borderBottom: '1px solid var(--color-border)', paddingBottom: 'var(--space-lg)' }}>
|
<div style={{ display: 'flex', gap: 'var(--space-sm)', marginBottom: 'var(--space-2xl)', borderBottom: '1px solid var(--color-border)', paddingBottom: 'var(--space-lg)' }}>
|
||||||
{tabs.map(tab => (
|
{tabs.map(tab => (
|
||||||
<button
|
<button
|
||||||
key={tab.key}
|
key={tab.key}
|
||||||
onClick={() => setActiveTab(tab.key)}
|
onClick={() => setActiveTab(tab.key)}
|
||||||
style={{
|
style={{
|
||||||
padding: 'var(--space-sm) var(--space-lg)',
|
padding: 'var(--space-sm) var(--space-lg)',
|
||||||
borderRadius: 'var(--radius-md)',
|
borderRadius: 'var(--radius-md)',
|
||||||
fontSize: 'var(--text-sm)', fontWeight: 600,
|
fontSize: 'var(--text-sm)', fontWeight: 600,
|
||||||
background: activeTab === tab.key ? 'var(--color-accent-light)' : 'transparent',
|
background: activeTab === tab.key ? 'var(--color-accent-light)' : 'transparent',
|
||||||
color: activeTab === tab.key ? 'var(--color-accent)' : 'var(--color-text-secondary)',
|
color: activeTab === tab.key ? 'var(--color-accent)' : 'var(--color-text-secondary)',
|
||||||
transition: 'all var(--transition-fast)',
|
transition: 'all var(--transition-fast)',
|
||||||
display: 'flex', alignItems: 'center', gap: 'var(--space-sm)',
|
display: 'flex', alignItems: 'center', gap: 'var(--space-sm)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{tab.label}
|
{tab.label}
|
||||||
{tab.count > 0 && (
|
{tab.count > 0 && (
|
||||||
<span style={{
|
<span style={{
|
||||||
background: activeTab === tab.key ? 'var(--color-accent)' : 'var(--color-text-disabled)',
|
background: activeTab === tab.key ? 'var(--color-accent)' : 'var(--color-text-disabled)',
|
||||||
color: '#FFFFFF', padding: '0 6px', borderRadius: 'var(--radius-full)',
|
color: '#FFFFFF', padding: '0 6px', borderRadius: 'var(--radius-full)',
|
||||||
fontSize: 'var(--text-xs)', lineHeight: '18px', minWidth: 18, textAlign: 'center',
|
fontSize: 'var(--text-xs)', lineHeight: '18px', minWidth: 18, textAlign: 'center',
|
||||||
}}>
|
}}>
|
||||||
{tab.count}
|
{tab.count}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pending Review Tab */}
|
{/* Pending Review Tab */}
|
||||||
{activeTab === 'review' && (
|
{activeTab === 'review' && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">待审核应用</h3>
|
<h3 className="admin-card-title">待审核应用</h3>
|
||||||
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={loadReview}>刷新</button>
|
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={loadReview}>刷新</button>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>应用名</th>
|
<th>应用名</th>
|
||||||
<th>类型</th>
|
<th>类型</th>
|
||||||
<th>发布者</th>
|
<th>发布者</th>
|
||||||
<th>价格</th>
|
<th>价格</th>
|
||||||
<th>安检</th>
|
<th>安检</th>
|
||||||
<th>发布时间</th>
|
<th>发布时间</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{reviewApps.map(app => (
|
{reviewApps.map(app => (
|
||||||
<tr key={app.id}>
|
<tr key={app.id}>
|
||||||
<td style={{ fontWeight: 600 }}>{app.name}</td>
|
<td style={{ fontWeight: 600 }}>{app.name}</td>
|
||||||
<td>
|
<td>
|
||||||
<span className={`admin-badge ${app.type === 'agent' ? 'badge-info' : app.type === 'skill' ? 'badge-success' : 'badge-warning'}`}>
|
<span className={`admin-badge ${app.type === 'agent' ? 'badge-info' : app.type === 'skill' ? 'badge-success' : 'badge-warning'}`}>
|
||||||
{app.type.toUpperCase()}
|
{app.type.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{app.publisherName}</td>
|
<td>{app.publisherName}</td>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{app.price} 元</td>
|
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{app.price} 元</td>
|
||||||
<td><SecurityBadge scan={app.securityScan} /></td>
|
<td><SecurityBadge scan={app.securityScan} /></td>
|
||||||
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(app.createdAt)}</td>
|
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>{formatDate(app.createdAt)}</td>
|
||||||
<td>
|
<td>
|
||||||
<div style={{ display: 'flex', gap: 'var(--space-sm)' }}>
|
<div style={{ display: 'flex', gap: 'var(--space-sm)' }}>
|
||||||
<button className="admin-btn admin-btn-primary admin-btn-sm" onClick={() => handleApprove(app.id)}>
|
<button className="admin-btn admin-btn-primary admin-btn-sm" onClick={() => handleApprove(app.id)}>
|
||||||
<SVGIcon size={12}><polyline points="20 6 9 17 4 12"/></SVGIcon>
|
<SVGIcon size={12}><polyline points="20 6 9 17 4 12"/></SVGIcon>
|
||||||
通过(绿标)
|
通过(绿标)
|
||||||
</button>
|
</button>
|
||||||
<button className="admin-btn admin-btn-danger admin-btn-sm" onClick={() => handleReject(app.id)}>
|
<button className="admin-btn admin-btn-danger admin-btn-sm" onClick={() => handleReject(app.id)}>
|
||||||
<SVGIcon size={12}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></SVGIcon>
|
<SVGIcon size={12}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></SVGIcon>
|
||||||
拒绝
|
拒绝
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{reviewApps.length === 0 && !loading && (
|
{reviewApps.length === 0 && !loading && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} style={{ textAlign: 'center', color: 'var(--color-text-disabled)', padding: 'var(--space-3xl)' }}>
|
<td colSpan={7} style={{ textAlign: 'center', color: 'var(--color-text-disabled)', padding: 'var(--space-3xl)' }}>
|
||||||
暂无待审核应用
|
暂无待审核应用
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
{loading && (
|
{loading && (
|
||||||
<tr><td colSpan={7} style={{ textAlign: 'center', padding: 'var(--space-3xl)' }}>加载中...</td></tr>
|
<tr><td colSpan={7} style={{ textAlign: 'center', padding: 'var(--space-3xl)' }}>加载中...</td></tr>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Coupon Management Tab */}
|
{/* Coupon Management Tab */}
|
||||||
{activeTab === 'coupon' && (
|
{activeTab === 'coupon' && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">优惠券列表</h3>
|
<h3 className="admin-card-title">优惠券列表</h3>
|
||||||
<button className="admin-btn admin-btn-primary admin-btn-sm" onClick={() => setShowCouponModal(true)}>
|
<button className="admin-btn admin-btn-primary admin-btn-sm" onClick={() => setShowCouponModal(true)}>
|
||||||
<SVGIcon><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></SVGIcon>
|
<SVGIcon><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></SVGIcon>
|
||||||
创建优惠券
|
创建优惠券
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>兑换码</th>
|
<th>兑换码</th>
|
||||||
<th>类型</th>
|
<th>类型</th>
|
||||||
<th>面值</th>
|
<th>面值</th>
|
||||||
<th>最低消费</th>
|
<th>最低消费</th>
|
||||||
<th>有效期</th>
|
<th>有效期</th>
|
||||||
<th>状态</th>
|
<th>状态</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{coupons.map(c => (
|
{coupons.map(c => (
|
||||||
<tr key={c.id}>
|
<tr key={c.id}>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{c.code}</td>
|
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{c.code}</td>
|
||||||
<td>
|
<td>
|
||||||
<span className={`admin-badge ${c.type === 'fixed' ? 'badge-info' : 'badge-warning'}`}>
|
<span className={`admin-badge ${c.type === 'fixed' ? 'badge-info' : 'badge-warning'}`}>
|
||||||
{c.type === 'fixed' ? '固定金额' : '百分比'}
|
{c.type === 'fixed' ? '固定金额' : '百分比'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
|
<td style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
|
||||||
{c.type === 'fixed' ? `${c.value} 元` : `${c.value}%`}
|
{c.type === 'fixed' ? `${c.value} 元` : `${c.value}%`}
|
||||||
</td>
|
</td>
|
||||||
<td>{c.minAmount > 0 ? `${c.minAmount} 元` : '无门槛'}</td>
|
<td>{c.minAmount > 0 ? `${c.minAmount} 元` : '无门槛'}</td>
|
||||||
<td style={{ fontSize: 'var(--text-xs)' }}>{c.validFrom} 至 {c.validTo}</td>
|
<td style={{ fontSize: 'var(--text-xs)' }}>{c.validFrom} 至 {c.validTo}</td>
|
||||||
<td>
|
<td>
|
||||||
<span className={`admin-badge ${c.status === 'active' ? 'badge-success' : 'badge-error'}`}>
|
<span className={`admin-badge ${c.status === 'active' ? 'badge-success' : 'badge-error'}`}>
|
||||||
{c.status === 'active' ? '有效' : '已过期'}
|
{c.status === 'active' ? '有效' : '已过期'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td><span style={{ color: 'var(--color-text-disabled)' }}>只读</span></td>
|
<td><span style={{ color: 'var(--color-text-disabled)' }}>只读</span></td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Official App Management Tab */}
|
{/* Official App Management Tab */}
|
||||||
{activeTab === 'official' && (
|
{activeTab === 'official' && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">官方应用列表</h3>
|
<h3 className="admin-card-title">官方应用列表</h3>
|
||||||
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={loadOfficial}>刷新</button>
|
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={loadOfficial}>刷新</button>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>应用名</th>
|
<th>应用名</th>
|
||||||
<th>类型</th>
|
<th>类型</th>
|
||||||
<th>版本</th>
|
<th>版本</th>
|
||||||
<th>绿标</th>
|
<th>绿标</th>
|
||||||
<th>安检</th>
|
<th>安检</th>
|
||||||
<th>安装量</th>
|
<th>安装量</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{officialApps.map(app => (
|
{officialApps.map(app => (
|
||||||
<tr key={app.id}>
|
<tr key={app.id}>
|
||||||
<td style={{ fontWeight: 600 }}>{app.name}</td>
|
<td style={{ fontWeight: 600 }}>{app.name}</td>
|
||||||
<td>
|
<td>
|
||||||
<span className={`admin-badge ${app.type === 'agent' ? 'badge-info' : app.type === 'skill' ? 'badge-success' : 'badge-warning'}`}>
|
<span className={`admin-badge ${app.type === 'agent' ? 'badge-info' : app.type === 'skill' ? 'badge-success' : 'badge-warning'}`}>
|
||||||
{app.type.toUpperCase()}
|
{app.type.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)' }}>v{app.version}</td>
|
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)' }}>v{app.version}</td>
|
||||||
<td>
|
<td>
|
||||||
{app.verified
|
{app.verified
|
||||||
? <span style={{ color: '#16a34a', fontWeight: 600 }}>✓ 已认证</span>
|
? <span style={{ color: '#16a34a', fontWeight: 600 }}>✓ 已认证</span>
|
||||||
: <span style={{ color: 'var(--color-text-disabled)' }}>未认证</span>}
|
: <span style={{ color: 'var(--color-text-disabled)' }}>未认证</span>}
|
||||||
</td>
|
</td>
|
||||||
<td><SecurityBadge scan={app.securityScan} /></td>
|
<td><SecurityBadge scan={app.securityScan} /></td>
|
||||||
<td>{app.installCount.toLocaleString()}</td>
|
<td>{app.installCount.toLocaleString()}</td>
|
||||||
<td>
|
<td>
|
||||||
<div style={{ display: 'flex', gap: 'var(--space-sm)' }}>
|
<div style={{ display: 'flex', gap: 'var(--space-sm)' }}>
|
||||||
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => handleRescan(app.id)}>重新安检</button>
|
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => handleRescan(app.id)}>重新安检</button>
|
||||||
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => openVersions(app)}>版本历史</button>
|
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => openVersions(app)}>版本历史</button>
|
||||||
<button className="admin-btn admin-btn-danger admin-btn-sm" onClick={() => handleRemoveOfficial(app.id)}>下架</button>
|
<button className="admin-btn admin-btn-danger admin-btn-sm" onClick={() => handleRemoveOfficial(app.id)}>下架</button>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{officialApps.length === 0 && !loading && (
|
{officialApps.length === 0 && !loading && (
|
||||||
<tr><td colSpan={7} style={{ textAlign: 'center', color: 'var(--color-text-disabled)', padding: 'var(--space-3xl)' }}>暂无官方应用</td></tr>
|
<tr><td colSpan={7} style={{ textAlign: 'center', color: 'var(--color-text-disabled)', padding: 'var(--space-3xl)' }}>暂无官方应用</td></tr>
|
||||||
)}
|
)}
|
||||||
{loading && (
|
{loading && (
|
||||||
<tr><td colSpan={7} style={{ textAlign: 'center', padding: 'var(--space-3xl)' }}>加载中...</td></tr>
|
<tr><td colSpan={7} style={{ textAlign: 'center', padding: 'var(--space-3xl)' }}>加载中...</td></tr>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Version History Modal */}
|
{/* Version History Modal */}
|
||||||
{versionsApp && (
|
{versionsApp && (
|
||||||
<div style={{
|
<div style={{
|
||||||
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
|
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
|
||||||
background: 'rgba(0,0,0,0.4)', zIndex: 'var(--z-modal)',
|
background: 'rgba(0,0,0,0.4)', zIndex: 'var(--z-modal)',
|
||||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||||
animation: 'fadeIn var(--transition-normal)',
|
animation: 'fadeIn var(--transition-normal)',
|
||||||
}} onClick={() => setVersionsApp(null)}>
|
}} onClick={() => setVersionsApp(null)}>
|
||||||
<div style={{
|
<div style={{
|
||||||
background: '#FFFFFF', borderRadius: 'var(--radius-2xl)', width: 520, maxHeight: '90vh', overflow: 'auto',
|
background: '#FFFFFF', borderRadius: 'var(--radius-2xl)', width: 520, maxHeight: '90vh', overflow: 'auto',
|
||||||
padding: 'var(--space-3xl)', boxShadow: 'var(--shadow-xl)',
|
padding: 'var(--space-3xl)', boxShadow: 'var(--shadow-xl)',
|
||||||
}} onClick={e => e.stopPropagation()}>
|
}} onClick={e => e.stopPropagation()}>
|
||||||
<h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 700, marginBottom: 'var(--space-lg)' }}>
|
<h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 700, marginBottom: 'var(--space-lg)' }}>
|
||||||
版本历史 · {versionsApp.name}
|
版本历史 · {versionsApp.name}
|
||||||
</h3>
|
</h3>
|
||||||
<p style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)', marginBottom: 'var(--space-2xl)' }}>
|
<p style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)', marginBottom: 'var(--space-2xl)' }}>
|
||||||
当前版本:v{versionsApp.version}
|
当前版本:v{versionsApp.version}
|
||||||
</p>
|
</p>
|
||||||
{loadingVersions ? (
|
{loadingVersions ? (
|
||||||
<p style={{ color: 'var(--color-text-disabled)' }}>加载中...</p>
|
<p style={{ color: 'var(--color-text-disabled)' }}>加载中...</p>
|
||||||
) : versions.length === 0 ? (
|
) : versions.length === 0 ? (
|
||||||
<p style={{ color: 'var(--color-text-disabled)' }}>暂无历史版本</p>
|
<p style={{ color: 'var(--color-text-disabled)' }}>暂无历史版本</p>
|
||||||
) : (
|
) : (
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>版本</th><th>安检</th><th>创建时间</th><th>操作</th></tr>
|
<tr><th>版本</th><th>安检</th><th>创建时间</th><th>操作</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{versions.map((v: any) => (
|
{versions.map((v: any) => (
|
||||||
<tr key={v.id}>
|
<tr key={v.id}>
|
||||||
<td style={{ fontFamily: 'var(--font-mono)' }}>v{v.version}</td>
|
<td style={{ fontFamily: 'var(--font-mono)' }}>v{v.version}</td>
|
||||||
<td><SecurityBadge scan={v.security_scan} /></td>
|
<td><SecurityBadge scan={v.security_scan} /></td>
|
||||||
<td style={{ fontSize: 'var(--text-xs)' }}>{formatDate(v.created_at)}</td>
|
<td style={{ fontSize: 'var(--text-xs)' }}>{formatDate(v.created_at)}</td>
|
||||||
<td>
|
<td>
|
||||||
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => handleRollback(versionsApp.id, v.id)}>
|
<button className="admin-btn admin-btn-outline admin-btn-sm" onClick={() => handleRollback(versionsApp.id, v.id)}>
|
||||||
回滚到此版本
|
回滚到此版本
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
<div className="admin-form-actions" style={{ marginTop: 'var(--space-2xl)' }}>
|
<div className="admin-form-actions" style={{ marginTop: 'var(--space-2xl)' }}>
|
||||||
<button className="admin-btn admin-btn-outline" onClick={() => setVersionsApp(null)}>关闭</button>
|
<button className="admin-btn admin-btn-outline" onClick={() => setVersionsApp(null)}>关闭</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Market;
|
export default Market;
|
||||||
+548
-548
File diff suppressed because it is too large.
Load diff
@@ -1,379 +1,379 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { adminAPI } from '@/api';
|
import { adminAPI } from '@/api';
|
||||||
|
|
||||||
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
|
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
|
||||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
{children}
|
{children}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
const SiteSettings: React.FC = () => {
|
const SiteSettings: React.FC = () => {
|
||||||
const [brand, setBrand] = useState<Record<string, string>>({
|
const [brand, setBrand] = useState<Record<string, string>>({
|
||||||
logo: '', siteName: '', announcement: '', icpNumber: '', contactPhone: '',
|
logo: '', siteName: '', announcement: '', icpNumber: '', contactPhone: '',
|
||||||
});
|
});
|
||||||
const [mail, setMail] = useState({
|
const [mail, setMail] = useState({
|
||||||
smtp_host: '', smtp_port: 587, username: '', password: '', from_address: '', use_tls: true,
|
smtp_host: '', smtp_port: 587, username: '', password: '', from_address: '', use_tls: true,
|
||||||
});
|
});
|
||||||
const [savedMsg, setSavedMsg] = useState<string | null>(null);
|
const [savedMsg, setSavedMsg] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [testResult, setTestResult] = useState<string | null>(null);
|
const [testResult, setTestResult] = useState<string | null>(null);
|
||||||
const [showEmailTest, setShowEmailTest] = useState(false);
|
const [showEmailTest, setShowEmailTest] = useState(false);
|
||||||
const [emailTestTo, setEmailTestTo] = useState('');
|
const [emailTestTo, setEmailTestTo] = useState('');
|
||||||
const [emailTestSubject, setEmailTestSubject] = useState('');
|
const [emailTestSubject, setEmailTestSubject] = useState('');
|
||||||
const [emailTestBody, setEmailTestBody] = useState('');
|
const [emailTestBody, setEmailTestBody] = useState('');
|
||||||
const [emailGenerating, setEmailGenerating] = useState(false);
|
const [emailGenerating, setEmailGenerating] = useState(false);
|
||||||
|
|
||||||
// AI生成测试邮件内容
|
// AI生成测试邮件内容
|
||||||
const handleAIGenerateContent = async () => {
|
const handleAIGenerateContent = async () => {
|
||||||
setEmailGenerating(true);
|
setEmailGenerating(true);
|
||||||
try {
|
try {
|
||||||
const res = await adminAPI.generateEmailContent('测试邮件');
|
const res = await adminAPI.generateEmailContent('测试邮件');
|
||||||
const data = (res as any).data || res;
|
const data = (res as any).data || res;
|
||||||
setEmailTestSubject(data.subject || '');
|
setEmailTestSubject(data.subject || '');
|
||||||
setEmailTestBody(data.body || '');
|
setEmailTestBody(data.body || '');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// 降级:使用客户端预设内容
|
// 降级:使用客户端预设内容
|
||||||
const subjects = [
|
const subjects = [
|
||||||
'【测试】AIFlow邮件服务配置验证',
|
'【测试】AIFlow邮件服务配置验证',
|
||||||
'AIFlow平台 - 邮件投递测试',
|
'AIFlow平台 - 邮件投递测试',
|
||||||
'测试邮件:您的SMTP服务已就绪',
|
'测试邮件:您的SMTP服务已就绪',
|
||||||
];
|
];
|
||||||
const bodies = [
|
const bodies = [
|
||||||
'您好!\n\n这是一封来自 AIFlow 智能自动化平台的测试邮件。\n\n如果您收到此邮件,说明SMTP邮件服务已配置成功。\n\n此致\nAIFlow 平台团队',
|
'您好!\n\n这是一封来自 AIFlow 智能自动化平台的测试邮件。\n\n如果您收到此邮件,说明SMTP邮件服务已配置成功。\n\n此致\nAIFlow 平台团队',
|
||||||
'Hi,\n\nThis is a test email from AIFlow Platform.\n\nIf you received this, the SMTP service works fine.\n\nBest regards,\nAIFlow Team',
|
'Hi,\n\nThis is a test email from AIFlow Platform.\n\nIf you received this, the SMTP service works fine.\n\nBest regards,\nAIFlow Team',
|
||||||
'【系统通知】\n邮件服务连通性测试通过。\n\n发件服务器配置正确。\n\n—— AIFlow',
|
'【系统通知】\n邮件服务连通性测试通过。\n\n发件服务器配置正确。\n\n—— AIFlow',
|
||||||
];
|
];
|
||||||
setEmailTestSubject(subjects[Math.floor(Math.random() * subjects.length)]);
|
setEmailTestSubject(subjects[Math.floor(Math.random() * subjects.length)]);
|
||||||
setEmailTestBody(bodies[Math.floor(Math.random() * bodies.length)]);
|
setEmailTestBody(bodies[Math.floor(Math.random() * bodies.length)]);
|
||||||
} finally {
|
} finally {
|
||||||
setEmailGenerating(false);
|
setEmailGenerating(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 加载真实配置
|
// 加载真实配置
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function loadConfig() {
|
async function loadConfig() {
|
||||||
try {
|
try {
|
||||||
const [siteRes, emailRes, smsRes] = await Promise.all([
|
const [siteRes, emailRes, smsRes] = await Promise.all([
|
||||||
adminAPI.getSiteSettings(),
|
adminAPI.getSiteSettings(),
|
||||||
adminAPI.getEmailConfig(),
|
adminAPI.getEmailConfig(),
|
||||||
adminAPI.getSmsConfig(),
|
adminAPI.getSmsConfig(),
|
||||||
]);
|
]);
|
||||||
if (siteRes?.data) {
|
if (siteRes?.data) {
|
||||||
setBrand({
|
setBrand({
|
||||||
logo: siteRes.data.logo || '',
|
logo: siteRes.data.logo || '',
|
||||||
siteName: siteRes.data.site_name || siteRes.data.siteName || '',
|
siteName: siteRes.data.site_name || siteRes.data.siteName || '',
|
||||||
announcement: siteRes.data.announcement || '',
|
announcement: siteRes.data.announcement || '',
|
||||||
icpNumber: siteRes.data.icp_number || siteRes.data.icpNumber || '',
|
icpNumber: siteRes.data.icp_number || siteRes.data.icpNumber || '',
|
||||||
contactPhone: siteRes.data.contact_phone || siteRes.data.contactPhone || '',
|
contactPhone: siteRes.data.contact_phone || siteRes.data.contactPhone || '',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (emailRes?.data) {
|
if (emailRes?.data) {
|
||||||
setMail({
|
setMail({
|
||||||
smtp_host: emailRes.data.smtp_host || '',
|
smtp_host: emailRes.data.smtp_host || '',
|
||||||
smtp_port: emailRes.data.smtp_port || 587,
|
smtp_port: emailRes.data.smtp_port || 587,
|
||||||
username: emailRes.data.username || '',
|
username: emailRes.data.username || '',
|
||||||
password: emailRes.data.password || '',
|
password: emailRes.data.password || '',
|
||||||
from_address: emailRes.data.from_address || '',
|
from_address: emailRes.data.from_address || '',
|
||||||
use_tls: emailRes.data.use_tls !== false,
|
use_tls: emailRes.data.use_tls !== false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (smsRes?.data) {
|
if (smsRes?.data) {
|
||||||
setSms({
|
setSms({
|
||||||
provider: smsRes.data.provider || '',
|
provider: smsRes.data.provider || '',
|
||||||
api_key: smsRes.data.api_key || '',
|
api_key: smsRes.data.api_key || '',
|
||||||
api_secret: smsRes.data.api_secret || '',
|
api_secret: smsRes.data.api_secret || '',
|
||||||
sign_name: smsRes.data.sign_name || '',
|
sign_name: smsRes.data.sign_name || '',
|
||||||
template_code: smsRes.data.template_code || '',
|
template_code: smsRes.data.template_code || '',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('加载配置失败:', e);
|
console.error('加载配置失败:', e);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loadConfig();
|
loadConfig();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const showSaved = (block: string) => {
|
const showSaved = (block: string) => {
|
||||||
setSavedMsg(block + ' 保存成功');
|
setSavedMsg(block + ' 保存成功');
|
||||||
setTimeout(() => setSavedMsg(null), 2000);
|
setTimeout(() => setSavedMsg(null), 2000);
|
||||||
};
|
};
|
||||||
|
|
||||||
const showTestResult = (result: string) => {
|
const showTestResult = (result: string) => {
|
||||||
setTestResult(result);
|
setTestResult(result);
|
||||||
setTimeout(() => setTestResult(null), 5000);
|
setTimeout(() => setTestResult(null), 5000);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 保存品牌设置
|
// 保存品牌设置
|
||||||
const saveSiteSettings = async () => {
|
const saveSiteSettings = async () => {
|
||||||
try {
|
try {
|
||||||
await adminAPI.updateSiteSettings({
|
await adminAPI.updateSiteSettings({
|
||||||
logo: brand.logo,
|
logo: brand.logo,
|
||||||
site_name: brand.siteName,
|
site_name: brand.siteName,
|
||||||
announcement: brand.announcement,
|
announcement: brand.announcement,
|
||||||
icp_number: brand.icpNumber,
|
icp_number: brand.icpNumber,
|
||||||
contact_phone: brand.contactPhone,
|
contact_phone: brand.contactPhone,
|
||||||
});
|
});
|
||||||
showSaved('品牌设置');
|
showSaved('品牌设置');
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert('保存失败: ' + (e.detail || e.message));
|
alert('保存失败: ' + (e.detail || e.message));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 保存邮件配置
|
// 保存邮件配置
|
||||||
const saveEmailConfig = async () => {
|
const saveEmailConfig = async () => {
|
||||||
try {
|
try {
|
||||||
await adminAPI.updateEmailConfig({
|
await adminAPI.updateEmailConfig({
|
||||||
smtp_host: mail.smtp_host,
|
smtp_host: mail.smtp_host,
|
||||||
smtp_port: mail.smtp_port,
|
smtp_port: mail.smtp_port,
|
||||||
username: mail.username,
|
username: mail.username,
|
||||||
password: mail.password,
|
password: mail.password,
|
||||||
from_address: mail.from_address,
|
from_address: mail.from_address,
|
||||||
use_tls: mail.use_tls,
|
use_tls: mail.use_tls,
|
||||||
});
|
});
|
||||||
showSaved('邮件配置');
|
showSaved('邮件配置');
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert('保存失败: ' + (e.detail || e.message));
|
alert('保存失败: ' + (e.detail || e.message));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 保存短信配置
|
// 保存短信配置
|
||||||
// 发送测试邮件 - 先保存配置再发送
|
// 发送测试邮件 - 先保存配置再发送
|
||||||
const sendTestEmail = async () => {
|
const sendTestEmail = async () => {
|
||||||
if (!emailTestTo.trim()) {
|
if (!emailTestTo.trim()) {
|
||||||
showTestResult('请输入收件邮箱地址');
|
showTestResult('请输入收件邮箱地址');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
// 测试前先保存邮件配置到数据库,确保使用最新配置
|
// 测试前先保存邮件配置到数据库,确保使用最新配置
|
||||||
await adminAPI.updateEmailConfig({
|
await adminAPI.updateEmailConfig({
|
||||||
smtp_host: mail.smtp_host,
|
smtp_host: mail.smtp_host,
|
||||||
smtp_port: mail.smtp_port,
|
smtp_port: mail.smtp_port,
|
||||||
username: mail.username,
|
username: mail.username,
|
||||||
password: mail.password,
|
password: mail.password,
|
||||||
from_address: mail.from_address,
|
from_address: mail.from_address,
|
||||||
use_tls: mail.use_tls,
|
use_tls: mail.use_tls,
|
||||||
});
|
});
|
||||||
const res = await adminAPI.testEmail({
|
const res = await adminAPI.testEmail({
|
||||||
test_to: emailTestTo.trim(),
|
test_to: emailTestTo.trim(),
|
||||||
test_subject: emailTestSubject || undefined,
|
test_subject: emailTestSubject || undefined,
|
||||||
test_body: emailTestBody || undefined,
|
test_body: emailTestBody || undefined,
|
||||||
});
|
});
|
||||||
showTestResult('测试邮件已发送至 ' + emailTestTo + ': ' + ((res as any)?.message || 'OK'));
|
showTestResult('测试邮件已发送至 ' + emailTestTo + ': ' + ((res as any)?.message || 'OK'));
|
||||||
setShowEmailTest(false);
|
setShowEmailTest(false);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
showTestResult('测试邮件发送失败: ' + (e.detail || e.message));
|
showTestResult('测试邮件发送失败: ' + (e.detail || e.message));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openEmailTest = () => {
|
const openEmailTest = () => {
|
||||||
setEmailTestTo('');
|
setEmailTestTo('');
|
||||||
setEmailTestSubject('');
|
setEmailTestSubject('');
|
||||||
setEmailTestBody('');
|
setEmailTestBody('');
|
||||||
setShowEmailTest(true);
|
setShowEmailTest(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return <div style={{ padding: 40, textAlign: 'center' }}>加载中...</div>;
|
return <div style={{ padding: 40, textAlign: 'center' }}>加载中...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
<div style={{ animation: 'fadeIn var(--transition-normal)' }}>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--space-2xl)' }}>
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--space-2xl)' }}>
|
||||||
<h1 className="admin-page-title" style={{ marginBottom: 0 }}>网站基础设置</h1>
|
<h1 className="admin-page-title" style={{ marginBottom: 0 }}>网站基础设置</h1>
|
||||||
{savedMsg && (
|
{savedMsg && (
|
||||||
<span className="admin-badge badge-success" style={{ padding: '6px 14px', fontSize: 'var(--text-sm)' }}>
|
<span className="admin-badge badge-success" style={{ padding: '6px 14px', fontSize: 'var(--text-sm)' }}>
|
||||||
<SVGIcon><polyline points="20 6 9 17 4 12"/></SVGIcon>
|
<SVGIcon><polyline points="20 6 9 17 4 12"/></SVGIcon>
|
||||||
{' '}{savedMsg}
|
{' '}{savedMsg}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Brand Settings */}
|
{/* Brand Settings */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">
|
<h3 className="admin-card-title">
|
||||||
<SVGIcon size={18}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></SVGIcon>
|
<SVGIcon size={18}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></SVGIcon>
|
||||||
{' '}品牌设置
|
{' '}品牌设置
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-row">
|
<div className="admin-form-row">
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">LOGO URL</label>
|
<label className="admin-form-label">LOGO URL</label>
|
||||||
<input className="admin-form-input" value={brand.logo} onChange={e => setBrand({ ...brand, logo: e.target.value })} />
|
<input className="admin-form-input" value={brand.logo} onChange={e => setBrand({ ...brand, logo: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">网站名称</label>
|
<label className="admin-form-label">网站名称</label>
|
||||||
<input className="admin-form-input" value={brand.siteName} onChange={e => setBrand({ ...brand, siteName: e.target.value })} />
|
<input className="admin-form-input" value={brand.siteName} onChange={e => setBrand({ ...brand, siteName: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">首页公告</label>
|
<label className="admin-form-label">首页公告</label>
|
||||||
<textarea
|
<textarea
|
||||||
className="admin-form-input admin-form-textarea"
|
className="admin-form-input admin-form-textarea"
|
||||||
value={brand.announcement}
|
value={brand.announcement}
|
||||||
onChange={e => setBrand({ ...brand, announcement: e.target.value })}
|
onChange={e => setBrand({ ...brand, announcement: e.target.value })}
|
||||||
style={{ minHeight: 60 }}
|
style={{ minHeight: 60 }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-row">
|
<div className="admin-form-row">
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">备案号</label>
|
<label className="admin-form-label">备案号</label>
|
||||||
<input className="admin-form-input" value={brand.icpNumber} onChange={e => setBrand({ ...brand, icpNumber: e.target.value })} />
|
<input className="admin-form-input" value={brand.icpNumber} onChange={e => setBrand({ ...brand, icpNumber: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">客服联系方式</label>
|
<label className="admin-form-label">客服联系方式</label>
|
||||||
<input className="admin-form-input" value={brand.contactPhone} onChange={e => setBrand({ ...brand, contactPhone: e.target.value })} />
|
<input className="admin-form-input" value={brand.contactPhone} onChange={e => setBrand({ ...brand, contactPhone: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-actions">
|
<div className="admin-form-actions">
|
||||||
<button className="admin-btn admin-btn-primary" onClick={saveSiteSettings}>
|
<button className="admin-btn admin-btn-primary" onClick={saveSiteSettings}>
|
||||||
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></SVGIcon>
|
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></SVGIcon>
|
||||||
保存设置
|
保存设置
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mail Config */}
|
{/* Mail Config */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<div className="admin-card-header">
|
<div className="admin-card-header">
|
||||||
<h3 className="admin-card-title">
|
<h3 className="admin-card-title">
|
||||||
<SVGIcon size={18}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></SVGIcon>
|
<SVGIcon size={18}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></SVGIcon>
|
||||||
{' '}邮件配置
|
{' '}邮件配置
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-row">
|
<div className="admin-form-row">
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">SMTP服务器</label>
|
<label className="admin-form-label">SMTP服务器</label>
|
||||||
<input className="admin-form-input" value={mail.smtp_host} onChange={e => setMail({ ...mail, smtp_host: e.target.value })} />
|
<input className="admin-form-input" value={mail.smtp_host} onChange={e => setMail({ ...mail, smtp_host: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">端口</label>
|
<label className="admin-form-label">端口</label>
|
||||||
<input className="admin-form-input" type="number" value={mail.smtp_port} onChange={e => setMail({ ...mail, smtp_port: Number(e.target.value) })} />
|
<input className="admin-form-input" type="number" value={mail.smtp_port} onChange={e => setMail({ ...mail, smtp_port: Number(e.target.value) })} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-row">
|
<div className="admin-form-row">
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">用户名</label>
|
<label className="admin-form-label">用户名</label>
|
||||||
<input className="admin-form-input" value={mail.username} onChange={e => setMail({ ...mail, username: e.target.value })} />
|
<input className="admin-form-input" value={mail.username} onChange={e => setMail({ ...mail, username: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">密码</label>
|
<label className="admin-form-label">密码</label>
|
||||||
<input className="admin-form-input" type="password" value={mail.password} onChange={e => setMail({ ...mail, password: e.target.value })} />
|
<input className="admin-form-input" type="password" value={mail.password} onChange={e => setMail({ ...mail, password: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-group" style={{ maxWidth: '50%' }}>
|
<div className="admin-form-group" style={{ maxWidth: '50%' }}>
|
||||||
<label className="admin-form-label">发件地址</label>
|
<label className="admin-form-label">发件地址</label>
|
||||||
<input className="admin-form-input" value={mail.from_address} onChange={e => setMail({ ...mail, from_address: e.target.value })} />
|
<input className="admin-form-input" value={mail.from_address} onChange={e => setMail({ ...mail, from_address: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-form-actions">
|
<div className="admin-form-actions">
|
||||||
<button className="admin-btn admin-btn-primary" onClick={saveEmailConfig}>
|
<button className="admin-btn admin-btn-primary" onClick={saveEmailConfig}>
|
||||||
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></SVGIcon>
|
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></SVGIcon>
|
||||||
保存设置
|
保存设置
|
||||||
</button>
|
</button>
|
||||||
<button className="admin-btn admin-btn-outline" onClick={openEmailTest}>
|
<button className="admin-btn admin-btn-outline" onClick={openEmailTest}>
|
||||||
<SVGIcon><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></SVGIcon>
|
<SVGIcon><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></SVGIcon>
|
||||||
发送测试邮件
|
发送测试邮件
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* SMS Config */}
|
{/* SMS Config */}
|
||||||
{/* Email Test Modal */}
|
{/* Email Test Modal */}
|
||||||
{showEmailTest && (
|
{showEmailTest && (
|
||||||
<div style={{
|
<div style={{
|
||||||
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
|
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
|
||||||
background: 'rgba(0,0,0,0.4)', zIndex: 'var(--z-modal)',
|
background: 'rgba(0,0,0,0.4)', zIndex: 'var(--z-modal)',
|
||||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||||
}} onClick={() => setShowEmailTest(false)}>
|
}} onClick={() => setShowEmailTest(false)}>
|
||||||
<div style={{
|
<div style={{
|
||||||
background: '#fff', borderRadius: 'var(--radius-2xl)', width: 520, maxHeight: '90vh', overflow: 'auto',
|
background: '#fff', borderRadius: 'var(--radius-2xl)', width: 520, maxHeight: '90vh', overflow: 'auto',
|
||||||
padding: 'var(--space-3xl)', boxShadow: 'var(--shadow-xl)',
|
padding: 'var(--space-3xl)', boxShadow: 'var(--shadow-xl)',
|
||||||
}} onClick={e => e.stopPropagation()}>
|
}} onClick={e => e.stopPropagation()}>
|
||||||
<h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 700, marginBottom: 'var(--space-2xl)' }}>
|
<h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 700, marginBottom: 'var(--space-2xl)' }}>
|
||||||
<SVGIcon size={20}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></SVGIcon>
|
<SVGIcon size={20}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></SVGIcon>
|
||||||
{' '}发送测试邮件
|
{' '}发送测试邮件
|
||||||
</h3>
|
</h3>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">收件邮箱 <span style={{ color: 'var(--color-error)' }}>*</span></label>
|
<label className="admin-form-label">收件邮箱 <span style={{ color: 'var(--color-error)' }}>*</span></label>
|
||||||
<input
|
<input
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
type="email"
|
type="email"
|
||||||
value={emailTestTo}
|
value={emailTestTo}
|
||||||
onChange={e => setEmailTestTo(e.target.value)}
|
onChange={e => setEmailTestTo(e.target.value)}
|
||||||
placeholder="例如: admin@example.com"
|
placeholder="例如: admin@example.com"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">邮件主题</label>
|
<label className="admin-form-label">邮件主题</label>
|
||||||
<input
|
<input
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
value={emailTestSubject}
|
value={emailTestSubject}
|
||||||
onChange={e => setEmailTestSubject(e.target.value)}
|
onChange={e => setEmailTestSubject(e.target.value)}
|
||||||
placeholder="测试邮件标题"
|
placeholder="测试邮件标题"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">邮件内容</label>
|
<label className="admin-form-label">邮件内容</label>
|
||||||
<textarea
|
<textarea
|
||||||
className="admin-form-input admin-form-textarea"
|
className="admin-form-input admin-form-textarea"
|
||||||
value={emailTestBody}
|
value={emailTestBody}
|
||||||
onChange={e => setEmailTestBody(e.target.value)}
|
onChange={e => setEmailTestBody(e.target.value)}
|
||||||
style={{ minHeight: 120 }}
|
style={{ minHeight: 120 }}
|
||||||
placeholder="测试邮件内容..."
|
placeholder="测试邮件内容..."
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ display: 'flex', gap: 'var(--space-sm)', justifyContent: 'space-between', marginBottom: 'var(--space-lg)' }}>
|
<div style={{ display: 'flex', gap: 'var(--space-sm)', justifyContent: 'space-between', marginBottom: 'var(--space-lg)' }}>
|
||||||
<button
|
<button
|
||||||
className="admin-btn admin-btn-outline admin-btn-sm"
|
className="admin-btn admin-btn-outline admin-btn-sm"
|
||||||
onClick={handleAIGenerateContent}
|
onClick={handleAIGenerateContent}
|
||||||
disabled={emailGenerating}
|
disabled={emailGenerating}
|
||||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
|
style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
|
||||||
>
|
>
|
||||||
<SVGIcon size={12}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon>
|
<SVGIcon size={12}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></SVGIcon>
|
||||||
{emailGenerating ? '生成中...' : 'AI生成测试内容'}
|
{emailGenerating ? '生成中...' : 'AI生成测试内容'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-form-actions">
|
<div className="admin-form-actions">
|
||||||
<button
|
<button
|
||||||
className="admin-btn admin-btn-primary"
|
className="admin-btn admin-btn-primary"
|
||||||
onClick={sendTestEmail}
|
onClick={sendTestEmail}
|
||||||
disabled={!emailTestTo.trim()}
|
disabled={!emailTestTo.trim()}
|
||||||
>
|
>
|
||||||
<SVGIcon><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></SVGIcon>
|
<SVGIcon><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></SVGIcon>
|
||||||
发送测试邮件
|
发送测试邮件
|
||||||
</button>
|
</button>
|
||||||
<button className="admin-btn admin-btn-outline" onClick={() => setShowEmailTest(false)}>
|
<button className="admin-btn admin-btn-outline" onClick={() => setShowEmailTest(false)}>
|
||||||
取消
|
取消
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Test Result Toast */}
|
{/* Test Result Toast */}
|
||||||
{testResult && (
|
{testResult && (
|
||||||
<div style={{
|
<div style={{
|
||||||
position: 'fixed', bottom: 24, right: 24, padding: '12px 20px',
|
position: 'fixed', bottom: 24, right: 24, padding: '12px 20px',
|
||||||
background: testResult.includes('失败') ? 'var(--color-error)' : 'var(--color-success)',
|
background: testResult.includes('失败') ? 'var(--color-error)' : 'var(--color-success)',
|
||||||
color: '#fff', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
color: '#fff', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||||
zIndex: 9999, fontSize: 'var(--text-sm)',
|
zIndex: 9999, fontSize: 'var(--text-sm)',
|
||||||
}}>
|
}}>
|
||||||
{testResult}
|
{testResult}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default SiteSettings;
|
export default SiteSettings;
|
||||||
@@ -52,16 +52,22 @@ const STATE_CONFIG: Record<SkillState, { label: string; color: string; bg: strin
|
|||||||
frozen: { label: '已冻结', color: '#EF4444', bg: '#FEE2E2' },
|
frozen: { label: '已冻结', color: '#EF4444', bg: '#FEE2E2' },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 业务场景分类:与前端「应用市场」保持一致的 14 类标准(前台分类为准)
|
||||||
const CATEGORIES = [
|
const CATEGORIES = [
|
||||||
{ id: 'writing', label: '文字创作' },
|
{ id: 'design', label: '🎨 做设计' },
|
||||||
{ id: 'coding', label: '代码能力' },
|
{ id: 'frontend', label: '💻 写前端' },
|
||||||
{ id: 'data_analysis', label: '数据分析' },
|
{ id: 'mobile', label: '📱 做移动端' },
|
||||||
{ id: 'qa', label: '知识问答' },
|
{ id: 'backend', label: '🧪 后端/全栈' },
|
||||||
{ id: 'automation', label: '流程自动化' },
|
{ id: 'qa', label: '🧪 测试质量' },
|
||||||
{ id: 'creativity', label: '创意生成' },
|
{ id: 'search', label: '🔍 搜索信息' },
|
||||||
{ id: 'communication', label: '沟通协作' },
|
{ id: 'docs', label: '✍️ 写文档' },
|
||||||
{ id: 'reasoning', label: '逻辑推理' },
|
{ id: 'marketing', label: '📢 推广获客' },
|
||||||
{ id: 'other', label: '其他' },
|
{ id: 'workflow', label: '🔄 工作流' },
|
||||||
|
{ id: 'secops', label: '🛡️ 安全运维' },
|
||||||
|
{ id: 'learning', label: '🎓 学习教学' },
|
||||||
|
{ id: 'video', label: '🎬 视频多媒体' },
|
||||||
|
{ id: 'collab', label: '🏢 办公协作' },
|
||||||
|
{ id: 'ai', label: '🛠️ AI能力' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const PAGE_SIZE = 15;
|
const PAGE_SIZE = 15;
|
||||||
@@ -398,6 +404,7 @@ const Skills: React.FC = () => {
|
|||||||
<th>技能名称</th>
|
<th>技能名称</th>
|
||||||
<th>状态</th>
|
<th>状态</th>
|
||||||
<th>分类</th>
|
<th>分类</th>
|
||||||
|
<th>标签</th>
|
||||||
<th>所有者</th>
|
<th>所有者</th>
|
||||||
<th>版本</th>
|
<th>版本</th>
|
||||||
<th>使用次数</th>
|
<th>使用次数</th>
|
||||||
@@ -408,9 +415,9 @@ const Skills: React.FC = () => {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<tr><td colSpan={9} style={{ textAlign: 'center', padding: 40, color: '#6B7280' }}>加载中...</td></tr>
|
<tr><td colSpan={10} style={{ textAlign: 'center', padding: 40, color: '#6B7280' }}>加载中...</td></tr>
|
||||||
) : skills.length === 0 ? (
|
) : skills.length === 0 ? (
|
||||||
<tr><td colSpan={9} style={{ textAlign: 'center', padding: 40, color: '#6B7280' }}>暂无技能</td></tr>
|
<tr><td colSpan={10} style={{ textAlign: 'center', padding: 40, color: '#6B7280' }}>暂无技能</td></tr>
|
||||||
) : skills.map(skill => {
|
) : skills.map(skill => {
|
||||||
const cfg = STATE_CONFIG[skill.state as SkillState] || STATE_CONFIG.baby;
|
const cfg = STATE_CONFIG[skill.state as SkillState] || STATE_CONFIG.baby;
|
||||||
const published = isPublished(skill);
|
const published = isPublished(skill);
|
||||||
@@ -441,6 +448,16 @@ const Skills: React.FC = () => {
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{skill.category_label || '-'}</td>
|
<td>{skill.category_label || '-'}</td>
|
||||||
|
<td>
|
||||||
|
{skill.tags && skill.tags.length > 0 ? (
|
||||||
|
<div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
|
||||||
|
{skill.tags.slice(0, 3).map(tag => (
|
||||||
|
<span key={tag} style={{ fontSize: 11, padding: '1px 6px', background: '#EEF2FF', color: '#6366F1', borderRadius: 4 }}>{tag}</span>
|
||||||
|
))}
|
||||||
|
{skill.tags.length > 3 && <span style={{ fontSize: 11, color: '#6B7280' }}>+{skill.tags.length - 3}</span>}
|
||||||
|
</div>
|
||||||
|
) : <span style={{ color: '#9CA3AF', fontSize: 12 }}>-</span>}
|
||||||
|
</td>
|
||||||
<td>{skill.owner_username || skill.user_id}</td>
|
<td>{skill.owner_username || skill.user_id}</td>
|
||||||
<td>v{skill.version}</td>
|
<td>v{skill.version}</td>
|
||||||
<td>{skill.use_count}</td>
|
<td>{skill.use_count}</td>
|
||||||
|
|||||||
+1786
-1554
File diff suppressed because it is too large.
Load diff
+1959
-1738
File diff suppressed because it is too large.
Load diff
@@ -1000,51 +1000,7 @@
|
|||||||
margin-bottom: var(--space-lg);
|
margin-bottom: var(--space-lg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.evo-anim-toggle {
|
/* 技能图谱动画已在 #717 中移除(边框光晕溢出且无实际用途) */
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-sm);
|
|
||||||
font-size: var(--text-xs);
|
|
||||||
color: var(--color-text-tertiary);
|
|
||||||
cursor: pointer;
|
|
||||||
user-select: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.evo-anim-toggle input {
|
|
||||||
width: 14px;
|
|
||||||
height: 14px;
|
|
||||||
accent-color: var(--color-accent);
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Baby sprout animation */
|
|
||||||
.evo-skill-node.baby.anim-on .evo-node-dot {
|
|
||||||
animation: baby-sprout 2s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
.evo-skill-node.baby.anim-on {
|
|
||||||
animation: baby-glow 2s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes baby-sprout {
|
|
||||||
0%, 100% { transform: scale(1); }
|
|
||||||
50% { transform: scale(1.15); }
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes baby-glow {
|
|
||||||
0%, 100% { box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.3); }
|
|
||||||
50% { box-shadow: 0 0 16px 4px rgba(245, 158, 11, 0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Staging breathe animation */
|
|
||||||
.evo-skill-node.staging.anim-on {
|
|
||||||
animation: staging-breathe 3s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes staging-breathe {
|
|
||||||
0%, 100% { transform: scale(1); opacity: 0.85; }
|
|
||||||
50% { transform: scale(1.06); opacity: 1; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Toast */
|
/* Toast */
|
||||||
.evo-toast {
|
.evo-toast {
|
||||||
@@ -1535,47 +1491,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ===== v2: Baby Sprout Animation (GAP-03) ===== */
|
/* ===== v2: 技能图谱动画已在 #717 中移除(边框溢出且无实际用途) ===== */
|
||||||
.evo-skill-node.state-baby.anim-on {
|
|
||||||
animation: baby-sprout 2s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes baby-sprout {
|
|
||||||
0%, 100% {
|
|
||||||
transform: scale(1);
|
|
||||||
box-shadow: 0 0 0 0 rgba(255, 182, 193, 0.4);
|
|
||||||
}
|
|
||||||
50% {
|
|
||||||
transform: scale(1.15);
|
|
||||||
box-shadow: 0 0 20px 4px rgba(255, 182, 193, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Baby skill sprout icon */
|
|
||||||
.evo-skill-node.state-baby.anim-on .evo-node-dot::after {
|
|
||||||
content: '🌱';
|
|
||||||
position: absolute;
|
|
||||||
top: -18px;
|
|
||||||
left: 50%;
|
|
||||||
transform: translateX(-50%);
|
|
||||||
font-size: 14px;
|
|
||||||
animation: sprout-wiggle 1.5s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes sprout-wiggle {
|
|
||||||
0%, 100% { transform: translateX(-50%) rotate(-5deg); }
|
|
||||||
50% { transform: translateX(-50%) rotate(5deg); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Staging breathe animation */
|
|
||||||
.evo-skill-node.state-staging.anim-on {
|
|
||||||
animation: staging-breathe 3s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes staging-breathe {
|
|
||||||
0%, 100% { transform: scale(1); opacity: 0.8; }
|
|
||||||
50% { transform: scale(1.08); opacity: 1; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== v2: Toast messages ===== */
|
/* ===== v2: Toast messages ===== */
|
||||||
.evo-toast {
|
.evo-toast {
|
||||||
|
|||||||
@@ -62,9 +62,7 @@ const shareThemes = [
|
|||||||
// ==================== Panel A: Skill Tree ====================
|
// ==================== Panel A: Skill Tree ====================
|
||||||
const SkillTreePanel: React.FC<{
|
const SkillTreePanel: React.FC<{
|
||||||
skills: EvolutionSkill[];
|
skills: EvolutionSkill[];
|
||||||
animEnabled: boolean;
|
}> = ({ skills }) => {
|
||||||
onToggleAnim: () => void;
|
|
||||||
}> = ({ skills, animEnabled, onToggleAnim }) => {
|
|
||||||
const [hoveredSkill, setHoveredSkill] = useState<string | null>(null);
|
const [hoveredSkill, setHoveredSkill] = useState<string | null>(null);
|
||||||
const [selectedSkill, setSelectedSkill] = useState<EvolutionSkill | null>(null);
|
const [selectedSkill, setSelectedSkill] = useState<EvolutionSkill | null>(null);
|
||||||
const [showVersionHistory, setShowVersionHistory] = useState(false);
|
const [showVersionHistory, setShowVersionHistory] = useState(false);
|
||||||
@@ -136,14 +134,6 @@ const SkillTreePanel: React.FC<{
|
|||||||
{/* Publish toast */}
|
{/* Publish toast */}
|
||||||
{publishMsg && <div className="evo-toast evo-toast-info">{publishMsg}</div>}
|
{publishMsg && <div className="evo-toast evo-toast-info">{publishMsg}</div>}
|
||||||
|
|
||||||
{/* Anim Toggle */}
|
|
||||||
<div className="evo-panel-toolbar">
|
|
||||||
<label className="evo-anim-toggle">
|
|
||||||
<input type="checkbox" checked={animEnabled} onChange={onToggleAnim} />
|
|
||||||
<span>动画效果</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Skill detail modal */}
|
{/* Skill detail modal */}
|
||||||
{selectedSkill && !showVersionHistory && (
|
{selectedSkill && !showVersionHistory && (
|
||||||
<div className="evo-skill-detail-modal" onClick={() => setSelectedSkill(null)}>
|
<div className="evo-skill-detail-modal" onClick={() => setSelectedSkill(null)}>
|
||||||
@@ -305,7 +295,7 @@ const SkillTreePanel: React.FC<{
|
|||||||
<React.Fragment key={skill.id}>
|
<React.Fragment key={skill.id}>
|
||||||
{idx > 0 && <div className="evo-node-connector" />}
|
{idx > 0 && <div className="evo-node-connector" />}
|
||||||
<div
|
<div
|
||||||
className={`evo-skill-node ${skill.state} ${isHovered ? 'hovered' : ''} ${animEnabled ? 'anim-on' : ''}`}
|
className={`evo-skill-node ${skill.state} ${isHovered ? 'hovered' : ''}`}
|
||||||
onMouseEnter={() => setHoveredSkill(skill.id)}
|
onMouseEnter={() => setHoveredSkill(skill.id)}
|
||||||
onMouseLeave={() => setHoveredSkill(null)}
|
onMouseLeave={() => setHoveredSkill(null)}
|
||||||
onClick={() => setSelectedSkill(skill)}
|
onClick={() => setSelectedSkill(skill)}
|
||||||
@@ -944,22 +934,10 @@ const EvolutionDashboard: React.FC = () => {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [globalSelectedSkill, setGlobalSelectedSkill] = useState<EvolutionSkill | null>(null);
|
const [globalSelectedSkill, setGlobalSelectedSkill] = useState<EvolutionSkill | null>(null);
|
||||||
const [animEnabled, setAnimEnabled] = useState(() => {
|
|
||||||
return localStorage.getItem('evo_anim_enabled') !== 'false';
|
|
||||||
});
|
|
||||||
|
|
||||||
const totalSkills = skills.length;
|
const totalSkills = skills.length;
|
||||||
const mainCount = skills.filter(s => s.state === 'main').length;
|
const mainCount = skills.filter(s => s.state === 'main').length;
|
||||||
const babyCount = skills.filter(s => s.state === 'baby').length;
|
const babyCount = skills.filter(s => s.state === 'baby').length;
|
||||||
|
|
||||||
const toggleAnim = useCallback(() => {
|
|
||||||
setAnimEnabled(prev => {
|
|
||||||
const next = !prev;
|
|
||||||
localStorage.setItem('evo_anim_enabled', String(next));
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleViewSkill = (skillName: string) => {
|
const handleViewSkill = (skillName: string) => {
|
||||||
const skill = skills.find(s => s.skill_name === skillName);
|
const skill = skills.find(s => s.skill_name === skillName);
|
||||||
if (skill) {
|
if (skill) {
|
||||||
@@ -1071,7 +1049,7 @@ const EvolutionDashboard: React.FC = () => {
|
|||||||
))}
|
))}
|
||||||
</aside>
|
</aside>
|
||||||
<main className="evo-main">
|
<main className="evo-main">
|
||||||
{activePanel === 'skill-tree' && <SkillTreePanel skills={skills} animEnabled={animEnabled} onToggleAnim={toggleAnim} />}
|
{activePanel === 'skill-tree' && <SkillTreePanel skills={skills} />}
|
||||||
{activePanel === 'timeline' && <TimelinePanel events={events} onViewSkill={handleViewSkill} />}
|
{activePanel === 'timeline' && <TimelinePanel events={events} onViewSkill={handleViewSkill} />}
|
||||||
{activePanel === 'statistics' && (stats ? <StatisticsPanel stats={stats} onViewSkill={handleViewSkill} /> : <div className="evo-panel-content"><p>加载中...</p></div>)}
|
{activePanel === 'statistics' && (stats ? <StatisticsPanel stats={stats} onViewSkill={handleViewSkill} /> : <div className="evo-panel-content"><p>加载中...</p></div>)}
|
||||||
{activePanel === 'profile' && (profile ? <ProfilePanel profile={profile} skills={skills} /> : <div className="evo-panel-content"><p>加载中...</p></div>)}
|
{activePanel === 'profile' && (profile ? <ProfilePanel profile={profile} skills={skills} /> : <div className="evo-panel-content"><p>加载中...</p></div>)}
|
||||||
|
|||||||
@@ -1805,3 +1805,23 @@
|
|||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
color: var(--color-text-tertiary);
|
color: var(--color-text-tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 官方内置技能徽标(见 #716:官方导入并发布的技能默认全局已安装) */
|
||||||
|
.modal-official-badge,
|
||||||
|
.market-card-official-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 4px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 18px;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--color-accent);
|
||||||
|
background: color-mix(in srgb, var(--color-accent) 12%, transparent);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--color-accent) 35%, transparent);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-official-badge {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
+2038
-2031
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,12 @@
|
|||||||
padding: var(--space-3xl) var(--space-4xl);
|
padding: var(--space-3xl) var(--space-4xl);
|
||||||
max-width: 1280px;
|
max-width: 1280px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
|
/* 见 #714:FrontLayout 的 .front-main 裁剪了主内容区,
|
||||||
|
此处让页面自身在可用高度内纵向滚动,避免内容被截断无法上下查阅 */
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
animation: fadeIn var(--transition-normal);
|
animation: fadeIn var(--transition-normal);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +335,8 @@
|
|||||||
|
|
||||||
.tkd-table-scroll {
|
.tkd-table-scroll {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
|
overflow-y: auto;
|
||||||
|
max-height: 60vh;
|
||||||
padding: var(--space-lg) var(--space-xl) var(--space-sm);
|
padding: var(--space-lg) var(--space-xl) var(--space-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ html {
|
|||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
-moz-osx-font-smoothing: grayscale;
|
-moz-osx-font-smoothing: grayscale;
|
||||||
text-rendering: optimizeLegibility;
|
text-rendering: optimizeLegibility;
|
||||||
|
overflow-x: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@@ -120,6 +121,7 @@ body {
|
|||||||
background: var(--color-bg-primary);
|
background: var(--color-bg-primary);
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
overflow-x: hidden;
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+556
-548
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,80 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { renderMarkdownToHtml } from './markdown';
|
||||||
|
|
||||||
|
// 前台聊天 Markdown 渲染曾两次被 bug 击穿:
|
||||||
|
// 1) 段落内单个 \n 被转成 <br/>,导致 AI 回复被强制大量换行、内容撑成多行;
|
||||||
|
// 2) 表格在加粗/链接转换之前被提取,单元格内 **xxx** 原样显示、且 <br> 未压缩。
|
||||||
|
// 本测试固化「渲染管线」契约,防止回归。管线代码见 ./markdown.ts(从 ChatPage 抽出)。
|
||||||
|
describe('renderMarkdownToHtml', () => {
|
||||||
|
it('段落内单个 \\n 转为空格(而非 <br/>)', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('第一行\n第二行');
|
||||||
|
expect(html).not.toContain('<br');
|
||||||
|
expect(html).toContain('第一行 第二行');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('双换行转为段落分隔', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('段一\n\n段二');
|
||||||
|
expect(html).toContain('段一</p><p class="md-p">段二');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('3+ 连续空行压缩为 2 个(与 2 个空行结果一致)', () => {
|
||||||
|
const many = renderMarkdownToHtml('a\n\n\n\n\nb').html;
|
||||||
|
const few = renderMarkdownToHtml('a\n\nb').html;
|
||||||
|
expect(many).toBe(few);
|
||||||
|
expect(many).toContain('a</p><p class="md-p">b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('表格在加粗之后提取,单元格内的 **xxx** 被渲染为 <strong>', () => {
|
||||||
|
const input = '| 能力 | 说明 |\n| --- | --- |\n| **渠道排序** | 按优先级 |\n';
|
||||||
|
const { html } = renderMarkdownToHtml(input);
|
||||||
|
expect(html).toContain('<table class="md-table">');
|
||||||
|
expect(html).toContain('<th');
|
||||||
|
expect(html).toContain('<td');
|
||||||
|
expect(html).toContain('<strong>渠道排序</strong>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('单元格内连续 <br> 被压缩为单个', () => {
|
||||||
|
const input = '| 列 |\n| --- |\n| a<br/><br/>b |\n';
|
||||||
|
const { html } = renderMarkdownToHtml(input);
|
||||||
|
expect(html).toContain('a<br/>b');
|
||||||
|
expect(html).not.toContain('<br/><br/>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无序列表渲染为 <ul><li>', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('- a\n- b');
|
||||||
|
expect(html).toContain('<ul class="md-ul">');
|
||||||
|
expect(html).toContain('<li class="md-li">a</li>');
|
||||||
|
expect(html).toContain('<li class="md-li">b</li>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('一级标题渲染为 h2', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('# Title');
|
||||||
|
expect(html).toContain('<h2 class="md-h2">Title</h2>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('代码块内容不被行内加粗转换', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('```\n**not bold**\n```');
|
||||||
|
expect(html).toContain('<pre class="md-code-block">');
|
||||||
|
expect(html).not.toContain('<strong>not bold</strong>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('行内代码被抽取保护', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('use `npm run` here');
|
||||||
|
expect(html).toContain('<code class="md-inline-code">npm run</code>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('[文本](url) 链接渲染', () => {
|
||||||
|
const { html } = renderMarkdownToHtml('[Google](https://g.com)');
|
||||||
|
expect(html).toContain('<a class="md-link" href="https://g.com"');
|
||||||
|
expect(html).toContain('Google');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('媒体(<img>)以占位符保留并返回结构化 media 列表', () => {
|
||||||
|
const { html, media } = renderMarkdownToHtml('看这张图 <img src="https://x.com/a.png" alt="图">');
|
||||||
|
expect(media.length).toBe(1);
|
||||||
|
expect(media[0].type).toBe('img');
|
||||||
|
expect(media[0].src).toBe('https://x.com/a.png');
|
||||||
|
expect(media[0].alt).toBe('图');
|
||||||
|
expect(html).toContain('\x00MEDIA0\x00');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import katex from 'katex';
|
||||||
|
import hljs from 'highlight.js';
|
||||||
|
|
||||||
|
export interface MediaInfo {
|
||||||
|
type: 'img' | 'video';
|
||||||
|
src: string;
|
||||||
|
alt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RenderResult {
|
||||||
|
html: string;
|
||||||
|
media: MediaInfo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(text: string): string {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 Markdown 文本转为带占位符的 HTML 字符串。
|
||||||
|
*
|
||||||
|
* 设计契约(曾被线上 bug 击穿、用单测固化,见 markdown.test.ts):
|
||||||
|
* - 段落内【单个 \n 转为空格】而非 <br/>,避免 AI 回复被强制大量换行;
|
||||||
|
* - 【3+ 连续空行压缩为 2 个】(/\n{3,}/ -> \n\n),避免多余空白把内容撑成多行;
|
||||||
|
* - 【表格在加粗/链接转换之后提取】,单元格内的 **xxx** / [文本](url) 才能被渲染;
|
||||||
|
* 且单元格内连续 <br> 被压缩为单个(normalizeCell)。
|
||||||
|
*
|
||||||
|
* 媒体(<img>/<video>)以 \x00MEDIA<n>\x00 占位符保留在返回的 html 中,
|
||||||
|
* 由调用方(ChatPage 的 MarkdownContent)切分后渲染为 React 组件。
|
||||||
|
*/
|
||||||
|
export function renderMarkdownToHtml(content: string): RenderResult {
|
||||||
|
let text = content;
|
||||||
|
|
||||||
|
// 1. Extract code blocks first (protect from other replacements)
|
||||||
|
const codeBlocks: string[] = [];
|
||||||
|
const mermaidBlocks: string[] = [];
|
||||||
|
text = text.replace(/```(\w*)\n?([\s\S]*?)```/g, (_m: string, _lang: string, code: string) => {
|
||||||
|
if (_lang === 'mermaid') {
|
||||||
|
const idx = mermaidBlocks.length;
|
||||||
|
mermaidBlocks.push('<div class="md-mermaid" data-code="' + escapeHtml(code.trim()) + '"></div>');
|
||||||
|
return '\x00MERMAID' + idx + '\x00';
|
||||||
|
}
|
||||||
|
const idx = codeBlocks.length;
|
||||||
|
codeBlocks.push('<pre class="md-code-block"><code class="md-code">' + escapeHtml(code.trim()) + '</code></pre>');
|
||||||
|
return '\x00CODEBLOCK' + idx + '\x00';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Extract inline code
|
||||||
|
const inlineCodes: string[] = [];
|
||||||
|
text = text.replace(/`([^`]+)`/g, (_m: string, code: string) => {
|
||||||
|
const idx = inlineCodes.length;
|
||||||
|
inlineCodes.push('<code class="md-inline-code">' + escapeHtml(code) + '</code>');
|
||||||
|
return '\x00INLINE' + idx + '\x00';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2.5 Extract media blocks (<img>/<video>) -> 结构化,后续渲染为 React 组件
|
||||||
|
const mediaBlocks: MediaInfo[] = [];
|
||||||
|
text = text.replace(/<(img|video)([^>]*?)\/?>/gi, (_m: string, tag: string, attrs: string) => {
|
||||||
|
const type = tag.toLowerCase() === 'img' ? 'img' : 'video';
|
||||||
|
const srcM = attrs.match(/src=["']([^"']+)["']/i);
|
||||||
|
const altM = attrs.match(/alt=["']([^"']*)["']/i);
|
||||||
|
mediaBlocks.push({ type, src: srcM ? srcM[1] : '', alt: altM ? altM[1] : '' });
|
||||||
|
return '\x00MEDIA' + (mediaBlocks.length - 1) + '\x00';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2.6 Normalize excessive blank lines in prose (code blocks already extracted)
|
||||||
|
text = text.replace(/\n{3,}/g, '\n\n').trim();
|
||||||
|
|
||||||
|
// 2.8 LaTeX 数学公式:$$...$$(块级)和 $...$(行内)
|
||||||
|
const mathBlocks: string[] = [];
|
||||||
|
text = text.replace(/\$\$([\s\S]+?)\$\$/g, (_m: string, formula: string) => {
|
||||||
|
try {
|
||||||
|
const rendered = katex.renderToString(formula.trim(), { displayMode: true, throwOnError: false });
|
||||||
|
const idx = mathBlocks.length;
|
||||||
|
mathBlocks.push(`<div class="md-math-block">${rendered}</div>`);
|
||||||
|
return '\x00MATHBLOCK' + idx + '\x00';
|
||||||
|
} catch { return _m; }
|
||||||
|
});
|
||||||
|
text = text.replace(/\$([^\s$][^$]*[^\s$])\$/g, (_m: string, formula: string) => {
|
||||||
|
try {
|
||||||
|
const rendered = katex.renderToString(formula.trim(), { displayMode: false, throwOnError: false });
|
||||||
|
const idx = mathBlocks.length;
|
||||||
|
mathBlocks.push(`<span class="md-math-inline">${rendered}</span>`);
|
||||||
|
return '\x00MATHBLOCK' + idx + '\x00';
|
||||||
|
} catch { return _m; }
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2.9 Strikethrough: ~~text~~ -> <del>text</del>
|
||||||
|
text = text.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||||||
|
|
||||||
|
// 2.10 Auto-link bare URLs: http(s)://... -> <a>
|
||||||
|
text = text.replace(/(?<![="'>])https?:\/\/[^\s<>[\]()]+/g, (url: string) =>
|
||||||
|
`<a class="md-link" href="${url}" target="_blank" rel="noopener">${url}</a>`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. Headers
|
||||||
|
text = text.replace(/^#### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||||
|
text = text.replace(/^### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||||
|
text = text.replace(/^## (.+)$/gm, '<h3 class="md-h3">$1</h3>');
|
||||||
|
text = text.replace(/^# (.+)$/gm, '<h2 class="md-h2">$1</h2>');
|
||||||
|
|
||||||
|
// 4. Horizontal rule
|
||||||
|
text = text.replace(/^---+$/gm, '<hr class="md-hr">');
|
||||||
|
|
||||||
|
// 5. Blockquotes
|
||||||
|
text = text.replace(/^> (.+)$/gm, '<blockquote class="md-blockquote">$1</blockquote>');
|
||||||
|
|
||||||
|
// 6. Links [text](url)
|
||||||
|
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a class="md-link" href="$2" target="_blank" rel="noopener">$1</a>');
|
||||||
|
|
||||||
|
// 7. Bold and italic
|
||||||
|
text = text.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||||
|
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||||
|
text = text.replace(/(?<!\w)\*(?!\*)(.+?)(?<!\*)\*(?!\w)/g, '<em>$1</em>');
|
||||||
|
|
||||||
|
// 7.5 Extract Markdown tables after inline formatting so cells support bold/italic/links.
|
||||||
|
// 表格提取放在加粗/链接之后,避免单元格内 **xxx** 原样显示;同时压缩单元格内多余 <br>。
|
||||||
|
const tableBlocks: string[] = [];
|
||||||
|
text = text.replace(
|
||||||
|
/((?:^\|.+\|\r?\n)+^\|[\s\-:|]+\|\r?\n(?:^\|.+\|\r?\n?)+)/gm,
|
||||||
|
(_m: string, block: string) => {
|
||||||
|
const lines = block.trim().split(/\r?\n/).filter((l: string) => l.trim());
|
||||||
|
if (lines.length < 2) return block;
|
||||||
|
const headerCells = lines[0].split('|').slice(1, -1).map((c: string) => c.trim());
|
||||||
|
const alignCells = lines[1].split('|').slice(1, -1).map((c: string) => {
|
||||||
|
const t = c.trim();
|
||||||
|
const left = t.startsWith(':');
|
||||||
|
const right = t.endsWith(':');
|
||||||
|
if (left && right) return 'center';
|
||||||
|
if (right) return 'right';
|
||||||
|
if (left) return 'left';
|
||||||
|
return 'left';
|
||||||
|
});
|
||||||
|
const normalizeCell = (cell: string) => {
|
||||||
|
return cell
|
||||||
|
.replace(/<br\s*\/?>\s*/gi, '<br/>')
|
||||||
|
.replace(/\n/g, '<br/>')
|
||||||
|
.replace(/(<br\/>){2,}/g, '<br/>')
|
||||||
|
.replace(/^(<br\/>)+|(<br\/>)+$/g, '');
|
||||||
|
};
|
||||||
|
const bodyRows = lines.slice(2).map((row: string) =>
|
||||||
|
row.split('|').slice(1, -1).map((c: string) => normalizeCell(c.trim()))
|
||||||
|
);
|
||||||
|
const thead = headerCells.map((c: string, i: number) =>
|
||||||
|
`<th style="text-align:${alignCells[i] || 'left'}">${normalizeCell(c)}</th>`
|
||||||
|
).join('');
|
||||||
|
const tbody = bodyRows.map((r: string[]) =>
|
||||||
|
'<tr>' + r.map((c: string, i: number) =>
|
||||||
|
`<td style="text-align:${alignCells[i] || 'left'}">${c}</td>`
|
||||||
|
).join('') + '</tr>'
|
||||||
|
).join('');
|
||||||
|
const html = `<table class="md-table"><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table>`;
|
||||||
|
const idx = tableBlocks.length;
|
||||||
|
tableBlocks.push(html);
|
||||||
|
return '\x00TABLE' + idx + '\x00';
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 8. Lists
|
||||||
|
text = text.replace(/^\s*[-*] (.+)$/gm, '<li class="md-li">$1</li>');
|
||||||
|
text = text.replace(/^\s*\d+\. (.+)$/gm, '<li class="md-li">$1</li>');
|
||||||
|
// Wrap consecutive <li> in <ul>
|
||||||
|
text = text.replace(/((?:<li class="md-li">[\s\S]*?<\/li>\n?)+)/g, '<ul class="md-ul">$1</ul>');
|
||||||
|
|
||||||
|
// 9. Convert double newlines to paragraph breaks, single newlines to spaces
|
||||||
|
text = text.replace(/\n\n/g, '</p><p class="md-p">');
|
||||||
|
text = text.replace(/\n/g, ' ');
|
||||||
|
|
||||||
|
// 10. Restore code blocks and inline codes
|
||||||
|
text = text.replace(/\x00CODEBLOCK(\d+)\x00/g, (_m: string, idx: string) => codeBlocks[parseInt(idx)] || '');
|
||||||
|
text = text.replace(/\x00MERMAID(\d+)\x00/g, (_m: string, idx: string) => mermaidBlocks[parseInt(idx)] || '');
|
||||||
|
text = text.replace(/\x00INLINE(\d+)\x00/g, (_m: string, idx: string) => inlineCodes[parseInt(idx)] || '');
|
||||||
|
text = text.replace(/\x00TABLE(\d+)\x00/g, (_m: string, idx: string) => tableBlocks[parseInt(idx)] || '');
|
||||||
|
text = text.replace(/\x00MATHBLOCK(\d+)\x00/g, (_m: string, idx: string) => mathBlocks[parseInt(idx)] || '');
|
||||||
|
|
||||||
|
// 10.5 Apply syntax highlighting to code blocks + add copy button
|
||||||
|
text = text.replace(
|
||||||
|
/<pre class="md-code-block"><code class="md-code">([\s\S]*?)<\/code><\/pre>/g,
|
||||||
|
(_m: string, code: string) => {
|
||||||
|
const decoded = code.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||||
|
let highlighted: string;
|
||||||
|
try { highlighted = hljs.highlightAuto(decoded).value; } catch { highlighted = code; }
|
||||||
|
return `<div class="md-code-wrapper">
|
||||||
|
<button class="md-code-copy" onclick="navigator.clipboard.writeText(this.parentElement.querySelector('code').textContent);this.textContent='已复制';setTimeout(()=>this.textContent='复制',2000)">复制</button>
|
||||||
|
<pre class="md-code-block"><code class="md-code hljs">${highlighted}</code></pre>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 11. Wrap in paragraph and clean up
|
||||||
|
text = '<p class="md-p">' + text + '</p>';
|
||||||
|
text = text.replace(/<p class="md-p"><\/p>/g, '');
|
||||||
|
text = text.replace(/<p class="md-p">(<h[234][\s\S]*?<\/h[234]>)<\/p>/g, '$1');
|
||||||
|
text = text.replace(/<p class="md-p">(<pre[\s\S]*?<\/pre>)<\/p>/g, '$1');
|
||||||
|
text = text.replace(/<p class="md-p">(<ul[\s\S]*?<\/ul>)<\/p>/g, '$1');
|
||||||
|
text = text.replace(/<p class="md-p">(<hr[\s\S]*?)<\/p>/g, '$1');
|
||||||
|
text = text.replace(/<p class="md-p">(<blockquote[\s\S]*?<\/blockquote>)<\/p>/g, '$1');
|
||||||
|
text = text.replace(/<p class="md-p">(<table[\s\S]*?<\/table>)<\/p>/g, '$1');
|
||||||
|
|
||||||
|
return { html: text, media: mediaBlocks };
|
||||||
|
}
|
||||||
+26
-26
@@ -1,26 +1,26 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES2020",
|
"target": "ES2020",
|
||||||
"useDefineForClassFields": true,
|
"useDefineForClassFields": true,
|
||||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"noImplicitAny": false,
|
"noImplicitAny": false,
|
||||||
"noUnusedLocals": false,
|
"noUnusedLocals": false,
|
||||||
"noUnusedParameters": false,
|
"noUnusedParameters": false,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["src/*"]
|
"@/*": ["src/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
"references": [{ "path": "./tsconfig.node.json" }]
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ CREATE TABLE IF NOT EXISTS `skill_trajectory_links` (
|
|||||||
`skill_name` VARCHAR(200) NOT NULL,
|
`skill_name` VARCHAR(200) NOT NULL,
|
||||||
`user_id` VARCHAR(36) NOT NULL,
|
`user_id` VARCHAR(36) NOT NULL,
|
||||||
`trajectory_id` VARCHAR(36),
|
`trajectory_id` VARCHAR(36),
|
||||||
`atom_id` VARCHAR(36),
|
`atom_id` VARCHAR(128),
|
||||||
`weightscore` INT DEFAULT 0,
|
`weightscore` INT DEFAULT 0,
|
||||||
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
INDEX `idx_stl_user_skill` (`user_id`, `skill_name`),
|
INDEX `idx_stl_user_skill` (`user_id`, `skill_name`),
|
||||||
|
|||||||
@@ -2,10 +2,16 @@
|
|||||||
-- 旧的 text/thinking/vision/tool/image/audio/asr/ocr/embedding/rerank/video 已不再使用,
|
-- 旧的 text/thinking/vision/tool/image/audio/asr/ocr/embedding/rerank/video 已不再使用,
|
||||||
-- 统一置空,后续由 AI 验证 / 导入阶段按业务场景重新归类。
|
-- 统一置空,后续由 AI 验证 / 导入阶段按业务场景重新归类。
|
||||||
-- 幂等:执行一次后不再有匹配行,可安全每次重启重跑。
|
-- 幂等:执行一次后不再有匹配行,可安全每次重启重跑。
|
||||||
|
-- 注意:当前业务场景标准 = 前台「应用市场」14 类 (MARKET_SCENES):
|
||||||
|
-- design, frontend, mobile, backend, qa, search, docs, marketing,
|
||||||
|
-- workflow, secops, learning, video, collab, ai
|
||||||
|
-- 这些为合法取值,必须保留,不得置空(#707 修复:此前 allowlist 不含 14 类导致重启被清空)。
|
||||||
UPDATE market_apps
|
UPDATE market_apps
|
||||||
SET capability = NULL
|
SET capability = NULL
|
||||||
WHERE capability IS NOT NULL
|
WHERE capability IS NOT NULL
|
||||||
AND capability NOT IN (
|
AND capability NOT IN (
|
||||||
|
'design', 'frontend', 'mobile', 'backend', 'qa', 'search', 'docs', 'marketing',
|
||||||
|
'workflow', 'secops', 'learning', 'video', 'collab', 'ai',
|
||||||
'freelance_content', 'freelance_client', 'freelance_finance',
|
'freelance_content', 'freelance_client', 'freelance_finance',
|
||||||
'office_doc', 'office_data', 'office_email', 'office_pm',
|
'office_doc', 'office_data', 'office_email', 'office_pm',
|
||||||
'edu_prepare', 'edu_grade', 'edu_tutor', 'edu_home',
|
'edu_prepare', 'edu_grade', 'edu_tutor', 'edu_home',
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
CREATE TABLE IF NOT EXISTS conversation_summaries (
|
CREATE TABLE IF NOT EXISTS conversation_summaries (
|
||||||
conversation_id VARCHAR(64) NOT NULL,
|
conversation_id VARCHAR(64) NOT NULL,
|
||||||
summary_text TEXT NULL,
|
summary_text TEXT NULL,
|
||||||
token_count INT NULL DEFAULT 0,
|
token_count INT NULL DEFAULT 0,
|
||||||
updated_at DATETIME(3) NULL,
|
updated_at DATETIME(3) NULL,
|
||||||
PRIMARY KEY (conversation_id)
|
PRIMARY KEY (conversation_id)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- 021: 加宽 skill_trajectory_links.atom_id 列
|
||||||
|
-- 背景:atom_id 实际值形如 "{trajectory_id}_atom_{i}"(UUID 36 + "_atom_" + 序号 ≈ 45 字符),
|
||||||
|
-- 原 VARCHAR(36) 过短导致写入时 DataError(1406) Data too long,并使会话进入 rolled-back 状态,
|
||||||
|
-- 级联触发 PendingRollbackError 与日志 trace_id KeyError 刷屏。
|
||||||
|
-- 本迁移幂等:重复执行 MODIFY 到相同类型为无害 no-op。
|
||||||
|
|
||||||
|
ALTER TABLE `skill_trajectory_links` MODIFY COLUMN `atom_id` VARCHAR(128) NULL;
|
||||||
@@ -56,7 +56,7 @@ CREATE TABLE IF NOT EXISTS `distribution_licenses` (
|
|||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
-- Insert seed data: sample distributions
|
-- Insert seed data: sample distributions
|
||||||
INSERT INTO `distributions` (`id`, `name`, `description`, `brand_name`, `brand_color`, `provider`, `model`, `features`, `status`) VALUES
|
INSERT IGNORE INTO `distributions` (`id`, `name`, `description`, `brand_name`, `brand_color`, `provider`, `model`, `features`, `status`) VALUES
|
||||||
('distro-starter', 'Starter Edition', '基础版发行包,适合个人开发者和小团队', 'AI Starter', '#6366f1', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec"]', 'active'),
|
('distro-starter', 'Starter Edition', '基础版发行包,适合个人开发者和小团队', 'AI Starter', '#6366f1', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec"]', 'active'),
|
||||||
('distro-enterprise', 'Enterprise Edition', '企业版发行包,包含完整 MCP 生态 + Agent 协作', 'AI Enterprise', '#f59e0b', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "knowledge_search", "agent_collab"]', 'active'),
|
('distro-enterprise', 'Enterprise Edition', '企业版发行包,包含完整 MCP 生态 + Agent 协作', 'AI Enterprise', '#f59e0b', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "knowledge_search", "agent_collab"]', 'active'),
|
||||||
('distro-devops', 'DevOps Edition', 'DevOps 专用发行包,CI/CD + 代码审查 + 部署', 'AI DevOps', '#10b981', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "automation", "webhook"]', 'active');
|
('distro-devops', 'DevOps Edition', 'DevOps 专用发行包,CI/CD + 代码审查 + 部署', 'AI DevOps', '#10b981', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "automation", "webhook"]', 'active');
|
||||||
@@ -84,6 +84,11 @@ CREATE TABLE IF NOT EXISTS usage_reports (
|
|||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
-- 5. Add privacy_mode to distributions table
|
-- 5. Add privacy_mode to distributions table
|
||||||
ALTER TABLE distributions
|
-- MariaDB 11.8 不支持 ADD COLUMN IF NOT EXISTS 语法,改用 information_schema 预检 + 动态 PREPARE 实现幂等
|
||||||
ADD COLUMN IF NOT EXISTS privacy_mode ENUM('local', 'cloud', 'hybrid') NOT NULL DEFAULT 'cloud'
|
SET @exist_pm := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'aiflow' AND TABLE_NAME = 'distributions' AND COLUMN_NAME = 'privacy_mode');
|
||||||
COMMENT 'Deployment mode for distribution' AFTER status;
|
SET @sql_pm := IF(@exist_pm = 0,
|
||||||
|
"ALTER TABLE distributions ADD COLUMN privacy_mode ENUM('local', 'cloud', 'hybrid') NOT NULL DEFAULT 'cloud' COMMENT 'Deployment mode for distribution' AFTER status",
|
||||||
|
'SELECT 1');
|
||||||
|
PREPARE stmt_pm FROM @sql_pm;
|
||||||
|
EXECUTE stmt_pm;
|
||||||
|
DEALLOCATE PREPARE stmt_pm;
|
||||||
Reference in new issue
Block a user