Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions dbm-ui/backend/db_monitor/views/callbacks/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
from backend.db_monitor.views.callbacks.base import AlarmCallback
from backend.db_report.portrait import MysqlPortraitDimensionCode, ingest_summary
from backend.db_report.portrait.exceptions import PortraitSDKBaseException
from backend.dbm_aiagent.agent.commands.commands import MySQLAlarmAnalyzerCommand
from backend.dbm_aiagent.agent.constants import DBMAgentCode
from backend.dbm_aiagent.agent.handlers import AgentHandler

logger = logging.getLogger("root")

Expand Down Expand Up @@ -265,6 +263,10 @@ def call_mysql_alarm_analyzer(callback_data: dict, alarm_base_info: dict):
return

try:
# 延迟导入,避免监控策略视图在单测收集期强依赖 aidev Agent 包
from backend.dbm_aiagent.agent.commands.commands import MySQLAlarmAnalyzerCommand
from backend.dbm_aiagent.agent.handlers import AgentHandler

# 调用 AI Agent 进行慢查询分析
user_prompt = extract_callback_key_info(callback_data)
logger.info(
Expand Down Expand Up @@ -325,6 +327,8 @@ def _call_agent_and_notify(
timeout: Agent 调用超时时间(秒)
"""
try:
from backend.dbm_aiagent.agent.handlers import AgentHandler

logger.info(_("[{}] 告警触发 AI 分析,集群: {}").format(log_tag, cluster_domain))
agent_output = AgentHandler.ask_agent_with_content(
agent_code=agent_code,
Expand Down
4 changes: 2 additions & 2 deletions dbm-ui/backend/db_monitor/views/callbacks/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,8 @@ def call_redis_alarm_correlation_analysis(callback_data: dict, alarm_base_info:
return

try:
from backend.dbm_aiagent.agent.handlers import AgentHandler

# 设置去重锁,防止后续同策略告警重复触发
cache.set(lock_key, 1, DEDUP_LOCK_TTL)

Expand All @@ -235,8 +237,6 @@ def call_redis_alarm_correlation_analysis(callback_data: dict, alarm_base_info:
"cluster_domains": list(cluster_domains),
}

from backend.dbm_aiagent.agent.handlers import AgentHandler

result_summary = AgentHandler.ask_agent_with_command(
command=RedisLatencyAlarmRootCauseCommand.command,
command_params=correlation_input,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
from django.db.models import Count
from django.utils import timezone

from backend import env
from backend.db_meta.enums import ClusterType, InstanceRole, TenDBClusterSpiderRole
from backend.db_periodic_task.local_tasks import register_periodic_task
from backend.db_periodic_task.local_tasks.mysql_backup.check_ignore import CheckIgnore
from backend.db_report.enums import AiAnalysisSubType
from backend.db_report.models.mysql_slowlog_ai_analysis import MysqlSlowlogAiAnalysis
from backend.db_report.models.mysql_slowlog_detail import MysqlSlowlogDetail
from backend.dbm_aiagent.agent.commands.commands import MySQLSlowLogCommand
from backend.dbm_aiagent.agent.handlers import AgentHandler

logger = logging.getLogger("root")

Expand All @@ -33,6 +33,10 @@
@register_periodic_task(run_every=crontab(minute=0))
def periodic_mysql_slowlog_ai_analysis():
"""周期任务:从慢日志详情表中查询过去 1 小时内慢查询数量超过阈值的集群,进行 AI 分析"""
if not env.ENABLE_DBM_AI:
return

from backend.dbm_aiagent.agent.handlers import AgentHandler

now = timezone.now()
time_window_start = now - timedelta(hours=1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,21 @@
"""
from celery.schedules import crontab

from backend import env
from backend.db_periodic_task.constants import GET_AND_DELETE_SET_LUA
from backend.db_periodic_task.local_tasks import register_periodic_task
from backend.dbm_aiagent.agent.constants import FLOW_LOG_AI_ANALYSIS_KEY
from backend.dbm_aiagent.agent.services.log_analysis.tasks import pipeline_log_ai_analysis
from backend.utils.redis import RedisConn


@register_periodic_task(run_every=crontab(minute="*"))
def periodic_pipeline_log_ai_analysis():
"""周期任务错误日志AI分析"""
if not env.ENABLE_DBM_AI:
return

from backend.dbm_aiagent.agent.services.log_analysis.tasks import pipeline_log_ai_analysis

script = RedisConn.register_script(GET_AND_DELETE_SET_LUA)
task_list = script(keys=[FLOW_LOG_AI_ANALYSIS_KEY])
for root_id in task_list:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@
from backend.db_report.models.mysql_cluster_skew_report import MysqlClusterSkewReport
from backend.db_report.portrait import MysqlPortraitDimensionCode, ingest_summary
from backend.db_report.portrait.exceptions import PortraitSDKBaseException
from backend.dbm_aiagent.agent.constants import DBMAgentCode
from backend.dbm_aiagent.agent.handlers import AgentHandler
from backend.dbm_aiagent.mcp_tools.mysql.impl.query_cluster_skew_data import has_cluster_skew

logger = logging.getLogger("celery.generate_mysql_skew_report")

Expand Down Expand Up @@ -167,6 +164,10 @@ def generate_report():

@app.task
def _generate_cluster_skew_report(cluster_type: str, domain: str, lock_key: str, bk_biz_id: int):
from backend.dbm_aiagent.agent.constants import DBMAgentCode
from backend.dbm_aiagent.agent.handlers import AgentHandler
from backend.dbm_aiagent.mcp_tools.mysql.impl.query_cluster_skew_data import has_cluster_skew

logger.info("generate %s skew report start: lock_key=%s", domain, lock_key)
try:
# 本地墙钟时间,不带时区,与 Doris detect_time、倾斜检测写入方式一致
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
from backend.db_report.portrait import MysqlPortraitDimensionCode, ingest_summary
from backend.db_report.portrait.exceptions import PortraitSDKBaseException
from backend.dbm_aiagent.agent.constants import DEFAULT_AGENT_CHAT_TIMEOUT, DBMAgentCode
from backend.dbm_aiagent.agent.handlers import AgentHandler

logger = logging.getLogger("celery")

Expand Down Expand Up @@ -215,6 +214,8 @@ def run_mysql_config_ai_inspect(row_id: int, lock_key: str):
logger.info(_("配置巡检开始调用 agent: id={} domain={}").format(row.id, row.cluster_domain))
t_start = time.monotonic()
try:
from backend.dbm_aiagent.agent.handlers import AgentHandler

res = AgentHandler.ask_agent_with_content(
agent_code=DBMAgentCode.MYSQL_CONFIG_PERF_TUNER,
content=str(content),
Expand Down
5 changes: 5 additions & 0 deletions dbm-ui/backend/dbm_aiagent/agent/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from aidev_bkplugin.views.agent import AgentInfoViewSet
from aidev_bkplugin.views.chat import ChatCompletionViewSet
from aidev_bkplugin.views.chat_group import ChatGroupViewSet
from aidev_bkplugin.views.llm import LLMViewSet
from aidev_bkplugin.views.session import (
ChatSessionContentFeedbackViewSet,
ChatSessionContentViewSet,
Expand Down Expand Up @@ -108,3 +109,7 @@ class AIChatGroupViewSet(AgentCodeResourceManagerMixin, ChatGroupViewSet):

class AIChatSessionShareView(AgentCodeResourceManagerMixin, ChatSessionShareView):
pass


class AILLMViewSet(AgentCodeResourceManagerMixin, LLMViewSet):
pass
18 changes: 11 additions & 7 deletions dbm-ui/backend/dbm_aiagent/agent/configs/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import logging

from aidev_agent.enums import CredentialType
from aidev_agent.packages.resource_manager import AgentResourceManager
from aidev_agent.pydantic_models import AgentConfig
from aidev_bkplugin.services.agent_builder import LLMOverrideResourceManager
from aidev_bkplugin.services.agent_session import SessionManager
from django.conf import settings
from django.core.cache import cache
Expand Down Expand Up @@ -52,15 +52,18 @@
}


class DBMAgentResourceManager(AgentResourceManager):
class DBMAgentResourceManager(LLMOverrideResourceManager):
"""DBM Agent配置管理器"""

def __init__(self, username="", agent_code: str = None, agent_secret: str = None):
def __init__(self, username="", agent_code: str = None, agent_secret: str = None, model: str = ""):
"""
:param model: 覆盖智能体发布时配置的 chat_model,为空时沿用平台配置
"""
agent_code = agent_code or settings.AGENT_APP_CODE
agent_secret = agent_secret or settings.AGENT_APP_SECRET
# TODO:这里不能传递真实的username,暂时为空
username = "" if username == DEFAULT_USERNAME else username
super().__init__(app_code=agent_code, app_secret=agent_secret, username=username)
super().__init__(app_code=agent_code, app_secret=agent_secret, username=username, model=model)

@classmethod
def set_backend_mcp_config(cls, agent_config: AgentConfig):
Expand Down Expand Up @@ -159,18 +162,19 @@ def get_paas_sbx_client(self, executor_info: dict, **kwargs):
return client


def build_resource_manager(agent_code, username) -> DBMAgentResourceManager:
def build_resource_manager(agent_code, username, model: str = "") -> DBMAgentResourceManager:
"""
构建子智能体 resource-manager
如果没配置,则默认走主智能体调用(快捷指令路由)
:param agent_code: 子智能体 code,未配置 token 时回退到主智能体
:param username: 用户名,用于用户态 access_token 注入(view 层透传)
:param model: 覆盖智能体发布时配置的 chat_model,为空时沿用平台配置
"""
agent_token_config = SystemSettings.get_setting_value(key=SystemSettingsEnum.AGENT_TOKEN_CONFIG, default={})
agent_token = agent_token_config.get(agent_code, "")
if not agent_token:
return DBMAgentResourceManager(username)
return DBMAgentResourceManager(username, agent_code, agent_token)
return DBMAgentResourceManager(username, model=model)
return DBMAgentResourceManager(username, agent_code, agent_token, model=model)


def build_session_manager(agent_code, username) -> SessionManager:
Expand Down
Loading
Loading