system_config_tools.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # app/services/agent/tools/builtin/system_config_tools.py
  2. from typing import Optional, Dict, Any, List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select, desc
  5. from app.models.user import VasUser
  6. from app.models.configuration import Configuration
  7. from app.services.configuration_service import ConfigurationService
  8. from app.services.agent.tools.registry import agent_tool
  9. from app.core.logger import logger
  10. ADMIN_CHECK_MSG = "Permission denied: This operation is restricted to system administrators (admin)"
  11. @agent_tool(
  12. name="list_system_configurations",
  13. description="查询全站全局动态环境变量与系统运行配置参数列表(包含配置项 Key、说明、更新时间)",
  14. )
  15. async def list_system_configurations(
  16. *,
  17. db: AsyncSession,
  18. current_user: VasUser,
  19. ) -> Dict[str, Any]:
  20. """查询全站配置列表"""
  21. if current_user.role != "admin":
  22. return {"error": ADMIN_CHECK_MSG}
  23. configs = await ConfigurationService.get_all(db)
  24. items = []
  25. for c in configs:
  26. items.append({
  27. "id": c.id,
  28. "config_key": c.config_key,
  29. "description": c.description,
  30. "config_value": c.config_value[:100] + "..." if c.config_value and len(c.config_value) > 100 else c.config_value,
  31. "created_at": c.created_at.strftime("%Y-%m-%d %H:%M:%S") if c.created_at else None,
  32. "updated_at": c.updated_at.strftime("%Y-%m-%d %H:%M:%S") if c.updated_at else None,
  33. })
  34. return {
  35. "count": len(items),
  36. "configurations": items,
  37. }
  38. @agent_tool(
  39. name="get_system_configuration",
  40. description="获取指定配置 Key 的完整内容与参数定义",
  41. )
  42. async def get_system_configuration(
  43. config_key: str,
  44. *,
  45. db: AsyncSession,
  46. current_user: VasUser,
  47. ) -> Dict[str, Any]:
  48. """获取单个全局配置"""
  49. if current_user.role != "admin":
  50. return {"error": ADMIN_CHECK_MSG}
  51. clean_key = config_key.strip()
  52. try:
  53. c = await ConfigurationService.get_by_key(db, clean_key)
  54. return {
  55. "id": c.id,
  56. "config_key": c.config_key,
  57. "description": c.description,
  58. "config_value": c.config_value,
  59. "created_at": c.created_at.strftime("%Y-%m-%d %H:%M:%S") if c.created_at else None,
  60. "updated_at": c.updated_at.strftime("%Y-%m-%d %H:%M:%S") if c.updated_at else None,
  61. }
  62. except Exception as e:
  63. return {"error": f"Config key '{clean_key}' not found or error: {str(e)}"}
  64. @agent_tool(
  65. name="set_system_configuration",
  66. description="设置或修改全局动态环境变量/系统配置(支持更新已有值或创建新键值配置)",
  67. is_dangerous=True,
  68. )
  69. async def set_system_configuration(
  70. config_key: str,
  71. config_value: str,
  72. description: Optional[str] = None,
  73. *,
  74. db: AsyncSession,
  75. current_user: VasUser,
  76. ) -> Dict[str, Any]:
  77. """更新或创建全局动态配置"""
  78. if current_user.role != "admin":
  79. return {"error": ADMIN_CHECK_MSG}
  80. clean_key = config_key.strip()
  81. if not clean_key:
  82. return {"error": "Config key cannot be empty"}
  83. stmt = select(Configuration).where(Configuration.config_key == clean_key)
  84. res = await db.execute(stmt)
  85. c = res.scalar_one_or_none()
  86. if c:
  87. c.config_value = config_value
  88. if description is not None:
  89. c.description = description
  90. await db.commit()
  91. await db.refresh(c)
  92. action = "updated"
  93. else:
  94. c = Configuration(
  95. config_key=clean_key,
  96. config_value=config_value,
  97. description=description or "",
  98. )
  99. db.add(c)
  100. await db.commit()
  101. await db.refresh(c)
  102. action = "created"
  103. logger.info(f"⚙️ [AI_AGENT] Config {action}: key={clean_key} by admin={current_user.id}")
  104. return {
  105. "success": True,
  106. "action": action,
  107. "config_key": c.config_key,
  108. "config_value": c.config_value,
  109. "updated_at": c.updated_at.strftime("%Y-%m-%d %H:%M:%S") if c.updated_at else None,
  110. }