Files
chat_app/backend/app/services/glm_service.py
2025-12-12 03:29:09 +08:00

126 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
GLM聊天服务,包含角色配置管理
"""
import logging
from typing import Optional
from app.models.glm_role import GLMRole
logger = logging.getLogger(__name__)
class GLMService:
"""GLM聊天服务,包含角色配置管理"""
def __init__(self):
self._current_role: Optional[GLMRole] = None
async def get_current_role(self) -> GLMRole:
"""获取当前激活的角色配置"""
if self._current_role is None:
self._current_role = await self._load_or_create_role()
return self._current_role
async def update_role(self, role_data: dict) -> GLMRole:
"""更新角色配置
Args:
role_data: 角色配置数据,包含name, description, skills, restrictions字段
Returns:
更新后的GLMRole实例
"""
role = await self.get_current_role()
# 更新字段
if "name" in role_data:
role.name = role_data["name"]
if "description" in role_data:
role.description = role_data["description"]
if "skills" in role_data:
role.skills = role_data["skills"]
if "restrictions" in role_data:
role.restrictions = role_data["restrictions"]
role.update_timestamp()
await role.save()
# 更新缓存
self._current_role = role
logger.info(f"角色配置已更新: {role.name}")
return role
async def _load_or_create_role(self) -> GLMRole:
"""加载或创建默认角色"""
# 1. 尝试获取激活的角色
active_role = await GLMRole.find_one(GLMRole.is_active == True)
if active_role:
logger.info(f"加载激活角色: {active_role.name}")
return active_role
# 2. 尝试获取默认角色
default_role = await GLMRole.find_one(GLMRole.is_default == True)
if default_role:
default_role.is_active = True
await default_role.save()
logger.info(f"加载默认角色并激活: {default_role.name}")
return default_role
# 3. 创建默认角色
logger.info("创建默认角色配置")
return await self._create_default_role()
async def _create_default_role(self) -> GLMRole:
"""创建默认角色配置"""
# 导入DEFAULT_ROLE_CONFIG
from app.routes.glm_routes import DEFAULT_ROLE_CONFIG
role = GLMRole(
name=DEFAULT_ROLE_CONFIG.name,
description=DEFAULT_ROLE_CONFIG.description,
skills=DEFAULT_ROLE_CONFIG.skills,
restrictions=DEFAULT_ROLE_CONFIG.restrictions,
is_active=True,
is_default=True,
)
await role.save()
logger.info(f"默认角色创建成功: {role.name}")
return role
async def ensure_default_role(self):
"""确保存在默认角色配置(应用启动时调用)"""
try:
role = await self._load_or_create_role()
logger.info(f"默认角色已确保存在: {role.name}")
return role
except Exception as e:
logger.error(f"确保默认角色存在时出错: {e}")
raise
async def close(self):
"""关闭服务,清理资源"""
self._current_role = None
logger.info("GLM服务已关闭")
# 全局服务实例(单例模式)
_glm_service: Optional[GLMService] = None
def get_glm_service() -> GLMService:
"""获取GLM服务实例(单例)"""
global _glm_service
if _glm_service is None:
_glm_service = GLMService()
return _glm_service
def close_glm_service():
"""关闭GLM服务"""
global _glm_service
if _glm_service:
_glm_service.close()
_glm_service = None