feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""领域服务层:Git 读取、文件工具等可独立单测的能力"""
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
自动备份服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
定时备份 SQLite 数据库、配置文件、向量库元数据到指定目录。
|
||||
支持手动触发和定时调度。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选 SQLite 版本化备份(.backup):在线备份不锁库;
|
||||
2. 备份文件用时间戳命名:便于保留多个版本;
|
||||
3. 自动清理过期备份(保留最近 N 天)。
|
||||
|
||||
【实现思路】
|
||||
- backup_now():立即执行备份;
|
||||
- auto_backup_loop():后台定时循环(每 N 小时);
|
||||
- 清理超过保留期的旧备份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app.config.settings import load_settings
|
||||
|
||||
logger = logging.getLogger("agent.backup")
|
||||
|
||||
# 备份配置
|
||||
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups\auto")
|
||||
RETENTION_DAYS = 30 # 保留最近 30 天
|
||||
BACKUP_INTERVAL_SECONDS = 12 * 3600 # 每 12 小时一次
|
||||
|
||||
|
||||
def backup_now() -> dict:
|
||||
"""
|
||||
立即执行全量备份。
|
||||
|
||||
【备份内容】SQLite + .env + 配置 + 向量库元数据
|
||||
【返回】{success, backup_path, files, size_bytes}
|
||||
"""
|
||||
settings = load_settings()
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
backup_path = BACKUP_DIR / f"backup_{timestamp}"
|
||||
backup_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
files_copied = []
|
||||
total_bytes = 0
|
||||
|
||||
try:
|
||||
# 1. SQLite 数据库(在线备份,不锁库)
|
||||
db_path = settings.sqlite_db_path
|
||||
if db_path.exists():
|
||||
dest = backup_path / "agent.db"
|
||||
# 用 SQLite .backup API(安全在线备份)
|
||||
src_conn = sqlite3.connect(str(db_path))
|
||||
dest_conn = sqlite3.connect(str(dest))
|
||||
try:
|
||||
src_conn.backup(dest_conn)
|
||||
finally:
|
||||
# 【修复】close 必须在 finally,否则 backup 抛异常时两个连接都泄漏
|
||||
dest_conn.close()
|
||||
src_conn.close()
|
||||
size = dest.stat().st_size
|
||||
total_bytes += size
|
||||
files_copied.append({"name": "agent.db", "size": size})
|
||||
|
||||
# 2. .env 配置
|
||||
env_path = Path(r"D:\Agent\agent\backend\.env")
|
||||
if env_path.exists():
|
||||
dest = backup_path / ".env"
|
||||
shutil.copy2(env_path, dest)
|
||||
size = dest.stat().st_size
|
||||
total_bytes += size
|
||||
files_copied.append({"name": ".env", "size": size})
|
||||
|
||||
# 3. 备注文件
|
||||
remarks_path = Path(r"D:\Agent\agent\backend\.env.remarks.json")
|
||||
if remarks_path.exists():
|
||||
dest = backup_path / ".env.remarks.json"
|
||||
shutil.copy2(remarks_path, dest)
|
||||
size = dest.stat().st_size
|
||||
total_bytes += size
|
||||
files_copied.append({"name": ".env.remarks.json", "size": size})
|
||||
|
||||
# 4. 向量库元数据(只备 SQLite,不备大文件)
|
||||
chroma_db = settings.chroma_dir / "chroma.sqlite3"
|
||||
if chroma_db.exists():
|
||||
dest = backup_path / "chroma.sqlite3"
|
||||
shutil.copy2(chroma_db, dest)
|
||||
size = dest.stat().st_size
|
||||
total_bytes += size
|
||||
files_copied.append({"name": "chroma.sqlite3", "size": size})
|
||||
|
||||
# 5. 清理过期备份
|
||||
cleaned = _cleanup_old_backups()
|
||||
|
||||
logger.info("备份完成:%s(%d 个文件,%.1fKB)", backup_path, len(files_copied), total_bytes / 1024)
|
||||
return {
|
||||
"success": True,
|
||||
"backup_path": str(backup_path),
|
||||
"files": files_copied,
|
||||
"size_bytes": total_bytes,
|
||||
"cleaned_old": cleaned,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("备份失败")
|
||||
return {"success": False, "message": f"备份失败:{exc}"}
|
||||
|
||||
|
||||
def _cleanup_old_backups() -> int:
|
||||
"""清理超过保留期的旧备份。"""
|
||||
if not BACKUP_DIR.exists():
|
||||
return 0
|
||||
cutoff = time.time() - RETENTION_DAYS * 86400
|
||||
cleaned = 0
|
||||
for item in BACKUP_DIR.iterdir():
|
||||
if item.is_dir() and item.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(item, ignore_errors=True)
|
||||
cleaned += 1
|
||||
return cleaned
|
||||
|
||||
|
||||
def list_backups() -> list[dict]:
|
||||
"""列出所有备份(供前端展示)。"""
|
||||
if not BACKUP_DIR.exists():
|
||||
return []
|
||||
items = []
|
||||
for item in sorted(BACKUP_DIR.iterdir(), reverse=True):
|
||||
if item.is_dir():
|
||||
total_size = sum(f.stat().st_size for f in item.rglob("*") if f.is_file())
|
||||
file_count = sum(1 for f in item.rglob("*") if f.is_file())
|
||||
items.append({
|
||||
"name": item.name,
|
||||
"path": str(item),
|
||||
"size_bytes": total_size,
|
||||
"file_count": file_count,
|
||||
"created_at": datetime.fromtimestamp(item.stat().st_mtime).isoformat(),
|
||||
})
|
||||
return items
|
||||
@@ -0,0 +1,433 @@
|
||||
"""
|
||||
数据库操作引擎
|
||||
==============
|
||||
|
||||
【功能说明】
|
||||
基于 SQLAlchemy 对目标数据库执行 SQL CRUD 操作。
|
||||
支持 MySQL / PostgreSQL / SQLite 三种数据库。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选 SQLAlchemy:统一抽象多种数据库,改类型只改连接串;
|
||||
2. 参数化查询:防 SQL 注入(硬约束 5 安全兜底);
|
||||
3. 连接池 + 短连接:每次操作独立连接,避免连接泄漏。
|
||||
|
||||
【实现思路】
|
||||
- create_engine():按连接配置创建 SQLAlchemy 引擎;
|
||||
- execute_sql():通用 SQL 执行(INSERT/UPDATE/DELETE/SELECT);
|
||||
- query_with_pagination():SELECT 分页查询;
|
||||
- test_connection():连接测试。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:SQL 注入。
|
||||
应对:强制使用参数化查询,不拼接用户输入。
|
||||
风险2:大批量数据操作。
|
||||
应对:分页 + LIMIT 限制,防止全表扫描。
|
||||
风险3:数据库连接泄漏。
|
||||
应对:每次操作用 context manager 确保关闭连接。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from app.schemas.database import SqlExecuteResult
|
||||
|
||||
logger = logging.getLogger("agent.db_engine")
|
||||
|
||||
# 合法表名/列名(防 SQL 注入)
|
||||
_IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||
|
||||
|
||||
def _validate_identifier(name: str, kind: str = "表名") -> str:
|
||||
"""校验 SQL 标识符(表名/列名)合法性,防注入。"""
|
||||
if not name or not _IDENTIFIER_RE.match(name):
|
||||
raise ValueError(f"非法{kind}:{name!r}(只允许字母、数字、下划线,且不以数字开头)")
|
||||
return name
|
||||
|
||||
|
||||
def _build_engine(conn_info: dict):
|
||||
"""按连接配置创建 SQLAlchemy 引擎。"""
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||
if db_type == "sqlite":
|
||||
db_path = conn_info.get("database", ":memory:")
|
||||
url = f"sqlite:///{db_path}"
|
||||
elif db_type == "mysql":
|
||||
# URL 编码用户名和密码,防止特殊字符(@ : / # 等)破坏连接串
|
||||
user = quote_plus(str(conn_info.get("username", "")))
|
||||
pwd = quote_plus(str(conn_info.get("password", "")))
|
||||
url = (
|
||||
f"mysql+pymysql://{user}:{pwd}"
|
||||
f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}"
|
||||
)
|
||||
elif db_type == "postgresql":
|
||||
user = quote_plus(str(conn_info.get("username", "")))
|
||||
pwd = quote_plus(str(conn_info.get("password", "")))
|
||||
url = (
|
||||
f"postgresql://{user}:{pwd}"
|
||||
f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}"
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"不支持的数据库类型:{db_type}")
|
||||
|
||||
return create_engine(url, pool_pre_ping=True, pool_recycle=3600)
|
||||
|
||||
|
||||
def list_tables(conn_info: dict) -> list[str]:
|
||||
"""列出数据库中的所有表名(多数据库适配)。"""
|
||||
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||
engine = _build_engine(conn_info)
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
from sqlalchemy import text
|
||||
|
||||
if db_type == "mysql":
|
||||
result = conn.execute(text("SHOW TABLES"))
|
||||
return [row[0] for row in result]
|
||||
elif db_type == "postgresql":
|
||||
result = conn.execute(
|
||||
text(
|
||||
"SELECT tablename FROM pg_tables "
|
||||
"WHERE schemaname = 'public' ORDER BY tablename"
|
||||
)
|
||||
)
|
||||
return [row[0] for row in result]
|
||||
else: # sqlite
|
||||
result = conn.execute(
|
||||
text("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||
)
|
||||
return [row[0] for row in result]
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("列出表失败:%s", exc)
|
||||
return []
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def get_table_structure(conn_info: dict, table_name: str) -> dict:
|
||||
"""
|
||||
查询表结构(列名、类型、可空、主键、默认值、注释)。
|
||||
|
||||
【多数据库适配】
|
||||
- MySQL:SHOW FULL COLUMNS FROM {table}
|
||||
- PostgreSQL:information_schema.columns
|
||||
- SQLite:PRAGMA table_info({table})
|
||||
"""
|
||||
_validate_identifier(table_name, "表名")
|
||||
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||
engine = _build_engine(conn_info)
|
||||
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
from sqlalchemy import text
|
||||
|
||||
if db_type == "mysql":
|
||||
result = conn.execute(text(f"SHOW FULL COLUMNS FROM {table_name}"))
|
||||
columns = []
|
||||
for row in result.mappings():
|
||||
columns.append({
|
||||
"name": row.get("Field", ""),
|
||||
"type": row.get("Type", ""),
|
||||
"nullable": row.get("Null", "") == "YES",
|
||||
"key": row.get("Key", ""),
|
||||
"default": row.get("Default", ""),
|
||||
"comment": row.get("Comment", ""),
|
||||
})
|
||||
elif db_type == "postgresql":
|
||||
result = conn.execute(
|
||||
text(
|
||||
"SELECT column_name, data_type, is_nullable, column_default "
|
||||
"FROM information_schema.columns WHERE table_name = :tname "
|
||||
"ORDER BY ordinal_position"
|
||||
),
|
||||
{"tname": table_name},
|
||||
)
|
||||
columns = [
|
||||
{
|
||||
"name": r["column_name"],
|
||||
"type": r["data_type"],
|
||||
"nullable": r["is_nullable"] == "YES",
|
||||
"key": "",
|
||||
"default": r["column_default"] or "",
|
||||
"comment": "",
|
||||
}
|
||||
for r in result.mappings()
|
||||
]
|
||||
else: # sqlite
|
||||
result = conn.execute(text(f"PRAGMA table_info({table_name})"))
|
||||
columns = [
|
||||
{
|
||||
"name": r["name"],
|
||||
"type": r["type"],
|
||||
"nullable": not r["notnull"],
|
||||
"key": "PRI" if r["pk"] else "",
|
||||
"default": r["dflt_value"] or "",
|
||||
"comment": "",
|
||||
}
|
||||
for r in result.mappings()
|
||||
]
|
||||
|
||||
return {"success": True, "table": table_name, "columns": columns}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"查询表结构失败:{exc}", "columns": []}
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def alter_table(
|
||||
conn_info: dict,
|
||||
table_name: str,
|
||||
action: str,
|
||||
column_name: str,
|
||||
column_type: str = "",
|
||||
nullable: bool = True,
|
||||
default: str = "",
|
||||
comment: str = "",
|
||||
) -> dict:
|
||||
"""
|
||||
修改表结构(加列/改列/删列)。
|
||||
|
||||
【参数】
|
||||
action: add / modify / drop
|
||||
column_name: 列名
|
||||
column_type: 列类型(如 VARCHAR(255))
|
||||
nullable: 是否可空
|
||||
default: 默认值
|
||||
comment: 注释
|
||||
"""
|
||||
_validate_identifier(table_name, "表名")
|
||||
_validate_identifier(column_name, "列名")
|
||||
|
||||
# 校验列类型(只允许合法 SQL 类型表达式)
|
||||
if action in ("add", "modify") and column_type:
|
||||
if not re.match(r"^[a-zA-Z][a-zA-Z0-9_()]*$", column_type):
|
||||
return {"success": False, "message": f"非法列类型:{column_type}"}
|
||||
|
||||
db_type = conn_info.get("db_type", "sqlite").lower()
|
||||
engine = _build_engine(conn_info)
|
||||
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
from sqlalchemy import text
|
||||
|
||||
if action == "add":
|
||||
if db_type == "mysql":
|
||||
null_str = "NULL" if nullable else "NOT NULL"
|
||||
default_str = f" DEFAULT {default}" if default else ""
|
||||
comment_str = f" COMMENT '{comment}'" if comment else ""
|
||||
sql = (
|
||||
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} "
|
||||
f"{null_str}{default_str}{comment_str}"
|
||||
)
|
||||
elif db_type == "postgresql":
|
||||
null_str = "NULL" if nullable else "NOT NULL"
|
||||
default_str = f" DEFAULT {default}" if default else ""
|
||||
sql = (
|
||||
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} "
|
||||
f"{null_str}{default_str}"
|
||||
)
|
||||
else: # sqlite
|
||||
null_str = "" if nullable else " NOT NULL"
|
||||
default_str = f" DEFAULT {default}" if default else ""
|
||||
sql = (
|
||||
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}"
|
||||
f"{null_str}{default_str}"
|
||||
)
|
||||
|
||||
elif action == "modify":
|
||||
if db_type == "mysql":
|
||||
null_str = "NULL" if nullable else "NOT NULL"
|
||||
default_str = f" DEFAULT {default}" if default else ""
|
||||
comment_str = f" COMMENT '{comment}'" if comment else ""
|
||||
sql = (
|
||||
f"ALTER TABLE {table_name} MODIFY COLUMN {column_name} {column_type} "
|
||||
f"{null_str}{default_str}{comment_str}"
|
||||
)
|
||||
elif db_type == "postgresql":
|
||||
# PG 需要拆成多条
|
||||
conn.execute(text(
|
||||
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {column_type}"
|
||||
))
|
||||
null_str = "DROP NOT NULL" if nullable else "SET NOT NULL"
|
||||
conn.execute(text(
|
||||
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} {null_str}"
|
||||
))
|
||||
if default:
|
||||
conn.execute(text(
|
||||
f"ALTER TABLE {table_name} ALTER COLUMN {column_name} SET DEFAULT {default}"
|
||||
))
|
||||
return {"success": True, "message": f"列 {column_name} 修改成功"}
|
||||
else: # sqlite
|
||||
return {"success": False, "message": "SQLite 不支持 MODIFY COLUMN,请通过重建表修改"}
|
||||
|
||||
elif action == "drop":
|
||||
sql = f"ALTER TABLE {table_name} DROP COLUMN {column_name}"
|
||||
else:
|
||||
return {"success": False, "message": f"不支持的操作:{action}"}
|
||||
|
||||
conn.execute(text(sql))
|
||||
return {"success": True, "message": f"列 {column_name} {action} 成功"}
|
||||
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"修改表结构失败:{exc}"}
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_connection(conn_info: dict) -> dict:
|
||||
"""测试数据库连接是否成功。"""
|
||||
engine = None
|
||||
try:
|
||||
engine = _build_engine(conn_info)
|
||||
with engine.connect() as conn:
|
||||
from sqlalchemy import text
|
||||
|
||||
result = conn.execute(text("SELECT 1"))
|
||||
result.fetchone()
|
||||
return {"success": True, "message": "连接成功"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"连接失败:{exc}"}
|
||||
finally:
|
||||
if engine is not None:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _normalize_sql(sql: str) -> str:
|
||||
"""
|
||||
规范化 SQL:去掉尾部空白与分号。
|
||||
|
||||
【踩坑】用户习惯写 `SELECT * FROM t;` 带分号,但分页查询会包
|
||||
`SELECT COUNT(*) FROM (sql) AS _sub`,分号嵌在括号里导致语法错误。
|
||||
"""
|
||||
return sql.strip().rstrip(";").strip()
|
||||
|
||||
|
||||
def execute_sql(
|
||||
conn_info: dict,
|
||||
sql: str,
|
||||
params: list | dict | None = None,
|
||||
) -> SqlExecuteResult:
|
||||
"""
|
||||
执行 SQL(INSERT/UPDATE/DELETE/SELECT 通用)。
|
||||
|
||||
【安全】强制参数化查询,防 SQL 注入。
|
||||
"""
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
sql = _normalize_sql(sql)
|
||||
if not sql:
|
||||
return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0)
|
||||
|
||||
engine = _build_engine(conn_info)
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
if params:
|
||||
result = conn.execute(text(sql), params)
|
||||
else:
|
||||
result = conn.execute(text(sql))
|
||||
|
||||
# SELECT:返回数据
|
||||
if result.returns_rows:
|
||||
columns = list(result.keys()) if result.keys() else []
|
||||
rows = [dict(row) for row in result.mappings().all()]
|
||||
return SqlExecuteResult(
|
||||
success=True,
|
||||
message=f"查询返回 {len(rows)} 条记录",
|
||||
affected_rows=len(rows),
|
||||
data=rows,
|
||||
columns=columns,
|
||||
total=len(rows),
|
||||
)
|
||||
|
||||
# INSERT/UPDATE/DELETE:返回影响行数
|
||||
affected = result.rowcount if result.rowcount >= 0 else 0
|
||||
return SqlExecuteResult(
|
||||
success=True,
|
||||
message=f"操作成功,影响 {affected} 行",
|
||||
affected_rows=affected,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("SQL 执行失败:%s | %s", sql[:200], exc)
|
||||
return SqlExecuteResult(
|
||||
success=False, message=f"SQL 执行失败:{exc}", affected_rows=0
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def query_with_pagination(
|
||||
conn_info: dict,
|
||||
sql: str,
|
||||
params: list | dict | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> SqlExecuteResult:
|
||||
"""
|
||||
SELECT 分页查询。
|
||||
|
||||
【实现】在原始 SQL 外包一层 LIMIT/OFFSET,自动补 COUNT 总数。
|
||||
【修复】
|
||||
1. list 参数转为 dict(SQLAlchemy text() 不支持位置参数);
|
||||
2. 内部参数名加 __ 前缀,防止与用户 SQL 参数冲突;
|
||||
3. 非 SELECT 语句自动走 execute_sql(不包 COUNT/LIMIT)。
|
||||
"""
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
sql = _normalize_sql(sql)
|
||||
if not sql:
|
||||
return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0)
|
||||
|
||||
# 非 SELECT 语句走通用执行(不包分页)
|
||||
first_word = sql.split()[0].upper() if sql.split() else ""
|
||||
if first_word not in ("SELECT", "WITH"):
|
||||
return execute_sql(conn_info, sql, params)
|
||||
|
||||
engine = _build_engine(conn_info)
|
||||
try:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
# 统一参数为 dict(SQLAlchemy text() 只支持命名参数)
|
||||
if params and isinstance(params, list):
|
||||
return SqlExecuteResult(
|
||||
success=False,
|
||||
message="分页查询暂不支持位置参数(list),请使用命名参数(dict)",
|
||||
affected_rows=0,
|
||||
)
|
||||
base_params: dict[str, Any] = dict(params) if isinstance(params, dict) else {}
|
||||
|
||||
# 内部参数名加 __ 前缀,防止与用户参数冲突
|
||||
paged_sql = f"SELECT * FROM ({sql}) AS _sub LIMIT :__limit OFFSET :__offset"
|
||||
count_sql = f"SELECT COUNT(*) as cnt FROM ({sql}) AS _sub"
|
||||
paged_params = {**base_params, "__limit": page_size, "__offset": offset}
|
||||
|
||||
with engine.connect() as conn:
|
||||
# 查总数
|
||||
total_row = conn.execute(text(count_sql), base_params).fetchone()
|
||||
total = total_row[0] if total_row else 0
|
||||
|
||||
# 查分页数据
|
||||
result = conn.execute(text(paged_sql), paged_params)
|
||||
columns = list(result.keys()) if result.keys() else []
|
||||
rows = [dict(row) for row in result.mappings().all()]
|
||||
|
||||
return SqlExecuteResult(
|
||||
success=True,
|
||||
message=f"查询返回 {len(rows)} 条(共 {total} 条)",
|
||||
affected_rows=len(rows),
|
||||
data=rows,
|
||||
columns=columns,
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("分页查询失败:%s | %s", sql[:200], exc)
|
||||
return SqlExecuteResult(
|
||||
success=False, message=f"查询失败:{exc}", affected_rows=0
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,440 @@
|
||||
"""
|
||||
文档问答服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
基于指定目录下的文档提供多轮对话式问答。
|
||||
支持两种模式:
|
||||
1. 文本模式(默认):解析文档到内存,直接用原文回答(无需向量化,快);
|
||||
2. 向量模式(可选):手动触发向量化,用向量检索回答(大文档/高频问答时用)。
|
||||
|
||||
【技术选型理由】
|
||||
1. 文本模式优先:小文档量直接塞 LLM 上下文即可,省向量化时间;
|
||||
2. 向量化可选:用户按需触发,不强制;
|
||||
3. 复用已有 document_loader / vector_store 组件。
|
||||
|
||||
【实现思路】
|
||||
- load_directory():只解析文档存内存(快);
|
||||
- chat():文本模式直接用原文;有向量索引时用检索增强;
|
||||
- vectorize():手动触发向量化(按钮)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.doc_qa")
|
||||
|
||||
# 会话存储
|
||||
_conversations: dict[str, dict[str, Any]] = {}
|
||||
|
||||
# 持久化文件(对话历史跨重启保留)
|
||||
_PERSIST_FILE = Path(r"D:\Agent\agent\data\docqa_conversations.json")
|
||||
|
||||
|
||||
def _load_persisted() -> None:
|
||||
"""启动时从文件恢复对话历史。"""
|
||||
if not _PERSIST_FILE.exists():
|
||||
return
|
||||
try:
|
||||
data = json.loads(_PERSIST_FILE.read_text(encoding="utf-8"))
|
||||
for cid, conv in data.items():
|
||||
# 只恢复元数据和历史,documents 可能太大
|
||||
_conversations[cid] = {
|
||||
"directory": conv.get("directory", ""),
|
||||
"documents": conv.get("documents", []),
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"collection_name": conv.get("collection_name"),
|
||||
"history": conv.get("history", []),
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"total_chunks": conv.get("total_chunks", 0),
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
}
|
||||
logger.info("已恢复 %d 个对话历史", len(_conversations))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("恢复对话历史失败:%s", exc)
|
||||
|
||||
|
||||
def _save_persisted() -> None:
|
||||
"""持久化对话历史到文件。"""
|
||||
try:
|
||||
_PERSIST_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 只存必要字段,documents 可能很大
|
||||
data = {}
|
||||
for cid, conv in _conversations.items():
|
||||
data[cid] = {
|
||||
"directory": conv.get("directory", ""),
|
||||
"documents": conv.get("documents", [])[:50], # 最多存 50 个文档元数据
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"collection_name": conv.get("collection_name"),
|
||||
"history": conv.get("history", [])[-20:], # 最多存最近 20 轮
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"total_chunks": conv.get("total_chunks", 0),
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
}
|
||||
_PERSIST_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("保存对话历史失败:%s", exc)
|
||||
|
||||
|
||||
# 启动时恢复
|
||||
_load_persisted()
|
||||
|
||||
|
||||
def load_directory(
|
||||
directory: Path | None = None,
|
||||
conversation_id: str | None = None,
|
||||
file_paths: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
解析文档并存入内存(**不做向量化**,快)。
|
||||
|
||||
【参数】
|
||||
directory:目录路径(加载目录下全部文档)
|
||||
file_paths:文件路径列表(加载指定文件,与 directory 二选一)
|
||||
【返回】{conversation_id, total_chars, file_count, vectorized: False}
|
||||
"""
|
||||
from app.knowledge.document_loader import load_directory as _load, load_file
|
||||
|
||||
if conversation_id is None:
|
||||
conversation_id = f"conv_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
docs = []
|
||||
warnings = []
|
||||
target_label = ""
|
||||
|
||||
try:
|
||||
if file_paths:
|
||||
# 加载指定文件
|
||||
target_label = f"{len(file_paths)} 个文件"
|
||||
for fp in file_paths:
|
||||
try:
|
||||
docs.extend(load_file(Path(fp)))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
warnings.append(f"解析失败:{Path(fp).name},{exc}")
|
||||
elif directory:
|
||||
# 加载目录下全部文档
|
||||
directory = Path(directory)
|
||||
if not directory.exists():
|
||||
return {"success": False, "message": f"目录不存在:{directory}"}
|
||||
target_label = str(directory)
|
||||
docs, warnings = _load(directory)
|
||||
else:
|
||||
return {"success": False, "message": "directory 或 file_paths 必须提供其一"}
|
||||
|
||||
if not docs:
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"无可用文档(跳过 {len(warnings)} 个文件)",
|
||||
"conversation_id": conversation_id,
|
||||
}
|
||||
|
||||
# 存入内存(不做向量化)
|
||||
documents = [
|
||||
{
|
||||
"filename": d.metadata.get("filename", "未知"),
|
||||
"text": d.page_content,
|
||||
"chars": len(d.page_content),
|
||||
}
|
||||
for d in docs
|
||||
]
|
||||
total_chars = sum(d["chars"] for d in documents)
|
||||
|
||||
_conversations[conversation_id] = {
|
||||
"directory": target_label,
|
||||
"documents": documents,
|
||||
"vectorized": False,
|
||||
"collection_name": None,
|
||||
"history": [],
|
||||
"total_chars": total_chars,
|
||||
"title": Path(target_label).name if target_label else "新对话",
|
||||
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
}
|
||||
_save_persisted()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"conversation_id": conversation_id,
|
||||
"directory": target_label,
|
||||
"file_count": len(documents),
|
||||
"total_chars": total_chars,
|
||||
"vectorized": False,
|
||||
"files": documents,
|
||||
"warnings": warnings,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("文档解析失败")
|
||||
return {"success": False, "message": f"解析失败:{exc}", "conversation_id": conversation_id}
|
||||
|
||||
|
||||
def vectorize(conversation_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
手动触发向量化(按钮)。
|
||||
|
||||
【返回】{success, total_chunks, collection_name}
|
||||
"""
|
||||
from app.knowledge.embeddings import get_embedding_provider
|
||||
from app.knowledge.text_splitter import split_documents
|
||||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||
from app.knowledge.document_loader import LoadedDocument
|
||||
|
||||
conv = _conversations.get(conversation_id)
|
||||
if conv is None:
|
||||
return {"success": False, "message": "会话不存在,请先加载目录"}
|
||||
|
||||
if conv.get("vectorized"):
|
||||
return {"success": True, "message": "已向量化,无需重复操作", "total_chunks": conv.get("total_chunks", 0)}
|
||||
|
||||
try:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
provider = get_embedding_provider(
|
||||
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||
)
|
||||
collection_name = f"docqa_{conversation_id}"
|
||||
vs = KnowledgeVectorStore(
|
||||
persist_dir=settings.chroma_dir,
|
||||
collection_name=collection_name,
|
||||
embedding_provider=provider,
|
||||
)
|
||||
|
||||
# 内存文档 → LoadedDocument → 切分 → 入库
|
||||
docs = [
|
||||
LoadedDocument(page_content=d["text"], metadata={"filename": d["filename"], "source": ""})
|
||||
for d in conv["documents"]
|
||||
]
|
||||
chunks = split_documents(docs)
|
||||
|
||||
import uuid as uuid_mod
|
||||
|
||||
ids = [f"chunk_{uuid_mod.uuid4().hex[:12]}" for _ in chunks]
|
||||
vs.add_documents(
|
||||
[c.page_content for c in chunks],
|
||||
[c.metadata for c in chunks],
|
||||
ids,
|
||||
)
|
||||
|
||||
conv["vectorized"] = True
|
||||
conv["collection_name"] = collection_name
|
||||
conv["total_chunks"] = len(chunks)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"向量化完成:{len(chunks)} 个文本块",
|
||||
"total_chunks": len(chunks),
|
||||
"collection_name": collection_name,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("向量化失败")
|
||||
return {"success": False, "message": f"向量化失败:{exc}"}
|
||||
|
||||
|
||||
def chat(
|
||||
conversation_id: str,
|
||||
question: str,
|
||||
model_preference: str = "auto",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
多轮对话问答。
|
||||
|
||||
【模式】
|
||||
无文档:纯 LLM 对话(无 RAG,直接回答);
|
||||
有文档未向量化:文档原文直接进 LLM 上下文;
|
||||
有文档已向量化:向量检索 top-k 相关片段 + LLM 回答。
|
||||
"""
|
||||
from app.models.model_router import get_model_for_task
|
||||
|
||||
conv = _conversations.get(conversation_id)
|
||||
if conv is None:
|
||||
return {"success": False, "message": "会话不存在,请先创建对话或加载文档"}
|
||||
|
||||
try:
|
||||
docs = conv.get("documents", [])
|
||||
|
||||
if not docs:
|
||||
# ========== 无文档模式:纯 LLM 对话 ==========
|
||||
context = "(本次对话无关联文档,请直接回答用户问题)"
|
||||
sources = []
|
||||
mode = "chat"
|
||||
elif conv.get("vectorized") and conv.get("collection_name"):
|
||||
# ========== 向量模式:检索 top-5 相关片段 ==========
|
||||
from app.knowledge.embeddings import get_embedding_provider
|
||||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
provider = get_embedding_provider(
|
||||
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||
)
|
||||
vs = KnowledgeVectorStore(
|
||||
persist_dir=settings.chroma_dir,
|
||||
collection_name=conv["collection_name"],
|
||||
embedding_provider=provider,
|
||||
)
|
||||
hits = vs.search(question, top_k=5)
|
||||
context = "\n\n".join(
|
||||
f"【片段 {i + 1}】来源:{h.get('metadata', {}).get('filename', '未知')}\n{h.get('text', '')}"
|
||||
for i, h in enumerate(hits)
|
||||
)
|
||||
sources = [
|
||||
{
|
||||
"filename": h.get("metadata", {}).get("filename", ""),
|
||||
"score": h.get("score"),
|
||||
"excerpt": h.get("text", "")[:150],
|
||||
}
|
||||
for h in hits[:3]
|
||||
]
|
||||
mode = "vector"
|
||||
else:
|
||||
# ========== 文本模式:文档原文进上下文 ==========
|
||||
MAX_CONTEXT_CHARS = 500_000
|
||||
total_chars = sum(d["chars"] for d in docs)
|
||||
context_parts = []
|
||||
if total_chars <= MAX_CONTEXT_CHARS:
|
||||
for doc in docs:
|
||||
context_parts.append(f"【文档:{doc['filename']}】\n{doc['text']}")
|
||||
else:
|
||||
MIN_CHARS_PER_DOC = 2000
|
||||
for doc in docs:
|
||||
quota = max(MIN_CHARS_PER_DOC, int(MAX_CONTEXT_CHARS * doc["chars"] / total_chars))
|
||||
text = doc["text"][:quota]
|
||||
context_parts.append(f"【文档:{doc['filename']}(共{doc['chars']}字符)】\n{text}")
|
||||
if doc["chars"] > quota:
|
||||
context_parts.append(f"…({doc['filename']} 内容过长已截断)")
|
||||
context = "\n\n".join(context_parts)
|
||||
sources = [
|
||||
{"filename": d["filename"], "score": None, "excerpt": d["text"][:150]}
|
||||
for d in docs[:3]
|
||||
]
|
||||
mode = "text"
|
||||
|
||||
# 多轮对话历史(超过 20 轮自动压缩摘要)
|
||||
history = conv.get("history", [])
|
||||
history_text = ""
|
||||
if history:
|
||||
if len(history) > 20:
|
||||
# 上下文压缩:保留最近 8 轮 + 对前 12 轮做摘要
|
||||
recent = history[-8:]
|
||||
older = history[:-8]
|
||||
try:
|
||||
# 简单截断(避免每次调模型摘要),取前 200 字符每条
|
||||
summary = "\n".join(
|
||||
f"{m['role']}: {m['content'][:100]}" for m in older[:12]
|
||||
)
|
||||
history_text = f"【更早对话摘要】\n{summary}\n\n【近期对话】\n"
|
||||
except Exception: # noqa: BLE001
|
||||
summary = ""
|
||||
history_text = ""
|
||||
history_text += "\n".join(
|
||||
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||
)
|
||||
else:
|
||||
recent = history[-6:]
|
||||
history_text = "\n".join(
|
||||
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||
)
|
||||
|
||||
if docs:
|
||||
prompt = f"""你是一个基于文档的问答助手。请严格根据以下文档内容回答用户问题。
|
||||
|
||||
【文档内容】
|
||||
{context}
|
||||
|
||||
【对话历史】
|
||||
{history_text or '(无历史)'}
|
||||
|
||||
【用户问题】
|
||||
{question}
|
||||
|
||||
【回答要求】
|
||||
1. 严格基于上述文档内容回答,禁止编造
|
||||
2. 如果文档中没有相关内容,直接回答「根据已有文档,未找到相关答案」
|
||||
3. 引用文档原文时用引号标注
|
||||
4. 用中文回答,完整有条理"""
|
||||
else:
|
||||
prompt = f"""你是一个专业的问答助手。请回答用户的问题。
|
||||
|
||||
【对话历史】
|
||||
{history_text or '(无历史)'}
|
||||
|
||||
【用户问题】
|
||||
{question}
|
||||
|
||||
请用中文回答,完整有条理。"""
|
||||
|
||||
model = get_model_for_task(model_preference, "strong")
|
||||
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||||
resp = model.invoke(prompt)
|
||||
answer = resp.content if hasattr(resp, "content") else str(resp)
|
||||
|
||||
history.append({"role": "user", "content": question})
|
||||
history.append({"role": "assistant", "content": answer})
|
||||
conv["history"] = history
|
||||
conv["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 首次提问时用问题做标题
|
||||
if len(history) == 2 and conv.get("title") == conv.get("directory", "").split("\\")[-1]:
|
||||
conv["title"] = question[:20] + ("…" if len(question) > 20 else "")
|
||||
|
||||
_save_persisted()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"answer": answer,
|
||||
"model": model_name,
|
||||
"sources": sources,
|
||||
"history_count": len(history),
|
||||
"mode": mode,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("问答失败")
|
||||
return {"success": False, "message": f"问答失败:{exc}"}
|
||||
|
||||
|
||||
def clear_conversation(conversation_id: str) -> bool:
|
||||
"""清除会话历史。"""
|
||||
if conversation_id in _conversations:
|
||||
_conversations[conversation_id]["history"] = []
|
||||
_save_persisted()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def delete_conversation(conversation_id: str) -> bool:
|
||||
"""删除会话(彻底移除)。"""
|
||||
if conversation_id in _conversations:
|
||||
del _conversations[conversation_id]
|
||||
_save_persisted()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def list_conversations() -> list[dict[str, Any]]:
|
||||
"""列出所有活跃会话(含标题、时间、消息数)。"""
|
||||
items = []
|
||||
for cid, conv in _conversations.items():
|
||||
items.append({
|
||||
"conversation_id": cid,
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"directory": conv.get("directory", ""),
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"file_count": len(conv.get("documents", [])),
|
||||
"history_count": len(conv.get("history", [])),
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
})
|
||||
# 按更新时间倒序
|
||||
items.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
|
||||
return items
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
Git 深度集成服务
|
||||
================
|
||||
|
||||
【功能说明】
|
||||
Git 仓库深度操作:状态查看、diff 对比、分支管理、日志、blame、自动提交。
|
||||
对应用户需求:Agent 改码后自动 commit + 可视化 diff。
|
||||
|
||||
【技术选型理由】
|
||||
1. 复用已有 git_tools(只读+写操作),统一入口;
|
||||
2. 支持按任务分支隔离,改码自动 commit;
|
||||
3. diff 对比供前端可视化展示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from app.tools.path_guard import ensure_under_root
|
||||
|
||||
logger = logging.getLogger("agent.git_deep")
|
||||
|
||||
|
||||
def git_status(repo_path: str) -> dict:
|
||||
"""查看工作区状态。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git 操作")
|
||||
result = subprocess.run(
|
||||
["git", "status", "--short"],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout or "(工作区干净)"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def git_diff(repo_path: str, file_path: str = "") -> dict:
|
||||
"""查看工作区 diff(相对 HEAD)。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git diff")
|
||||
cmd = ["git", "diff", "HEAD"]
|
||||
if file_path:
|
||||
cmd.append(file_path)
|
||||
result = subprocess.run(
|
||||
cmd, cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||
)
|
||||
return {"success": True, "diff": result.stdout[:10000] or "(无差异)"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def git_commit(repo_path: str, message: str, task_id: str = "") -> dict:
|
||||
"""提交工作区改动(自动 add -A + commit)。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git 提交")
|
||||
subprocess.run(["git", "add", "-A"], cwd=str(root), capture_output=True, timeout=15)
|
||||
result = subprocess.run(
|
||||
["git", "commit", "-m", message],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
commit_hash = subprocess.run(
|
||||
["git", "rev-parse", "--short", "HEAD"],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
|
||||
).stdout.strip()
|
||||
return {"success": True, "commit_hash": commit_hash, "message": f"提交成功:{commit_hash}"}
|
||||
return {"success": False, "message": result.stderr or "提交失败"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def git_log(repo_path: str, limit: int = 20) -> dict:
|
||||
"""查看提交日志。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git log")
|
||||
result = subprocess.run(
|
||||
["git", "log", f"--max-count={limit}", "--oneline", "--graph"],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout or "(无提交记录)"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def git_branch(repo_path: str) -> dict:
|
||||
"""查看分支列表。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git branch")
|
||||
result = subprocess.run(
|
||||
["git", "branch", "-a"],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout or "(无分支信息)"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def git_blame(repo_path: str, file_path: str) -> dict:
|
||||
"""查看文件逐行变更记录(blame)。"""
|
||||
try:
|
||||
root = ensure_under_root(Path(repo_path), "Git blame")
|
||||
result = subprocess.run(
|
||||
["git", "blame", file_path],
|
||||
cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
|
||||
)
|
||||
return {"success": True, "output": result.stdout[:5000] or "(无记录)"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
Git 读取服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
封装对本地 Git 仓库的只读操作:读取分支列表、校验分支是否存在、
|
||||
读取仓库当前状态摘要。供项目管理 API 展示「前端/后端仓库分支」下拉框使用。
|
||||
|
||||
【技术选型理由】
|
||||
1. 决策点 12/13 已锁定「本地 Git 管理 + 真实分支语义」——分支必须来自
|
||||
真实 git 仓库,不能是自由文本标签,所以用 subprocess 调本机 git CLI。
|
||||
2. 不用 GitPython / pygit2:多一层原生依赖与编译风险,subprocess 足够
|
||||
且行为与你在 PyCharm/终端里看到的完全一致,便于教学对照。
|
||||
3. 只做只读操作(分支列表/校验):写操作(checkout/commit)属于
|
||||
代码修改链路(M4/M5),届时通过白名单执行器统一收口,本模块不越权。
|
||||
|
||||
【实现思路】
|
||||
- 所有命令用 list 参数传参(不经 shell 字符串拼接),杜绝命令注入;
|
||||
- 强制 subprocess 工作目录为传入的仓库路径,不信任环境变量里的 cwd;
|
||||
- 统一超时与输出截断,避免 git 卡死拖垮 API。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:目标路径不是 git 仓库(用户填错路径)。
|
||||
应对:捕获 git 返回码非 0,转成结构化「不是 Git 仓库」业务错误,
|
||||
绝不让 API 500。
|
||||
风险2:git 命令不存在(未安装)。
|
||||
应对:捕获 FileNotFoundError,返回「未检测到 git 命令,请先安装」。
|
||||
风险3:仓库损坏 / 文件锁冲突导致 git 长时间阻塞。
|
||||
应对:强制 timeout=15s,超时返回明确提示,不无限等待。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class GitError(RuntimeError):
|
||||
"""Git 操作失败的统一业务异常(带中文可读信息)"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "GitError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
class GitReadService:
|
||||
"""Git 只读服务(一期:分支列表与校验)"""
|
||||
|
||||
def __init__(self, timeout_seconds: int = 15) -> None:
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
def _run_git(self, repo_path: Path, args: list[str]) -> str:
|
||||
"""
|
||||
在指定仓库目录执行 git 子命令,返回 stdout 文本。
|
||||
|
||||
【安全要点】args 用 list 传参,绝不拼接 shell 字符串,防命令注入。
|
||||
"""
|
||||
if not Path(repo_path).exists():
|
||||
raise GitError(
|
||||
f"代码路径不存在:{repo_path}", error_type="PathNotFound"
|
||||
)
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=str(repo_path),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=self._timeout,
|
||||
shell=False,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
raise GitError(
|
||||
"未检测到 git 命令,请先安装 Git 并加入 PATH", error_type="GitNotFound"
|
||||
) from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise GitError(
|
||||
f"git 命令执行超时(>{self._timeout}秒):git {' '.join(args)}",
|
||||
error_type="GitTimeout",
|
||||
) from exc
|
||||
|
||||
if completed.returncode != 0:
|
||||
stderr = (completed.stderr or "").strip()
|
||||
raise GitError(
|
||||
f"git 命令执行失败(退出码 {completed.returncode}):{stderr[:500]}",
|
||||
error_type="GitCommandFailed",
|
||||
)
|
||||
return completed.stdout or ""
|
||||
|
||||
def is_git_repo(self, repo_path: Path) -> bool:
|
||||
"""判断指定路径是否是 git 仓库(含子目录)。"""
|
||||
try:
|
||||
out = self._run_git(repo_path, ["rev-parse", "--is-inside-work-tree"])
|
||||
return out.strip().lower() == "true"
|
||||
except GitError:
|
||||
return False
|
||||
|
||||
def list_branches(self, repo_path: Path) -> list[str]:
|
||||
"""
|
||||
列出仓库全部本地分支名。
|
||||
|
||||
【返回】分支名列表(不含星号前缀),按字母序去重。
|
||||
"""
|
||||
out = self._run_git(repo_path, ["branch", "--format=%(refname:short)"])
|
||||
branches = [line.strip() for line in out.splitlines() if line.strip()]
|
||||
return sorted(set(branches))
|
||||
|
||||
def branch_exists(self, repo_path: Path, branch_name: str) -> bool:
|
||||
"""校验指定分支是否存在(供前端下拉框与校验使用)。"""
|
||||
try:
|
||||
self._run_git(
|
||||
repo_path,
|
||||
["rev-parse", "--verify", "--quiet", f"refs/heads/{branch_name}"],
|
||||
)
|
||||
return True
|
||||
except GitError:
|
||||
return False
|
||||
|
||||
def current_branch(self, repo_path: Path) -> str:
|
||||
"""读取仓库当前所在分支名(HEAD 指向)。"""
|
||||
out = self._run_git(repo_path, ["rev-parse", "--abbrev-ref", "HEAD"])
|
||||
return out.strip() or "HEAD"
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
健康检查服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
全链路健康探活:服务自身、模型连接、向量库、SQLite、Git、磁盘空间。
|
||||
供运维监控、前端状态栏、外部监控系统调用。
|
||||
|
||||
【技术选型理由】
|
||||
1. 各组件独立探测,单项失败不影响整体(级联失败隔离);
|
||||
2. 返回结构化结果:status / latency_ms / message,便于机器解析;
|
||||
3. 缓存探测结果(30 秒),防止高频健康检查压垮依赖服务。
|
||||
|
||||
【实现思路】
|
||||
- check_all():并发探测全部组件 → 汇总健康状态;
|
||||
- 各子检查独立 try/except,失败降级为 unhealthy 不抛异常。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.config.settings import load_settings
|
||||
|
||||
logger = logging.getLogger("agent.health")
|
||||
|
||||
|
||||
def _check_service() -> dict:
|
||||
"""检查服务自身状态。"""
|
||||
return {
|
||||
"name": "service",
|
||||
"status": "healthy",
|
||||
"message": "服务运行中",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
|
||||
|
||||
def _check_database() -> dict:
|
||||
"""检查 SQLite 数据库连通性。"""
|
||||
start = time.time()
|
||||
try:
|
||||
settings = load_settings()
|
||||
db_path = settings.sqlite_db_path
|
||||
if not db_path.exists():
|
||||
return {
|
||||
"name": "database",
|
||||
"status": "degraded",
|
||||
"message": f"数据库文件不存在:{db_path}",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
conn = sqlite3.connect(str(db_path), timeout=3)
|
||||
try:
|
||||
conn.execute("SELECT 1")
|
||||
finally:
|
||||
# 【修复】close 必须在 finally,否则 execute 抛异常时连接泄漏
|
||||
conn.close()
|
||||
return {
|
||||
"name": "database",
|
||||
"status": "healthy",
|
||||
"message": "SQLite 连接正常",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {
|
||||
"name": "database",
|
||||
"status": "unhealthy",
|
||||
"message": f"数据库连接失败:{exc}",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
|
||||
|
||||
def _check_vectorstore() -> dict:
|
||||
"""检查向量库(Chroma)状态。"""
|
||||
start = time.time()
|
||||
try:
|
||||
settings = load_settings()
|
||||
chroma_dir = settings.chroma_dir
|
||||
if not chroma_dir.exists():
|
||||
return {
|
||||
"name": "vectorstore",
|
||||
"status": "degraded",
|
||||
"message": "向量库目录不存在",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
db_file = chroma_dir / "chroma.sqlite3"
|
||||
if not db_file.exists():
|
||||
return {
|
||||
"name": "vectorstore",
|
||||
"status": "degraded",
|
||||
"message": "向量库尚未初始化",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
return {
|
||||
"name": "vectorstore",
|
||||
"status": "healthy",
|
||||
"message": f"Chroma 就绪({db_file.stat().st_size // 1024}KB)",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {
|
||||
"name": "vectorstore",
|
||||
"status": "unhealthy",
|
||||
"message": f"向量库异常:{exc}",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
|
||||
|
||||
def _check_model_api() -> dict:
|
||||
"""检查模型服务连通性(ccswitch 代理)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
import httpx
|
||||
|
||||
settings = load_settings()
|
||||
if not settings.ccswitch_api_key:
|
||||
return {
|
||||
"name": "model_api",
|
||||
"status": "degraded",
|
||||
"message": "未配置 ccswitch 代理密钥",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
# 轻量探测:GET /models(不消耗 token)
|
||||
resp = httpx.get(
|
||||
f"{settings.ccswitch_base_url}/models",
|
||||
headers={"Authorization": f"Bearer {settings.ccswitch_api_key}"},
|
||||
timeout=5.0,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return {
|
||||
"name": "model_api",
|
||||
"status": "healthy",
|
||||
"message": "模型服务连接正常(ccswitch)",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
return {
|
||||
"name": "model_api",
|
||||
"status": "unhealthy",
|
||||
"message": f"模型服务返回 {resp.status_code}",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {
|
||||
"name": "model_api",
|
||||
"status": "unhealthy",
|
||||
"message": f"模型服务连接失败:{exc}",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
|
||||
|
||||
def _check_git() -> dict:
|
||||
"""检查 Git 可用性。"""
|
||||
start = time.time()
|
||||
git_path = shutil.which("git")
|
||||
if not git_path:
|
||||
return {
|
||||
"name": "git",
|
||||
"status": "unhealthy",
|
||||
"message": "git 命令未找到",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
return {
|
||||
"name": "git",
|
||||
"status": "healthy",
|
||||
"message": f"Git 可用({git_path})",
|
||||
"latency_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
|
||||
|
||||
def _check_disk() -> dict:
|
||||
"""检查磁盘空间。"""
|
||||
try:
|
||||
settings = load_settings()
|
||||
data_root = settings.data_root
|
||||
usage = shutil.disk_usage(str(data_root))
|
||||
free_gb = usage.free / (1024**3)
|
||||
total_gb = usage.total / (1024**3)
|
||||
pct = usage.used / usage.total * 100
|
||||
|
||||
if free_gb < 1:
|
||||
status = "unhealthy"
|
||||
msg = f"磁盘空间严重不足:剩余 {free_gb:.1f}GB"
|
||||
elif pct > 90:
|
||||
status = "degraded"
|
||||
msg = f"磁盘使用率 {pct:.1f}%,建议清理"
|
||||
else:
|
||||
status = "healthy"
|
||||
msg = f"磁盘 {usage.used / (1024**3):.1f}GB / {total_gb:.1f}GB({pct:.1f}%)"
|
||||
|
||||
return {"name": "disk", "status": status, "message": msg, "latency_ms": 0}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {
|
||||
"name": "disk",
|
||||
"status": "unhealthy",
|
||||
"message": f"磁盘检查失败:{exc}",
|
||||
"latency_ms": 0,
|
||||
}
|
||||
|
||||
|
||||
def check_all() -> dict:
|
||||
"""
|
||||
全链路健康检查。
|
||||
|
||||
【返回】{status, checks: [{name, status, message, latency_ms}], timestamp}
|
||||
"""
|
||||
checks = [
|
||||
_check_service(),
|
||||
_check_database(),
|
||||
_check_vectorstore(),
|
||||
_check_model_api(),
|
||||
_check_git(),
|
||||
_check_disk(),
|
||||
]
|
||||
|
||||
# 汇总状态:任一 unhealthy → unhealthy;任一 degraded → degraded
|
||||
statuses = [c["status"] for c in checks]
|
||||
if "unhealthy" in statuses:
|
||||
overall = "unhealthy"
|
||||
elif "degraded" in statuses:
|
||||
overall = "degraded"
|
||||
else:
|
||||
overall = "healthy"
|
||||
|
||||
return {
|
||||
"status": overall,
|
||||
"checks": checks,
|
||||
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"healthy_count": sum(1 for c in checks if c["status"] == "healthy"),
|
||||
"total_count": len(checks),
|
||||
}
|
||||
|
||||
|
||||
from datetime import datetime # noqa: E402
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
知识库自动更新服务
|
||||
==================
|
||||
|
||||
【功能说明】
|
||||
监控素材目录变化,自动重新解析和向量化变更的文档。
|
||||
对应功能 21:知识库保持与文档同步。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选文件哈希对比(MD5)检测变更:比 mtime 可靠,比轮询高效;
|
||||
2. 增量更新:只重新处理变更的文件,不全量重建;
|
||||
3. 支持手动触发和定时检查。
|
||||
|
||||
【实现思路】
|
||||
- check_and_update():对比文件哈希,变更的重新入库;
|
||||
- 定时循环每 N 分钟检查一次;
|
||||
- 维护文件哈希表(JSON 文件持久化)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from app.config.settings import load_settings
|
||||
|
||||
logger = logging.getLogger("agent.knowledge.auto_update")
|
||||
|
||||
# 文件哈希表(检测变更用)
|
||||
HASH_FILE = Path(r"D:\Agent\agent\data\knowledge_hashes.json")
|
||||
|
||||
|
||||
def _load_hashes() -> dict[str, str]:
|
||||
if not HASH_FILE.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(HASH_FILE.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_hashes(hashes: dict[str, str]) -> None:
|
||||
HASH_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
HASH_FILE.write_text(json.dumps(hashes, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _file_hash(path: Path) -> str:
|
||||
"""计算文件 MD5 哈希。"""
|
||||
try:
|
||||
return hashlib.md5(path.read_bytes()).hexdigest()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def check_and_update() -> dict:
|
||||
"""
|
||||
检查素材目录变更并自动更新知识库。
|
||||
|
||||
【返回】{changed: [文件名], total_files, message}
|
||||
"""
|
||||
settings = load_settings()
|
||||
scan_dir = settings.project_root / "需向量化数据"
|
||||
if not scan_dir.exists():
|
||||
return {"changed": [], "total_files": 0, "message": f"目录不存在:{scan_dir}"}
|
||||
|
||||
from app.knowledge.document_loader import SUPPORTED_EXTENSIONS
|
||||
|
||||
current_hashes = _load_hashes()
|
||||
new_hashes: dict[str, str] = {}
|
||||
changed_files: list[str] = []
|
||||
|
||||
# 扫描目录
|
||||
for f in scan_dir.rglob("*"):
|
||||
if not f.is_file() or f.suffix.lower() not in SUPPORTED_EXTENSIONS:
|
||||
continue
|
||||
key = str(f)
|
||||
h = _file_hash(f)
|
||||
new_hashes[key] = h
|
||||
if current_hashes.get(key) != h:
|
||||
changed_files.append(f.name)
|
||||
|
||||
# 找删除的文件
|
||||
deleted_keys = set(current_hashes) - set(new_hashes)
|
||||
|
||||
if not changed_files and not deleted_keys:
|
||||
_save_hashes(new_hashes)
|
||||
return {
|
||||
"changed": [],
|
||||
"total_files": len(new_hashes),
|
||||
"message": "无变更",
|
||||
}
|
||||
|
||||
# 有变更:更新知识库
|
||||
try:
|
||||
from app.knowledge.embeddings import get_embedding_provider
|
||||
from app.knowledge.knowledge_service import KnowledgeService
|
||||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||
|
||||
provider = get_embedding_provider(
|
||||
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||
)
|
||||
vs = KnowledgeVectorStore(
|
||||
persist_dir=settings.chroma_dir,
|
||||
collection_name=settings.chroma_collection_name,
|
||||
embedding_provider=provider,
|
||||
)
|
||||
service = KnowledgeService(vs, provider)
|
||||
|
||||
# 全量重建(简单可靠,增量替换后续优化)
|
||||
result = service.ingest_directory(scan_dir)
|
||||
|
||||
_save_hashes(new_hashes)
|
||||
|
||||
return {
|
||||
"changed": changed_files,
|
||||
"deleted": list(deleted_keys),
|
||||
"total_files": len(new_hashes),
|
||||
"ingested_chunks": result.get("ingested_chunks", 0),
|
||||
"message": f"知识库已更新:{len(changed_files)} 个文件变更",
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("自动更新失败")
|
||||
return {
|
||||
"changed": changed_files,
|
||||
"total_files": len(new_hashes),
|
||||
"message": f"更新失败:{exc}",
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
知识图谱服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
从文档中抽取实体与关系,构建轻量知识图谱,支持图查询。
|
||||
对应功能 23:深度理解文档语义关系。
|
||||
|
||||
【技术选型理由】
|
||||
1. 轻量图存储(SQLite 三元组),免 Neo4j 等外部依赖;
|
||||
2. LLM 驱动的实体关系抽取;
|
||||
3. 支持实体查询、关系查询、路径查询。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app.models.model_router import get_model_for_task
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.knowledge_graph")
|
||||
|
||||
|
||||
class KnowledgeGraphStore:
|
||||
"""知识图谱存储(三元组模型)"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS knowledge_triple (
|
||||
id TEXT PRIMARY KEY,
|
||||
subject TEXT NOT NULL,
|
||||
predicate TEXT NOT NULL,
|
||||
object TEXT NOT NULL,
|
||||
source TEXT DEFAULT '',
|
||||
confidence REAL DEFAULT 1.0,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_kg_subject ON knowledge_triple(subject);
|
||||
CREATE INDEX IF NOT EXISTS idx_kg_object ON knowledge_triple(object);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.executescript(ddl)
|
||||
conn.commit()
|
||||
|
||||
def add_triple(self, subject: str, predicate: str, obj: str, source: str = "", confidence: float = 1.0) -> str:
|
||||
"""添加一个三元组。"""
|
||||
triple_id = f"kg_{uuid.uuid4().hex[:8]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO knowledge_triple (id, subject, predicate, object, source, confidence, created_at) VALUES (?,?,?,?,?,?,?)",
|
||||
(triple_id, subject, predicate, obj, source, confidence, now),
|
||||
)
|
||||
conn.commit()
|
||||
return triple_id
|
||||
|
||||
def query_by_subject(self, subject: str) -> list[dict]:
|
||||
"""按主语查询关系。"""
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_triple WHERE subject = ? ORDER BY confidence DESC",
|
||||
(subject,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def query_by_object(self, obj: str) -> list[dict]:
|
||||
"""按宾语查询关系。"""
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_triple WHERE object = ? ORDER BY confidence DESC",
|
||||
(obj,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def query_relation(self, predicate: str) -> list[dict]:
|
||||
"""按关系查询。"""
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_triple WHERE predicate LIKE ? ORDER BY confidence DESC",
|
||||
(f"%{predicate}%",),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def search_entities(self, keyword: str, limit: int = 20) -> list[dict]:
|
||||
"""搜索实体(主语或宾语含关键词)。"""
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"""SELECT DISTINCT subject AS entity FROM knowledge_triple WHERE subject LIKE ?
|
||||
UNION
|
||||
SELECT DISTINCT object AS entity FROM knowledge_triple WHERE object LIKE ? LIMIT ?""",
|
||||
(f"%{keyword}%", f"%{keyword}%", limit),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def get_graph_stats(self) -> dict:
|
||||
"""获取图谱统计。"""
|
||||
with self._conn() as conn:
|
||||
triple_count = conn.execute("SELECT COUNT(*) FROM knowledge_triple").fetchone()[0]
|
||||
subject_count = conn.execute("SELECT COUNT(DISTINCT subject) FROM knowledge_triple").fetchone()[0]
|
||||
predicate_count = conn.execute("SELECT COUNT(DISTINCT predicate) FROM knowledge_triple").fetchone()[0]
|
||||
return {
|
||||
"triples": triple_count,
|
||||
"entities": subject_count,
|
||||
"relations": predicate_count,
|
||||
}
|
||||
|
||||
|
||||
def extract_triples(text: str, source: str = "", model_preference: str = "auto") -> dict:
|
||||
"""
|
||||
从文本中抽取实体关系三元组(LLM 驱动)。
|
||||
|
||||
【返回】{triples: [{subject, predicate, object}], count}
|
||||
"""
|
||||
prompt = f"""从下面的文本中抽取实体和关系,输出 JSON 三元组数组。
|
||||
|
||||
【文本】
|
||||
{text[:3000]}
|
||||
|
||||
【输出格式】
|
||||
只输出 JSON 数组,每个元素:
|
||||
[{{"subject": "实体1", "predicate": "关系", "object": "实体2"}}]
|
||||
|
||||
示例:
|
||||
[{{"subject": "网关", "predicate": "连接", "object": "MQTT服务器"}}]
|
||||
|
||||
只输出 JSON,不要解释。"""
|
||||
|
||||
try:
|
||||
model = get_model_for_task(model_preference, "strong")
|
||||
resp = model.invoke(prompt)
|
||||
content = resp.content if hasattr(resp, "content") else str(resp)
|
||||
|
||||
import re
|
||||
|
||||
json_match = re.search(r"\[.*\]", content, re.DOTALL)
|
||||
if json_match:
|
||||
triples = json.loads(json_match.group(0))
|
||||
if isinstance(triples, list):
|
||||
return {"triples": triples[:20], "count": len(triples), "source": source}
|
||||
return {"triples": [], "count": 0, "source": source}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("三元组抽取失败:%s", exc)
|
||||
return {"triples": [], "count": 0, "error": str(exc)}
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: KnowledgeGraphStore | None = None
|
||||
|
||||
|
||||
def get_kg_store() -> KnowledgeGraphStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
_store = KnowledgeGraphStore(settings.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,482 @@
|
||||
"""
|
||||
MCP 协议接入(框架预留)
|
||||
========================
|
||||
|
||||
【功能说明】
|
||||
MCP(Model Context Protocol)标准工具协议接入框架。
|
||||
对应功能 41:Agent 生态标准化对接。
|
||||
|
||||
【技术选型理由】
|
||||
1. MCP 是 Agent 工具接入的标准协议(Anthropic 主导);
|
||||
2. 框架化设计:支持注册/发现/调用 MCP Server 工具;
|
||||
3. 预留 httpx 传输层,可对接任意 MCP Server。
|
||||
|
||||
【实现思路】
|
||||
- McpToolRegistry:注册/查询/调用 MCP 工具;
|
||||
- 后续可接入 MCP Server(GitHub、数据库、浏览器等)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.mcp")
|
||||
|
||||
|
||||
class McpTool:
|
||||
"""MCP 工具定义"""
|
||||
|
||||
def __init__(self, name: str, description: str, input_schema: dict, server_url: str = ""):
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.input_schema = input_schema
|
||||
self.server_url = server_url
|
||||
|
||||
|
||||
class McpToolRegistry:
|
||||
"""MCP 工具注册表"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._tools: dict[str, McpTool] = {}
|
||||
|
||||
def register(self, tool: McpTool) -> None:
|
||||
self._tools[tool.name] = tool
|
||||
logger.info("MCP 工具已注册:%s", tool.name)
|
||||
|
||||
def list_tools(self) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"name": t.name,
|
||||
"description": t.description,
|
||||
"input_schema": t.input_schema,
|
||||
"server_url": t.server_url,
|
||||
}
|
||||
for t in self._tools.values()
|
||||
]
|
||||
|
||||
def get_tool(self, name: str) -> McpTool | None:
|
||||
return self._tools.get(name)
|
||||
|
||||
def call_tool(self, name: str, arguments: dict[str, Any]) -> dict:
|
||||
"""调用 MCP 工具(优先本地实现,其次 httpx 传输)。"""
|
||||
tool = self._tools.get(name)
|
||||
if tool is None:
|
||||
return {"success": False, "message": f"工具不存在:{name}"}
|
||||
|
||||
# 优先使用本地实现
|
||||
local_impl = _TOOL_IMPLEMENTATIONS.get(name)
|
||||
if local_impl:
|
||||
try:
|
||||
return local_impl(arguments)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"本地工具执行失败:{exc}"}
|
||||
|
||||
# 无本地实现:走远程 MCP Server
|
||||
if not tool.server_url:
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"工具 {name} 需要外部凭证配置(GITHUB_TOKEN/SLACK_TOKEN 等),当前未配置",
|
||||
}
|
||||
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.post(
|
||||
tool.server_url,
|
||||
json={"tool": name, "arguments": arguments},
|
||||
timeout=30.0,
|
||||
)
|
||||
return {"success": resp.status_code == 200, "data": resp.json() if resp.status_code == 200 else resp.text}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"调用失败:{exc}"}
|
||||
|
||||
|
||||
# 全局注册表
|
||||
registry = McpToolRegistry()
|
||||
|
||||
|
||||
# ========== 本地工具实现(无需外部凭证)==========
|
||||
|
||||
|
||||
def _tool_filesystem(arguments: dict) -> dict:
|
||||
"""MCP Filesystem 工具:文件读写、搜索、浏览。"""
|
||||
action = arguments.get("action", "read")
|
||||
path = arguments.get("path", "")
|
||||
try:
|
||||
p = Path(path)
|
||||
if action == "read":
|
||||
content = p.read_text(encoding="utf-8", errors="replace")[:50000]
|
||||
return {"success": True, "content": content}
|
||||
elif action == "write":
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(arguments.get("content", ""), encoding="utf-8")
|
||||
return {"success": True, "message": f"已写入 {path}"}
|
||||
elif action == "list":
|
||||
items = [
|
||||
{"name": x.name, "is_dir": x.is_dir(), "size": x.stat().st_size if x.is_file() else 0}
|
||||
for x in p.iterdir()
|
||||
]
|
||||
return {"success": True, "items": items}
|
||||
elif action == "search":
|
||||
pattern = arguments.get("pattern", "*")
|
||||
results = [
|
||||
str(x) for x in p.rglob(pattern) if x.is_file()
|
||||
][:50]
|
||||
return {"success": True, "results": results}
|
||||
else:
|
||||
return {"success": False, "message": f"不支持的操作:{action}"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_web_search(arguments: dict) -> dict:
|
||||
"""MCP WebSearch 工具:网页搜索(DuckDuckGo)。"""
|
||||
query = arguments.get("query", "")
|
||||
if not query:
|
||||
return {"success": False, "message": "query 必填"}
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.get(
|
||||
f"https://html.duckduckgo.com/html/?q={query}",
|
||||
headers={"User-Agent": "Mozilla/5.0"},
|
||||
timeout=10.0,
|
||||
)
|
||||
return {"success": True, "results": resp.text[:5000], "source": "duckduckgo"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_web_fetch(arguments: dict) -> dict:
|
||||
"""MCP WebFetch 工具:抓取网页内容。"""
|
||||
url = arguments.get("url", "")
|
||||
if not url:
|
||||
return {"success": False, "message": "url 必填"}
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.get(url, timeout=15.0, follow_redirects=True)
|
||||
return {
|
||||
"success": True,
|
||||
"status_code": resp.status_code,
|
||||
"content": resp.text[:20000],
|
||||
"content_type": resp.headers.get("content-type", ""),
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_memory(arguments: dict) -> dict:
|
||||
"""MCP Memory 工具:长期记忆存取。"""
|
||||
action = arguments.get("action", "recall")
|
||||
try:
|
||||
from app.services.memory_service import get_memory_store
|
||||
|
||||
store = get_memory_store()
|
||||
if action == "remember":
|
||||
mem_id = store.remember(
|
||||
content=arguments.get("content", ""),
|
||||
project_id=arguments.get("project_id", ""),
|
||||
category=arguments.get("category", "mcp"),
|
||||
)
|
||||
return {"success": True, "id": mem_id}
|
||||
elif action == "recall":
|
||||
items = store.recall(
|
||||
query=arguments.get("query", ""),
|
||||
project_id=arguments.get("project_id", ""),
|
||||
top_k=int(arguments.get("top_k", 5)),
|
||||
)
|
||||
return {"success": True, "memories": items}
|
||||
else:
|
||||
return {"success": False, "message": f"不支持:{action}"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_docker(arguments: dict) -> dict:
|
||||
"""MCP Docker 工具:容器管理。"""
|
||||
action = arguments.get("action", "ps")
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
cmd_map = {
|
||||
"ps": ["docker", "ps", "-a", "--format", "table {{.Names}}\t{{.Status}}\t{{.Image}}"],
|
||||
"images": ["docker", "images", "--format", "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"],
|
||||
"logs": ["docker", "logs", "--tail", "50", arguments.get("container", "")],
|
||||
"stats": ["docker", "stats", "--no-stream"],
|
||||
}
|
||||
cmd = cmd_map.get(action)
|
||||
if not cmd:
|
||||
return {"success": False, "message": f"不支持:{action}"}
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
|
||||
return {"success": result.returncode == 0, "output": result.stdout[:5000], "error": result.stderr[:500]}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_health(arguments: dict) -> dict:
|
||||
"""MCP 健康检查工具:系统全链路探活。"""
|
||||
try:
|
||||
from app.services.health_service import check_all
|
||||
|
||||
return {"success": True, "health": check_all()}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_zentao(arguments: dict) -> dict:
|
||||
"""禅道项目管理工具。"""
|
||||
try:
|
||||
from app.services.zentao_service import get_zentao_service
|
||||
|
||||
service = get_zentao_service()
|
||||
action = arguments.get("action", "search")
|
||||
|
||||
if action == "create_bug":
|
||||
result = service.create_bug(
|
||||
title=arguments.get("title", ""),
|
||||
description=arguments.get("description", ""),
|
||||
project_id=arguments.get("project_id", ""),
|
||||
)
|
||||
return result
|
||||
elif action == "create_task":
|
||||
result = service.create_task(
|
||||
title=arguments.get("title", ""),
|
||||
description=arguments.get("description", ""),
|
||||
project_id=arguments.get("project_id", ""),
|
||||
)
|
||||
return result
|
||||
elif action == "search":
|
||||
result = service.search(keyword=arguments.get("title", ""))
|
||||
return result
|
||||
elif action == "update_status":
|
||||
result = service.update_status(
|
||||
issue_id=arguments.get("issue_id", ""),
|
||||
status=arguments.get("status", "done"),
|
||||
)
|
||||
return result
|
||||
else:
|
||||
return {"success": False, "message": f"不支持:{action}"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
def _tool_git(arguments: dict) -> dict:
|
||||
"""Git 深度集成工具。"""
|
||||
try:
|
||||
from app.tools.git_tools import get_diff, ensure_task_branch, commit_changes
|
||||
|
||||
action = arguments.get("action", "status")
|
||||
repo_path = arguments.get("repo_path", "")
|
||||
|
||||
if action == "diff":
|
||||
result = get_diff(repo_path)
|
||||
return {"success": True, **result}
|
||||
elif action == "status":
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["git", "status", "--short"],
|
||||
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout}
|
||||
elif action == "commit":
|
||||
result = commit_changes(
|
||||
repo_path,
|
||||
message=arguments.get("message", "自动提交"),
|
||||
task_id=arguments.get("task_id", ""),
|
||||
)
|
||||
return {"success": True, **result}
|
||||
elif action == "log":
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["git", "log", "--oneline", "-20"],
|
||||
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout}
|
||||
elif action == "branch":
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["git", "branch", "-a"],
|
||||
cwd=repo_path, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
)
|
||||
return {"success": True, "output": result.stdout}
|
||||
else:
|
||||
return {"success": False, "message": f"不支持:{action}"}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
# ========== 工具实现映射 ==========
|
||||
_TOOL_IMPLEMENTATIONS = {
|
||||
"filesystem": _tool_filesystem,
|
||||
"web_search": _tool_web_search,
|
||||
"web_fetch": _tool_web_fetch,
|
||||
"memory": _tool_memory,
|
||||
"docker": _tool_docker,
|
||||
"health_check": _tool_health,
|
||||
"zentao": _tool_zentao,
|
||||
"git": _tool_git,
|
||||
}
|
||||
|
||||
|
||||
# ========== 注册全部工具 ==========
|
||||
|
||||
registry.register(McpTool(
|
||||
name="filesystem",
|
||||
description="文件系统操作(读/写/列目录/搜索)",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["read", "write", "list", "search"]},
|
||||
"path": {"type": "string"},
|
||||
"content": {"type": "string"},
|
||||
"pattern": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="web_search",
|
||||
description="网页搜索(DuckDuckGo)",
|
||||
input_schema={"type": "object", "properties": {"query": {"type": "string"}}},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="web_fetch",
|
||||
description="抓取网页内容",
|
||||
input_schema={"type": "object", "properties": {"url": {"type": "string"}}},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="memory",
|
||||
description="长期记忆(存取项目约定、决策、规范)",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["remember", "recall"]},
|
||||
"content": {"type": "string"},
|
||||
"query": {"type": "string"},
|
||||
"project_id": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="docker",
|
||||
description="Docker 容器管理(ps/images/logs/stats)",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["ps", "images", "logs", "stats"]},
|
||||
"container": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="health_check",
|
||||
description="系统健康检查(全链路探活)",
|
||||
input_schema={"type": "object", "properties": {}},
|
||||
))
|
||||
|
||||
# ========== 需要凭证的工具(框架就绪)==========
|
||||
|
||||
registry.register(McpTool(
|
||||
name="github",
|
||||
description="GitHub 操作(PR/Issue/仓库)— 需要 GITHUB_TOKEN",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["create_pr", "list_issues", "create_issue", "get_repo"]},
|
||||
"repo": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
"body": {"type": "string"},
|
||||
},
|
||||
},
|
||||
server_url="", # 需配置
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="zentao",
|
||||
description="禅道项目管理(创建/查询/更新 Bug 和任务)",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["create_bug", "create_task", "search", "update_status"]},
|
||||
"title": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
"project_id": {"type": "string"},
|
||||
"issue_id": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="git",
|
||||
description="Git 深度集成(commit/diff/branch/log/blame)",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["status", "diff", "commit", "log", "branch", "blame"]},
|
||||
"repo_path": {"type": "string"},
|
||||
"message": {"type": "string"},
|
||||
"file_path": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="jira",
|
||||
description="Jira 任务管理(创建/查询/更新)— 需要 JIRA_TOKEN",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["create_issue", "search", "update"]},
|
||||
"project": {"type": "string"},
|
||||
"summary": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="redis",
|
||||
description="Redis 缓存操作(GET/SET/DEL)— 需要 Redis 连接",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["get", "set", "del", "keys"]},
|
||||
"key": {"type": "string"},
|
||||
"value": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="database",
|
||||
description="通用数据库查询(SQL)— 需要数据库连接",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"connection_id": {"type": "string"},
|
||||
"sql": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
registry.register(McpTool(
|
||||
name="email",
|
||||
description="邮件发送(SMTP)— 需要邮箱凭证",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"to": {"type": "string"},
|
||||
"subject": {"type": "string"},
|
||||
"body": {"type": "string"},
|
||||
},
|
||||
},
|
||||
))
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
长期记忆服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
记住项目约定、编码规范、历史决策,供 Agent 执行时智能召回。
|
||||
对应功能 20:Agent 越用越准的关键。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选 SQLite + 向量检索:结构化存储 + 语义召回,兼顾精确与模糊;
|
||||
2. 按项目隔离记忆(namespace),多项目互不干扰;
|
||||
3. 写入即向量化,下次执行时按相关性召回 top-k。
|
||||
|
||||
【实现思路】
|
||||
- remember():记录一条记忆(约定/规范/决策);
|
||||
- recall():按任务描述召回相关记忆;
|
||||
- list_memories():列出项目全部记忆。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.memory")
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
"""长期记忆存储"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS memory (
|
||||
id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL DEFAULT '',
|
||||
category TEXT NOT NULL DEFAULT 'general',
|
||||
content TEXT NOT NULL,
|
||||
source TEXT DEFAULT '',
|
||||
tags TEXT DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
def remember(
|
||||
self,
|
||||
content: str,
|
||||
project_id: str = "",
|
||||
category: str = "general",
|
||||
source: str = "",
|
||||
tags: list[str] | None = None,
|
||||
) -> str:
|
||||
"""记录一条长期记忆。"""
|
||||
mem_id = f"mem_{uuid.uuid4().hex[:12]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO memory (id, project_id, category, content, source, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(mem_id, project_id, category, content, source, json.dumps(tags or [], ensure_ascii=False), now, now),
|
||||
)
|
||||
conn.commit()
|
||||
logger.info("记忆已保存:%s(%s)", mem_id, category)
|
||||
return mem_id
|
||||
|
||||
def recall(self, query: str, project_id: str = "", top_k: int = 5) -> list[dict]:
|
||||
"""
|
||||
按查询召回相关记忆。
|
||||
|
||||
【策略】先精确匹配关键词,再按时间倒序补充,确保相关记忆被召回。
|
||||
"""
|
||||
keywords = [w for w in query.split() if len(w) >= 2][:5]
|
||||
results = []
|
||||
|
||||
with self._conn() as conn:
|
||||
if keywords:
|
||||
# 关键词匹配
|
||||
conditions = " OR ".join(["content LIKE ?"] * len(keywords))
|
||||
params = [f"%{k}%" for k in keywords]
|
||||
sql = f"SELECT * FROM memory WHERE ({conditions})"
|
||||
if project_id:
|
||||
sql += " AND (project_id = ? OR project_id = '')"
|
||||
params.append(project_id)
|
||||
sql += " ORDER BY updated_at DESC LIMIT ?"
|
||||
params.append(top_k)
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
results = [dict(r) for r in rows]
|
||||
|
||||
if not results:
|
||||
# 回退:取最近的记忆
|
||||
sql = "SELECT * FROM memory"
|
||||
params = []
|
||||
if project_id:
|
||||
sql += " WHERE project_id = ? OR project_id = ''"
|
||||
params.append(project_id)
|
||||
sql += " ORDER BY updated_at DESC LIMIT ?"
|
||||
params.append(top_k)
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
results = [dict(r) for r in rows]
|
||||
|
||||
return results
|
||||
|
||||
def list_memories(self, project_id: str = "", category: str = "") -> list[dict]:
|
||||
"""列出记忆(可按项目/分类筛选)。"""
|
||||
sql = "SELECT * FROM memory"
|
||||
conditions = []
|
||||
params = []
|
||||
if project_id:
|
||||
conditions.append("project_id = ?")
|
||||
params.append(project_id)
|
||||
if category:
|
||||
conditions.append("category = ?")
|
||||
params.append(category)
|
||||
if conditions:
|
||||
sql += " WHERE " + " AND ".join(conditions)
|
||||
sql += " ORDER BY updated_at DESC"
|
||||
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def delete(self, mem_id: str) -> bool:
|
||||
with self._conn() as conn:
|
||||
cursor = conn.execute("DELETE FROM memory WHERE id = ?", (mem_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: MemoryStore | None = None
|
||||
|
||||
|
||||
def get_memory_store() -> MemoryStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
_store = MemoryStore(settings.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,397 @@
|
||||
"""
|
||||
指标采集与统计服务
|
||||
==================
|
||||
|
||||
【功能说明】
|
||||
采集模型调用指标(token 消耗、延迟、成本)、任务执行指标、系统指标,
|
||||
供监控仪表盘、成本统计、性能分析使用。
|
||||
|
||||
【技术选型理由】
|
||||
1. 轻量 JSON 文件存储(单机场景够用,免额外基础设施);
|
||||
2. 调用方只需一行 record_model_call(),无侵入;
|
||||
3. 统计接口支持按日期/模型/维度聚合。
|
||||
|
||||
【实现思路】
|
||||
- record_model_call():记录每次模型调用(token、延迟、模型名);
|
||||
- record_task():记录任务执行(耗时、状态、步骤数);
|
||||
- get_dashboard():聚合统计供仪表盘展示;
|
||||
- 指标存 D:\\Agent\\agent\\data\\metrics.jsonl(追加式 JSONL)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.metrics")
|
||||
|
||||
# 指标文件
|
||||
METRICS_FILE = Path(r"D:\Agent\agent\data\metrics.jsonl")
|
||||
_lock = threading.Lock()
|
||||
|
||||
# 模型定价(每千 token,单位:元)—— 行业均价估算
|
||||
MODEL_PRICING = {
|
||||
"mimo-v2.6-pro": {"input": 0.002, "output": 0.008},
|
||||
"mimo-v2.6-flash": {"input": 0.0005, "output": 0.002},
|
||||
"glm-5.3": {"input": 0.002, "output": 0.008},
|
||||
"glm-5.3-flash": {"input": 0.0005, "output": 0.002},
|
||||
"default": {"input": 0.002, "output": 0.008},
|
||||
}
|
||||
|
||||
|
||||
def _get_price(model_name: str) -> dict:
|
||||
"""获取模型定价(未匹配则用默认价)。"""
|
||||
for key, price in MODEL_PRICING.items():
|
||||
if key != "default" and key.lower() in model_name.lower():
|
||||
return price
|
||||
return MODEL_PRICING["default"]
|
||||
|
||||
|
||||
def record_model_call(
|
||||
model_name: str,
|
||||
provider: str = "",
|
||||
input_tokens: int = 0,
|
||||
output_tokens: int = 0,
|
||||
latency_ms: float = 0,
|
||||
success: bool = True,
|
||||
task_id: str = "",
|
||||
) -> None:
|
||||
"""
|
||||
记录一次模型调用(异步追加,不阻塞主流程)。
|
||||
|
||||
【参数】provider:所属 Provider(如 ccswitch / zhipu),供按平台聚合用量。
|
||||
【安全】写入失败只记日志,不影响业务。
|
||||
"""
|
||||
try:
|
||||
price = _get_price(model_name)
|
||||
cost = (input_tokens / 1000 * price["input"]) + (output_tokens / 1000 * price["output"])
|
||||
entry = {
|
||||
"type": "model_call",
|
||||
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"model": model_name,
|
||||
"provider": provider,
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"total_tokens": input_tokens + output_tokens,
|
||||
"latency_ms": round(latency_ms, 1),
|
||||
"success": success,
|
||||
"cost": round(cost, 6),
|
||||
"task_id": task_id,
|
||||
}
|
||||
with _lock:
|
||||
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(METRICS_FILE, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("指标写入失败:%s", exc)
|
||||
|
||||
|
||||
def record_task(
|
||||
task_id: str,
|
||||
duration_s: float = 0,
|
||||
status: str = "done",
|
||||
steps: int = 0,
|
||||
project_id: str = "",
|
||||
) -> None:
|
||||
"""记录任务执行指标。"""
|
||||
try:
|
||||
entry = {
|
||||
"type": "task",
|
||||
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"task_id": task_id,
|
||||
"duration_s": round(duration_s, 1),
|
||||
"status": status,
|
||||
"steps": steps,
|
||||
"project_id": project_id,
|
||||
}
|
||||
with _lock:
|
||||
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(METRICS_FILE, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("指标写入失败:%s", exc)
|
||||
|
||||
|
||||
def _read_metrics(hours: int = 24) -> list[dict]:
|
||||
"""读取最近 N 小时的指标。"""
|
||||
if not METRICS_FILE.exists():
|
||||
return []
|
||||
cutoff = datetime.now().astimezone() - timedelta(hours=hours)
|
||||
results = []
|
||||
try:
|
||||
with open(METRICS_FILE, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
ts = entry.get("timestamp", "")
|
||||
if ts and datetime.fromisoformat(ts) >= cutoff:
|
||||
results.append(entry)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("读取指标失败:%s", exc)
|
||||
return results
|
||||
|
||||
|
||||
def get_dashboard(hours: int = 24) -> dict:
|
||||
"""
|
||||
获取监控仪表盘数据(最近 N 小时)。
|
||||
|
||||
【返回】
|
||||
model_stats: 按模型聚合的 token/成本/延迟/调用次数
|
||||
task_stats: 任务状态分布、平均耗时
|
||||
totals: 总 token / 总成本 / 总调用次数
|
||||
"""
|
||||
entries = _read_metrics(hours)
|
||||
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||
task_calls = [e for e in entries if e.get("type") == "task"]
|
||||
|
||||
# 按模型聚合
|
||||
model_stats: dict[str, dict] = {}
|
||||
provider_stats: dict[str, dict] = {}
|
||||
for e in model_calls:
|
||||
name = e.get("model", "unknown")
|
||||
provider = e.get("provider") or "unknown"
|
||||
|
||||
# 按模型聚合
|
||||
if name not in model_stats:
|
||||
model_stats[name] = {
|
||||
"model": name,
|
||||
"provider": provider,
|
||||
"calls": 0,
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"total_tokens": 0,
|
||||
"cost": 0.0,
|
||||
"total_latency_ms": 0.0,
|
||||
"success_count": 0,
|
||||
}
|
||||
m = model_stats[name]
|
||||
m["calls"] += 1
|
||||
m["input_tokens"] += e.get("input_tokens", 0)
|
||||
m["output_tokens"] += e.get("output_tokens", 0)
|
||||
m["total_tokens"] += e.get("total_tokens", 0)
|
||||
m["cost"] += e.get("cost", 0)
|
||||
m["total_latency_ms"] += e.get("latency_ms", 0)
|
||||
if e.get("success"):
|
||||
m["success_count"] += 1
|
||||
|
||||
# 按 Provider 聚合(痛点 1:多平台用量统一查看)
|
||||
if provider not in provider_stats:
|
||||
provider_stats[provider] = {
|
||||
"provider": provider,
|
||||
"calls": 0,
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"total_tokens": 0,
|
||||
"cost": 0.0,
|
||||
"total_latency_ms": 0.0,
|
||||
"success_count": 0,
|
||||
"models": set(),
|
||||
}
|
||||
p = provider_stats[provider]
|
||||
p["calls"] += 1
|
||||
p["input_tokens"] += e.get("input_tokens", 0)
|
||||
p["output_tokens"] += e.get("output_tokens", 0)
|
||||
p["total_tokens"] += e.get("total_tokens", 0)
|
||||
p["cost"] += e.get("cost", 0)
|
||||
p["total_latency_ms"] += e.get("latency_ms", 0)
|
||||
p["models"].add(name)
|
||||
if e.get("success"):
|
||||
p["success_count"] += 1
|
||||
|
||||
# 计算平均延迟
|
||||
for m in model_stats.values():
|
||||
m["avg_latency_ms"] = round(m["total_latency_ms"] / m["calls"], 1) if m["calls"] > 0 else 0
|
||||
m["success_rate"] = round(m["success_count"] / m["calls"] * 100, 1) if m["calls"] > 0 else 0
|
||||
m["cost"] = round(m["cost"], 4)
|
||||
|
||||
for p in provider_stats.values():
|
||||
p["avg_latency_ms"] = round(p["total_latency_ms"] / p["calls"], 1) if p["calls"] > 0 else 0
|
||||
p["success_rate"] = round(p["success_count"] / p["calls"] * 100, 1) if p["calls"] > 0 else 0
|
||||
p["cost"] = round(p["cost"], 4)
|
||||
p["models"] = sorted(p["models"])
|
||||
|
||||
# 任务统计
|
||||
status_dist: dict[str, int] = {}
|
||||
total_duration = 0
|
||||
for e in task_calls:
|
||||
s = e.get("status", "unknown")
|
||||
status_dist[s] = status_dist.get(s, 0) + 1
|
||||
total_duration += e.get("duration_s", 0)
|
||||
|
||||
avg_duration = round(total_duration / len(task_calls), 1) if task_calls else 0
|
||||
|
||||
# 汇总
|
||||
total_cost = sum(m["cost"] for m in model_stats.values())
|
||||
total_tokens = sum(m["total_tokens"] for m in model_stats.values())
|
||||
total_calls = sum(m["calls"] for m in model_stats.values())
|
||||
|
||||
return {
|
||||
"period_hours": hours,
|
||||
"model_stats": sorted(model_stats.values(), key=lambda x: x["cost"], reverse=True),
|
||||
"provider_stats": sorted(provider_stats.values(), key=lambda x: x["cost"], reverse=True),
|
||||
"task_stats": {
|
||||
"total": len(task_calls),
|
||||
"status_distribution": status_dist,
|
||||
"avg_duration_s": avg_duration,
|
||||
},
|
||||
"totals": {
|
||||
"model_calls": total_calls,
|
||||
"total_tokens": total_tokens,
|
||||
"total_cost": round(total_cost, 4),
|
||||
"avg_latency_ms": round(
|
||||
sum(m["total_latency_ms"] for m in model_stats.values()) / total_calls, 1
|
||||
)
|
||||
if total_calls > 0
|
||||
else 0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ========== 趋势分析与成本预测(B2:用量深度分析)==========
|
||||
|
||||
|
||||
def get_trend(days: int = 7) -> dict:
|
||||
"""
|
||||
按天聚合用量趋势(最近 N 天)。
|
||||
|
||||
【返回】
|
||||
daily: [{date, calls, tokens, cost, avg_latency}]
|
||||
providers: 按 Provider 的每日趋势
|
||||
summary: 日均用量、峰值
|
||||
"""
|
||||
# 读取最近 N 天的数据(hours = days * 24)
|
||||
entries = _read_metrics(days * 24)
|
||||
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||
|
||||
# 按日期聚合
|
||||
daily_map: dict[str, dict] = {}
|
||||
provider_daily: dict[str, dict[str, dict]] = {}
|
||||
|
||||
for e in model_calls:
|
||||
date = e.get("timestamp", "")[:10] # YYYY-MM-DD
|
||||
if not date:
|
||||
continue
|
||||
provider = e.get("provider") or "unknown"
|
||||
|
||||
# 全局每日
|
||||
if date not in daily_map:
|
||||
daily_map[date] = {
|
||||
"date": date,
|
||||
"calls": 0,
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"total_tokens": 0,
|
||||
"cost": 0.0,
|
||||
"total_latency_ms": 0.0,
|
||||
}
|
||||
d = daily_map[date]
|
||||
d["calls"] += 1
|
||||
d["input_tokens"] += e.get("input_tokens", 0)
|
||||
d["output_tokens"] += e.get("output_tokens", 0)
|
||||
d["total_tokens"] += e.get("total_tokens", 0)
|
||||
d["cost"] += e.get("cost", 0)
|
||||
d["total_latency_ms"] += e.get("latency_ms", 0)
|
||||
|
||||
# 按 Provider 每日
|
||||
if provider not in provider_daily:
|
||||
provider_daily[provider] = {}
|
||||
if date not in provider_daily[provider]:
|
||||
provider_daily[provider][date] = {
|
||||
"date": date,
|
||||
"calls": 0,
|
||||
"tokens": 0,
|
||||
"cost": 0.0,
|
||||
}
|
||||
pd = provider_daily[provider][date]
|
||||
pd["calls"] += 1
|
||||
pd["tokens"] += e.get("total_tokens", 0)
|
||||
pd["cost"] += e.get("cost", 0)
|
||||
|
||||
# 转列表并排序
|
||||
daily = sorted(daily_map.values(), key=lambda x: x["date"])
|
||||
for d in daily:
|
||||
d["cost"] = round(d["cost"], 4)
|
||||
d["avg_latency_ms"] = round(d["total_latency_ms"] / d["calls"], 1) if d["calls"] else 0
|
||||
|
||||
# Provider 趋势
|
||||
provider_trend = []
|
||||
for prov, day_map in provider_daily.items():
|
||||
days_list = sorted(day_map.values(), key=lambda x: x["date"])
|
||||
for item in days_list:
|
||||
item["cost"] = round(item["cost"], 4)
|
||||
provider_trend.append({"provider": prov, "daily": days_list})
|
||||
|
||||
# 日均与峰值
|
||||
if daily:
|
||||
avg_cost = sum(d["cost"] for d in daily) / len(daily)
|
||||
avg_calls = sum(d["calls"] for d in daily) / len(daily)
|
||||
peak_day = max(daily, key=lambda x: x["cost"])
|
||||
else:
|
||||
avg_cost = avg_calls = 0
|
||||
peak_day = None
|
||||
|
||||
return {
|
||||
"period_days": days,
|
||||
"daily": daily,
|
||||
"provider_trend": provider_trend,
|
||||
"summary": {
|
||||
"avg_daily_cost": round(avg_cost, 4),
|
||||
"avg_daily_calls": round(avg_calls, 1),
|
||||
"peak_day": peak_day,
|
||||
"total_days": len(daily),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_cost_forecast(days: int = 7) -> dict:
|
||||
"""
|
||||
基于最近 N 天用量预测未来 30 天成本。
|
||||
|
||||
【算法】按日均成本线性外推 + 最近 3 天加权平均(近期趋势权重高)。
|
||||
"""
|
||||
entries = _read_metrics(days * 24)
|
||||
model_calls = [e for e in entries if e.get("type") == "model_call"]
|
||||
|
||||
daily_cost: dict[str, float] = {}
|
||||
for e in model_calls:
|
||||
date = e.get("timestamp", "")[:10]
|
||||
if date:
|
||||
daily_cost[date] = daily_cost.get(date, 0) + e.get("cost", 0)
|
||||
|
||||
if not daily_cost:
|
||||
return {
|
||||
"forecast_30d": 0,
|
||||
"avg_daily_cost": 0,
|
||||
"basis_days": 0,
|
||||
"note": "暂无用量数据",
|
||||
}
|
||||
|
||||
dates = sorted(daily_cost.keys())
|
||||
total_cost = sum(daily_cost.values())
|
||||
avg_daily = total_cost / len(dates)
|
||||
|
||||
# 最近 3 天加权平均(近期权重 0.6,历史 0.4)
|
||||
recent_dates = dates[-3:]
|
||||
recent_avg = sum(daily_cost[d] for d in recent_dates) / len(recent_dates)
|
||||
weighted_daily = recent_avg * 0.6 + avg_daily * 0.4
|
||||
|
||||
forecast_30d = weighted_daily * 30
|
||||
|
||||
return {
|
||||
"forecast_30d": round(forecast_30d, 2),
|
||||
"avg_daily_cost": round(avg_daily, 4),
|
||||
"recent_daily_cost": round(recent_avg, 4),
|
||||
"weighted_daily_cost": round(weighted_daily, 4),
|
||||
"basis_days": len(dates),
|
||||
"date_range": {"start": dates[0], "end": dates[-1]},
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
平台用量定时抓取调度器
|
||||
=====================
|
||||
|
||||
【功能说明】
|
||||
可配置的定时任务:按设定间隔自动抓取平台用量数据。
|
||||
支持手动触发、停止、查看运行状态。
|
||||
|
||||
【技术选型理由】
|
||||
1. asyncio 后台任务:无需外部调度器(APScheduler 等);
|
||||
2. 配置存 SQLite:可持久化、可 API 修改;
|
||||
3. 抓取用 asyncio.to_thread 包裹:Playwright 同步 API 不占用事件循环。
|
||||
|
||||
【实现思路】
|
||||
- PlatformScheduler 单例:启动时读配置,后台循环判断是否到点;
|
||||
- 到点 → asyncio.to_thread(scrape_all_accounts) → 记录结果;
|
||||
- 配置变更 → 即时生效(重启循环)。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:同步抓取阻塞事件循环。
|
||||
应对:asyncio.to_thread 在线程池执行同步抓取。
|
||||
风险2:服务器重启后定时任务丢失。
|
||||
应对:应用启动时自动恢复调度器(若配置为 enabled)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.platform_scheduler")
|
||||
|
||||
|
||||
class PlatformScheduler:
|
||||
"""平台用量定时抓取调度器"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task | None = None
|
||||
self._running = False
|
||||
self._last_trigger: float = 0.0
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""调度器是否正在运行。"""
|
||||
return self._running and self._task is not None and not self._task.done()
|
||||
|
||||
async def start(self) -> dict:
|
||||
"""启动调度器(后台循环)。"""
|
||||
if self.is_running():
|
||||
return {"success": True, "message": "调度器已在运行"}
|
||||
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
config = store.get_schedule()
|
||||
if not config.get("enabled"):
|
||||
return {"success": False, "message": "定时抓取未启用,请先在配置中开启"}
|
||||
|
||||
self._running = True
|
||||
self._task = asyncio.create_task(self._loop())
|
||||
logger.info("定时抓取调度器已启动(间隔 %d 分钟)", config.get("interval_minutes", 360))
|
||||
return {"success": True, "message": "调度器已启动"}
|
||||
|
||||
async def stop(self) -> dict:
|
||||
"""停止调度器。"""
|
||||
self._running = False
|
||||
if self._task and not self._task.done():
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
logger.info("定时抓取调度器已停止")
|
||||
return {"success": True, "message": "调度器已停止"}
|
||||
|
||||
async def trigger_now(self) -> dict:
|
||||
"""立即触发一次抓取(不等定时)。"""
|
||||
if self._last_trigger and (
|
||||
datetime.now().timestamp() - self._last_trigger < 30
|
||||
):
|
||||
return {"success": False, "message": "30 秒内已触发过,请稍后再试"}
|
||||
|
||||
self._last_trigger = datetime.now().timestamp()
|
||||
logger.info("手动触发定时抓取")
|
||||
result = await asyncio.to_thread(self._scrape_once)
|
||||
return result
|
||||
|
||||
async def _loop(self) -> None:
|
||||
"""后台循环:按间隔判断是否到点并执行抓取。"""
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
last_run = datetime.now().timestamp()
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
config = store.get_schedule()
|
||||
if not config.get("enabled"):
|
||||
logger.info("定时抓取已停用,调度器退出")
|
||||
break
|
||||
|
||||
interval_seconds = max(
|
||||
60, int(config.get("interval_minutes", 360)) * 60
|
||||
)
|
||||
now = datetime.now().timestamp()
|
||||
|
||||
if now - last_run >= interval_seconds:
|
||||
logger.info("定时抓取触发(间隔 %d 分钟)", config["interval_minutes"])
|
||||
result = await asyncio.to_thread(self._scrape_once)
|
||||
store.record_schedule_run(result.get("message", ""))
|
||||
last_run = now
|
||||
|
||||
await asyncio.sleep(30) # 每 30 秒检查一次是否到点
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("调度器循环异常:%s", exc)
|
||||
await asyncio.sleep(60)
|
||||
|
||||
def _scrape_once(self) -> dict:
|
||||
"""执行一次抓取(同步,在线程池中运行)。"""
|
||||
from app.services.platform_scraper import scrape_all_accounts
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
config = store.get_schedule()
|
||||
account_ids = config.get("account_ids", [])
|
||||
|
||||
try:
|
||||
if account_ids:
|
||||
# 只抓指定账号
|
||||
results = []
|
||||
for aid in account_ids:
|
||||
from app.services.platform_scraper import scrape_usage
|
||||
|
||||
r = scrape_usage(aid)
|
||||
results.append({"account_id": aid, **r})
|
||||
else:
|
||||
# 抓所有激活账号
|
||||
results = scrape_all_accounts()
|
||||
|
||||
success = sum(1 for r in results if r.get("success"))
|
||||
message = f"定时抓取完成:成功 {success}/{len(results)}"
|
||||
logger.info(message)
|
||||
return {"success": True, "message": message, "results": results}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
message = f"定时抓取失败:{exc}"
|
||||
logger.warning(message)
|
||||
return {"success": False, "message": message}
|
||||
|
||||
|
||||
# 全局单例
|
||||
_scheduler: PlatformScheduler | None = None
|
||||
|
||||
|
||||
def get_scheduler() -> PlatformScheduler:
|
||||
global _scheduler
|
||||
if _scheduler is None:
|
||||
_scheduler = PlatformScheduler()
|
||||
return _scheduler
|
||||
@@ -0,0 +1,590 @@
|
||||
"""
|
||||
平台用量抓取服务(Playwright 自动化)
|
||||
====================================
|
||||
|
||||
【功能说明】
|
||||
用 Playwright 内置浏览器打开平台控制台,登录后保存 Cookie,
|
||||
之后用 Cookie 自动抓取用量数据(多账号多套餐并行)。
|
||||
|
||||
【技术选型理由】
|
||||
1. Playwright:能渲染 JS SPA(小米/火山控制台都是 React/Vue);
|
||||
2. Cookie 持久化:登录一次,之后自动复用;
|
||||
3. 无头模式:正式抓取用 headless,登录时用有头模式。
|
||||
|
||||
【实现思路】
|
||||
- login_and_save_cookies():打开浏览器让你登录,登录后保存 Cookie;
|
||||
- scrape_usage():用 Cookie 后台抓取用量页面并解析;
|
||||
- 多账号串行执行(避免并发浏览器吃内存)。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:平台改版导致 CSS 选择器失效。
|
||||
应对:解析失败时截图保存 + 返回页面文本供人工分析;
|
||||
风险2:Cookie 过期。
|
||||
应对:抓取时检测登录态,失效则提示重新登录;
|
||||
风险3:页面加载慢。
|
||||
应对:等待 networkidle + 显式等待关键元素,超时 30s。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("agent.platform_scraper")
|
||||
|
||||
# 浏览器内核路径(已下载到 D 盘)
|
||||
BROWSERS_PATH = Path(r"D:\Agent\agent\data\pw-browsers")
|
||||
SCREENSHOT_DIR = Path(r"D:\Agent\agent\data\platform_screenshots")
|
||||
|
||||
|
||||
def _ensure_browsers_env() -> None:
|
||||
"""确保 Playwright 浏览器路径指向 D 盘。"""
|
||||
os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", str(BROWSERS_PATH))
|
||||
|
||||
|
||||
# ========== 登录会话管理(两步式:打开浏览器 → 用户点完成 → 保存)==========
|
||||
|
||||
# 登录会话:account_id → {playwright, browser, context, page, initial_url, started_at}
|
||||
_login_sessions: dict[str, dict[str, Any]] = {}
|
||||
|
||||
|
||||
def start_login(account_id: str, console_url: str) -> dict:
|
||||
"""
|
||||
第一步:打开浏览器(保持存活,等用户点「登录完成」)。
|
||||
|
||||
【改进】不再等待超时,浏览器一直开着,直到 finish_login 被调用。
|
||||
"""
|
||||
_ensure_browsers_env()
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
# 如果该账号已有活跃会话,先关闭
|
||||
if account_id in _login_sessions:
|
||||
finish_login(account_id, save=False)
|
||||
|
||||
try:
|
||||
pw = sync_playwright().start()
|
||||
browser = pw.chromium.launch(headless=False)
|
||||
context = browser.new_context(
|
||||
viewport={"width": 1400, "height": 900},
|
||||
locale="zh-CN",
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(console_url, timeout=30000)
|
||||
|
||||
_login_sessions[account_id] = {
|
||||
"pw": pw,
|
||||
"browser": browser,
|
||||
"context": context,
|
||||
"page": page,
|
||||
"initial_url": page.url,
|
||||
"started_at": datetime.now().astimezone().isoformat(),
|
||||
}
|
||||
|
||||
logger.info("登录浏览器已打开(account=%s),等待用户完成登录", account_id)
|
||||
return {
|
||||
"success": True,
|
||||
"message": "浏览器已打开,请在浏览器中完成登录,完成后点击「登录完成」",
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"打开浏览器失败:{exc}"}
|
||||
|
||||
|
||||
def finish_login(account_id: str, save: bool = True) -> dict:
|
||||
"""
|
||||
第二步:保存 Cookie + localStorage,关闭浏览器。
|
||||
|
||||
【参数】save=True 正常保存;False 表示取消登录(不保存)。
|
||||
"""
|
||||
session = _login_sessions.pop(account_id, None)
|
||||
if session is None:
|
||||
return {"success": False, "message": "没有进行中的登录会话"}
|
||||
|
||||
cookies: list = []
|
||||
local_storage: dict = {}
|
||||
|
||||
try:
|
||||
cookies = session["context"].cookies()
|
||||
except Exception: # noqa: BLE001
|
||||
cookies = []
|
||||
|
||||
try:
|
||||
raw = session["page"].evaluate("() => JSON.stringify(localStorage)")
|
||||
local_storage = json.loads(raw) if raw else {}
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 关闭浏览器
|
||||
try:
|
||||
session["browser"].close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
session["pw"].stop()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
if not save:
|
||||
return {"success": True, "message": "登录会话已取消"}
|
||||
|
||||
if not cookies and not local_storage:
|
||||
return {
|
||||
"success": False,
|
||||
"message": "未获取到登录态,请确认已在浏览器中完成登录",
|
||||
}
|
||||
|
||||
# 保存到数据库
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
session_data = {"cookies": cookies, "local_storage": local_storage}
|
||||
store.save_cookies(account_id, json.dumps(session_data, ensure_ascii=False))
|
||||
|
||||
logger.info(
|
||||
"登录态已保存(account=%s,Cookie %d 个 + localStorage %d 项)",
|
||||
account_id,
|
||||
len(cookies),
|
||||
len(local_storage),
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"登录态已保存(Cookie {len(cookies)} 个)",
|
||||
"cookie_count": len(cookies),
|
||||
"local_storage_count": len(local_storage),
|
||||
}
|
||||
|
||||
|
||||
def login_and_save_cookies(
|
||||
console_url: str,
|
||||
account_id: str,
|
||||
timeout_seconds: int = 180,
|
||||
) -> dict:
|
||||
"""
|
||||
兼容旧接口:一步式登录(内部调用两步式)。
|
||||
"""
|
||||
start_result = start_login(account_id, console_url)
|
||||
if not start_result.get("success"):
|
||||
return start_result
|
||||
|
||||
# 等待一段时间后自动保存(兼容旧调用方)
|
||||
import time
|
||||
|
||||
time.sleep(min(timeout_seconds, 30))
|
||||
return finish_login(account_id)
|
||||
|
||||
|
||||
def scrape_usage(account_id: str, timeout_seconds: int = 30) -> dict:
|
||||
"""
|
||||
用已保存的 Cookie 后台抓取用量数据。
|
||||
|
||||
【策略】
|
||||
1. 加载 Cookie → 打开控制台 URL;
|
||||
2. 等待页面渲染完成(含 JS 动态内容)→ 截图保存;
|
||||
3. 多策略提取页面文本 → 解析用量数据;
|
||||
4. 保存用量快照 + 原始文本(供调试)。
|
||||
"""
|
||||
_ensure_browsers_env()
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
account = store.get_with_cookies(account_id)
|
||||
if not account:
|
||||
return {"success": False, "message": f"账号不存在:{account_id}"}
|
||||
if not account.get("cookies"):
|
||||
return {
|
||||
"success": False,
|
||||
"message": "该账号尚未登录,请先执行「登录」保存 Cookie",
|
||||
}
|
||||
|
||||
try:
|
||||
session = json.loads(account["cookies"])
|
||||
# 兼容旧格式(纯 Cookie 数组)与新格式({cookies, local_storage})
|
||||
if isinstance(session, list):
|
||||
cookies = session
|
||||
local_storage = {}
|
||||
else:
|
||||
cookies = session.get("cookies", [])
|
||||
local_storage = session.get("local_storage", {})
|
||||
except json.JSONDecodeError:
|
||||
return {"success": False, "message": "Cookie 格式损坏,请重新登录"}
|
||||
|
||||
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
screenshot_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.png"
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
context = browser.new_context(
|
||||
viewport={"width": 1400, "height": 900},
|
||||
locale="zh-CN",
|
||||
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
)
|
||||
context.add_cookies(cookies)
|
||||
page = context.new_page()
|
||||
|
||||
# 恢复 localStorage(有些站点用 token 存在这里)
|
||||
if local_storage:
|
||||
try:
|
||||
import json as _json
|
||||
|
||||
storage_script = (
|
||||
"localStorage.clear();"
|
||||
+ "".join(
|
||||
f"localStorage.setItem({json.dumps(k)}, {json.dumps(v)});"
|
||||
for k, v in local_storage.items()
|
||||
)
|
||||
)
|
||||
page.add_init_script(storage_script)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
try:
|
||||
page.goto(account["console_url"], timeout=30000)
|
||||
|
||||
# 关键改进:等待 JS 渲染完成(SPA 需要额外时间)
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=timeout_seconds * 1000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 额外等待 3 秒让动态内容渲染
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 尝试等待页面出现文本内容
|
||||
try:
|
||||
page.wait_for_function(
|
||||
"document.body.innerText.length > 100",
|
||||
timeout=10000,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 截图
|
||||
page.screenshot(path=str(screenshot_path), full_page=True)
|
||||
|
||||
# 多策略提取文本
|
||||
page_text = ""
|
||||
try:
|
||||
page_text = page.inner_text("body")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if not page_text or len(page_text) < 50:
|
||||
# 降级:从 HTML 提取
|
||||
try:
|
||||
html = page.content()
|
||||
import re as _re
|
||||
|
||||
clean = _re.sub(r"<(script|style)[^>]*>.*?</\1>", "", html, flags=_re.DOTALL)
|
||||
clean = _re.sub(r"<[^>]+>", " ", clean)
|
||||
page_text = _re.sub(r"\s+", " ", clean)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 保存原始文本(供调试)
|
||||
text_path = SCREENSHOT_DIR / f"{account['brand']}_{account['account_name']}_{ts}.txt"
|
||||
try:
|
||||
text_path.write_text(page_text[:20000], encoding="utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
browser.close()
|
||||
|
||||
# 关键改进:检测是否在登录页(Cookie 失效)
|
||||
login_keywords = ["登录", "注册", "忘记密码", "立即登录", "请登录", "未登录", "Login"]
|
||||
is_login_page = any(kw in page_text[:500] for kw in login_keywords)
|
||||
if is_login_page and not any(
|
||||
kw in page_text for kw in ["退出登录", "个人中心", "用户中心"]
|
||||
):
|
||||
# 记录登录过期(供前端右上角提示)
|
||||
_record_login_expired(
|
||||
account_id,
|
||||
account.get("brand", ""),
|
||||
account.get("account_name", ""),
|
||||
)
|
||||
return {
|
||||
"success": False,
|
||||
"message": "Cookie 已过期或未登录,请重新执行「登录」",
|
||||
"screenshot": str(screenshot_path),
|
||||
"page_text_preview": page_text[:300],
|
||||
}
|
||||
|
||||
# 解析用量数据
|
||||
usage_data = _parse_usage_text(page_text, account["brand"])
|
||||
usage_data["raw_text_preview"] = page_text[:300]
|
||||
|
||||
# 保存快照
|
||||
snapshot = store.save_snapshot(account_id, usage_data)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"抓取完成({account['brand']}-{account['account_name']})",
|
||||
"usage": usage_data,
|
||||
"screenshot": str(screenshot_path),
|
||||
"snapshot_id": snapshot["id"],
|
||||
"page_text_length": len(page_text),
|
||||
"page_text_preview": page_text[:500],
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
try:
|
||||
browser.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return {"success": False, "message": f"抓取失败:{exc}"}
|
||||
|
||||
|
||||
def _parse_usage_text(text: str, brand: str) -> dict:
|
||||
"""
|
||||
从页面文本中解析用量数据(按指标名精确提取)。
|
||||
|
||||
【火山引擎式布局】指标名 → 重置信息 → 数值独占一行 → % → 坐标轴标签
|
||||
【小米式布局】直接用文字描述(如「已用 45%」)
|
||||
|
||||
【提取指标】
|
||||
- 剩余时间(如「25天」)
|
||||
- 近5小时用量
|
||||
- 近一周用量
|
||||
- 近一月用量
|
||||
"""
|
||||
import re
|
||||
|
||||
usage_percent = 0.0
|
||||
used_amount = ""
|
||||
total_amount = ""
|
||||
remain_amount = ""
|
||||
expire_date = ""
|
||||
usage_5h = ""
|
||||
usage_1w = ""
|
||||
usage_1m = ""
|
||||
|
||||
lines = text.splitlines()
|
||||
lines_stripped = [l.strip() for l in lines]
|
||||
|
||||
def _find_value_after_label(label: str, max_lookahead: int = 6) -> str:
|
||||
"""
|
||||
在文本行中找标签,然后往后扫描找数值(跳过「重置」等中间行)。
|
||||
【布局】标签 → [重置信息] → 数值 → % → 坐标轴标签
|
||||
"""
|
||||
for i, line in enumerate(lines_stripped):
|
||||
if label in line:
|
||||
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
|
||||
candidate = lines_stripped[j]
|
||||
if not candidate:
|
||||
continue
|
||||
if any(kw in candidate for kw in ["重置", "即将", "后重置"]):
|
||||
continue
|
||||
if candidate == "%":
|
||||
continue
|
||||
if candidate in ("0%", "50%", "100%"):
|
||||
continue
|
||||
if re.match(r"^[\d,\.]+\s*(%|天|日|月|小时|个)?$", candidate):
|
||||
return candidate
|
||||
if re.match(r"^[\d,\.]+", candidate):
|
||||
return candidate
|
||||
return ""
|
||||
|
||||
def _find_reset_after_label(label: str, max_lookahead: int = 6) -> str:
|
||||
"""
|
||||
找标签后的「重置时间」信息(如「即将重置」「5天9小时后重置」)。
|
||||
"""
|
||||
for i, line in enumerate(lines_stripped):
|
||||
if label in line:
|
||||
for j in range(i + 1, min(i + max_lookahead, len(lines_stripped))):
|
||||
candidate = lines_stripped[j]
|
||||
if not candidate:
|
||||
continue
|
||||
# 匹配重置时间模式
|
||||
if "重置" in candidate:
|
||||
return candidate
|
||||
return ""
|
||||
|
||||
# 提取「剩余时间」
|
||||
remain_time = _find_value_after_label("剩余时间")
|
||||
if remain_time:
|
||||
remain_amount = remain_time
|
||||
|
||||
# 提取「近5小时用量」及其重置时间
|
||||
usage_5h = _find_value_after_label("近5小时用量")
|
||||
reset_5h = _find_reset_after_label("近5小时用量")
|
||||
|
||||
# 提取「近一周用量」及其重置时间
|
||||
usage_1w = _find_value_after_label("近一周用量")
|
||||
reset_1w = _find_reset_after_label("近一周用量")
|
||||
|
||||
# 提取「近一月用量」及其重置时间
|
||||
usage_1m = _find_value_after_label("近一月用量")
|
||||
reset_1m = _find_reset_after_label("近一月用量")
|
||||
|
||||
# 主用量百分比:优先取近一月 > 近一周 > 近5小时
|
||||
for val in [usage_1m, usage_1w, usage_5h]:
|
||||
m = re.match(r"([\d\.]+)", val or "")
|
||||
if m:
|
||||
usage_percent = float(m.group(1))
|
||||
break
|
||||
|
||||
# 通用模式补充(兼容小米等其他平台)
|
||||
if not any([usage_5h, usage_1w, usage_1m]):
|
||||
# 小米式:「已用 45%」
|
||||
pct_with_label = re.search(
|
||||
r"(?:已用|使用|已消耗|用量|used)[^%\n]{0,20}?(\d+(?:\.\d+)?)\s*%", text, re.IGNORECASE
|
||||
)
|
||||
if pct_with_label:
|
||||
usage_percent = float(pct_with_label.group(1))
|
||||
else:
|
||||
pct_matches = re.findall(r"(\d+(?:\.\d+)?)\s*%", text)
|
||||
real_pcts = [float(p) for p in pct_matches if float(p) not in (0, 50, 100)]
|
||||
if real_pcts:
|
||||
usage_percent = real_pcts[0]
|
||||
|
||||
# 小米式:「当前套餐用量」后的「X / Y」分数(已用/总量)
|
||||
xiaomi_fraction = re.search(
|
||||
r"当前套餐用量\s*\n\s*([\d,]+)\s*/\s*([\d,]+)", text
|
||||
)
|
||||
if xiaomi_fraction:
|
||||
used_amount = xiaomi_fraction.group(1).strip()
|
||||
total_amount = xiaomi_fraction.group(2).strip()
|
||||
# 计算剩余
|
||||
try:
|
||||
used_val = int(used_amount.replace(",", ""))
|
||||
total_val = int(total_amount.replace(",", ""))
|
||||
remain_val = total_val - used_val
|
||||
remain_amount = f"{remain_val:,}"
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 小米式:「Token 总消耗」后的数量
|
||||
if not used_amount:
|
||||
token_total = re.search(
|
||||
r"Token\s*总消耗\s*\n\s*([\d,]+)\s*(?:Tokens?)?", text
|
||||
)
|
||||
if token_total:
|
||||
used_amount = token_total.group(1).strip() + " Tokens"
|
||||
|
||||
# 分数形式(通用)
|
||||
if not used_amount:
|
||||
fraction = re.search(r"([\d,\.]+)\s*/\s*([\d,\.]+)", text)
|
||||
if fraction:
|
||||
used_amount = fraction.group(1)
|
||||
total_amount = fraction.group(2)
|
||||
|
||||
# Token 数量(通用)
|
||||
if not used_amount:
|
||||
token_match = re.search(r"([\d,\.]+)\s*(?:tokens?|tok)", text, re.IGNORECASE)
|
||||
if token_match:
|
||||
used_amount = token_match.group(1)
|
||||
|
||||
# 小米式:「有效期至」日期(如「有效期至 2026-11-13 23:59:59 (UTC)」)
|
||||
valid_until_match = re.search(r"有效期至\s*(\d{4}-\d{2}-\d{2})", text)
|
||||
valid_until = valid_until_match.group(1) if valid_until_match else ""
|
||||
|
||||
# 到期日期(优先取「结束时间」后的日期)
|
||||
expire_match = re.search(
|
||||
r"(?:结束时间|到期|截止|expire|end)[:\s]*(\d{4}-\d{2}-\d{2})", text, re.IGNORECASE
|
||||
)
|
||||
if expire_match:
|
||||
expire_date = expire_match.group(1)
|
||||
elif valid_until:
|
||||
expire_date = valid_until
|
||||
else:
|
||||
all_dates = re.findall(r"(\d{4}-\d{2}-\d{2})", text)
|
||||
if all_dates:
|
||||
expire_date = all_dates[-1]
|
||||
|
||||
return {
|
||||
"usage_percent": usage_percent,
|
||||
"used_amount": used_amount,
|
||||
"total_amount": total_amount,
|
||||
"remain_amount": remain_amount,
|
||||
"expire_date": expire_date,
|
||||
"valid_until": valid_until,
|
||||
"usage_5h": usage_5h,
|
||||
"usage_1w": usage_1w,
|
||||
"usage_1m": usage_1m,
|
||||
"reset_5h": reset_5h,
|
||||
"reset_1w": reset_1w,
|
||||
"reset_1m": reset_1m,
|
||||
"brand": brand,
|
||||
"raw_data": {
|
||||
"text_length": len(text),
|
||||
"text_preview": text[:500],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ========== 抓取进度追踪 ==========
|
||||
|
||||
# 全局进度:{running, total, completed, current_account, results, started_at}
|
||||
_scrape_progress: dict[str, Any] = {
|
||||
"running": False,
|
||||
"total": 0,
|
||||
"completed": 0,
|
||||
"current_account": "",
|
||||
"results": [],
|
||||
"started_at": "",
|
||||
}
|
||||
|
||||
# 登录过期追踪:account_id → {brand, account_name, detected_at}
|
||||
_login_expired: dict[str, dict[str, Any]] = {}
|
||||
|
||||
|
||||
def get_scrape_progress() -> dict:
|
||||
"""获取当前抓取进度(供前端轮询)。"""
|
||||
return dict(_scrape_progress)
|
||||
|
||||
|
||||
def get_login_expired() -> list[dict]:
|
||||
"""获取登录过期的账号列表(供前端右上角提示)。"""
|
||||
return [
|
||||
{"account_id": aid, **info} for aid, info in _login_expired.items()
|
||||
]
|
||||
|
||||
|
||||
def clear_login_expired(account_id: str) -> None:
|
||||
"""清除某账号的登录过期标记(重新登录后调用)。"""
|
||||
_login_expired.pop(account_id, None)
|
||||
|
||||
|
||||
def _record_login_expired(account_id: str, brand: str, account_name: str) -> None:
|
||||
"""记录登录过期。"""
|
||||
from datetime import datetime
|
||||
|
||||
_login_expired[account_id] = {
|
||||
"brand": brand,
|
||||
"account_name": account_name,
|
||||
"detected_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
}
|
||||
logger.warning("检测到登录过期:%s-%s", brand, account_name)
|
||||
|
||||
|
||||
def scrape_all_accounts() -> list[dict]:
|
||||
"""抓取所有已激活账号的用量(串行执行,带进度追踪)。"""
|
||||
from app.store.platform_account_store import get_platform_store
|
||||
|
||||
store = get_platform_store()
|
||||
accounts = [a for a in store.list_all() if a.get("is_active")]
|
||||
total = len(accounts)
|
||||
|
||||
# 重置进度
|
||||
_scrape_progress.update({
|
||||
"running": True,
|
||||
"total": total,
|
||||
"completed": 0,
|
||||
"current_account": "",
|
||||
"results": [],
|
||||
"started_at": datetime.now().astimezone().isoformat(),
|
||||
})
|
||||
|
||||
results = []
|
||||
try:
|
||||
for account in accounts:
|
||||
_scrape_progress["current_account"] = f"{account['brand']}-{account['account_name']}"
|
||||
result = scrape_usage(account["id"])
|
||||
results.append({"account_id": account["id"], "brand": account["brand"], **result})
|
||||
_scrape_progress["results"] = list(results)
|
||||
_scrape_progress["completed"] = len(results)
|
||||
finally:
|
||||
_scrape_progress["running"] = False
|
||||
|
||||
return results
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
提示词优化服务
|
||||
==============
|
||||
|
||||
【功能说明】
|
||||
基于 prompt-polisher Skill 定义,把用户的粗糙/口语化/不完整想法
|
||||
润色成结构清晰、无歧义、可直接发给 AI 执行的高质量提示词。
|
||||
|
||||
【技术选型理由】
|
||||
1. 直接读取 SKILL.md 作为 System Prompt,规则统一维护、可迭代;
|
||||
2. 调用强模型执行润色,结果结构化返回(润色后 + 改动说明 + 待定问题)。
|
||||
|
||||
【实现思路】
|
||||
- load_skill_prompt():读取 SKILL.md 内容;
|
||||
- polish():组装 Prompt → 调模型 → 解析输出结构;
|
||||
- 结果分为 polish_result / changes / questions 三部分。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:模型输出格式不符合预期。
|
||||
应对:宽松解析(提取【润色后】【改了什么】【还需要你定】三个区块)。
|
||||
风险2:SKILL.md 文件丢失或编码异常。
|
||||
应对:启动时缓存,文件不存在时用内置简化规则兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("agent.prompt_polisher")
|
||||
|
||||
# Skill 文件路径
|
||||
SKILL_PATH = Path(r"D:\Agent\SKILLS\prompt-polisher\SKILL.md")
|
||||
|
||||
# 内置兜底规则(SKILL.md 缺失时使用)
|
||||
FALLBACK_RULES = """你是一个提示词润色专家。把用户的粗糙想法润色成高质量提示词。
|
||||
|
||||
铁律:只润色提示词本身,不执行任务。不分析项目、不写代码、不查文件。
|
||||
|
||||
输出格式:
|
||||
【润色后】
|
||||
(可直接复制的提示词)
|
||||
|
||||
【改了什么】
|
||||
- 补了什么
|
||||
- 去掉了什么歧义
|
||||
|
||||
【还需要你定】(如有)
|
||||
- 问题 1:选项 A / 选项 B"""
|
||||
|
||||
|
||||
def _load_skill_prompt() -> str:
|
||||
"""读取 SKILL.md 作为系统提示词(缓存结果)。"""
|
||||
try:
|
||||
if SKILL_PATH.exists():
|
||||
return SKILL_PATH.read_text(encoding="utf-8")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("读取 SKILL.md 失败:%s,使用内置规则", exc)
|
||||
return FALLBACK_RULES
|
||||
|
||||
|
||||
# 缓存(模块加载时读一次)
|
||||
_SKILL_PROMPT: str | None = None
|
||||
|
||||
|
||||
def _get_skill_prompt() -> str:
|
||||
global _SKILL_PROMPT
|
||||
if _SKILL_PROMPT is None:
|
||||
_SKILL_PROMPT = _load_skill_prompt()
|
||||
return _SKILL_PROMPT
|
||||
|
||||
|
||||
def polish(text: str, model_preference: str = "auto") -> dict:
|
||||
"""
|
||||
优化用户输入的提示词。
|
||||
|
||||
【参数】
|
||||
text:用户原始输入(粗糙/口语化的想法)
|
||||
model_preference:模型偏好(auto=智能选)
|
||||
【返回】{polish_result, changes, questions, model}
|
||||
"""
|
||||
from app.models.model_router import get_model_for_task
|
||||
|
||||
if not text or not text.strip():
|
||||
return {"success": False, "message": "请输入要优化的内容"}
|
||||
|
||||
system_prompt = _get_skill_prompt()
|
||||
|
||||
user_prompt = f"""请润色下面这段提示词:
|
||||
|
||||
{text}"""
|
||||
|
||||
try:
|
||||
model = get_model_for_task(model_preference, "strong")
|
||||
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||||
|
||||
# 组装消息:System = Skill 规则,User = 用户原始输入
|
||||
from langchain_core.messages import HumanMessage, SystemMessage
|
||||
|
||||
resp = model.invoke(
|
||||
[
|
||||
SystemMessage(content=system_prompt),
|
||||
HumanMessage(content=user_prompt),
|
||||
]
|
||||
)
|
||||
output = resp.content if hasattr(resp, "content") else str(resp)
|
||||
|
||||
# 宽松解析输出结构
|
||||
polished, changes, questions = _parse_output(output)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"polish_result": polished or output,
|
||||
"changes": changes,
|
||||
"questions": questions,
|
||||
"model": model_name,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("提示词优化失败")
|
||||
return {"success": False, "message": f"优化失败:{exc}"}
|
||||
|
||||
|
||||
def _parse_output(output: str) -> tuple[str, list[str], list[str]]:
|
||||
"""
|
||||
宽松解析润色输出:提取【润色后】【改了什么】【还需要你定】三个区块。
|
||||
|
||||
【容错】区块标题可能有轻微变体,用正则宽松匹配。
|
||||
"""
|
||||
polished = ""
|
||||
changes: list[str] = []
|
||||
questions: list[str] = []
|
||||
|
||||
# 提取【润色后】区块
|
||||
m_polish = re.search(
|
||||
r"【润色后】\s*\n(.*?)(?=【改了什么】|【还需要你定】|$)",
|
||||
output,
|
||||
re.DOTALL,
|
||||
)
|
||||
if m_polish:
|
||||
polished = m_polish.group(1).strip()
|
||||
# 去掉代码块包裹标记
|
||||
polished = re.sub(r"^```[a-z]*\n?|```$", "", polished.strip(), flags=re.MULTILINE).strip()
|
||||
|
||||
# 提取【改了什么】
|
||||
m_changes = re.search(
|
||||
r"【改了什么】\s*\n(.*?)(?=【还需要你定】|【润色后】|$)",
|
||||
output,
|
||||
re.DOTALL,
|
||||
)
|
||||
if m_changes:
|
||||
raw = m_changes.group(1).strip()
|
||||
changes = [
|
||||
re.sub(r"^[-•*]\s*", "", line.strip())
|
||||
for line in raw.splitlines()
|
||||
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||||
]
|
||||
|
||||
# 提取【还需要你定】
|
||||
m_questions = re.search(
|
||||
r"【还需要你定】\s*\n(.*?)(?=【润色后】|【改了什么】|$)",
|
||||
output,
|
||||
re.DOTALL,
|
||||
)
|
||||
if m_questions:
|
||||
raw = m_questions.group(1).strip()
|
||||
questions = [
|
||||
re.sub(r"^[-•*]\s*", "", line.strip())
|
||||
for line in raw.splitlines()
|
||||
if line.strip() and re.sub(r"^[-•*]\s*", "", line.strip())
|
||||
]
|
||||
|
||||
return polished, changes, questions
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
任务模板服务
|
||||
============
|
||||
|
||||
【功能说明】常用开发/修复模板管理,一键复用到任务提交。
|
||||
【实现思路】模板存 SQLite,支持 CRUD + 分类 + 标签。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.template")
|
||||
|
||||
|
||||
class TaskTemplate:
|
||||
"""任务模板"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id: str,
|
||||
name: str,
|
||||
category: str,
|
||||
content: str,
|
||||
description: str,
|
||||
tags: list[str],
|
||||
created_at: str,
|
||||
updated_at: str,
|
||||
):
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.category = category
|
||||
self.content = content
|
||||
self.description = description
|
||||
self.tags = tags
|
||||
self.created_at = created_at
|
||||
self.updated_at = updated_at
|
||||
|
||||
|
||||
class TemplateStore:
|
||||
"""任务模板存储"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
self._seed_defaults()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS task_template (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
category TEXT NOT NULL DEFAULT '通用',
|
||||
content TEXT NOT NULL,
|
||||
description TEXT DEFAULT '',
|
||||
tags TEXT DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
def _seed_defaults(self) -> None:
|
||||
"""首次初始化默认模板。"""
|
||||
defaults = [
|
||||
{
|
||||
"name": "修复空指针异常",
|
||||
"category": "Bug修复",
|
||||
"content": "修复 {文件名} 中的空指针异常:当 {变量/参数} 为 null 时,应抛出 IllegalArgumentException 并给出明确错误信息,而不是 NPE。",
|
||||
"description": "Java NPE 修复模板",
|
||||
"tags": ["Java", "NPE", "异常处理"],
|
||||
},
|
||||
{
|
||||
"name": "新增 REST API 接口",
|
||||
"category": "功能开发",
|
||||
"content": "在 {Controller} 中新增 {接口名} 接口:路径 /api/{path},方法 {GET/POST/PUT/DELETE},入参 {参数说明},返回 {返回结构}。遵循项目现有编码规范,添加中文注释。",
|
||||
"description": "RESTful 接口开发模板",
|
||||
"tags": ["API", "REST", "Controller"],
|
||||
},
|
||||
{
|
||||
"name": "数据库表结构变更",
|
||||
"category": "数据库",
|
||||
"content": "在表 {表名} 中新增字段 {字段名}({类型},{约束}),并更新对应的 Entity/DTO/Mapper/Service 各层代码。确保兼容现有数据,添加默认值。",
|
||||
"description": "数据库变更模板",
|
||||
"tags": ["数据库", "DDL", "MyBatis"],
|
||||
},
|
||||
{
|
||||
"name": "单元测试生成",
|
||||
"category": "测试",
|
||||
"content": "为 {类名/方法名} 生成完整的单元测试,覆盖正常场景、边界条件、异常场景。使用 JUnit 5 + Mockito,测试方法命名遵循 test_{方法名}_{场景} 规范。",
|
||||
"description": "单元测试生成模板",
|
||||
"tags": ["测试", "JUnit", "Mockito"],
|
||||
},
|
||||
{
|
||||
"name": "代码重构优化",
|
||||
"category": "重构",
|
||||
"content": "重构 {类名/模块}:识别重复代码、过长方法、过大类,提取公共方法、应用设计模式(如策略/工厂),保持功能不变、测试通过。",
|
||||
"description": "代码重构模板",
|
||||
"tags": ["重构", "设计模式", "代码质量"],
|
||||
},
|
||||
]
|
||||
with self._conn() as conn:
|
||||
count = conn.execute("SELECT COUNT(*) FROM task_template").fetchone()[0]
|
||||
if count == 0:
|
||||
for item in defaults:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
conn.execute(
|
||||
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(f"tpl_{uuid.uuid4().hex[:12]}", item["name"], item["category"], item["content"], item["description"], str(item["tags"]), now, now),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def _row_to_obj(self, row: sqlite3.Row) -> TaskTemplate:
|
||||
import json as json_mod
|
||||
tags = []
|
||||
try:
|
||||
tags = json_mod.loads(row["tags"] or "[]")
|
||||
except Exception:
|
||||
pass
|
||||
return TaskTemplate(
|
||||
id=row["id"],
|
||||
name=row["name"],
|
||||
category=row["category"],
|
||||
content=row["content"],
|
||||
description=row["description"] or "",
|
||||
tags=tags,
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
)
|
||||
|
||||
def list_all(self, category: str = "") -> list[TaskTemplate]:
|
||||
sql = "SELECT * FROM task_template"
|
||||
params = []
|
||||
if category:
|
||||
sql += " WHERE category = ?"
|
||||
params.append(category)
|
||||
sql += " ORDER BY updated_at DESC"
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
return [self._row_to_obj(r) for r in rows]
|
||||
|
||||
def get(self, tpl_id: str) -> Optional[TaskTemplate]:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM task_template WHERE id = ?", (tpl_id,)).fetchone()
|
||||
return self._row_to_obj(row) if row else None
|
||||
|
||||
def create(self, name: str, category: str, content: str, description: str = "", tags: list[str] | None = None) -> TaskTemplate:
|
||||
import json as json_mod
|
||||
|
||||
tpl_id = f"tpl_{uuid.uuid4().hex[:12]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(tpl_id, name, category, content, description, json_mod.dumps(tags or [], ensure_ascii=False), now, now),
|
||||
)
|
||||
conn.commit()
|
||||
return self.get(tpl_id)
|
||||
|
||||
def update(self, tpl_id: str, **kwargs) -> Optional[TaskTemplate]:
|
||||
import json as json_mod
|
||||
|
||||
allowed = {"name", "category", "content", "description", "tags"}
|
||||
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||
if not updates:
|
||||
return self.get(tpl_id)
|
||||
if "tags" in updates:
|
||||
updates["tags"] = json_mod.dumps(updates["tags"], ensure_ascii=False)
|
||||
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||
values = list(updates.values()) + [tpl_id]
|
||||
with self._conn() as conn:
|
||||
conn.execute(f"UPDATE task_template SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(tpl_id)
|
||||
|
||||
def delete(self, tpl_id: str) -> bool:
|
||||
with self._conn() as conn:
|
||||
cursor = conn.execute("DELETE FROM task_template WHERE id = ?", (tpl_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: TemplateStore | None = None
|
||||
|
||||
|
||||
def get_template_store() -> TemplateStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
settings = __import__("app.config.settings", fromlist=["load_settings"]).load_settings()
|
||||
_store = TemplateStore(settings.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
测试生成服务
|
||||
============
|
||||
|
||||
【功能说明】为指定代码文件/类/方法自动生成单元测试。
|
||||
对应功能 25:改码后自动补测试。
|
||||
|
||||
【技术选型理由】
|
||||
1. 强模型 + 代码上下文 → 生成 JUnit/Mockito 测试;
|
||||
2. 可指定测试框架和覆盖场景。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.models.model_router import get_model_for_task
|
||||
|
||||
logger = logging.getLogger("agent.testgen")
|
||||
|
||||
|
||||
def generate_tests(
|
||||
source_code: str,
|
||||
file_name: str = "",
|
||||
test_framework: str = "junit5",
|
||||
model_preference: str = "auto",
|
||||
) -> dict:
|
||||
"""
|
||||
为指定代码生成单元测试。
|
||||
|
||||
【参数】
|
||||
source_code:Java 源代码
|
||||
file_name:文件名(供生成测试类名)
|
||||
test_framework:junit5 / mockito / spring
|
||||
model_preference:模型偏好
|
||||
"""
|
||||
if not source_code.strip():
|
||||
return {"success": False, "message": "请提供源代码"}
|
||||
|
||||
prompt = f"""你是资深 Java 测试工程师。请为下面的代码生成完整的单元测试。
|
||||
|
||||
【源文件】{file_name or '未命名'}
|
||||
【测试框架】{test_framework}
|
||||
|
||||
【源代码】
|
||||
```
|
||||
{source_code[:8000]}
|
||||
```
|
||||
|
||||
【要求】
|
||||
1. 使用 {test_framework} 框架,测试类命名为 `{{原类名}}Test`
|
||||
2. 覆盖:正常场景、边界条件、异常场景
|
||||
3. 外部依赖用 Mockito mock
|
||||
4. 每个测试方法命名:test_{{方法名}}_{{场景}}
|
||||
5. 添加中文注释说明每个测试的意图
|
||||
6. 直接输出完整测试代码,用 ```java 包裹"""
|
||||
|
||||
try:
|
||||
model = get_model_for_task(model_preference, "strong")
|
||||
model_name = getattr(model, "model_name", None) or getattr(model, "model", "")
|
||||
resp = model.invoke(prompt)
|
||||
output = resp.content if hasattr(resp, "content") else str(resp)
|
||||
|
||||
# 提取代码块
|
||||
import re
|
||||
|
||||
code_match = re.search(r"```java\s*\n(.*?)\n```", output, re.DOTALL)
|
||||
test_code = code_match.group(1) if code_match else output
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"test_code": test_code,
|
||||
"model": model_name,
|
||||
"file_name": file_name,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("测试生成失败")
|
||||
return {"success": False, "message": f"测试生成失败:{exc}"}
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
图片识别服务
|
||||
============
|
||||
|
||||
【功能说明】调用智谱 GLM-4V-Flash 识别图片内容(Bug 截图、UI 稿、日志截图等),
|
||||
供任务提交时自动分析图片附件,把图片内容附加到需求描述。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选智谱 GLM-4V-Flash:完全免费、中文效果好、OpenAI 兼容口;
|
||||
2. 不依赖 langchain-openai:智谱走自己的 OpenAI 兼容协议,直接 httpx 调用更轻量。
|
||||
|
||||
【实现思路】
|
||||
- analyze_image():base64 编码图片 → 调 GLM-4V-Flash → 返回文字描述;
|
||||
- analyze_images():批量分析多张图片,合并结果。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:图片过大/格式不支持。
|
||||
应对:前端限 10MB + 格式校验;后端 base64 编码前检查大小。
|
||||
风险2:API 超时/限流。
|
||||
应对:超时 30 秒 + 失败返回空字符串(不阻塞任务提交)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config.settings import load_settings
|
||||
|
||||
logger = logging.getLogger("agent.vision")
|
||||
|
||||
|
||||
def analyze_image(image_path: str | Path, prompt: str = "") -> str:
|
||||
"""
|
||||
识别图片内容。
|
||||
|
||||
【参数】
|
||||
image_path:图片文件路径(需在 D 盘可访问范围内)
|
||||
prompt:可选自定义提示词(默认让模型描述图片内容)
|
||||
【返回】图片内容的文字描述(失败返回空字符串,不抛异常)
|
||||
"""
|
||||
path = Path(image_path)
|
||||
if not path.exists():
|
||||
logger.warning("图片文件不存在:%s", path)
|
||||
return ""
|
||||
|
||||
# 检查大小(20MB 限制,base64 后更大)
|
||||
if path.stat().st_size > 20 * 1024 * 1024:
|
||||
logger.warning("图片过大:%s(%.1fMB)", path, path.stat().st_size / 1024 / 1024)
|
||||
return ""
|
||||
|
||||
try:
|
||||
image_b64 = base64.b64encode(path.read_bytes()).decode("utf-8")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("图片读取失败:%s %s", path, exc)
|
||||
return ""
|
||||
|
||||
# 根据扩展名确定 MIME 类型
|
||||
ext = path.suffix.lower()
|
||||
mime_map = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".gif": "image/gif",
|
||||
".bmp": "image/bmp",
|
||||
".webp": "image/webp",
|
||||
}
|
||||
mime = mime_map.get(ext, "image/png")
|
||||
|
||||
settings = load_settings()
|
||||
api_key = settings.zhipu_api_key
|
||||
base_url = settings.zhipu_base_url
|
||||
model = settings.zhipu_vision_model or "glm-4v-flash"
|
||||
|
||||
if not api_key:
|
||||
logger.warning("未配置智谱 API Key,跳过图片识别")
|
||||
return ""
|
||||
|
||||
user_prompt = prompt or (
|
||||
"请完整识别并提取图片中的所有文字内容,逐字逐句转录,不要遗漏、不要总结、不要改写。"
|
||||
"如果是报错截图,提取完整错误信息和堆栈;"
|
||||
"如果是代码截图,逐行提取代码;"
|
||||
"如果是表格/文档截图,按原格式完整转录;"
|
||||
"如果是UI界面,提取所有可见的文字、标签、按钮文本。"
|
||||
"保持原文,不做任何概括或省略。"
|
||||
)
|
||||
|
||||
try:
|
||||
resp = httpx.post(
|
||||
f"{base_url}/chat/completions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": user_prompt},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:{mime};base64,{image_b64}"
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
],
|
||||
"max_tokens": 800,
|
||||
},
|
||||
timeout=30.0,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
logger.info("图片识别成功:%s(返回 %d 字符)", path.name, len(content))
|
||||
return content.strip()
|
||||
except httpx.HTTPStatusError as exc:
|
||||
logger.warning("图片识别 HTTP 错误:%s %s", exc.response.status_code, exc.response.text[:200])
|
||||
return ""
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("图片识别失败:%s %s", path.name, exc)
|
||||
return ""
|
||||
|
||||
|
||||
def analyze_images(image_paths: list[str], prompt: str = "") -> str:
|
||||
"""
|
||||
批量识别图片内容并合并结果。
|
||||
|
||||
【返回】合并后的文字描述(空行分隔各图),失败的跳过。
|
||||
"""
|
||||
results = []
|
||||
for p in image_paths:
|
||||
desc = analyze_image(p, prompt)
|
||||
if desc:
|
||||
path = Path(p)
|
||||
results.append(f"【图片:{path.name}】\n{desc}")
|
||||
|
||||
return "\n\n".join(results)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
多租户工作空间服务
|
||||
==================
|
||||
|
||||
【功能说明】
|
||||
实现工作空间隔离:项目/知识库/任务/记忆按空间隔离。
|
||||
对应功能 7:多团队共存。
|
||||
|
||||
【技术选型理由】
|
||||
1. 轻量方案:所有实体加 workspace_id 字段,查询时过滤;
|
||||
2. 空间数据独立,互不可见(数据级隔离);
|
||||
3. 支持默认空间(个人)+ 团队空间。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.workspace")
|
||||
|
||||
|
||||
class WorkspaceStore:
|
||||
"""工作空间存储"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
self._seed_default()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS workspace (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT DEFAULT '',
|
||||
is_default INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
def _seed_default(self) -> None:
|
||||
with self._conn() as conn:
|
||||
count = conn.execute("SELECT COUNT(*) FROM workspace").fetchone()[0]
|
||||
if count == 0:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
conn.execute(
|
||||
"INSERT INTO workspace (id, name, description, is_default, created_at, updated_at) VALUES (?,?,?,?,?,?)",
|
||||
("ws_default", "默认空间", "个人工作空间", 1, now, now),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def list_all(self) -> list[dict]:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute("SELECT * FROM workspace ORDER BY is_default DESC, created_at").fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def get(self, ws_id: str) -> Optional[dict]:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM workspace WHERE id = ?", (ws_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def create(self, name: str, description: str = "") -> dict:
|
||||
ws_id = f"ws_{uuid.uuid4().hex[:8]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO workspace (id, name, description, is_default, created_at, updated_at) VALUES (?,?,?,0,?,?)",
|
||||
(ws_id, name, description, now, now),
|
||||
)
|
||||
conn.commit()
|
||||
return self.get(ws_id)
|
||||
|
||||
def delete(self, ws_id: str) -> bool:
|
||||
if ws_id == "ws_default":
|
||||
return False # 禁止删除默认空间
|
||||
with self._conn() as conn:
|
||||
cursor = conn.execute("DELETE FROM workspace WHERE id = ?", (ws_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: WorkspaceStore | None = None
|
||||
|
||||
|
||||
def get_workspace_store() -> WorkspaceStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
_store = WorkspaceStore(settings.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,499 @@
|
||||
"""
|
||||
禅道项目管理服务
|
||||
================
|
||||
|
||||
【功能说明】对接禅道项目管理平台(开源版 16.5+ / 18.x),支持创建/查询/更新 Bug 和任务。
|
||||
对应用户需求:Agent 任务与禅道 Issue 双向同步。
|
||||
|
||||
【技术选型理由】
|
||||
1. 禅道 18.x 开源版提供 REST v1 API(/api.php/v1/*),鉴权用 Bearer Token;
|
||||
2. Token 通过 POST /api.php/v1/tokens 用账号密码换取,有效期有限(默认约 7 天);
|
||||
3. 为避免 Token 过期导致调用失败,本模块做「自动登录 + 内存/落盘缓存 + 到期前主动续期 + 401 强制重登」;
|
||||
4. 未配置凭证时降级为本地记录,不影响主流程。
|
||||
|
||||
【实现思路】
|
||||
- ZentaoService 统一封装鉴权与业务接口;
|
||||
- _ensure_token():命中缓存直接用;缺失或临期则登录换新 Token 并落盘到 data_root;
|
||||
- _request():带 Bearer 头请求;401/403 时强制刷新并重试一次;
|
||||
- create_bug / create_task / search / update_status:对应 v1 的 bugs / tasks 资源;
|
||||
- 全程不打印密码与完整 Token(日志只打前 6 位做定位)。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:接口返回的 expireTime 格式不统一(时间戳 / 秒数 / 日期字符串)。
|
||||
应对:_parse_expire_time 兼容多种格式;解析不出时按 zentao_token_ttl_seconds 兜底,
|
||||
并在「剩余不足 5 分钟」时主动续期,宁可早换不突然过期。
|
||||
风险2:多线程并发首次调用会重复登录。
|
||||
应对:刷新动作用 threading.Lock 保护,拿到锁后再二次检查缓存。
|
||||
风险3:账号密码改了导致登录失败。
|
||||
应对:返回明确报错文案,不抛裸异常;同时保留 ZENTAO_TOKEN 手工令牌兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.config.settings import load_settings
|
||||
|
||||
logger = logging.getLogger("agent.zentao")
|
||||
|
||||
# 剩余有效期低于该阈值(秒)即主动续期,避免长请求撞上过期点
|
||||
REFRESH_MARGIN_SECONDS = 300
|
||||
# 登录/业务请求超时
|
||||
LOGIN_TIMEOUT = 20.0
|
||||
REQUEST_TIMEOUT = 20.0
|
||||
|
||||
|
||||
def _mask(token: str) -> str:
|
||||
"""日志用的 Token 脱敏,只露前 6 位。"""
|
||||
return f"{token[:6]}..." if token else "<empty>"
|
||||
|
||||
|
||||
# 报错信息里需要脱敏的敏感字段(token / 口令);结尾引号可选,兼容被截断的 JSON 片段
|
||||
_SENSITIVE_KEY_RE = re.compile(
|
||||
r'("(?:token|apiToken|apikey|access_token|accessToken|password|passwd)"\s*:\s*")([^"]+)("?)',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _redact_body(text: str, limit: int = 300) -> str:
|
||||
"""错误信息里的响应体脱敏,避免把完整 Token / 口令打进日志。"""
|
||||
snippet = (text or "")[:limit]
|
||||
return _SENSITIVE_KEY_RE.sub(lambda m: f"{m.group(1)}{_mask(m.group(2) or '')}{m.group(3)}", snippet)
|
||||
|
||||
|
||||
def _parse_expire_time(raw: Any, default_ttl: int) -> float:
|
||||
"""
|
||||
把禅道返回的 expireTime 归一成「过期时刻的 unix 时间戳」。
|
||||
|
||||
兼容:
|
||||
1730000000 → unix 秒
|
||||
1730000000000 → unix 毫秒
|
||||
604800 → 从现在起 N 秒
|
||||
"2026-10-30 12:00:00" → 日期字符串
|
||||
缺失/解析失败 → 现在 + default_ttl
|
||||
"""
|
||||
now = time.time()
|
||||
if raw is None or raw == "":
|
||||
return now + default_ttl
|
||||
|
||||
if isinstance(raw, (int, float)):
|
||||
val = float(raw)
|
||||
if val > 1e12: # 毫秒
|
||||
return val / 1000.0
|
||||
if val > 1e9: # unix 秒
|
||||
return val
|
||||
if val > 0: # 从现在起的秒数
|
||||
return now + val
|
||||
return now + default_ttl
|
||||
|
||||
if isinstance(raw, str):
|
||||
s = raw.strip()
|
||||
if s.isdigit():
|
||||
return _parse_expire_time(int(s), default_ttl)
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||
try:
|
||||
import datetime as _dt
|
||||
|
||||
return _dt.datetime.strptime(s, fmt).timestamp()
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
return now + default_ttl
|
||||
|
||||
|
||||
def _extract_token(payload: Any) -> tuple[str, float | None]:
|
||||
"""
|
||||
从登录响应里挖出 (token, expireTime)。
|
||||
兼容裸对象 / status+data 包裹 / token 嵌套等情况。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
return "", None
|
||||
|
||||
token = ""
|
||||
expire_raw: Any = None
|
||||
|
||||
for key in ("token", "apiToken", "apikey", "access_token", "accessToken"):
|
||||
if isinstance(payload.get(key), str) and payload.get(key):
|
||||
token = payload[key]
|
||||
break
|
||||
|
||||
for key in ("expireTime", "expire", "expiresAt", "expires_at", "expiry", "expires_in", "expiresIn"):
|
||||
if key in payload and payload[key] not in (None, ""):
|
||||
expire_raw = payload[key]
|
||||
break
|
||||
|
||||
if not token:
|
||||
data = payload.get("data")
|
||||
if isinstance(data, dict):
|
||||
token, expire_inner = _extract_token(data)
|
||||
if expire_raw is None:
|
||||
expire_raw = expire_inner
|
||||
elif isinstance(data, str) and data:
|
||||
token = data
|
||||
|
||||
return token, expire_raw
|
||||
|
||||
|
||||
class ZentaoService:
|
||||
"""禅道项目管理服务(自动管理 Token 生命周期)"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._base_url = ""
|
||||
self._account = ""
|
||||
self._password = ""
|
||||
self._static_token = ""
|
||||
self._token_ttl = 6 * 24 * 3600
|
||||
self._cache_path: Path | None = None
|
||||
|
||||
self._token = ""
|
||||
self._expire_at = 0.0
|
||||
|
||||
self._load_config()
|
||||
self._load_token_cache()
|
||||
|
||||
# ========== 配置与缓存 ==========
|
||||
|
||||
def _load_config(self) -> None:
|
||||
"""从 .env 加载禅道配置。"""
|
||||
try:
|
||||
settings = load_settings()
|
||||
self._base_url = str(getattr(settings, "zentao_url", "") or "").rstrip("/")
|
||||
self._account = getattr(settings, "zentao_account", "") or ""
|
||||
self._password = getattr(settings, "zentao_password", "") or ""
|
||||
self._static_token = getattr(settings, "zentao_token", "") or ""
|
||||
self._token_ttl = int(getattr(settings, "zentao_token_ttl_seconds", 6 * 24 * 3600) or 6 * 24 * 3600)
|
||||
self._cache_path = Path(settings.data_root) / "zentao_token.json"
|
||||
except Exception: # noqa: BLE001
|
||||
self._base_url = ""
|
||||
self._account = ""
|
||||
self._password = ""
|
||||
self._static_token = ""
|
||||
self._cache_path = None
|
||||
|
||||
def _load_token_cache(self) -> None:
|
||||
"""从磁盘恢复上次的 Token,服务重启不必重新登录。"""
|
||||
path = self._cache_path
|
||||
if path is None or not path.exists():
|
||||
return
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
if data.get("account") not in (None, self._account):
|
||||
return # 换账号了,旧缓存作废
|
||||
token = data.get("token") or ""
|
||||
expire_at = float(data.get("expire_at") or 0)
|
||||
if token and expire_at > time.time():
|
||||
self._token = token
|
||||
self._expire_at = expire_at
|
||||
logger.info("禅道 Token 已从缓存恢复,到期时间:%s", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(expire_at)))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("禅道 Token 缓存读取失败:%s", exc)
|
||||
|
||||
def _save_token_cache(self) -> None:
|
||||
path = self._cache_path
|
||||
if path is None:
|
||||
return
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"account": self._account,
|
||||
"token": self._token,
|
||||
"expire_at": self._expire_at,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("禅道 Token 缓存写入失败:%s", exc)
|
||||
|
||||
# ========== 对外属性 ==========
|
||||
|
||||
@property
|
||||
def is_configured(self) -> bool:
|
||||
"""是否具备可用凭证(账号密码 或 手工 Token)。"""
|
||||
return bool(self._base_url) and bool(
|
||||
(self._account and self._password) or self._static_token or self._token
|
||||
)
|
||||
|
||||
@property
|
||||
def has_login_credential(self) -> bool:
|
||||
return bool(self._account and self._password)
|
||||
|
||||
def token_status(self) -> dict:
|
||||
"""给外部(健康检查/调试)看的 Token 状态,不含明文 Token。"""
|
||||
now = time.time()
|
||||
return {
|
||||
"base_url": self._base_url,
|
||||
"mode": "account_password" if self.has_login_credential else ("static_token" if self._static_token else "none"),
|
||||
"token_masked": _mask(self._token or self._static_token),
|
||||
"expire_at": self._expire_at or None,
|
||||
"expire_at_text": (
|
||||
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)) if self._expire_at else None
|
||||
),
|
||||
"seconds_left": max(0, int(self._expire_at - now)) if self._expire_at else None,
|
||||
}
|
||||
|
||||
# ========== Token 生命周期 ==========
|
||||
|
||||
def refresh_token(self, force: bool = False) -> dict:
|
||||
"""
|
||||
刷新 Token。默认只在缺失/临期时刷新;force=True 则无条件重新登录。
|
||||
返回 {"success": bool, "message": str, ...}
|
||||
"""
|
||||
with self._lock:
|
||||
if not force and self._token and self._expire_at - time.time() > REFRESH_MARGIN_SECONDS:
|
||||
return {"success": True, "message": "Token 仍有效,无需刷新"}
|
||||
|
||||
# 手工 Token 兜底:没有账号密码就只能用它,不存在续期
|
||||
if not self.has_login_credential:
|
||||
if self._static_token:
|
||||
self._token = self._static_token
|
||||
self._expire_at = time.time() + self._token_ttl
|
||||
return {"success": True, "message": "使用手工配置的 ZENTAO_TOKEN"}
|
||||
return {"success": False, "message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD 或 ZENTAO_TOKEN)"}
|
||||
|
||||
result = self._login()
|
||||
return result
|
||||
|
||||
def _login(self) -> dict:
|
||||
"""调 REST v1 tokens 接口换新 Token。调用方需已持有 self._lock。"""
|
||||
if not self._base_url:
|
||||
return {"success": False, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
||||
|
||||
url = f"{self._base_url}/api.php/v1/tokens"
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.post(
|
||||
url,
|
||||
json={"account": self._account, "password": self._password},
|
||||
timeout=LOGIN_TIMEOUT,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "message": f"禅道登录请求失败:{exc}"}
|
||||
|
||||
# 禅道创建 Token 成功时返回 201 Created(REST 资源创建语义),与 _request() 判定保持一致
|
||||
if resp.status_code not in (200, 201):
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"禅道登录失败 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
||||
}
|
||||
|
||||
try:
|
||||
payload = resp.json()
|
||||
except Exception: # noqa: BLE001
|
||||
return {"success": False, "message": f"禅道登录响应非 JSON:{_redact_body(resp.text)}"}
|
||||
|
||||
token, expire_raw = _extract_token(payload)
|
||||
if not token:
|
||||
return {"success": False, "message": f"禅道登录响应缺少 token:{_redact_body(resp.text)}"}
|
||||
|
||||
self._token = token
|
||||
self._expire_at = _parse_expire_time(expire_raw, self._token_ttl)
|
||||
self._save_token_cache()
|
||||
|
||||
logger.info(
|
||||
"禅道 Token 已刷新(%s),到期时间:%s",
|
||||
_mask(token),
|
||||
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": "Token 已刷新",
|
||||
"token_masked": _mask(token),
|
||||
"expire_at_text": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
||||
}
|
||||
|
||||
def _ensure_token(self) -> str:
|
||||
"""返回可用 Token;缺失或临期则刷新。拿不到返回空串。"""
|
||||
now = time.time()
|
||||
if self._token and self._expire_at - now > REFRESH_MARGIN_SECONDS:
|
||||
return self._token
|
||||
|
||||
# 手工 Token 且无账号密码:直接用,不走登录
|
||||
if self._static_token and not self.has_login_credential:
|
||||
self._token = self._static_token
|
||||
if not self._expire_at:
|
||||
self._expire_at = now + self._token_ttl
|
||||
return self._token
|
||||
|
||||
self.refresh_token()
|
||||
return self._token
|
||||
|
||||
# ========== HTTP 封装 ==========
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
params: dict | None = None,
|
||||
json_body: dict | None = None,
|
||||
retry_on_auth_fail: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
带鉴权的禅道 REST 请求。
|
||||
|
||||
path 以 / 开头,拼在 {base_url}/api.php/v1 之后,
|
||||
例如 path="/bugs" → {base_url}/api.php/v1/bugs。
|
||||
"""
|
||||
if not self._base_url:
|
||||
return {"success": False, "status_code": 0, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
||||
|
||||
token = self._ensure_token()
|
||||
if not token:
|
||||
return {"success": False, "status_code": 0, "message": "禅道 Token 获取失败,请检查 ZENTAO_ACCOUNT/ZENTAO_PASSWORD"}
|
||||
|
||||
url = f"{self._base_url}/api.php/v1{path}"
|
||||
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.request(
|
||||
method.upper(),
|
||||
url,
|
||||
params=params,
|
||||
json=json_body,
|
||||
headers=headers,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "status_code": 0, "message": f"禅道调用失败:{exc}"}
|
||||
|
||||
# Token 失效:强制重登后重试一次
|
||||
if resp.status_code in (401, 403) and retry_on_auth_fail and self.has_login_credential:
|
||||
logger.info("禅道返回 %s,强制刷新 Token 后重试", resp.status_code)
|
||||
self.refresh_token(force=True)
|
||||
if self._token:
|
||||
try:
|
||||
import httpx
|
||||
|
||||
headers["Authorization"] = f"Bearer {self._token}"
|
||||
resp = httpx.request(
|
||||
method.upper(),
|
||||
url,
|
||||
params=params,
|
||||
json=json_body,
|
||||
headers=headers,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {"success": False, "status_code": 0, "message": f"禅道重试失败:{exc}"}
|
||||
|
||||
ok = resp.status_code in (200, 201)
|
||||
try:
|
||||
data: Any = resp.json()
|
||||
except Exception: # noqa: BLE001
|
||||
data = None
|
||||
|
||||
return {
|
||||
"success": ok,
|
||||
"status_code": resp.status_code,
|
||||
"data": data,
|
||||
# data 解析失败时 raw 会作为错误载荷回传给调用方(可能进日志/接口响应),必须脱敏
|
||||
"raw": _redact_body(resp.text) if data is None else None,
|
||||
"message": "" if ok else f"禅道返回 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
||||
}
|
||||
|
||||
# ========== 业务接口 ==========
|
||||
|
||||
def create_bug(self, title: str, description: str = "", project_id: str = "") -> dict:
|
||||
"""创建禅道 Bug。"""
|
||||
if not self.is_configured:
|
||||
return {
|
||||
"success": False,
|
||||
"message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD)",
|
||||
"local_record": {"title": title, "description": description, "type": "bug"},
|
||||
}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"title": title,
|
||||
"steps": description or title,
|
||||
}
|
||||
if project_id not in ("", None):
|
||||
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
||||
|
||||
result = self._request("POST", "/bugs", json_body=body)
|
||||
return {
|
||||
"success": result["success"],
|
||||
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||
"message": result.get("message", ""),
|
||||
}
|
||||
|
||||
def create_task(self, title: str, description: str = "", project_id: str = "") -> dict:
|
||||
"""创建禅道任务。"""
|
||||
if not self.is_configured:
|
||||
return {
|
||||
"success": False,
|
||||
"message": "禅道未配置",
|
||||
"local_record": {"title": title, "description": description, "type": "task"},
|
||||
}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"name": title,
|
||||
"desc": description or title,
|
||||
}
|
||||
if project_id not in ("", None):
|
||||
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
||||
|
||||
result = self._request("POST", "/tasks", json_body=body)
|
||||
return {
|
||||
"success": result["success"],
|
||||
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||
"message": result.get("message", ""),
|
||||
}
|
||||
|
||||
def search(self, keyword: str = "") -> dict:
|
||||
"""搜索禅道 Issue(Bug 列表,支持关键字过滤)。"""
|
||||
if not self.is_configured:
|
||||
return {"success": False, "message": "禅道未配置", "results": []}
|
||||
|
||||
params: dict[str, Any] = {"page": 1, "limit": 20}
|
||||
if keyword:
|
||||
params["keywords"] = keyword
|
||||
|
||||
result = self._request("GET", "/bugs", params=params)
|
||||
if not result["success"]:
|
||||
return {"success": False, "message": result.get("message", ""), "results": []}
|
||||
|
||||
data = result.get("data")
|
||||
# v1 常见返回:{"bugs": [...]} 或 [...]
|
||||
if isinstance(data, dict):
|
||||
items = data.get("bugs") or data.get("data") or data.get("items") or []
|
||||
elif isinstance(data, list):
|
||||
items = data
|
||||
else:
|
||||
items = []
|
||||
return {"success": True, "results": items}
|
||||
|
||||
def update_status(self, issue_id: str, status: str = "done") -> dict:
|
||||
"""更新禅道 Issue(Bug)状态。"""
|
||||
if not self.is_configured:
|
||||
return {"success": False, "message": "禅道未配置"}
|
||||
|
||||
result = self._request("PUT", f"/bugs/{issue_id}", json_body={"status": status})
|
||||
return {
|
||||
"success": result["success"],
|
||||
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
||||
"message": result.get("message", ""),
|
||||
}
|
||||
|
||||
|
||||
# 全局单例
|
||||
_service: ZentaoService | None = None
|
||||
|
||||
|
||||
def get_zentao_service() -> ZentaoService:
|
||||
global _service
|
||||
if _service is None:
|
||||
_service = ZentaoService()
|
||||
return _service
|
||||
Reference in New Issue
Block a user