基于DeepSeek构建的openGauss AI智能优化助手:数据库性能提升新利器

基于DeepSeek构建的openGauss AI智能优化助手:数据库性能提升新利器

  • 一、项目概述
    • 1.1 项目简介
    • 1.2 环境说明
    • 1.3 项目代码结构
  • 二、系统架构剖析
    • 2.1 架构图展示
    • 2.2 架构详细说明
  • 三、系统功能模块解读
    • 3.1 功能模块图展示
    • 3.2 功能模块详细说明
  • 四、系统数据流分析
    • 4.1 数据流图展示
    • 4.2 数据流详细解释
  • 五、核心技术组件工作原理揭秘
    • 5.1 工作原理图展示
    • 5.2 工作原理详细解释
  • 六、关键代码深度解析
    • 6.1 OpenGaussOptimizationAgent 类
    • 6.2 analyze_execution_plan 方法
  • 七、使用说明与系统演示
    • 7.1 使用说明
    • 7.2 系统演示效果
  • 八、代码获取与配置
  • 九、注意事项
  • 十、总结与展望

在当今数字化时代,数据库的性能和管理效率对于企业和开发者来说至关重要。openGauss 作为华为开源的国产高斯数据库,拥有广泛的应用场景。而基于 DeepSeek 构建的 openGauss AI 智能优化助手 deepseek-opengauss-agent,则为 openGauss 数据库的优化和管理带来了全新的解决方案。本文将深入介绍这个智能优化助手的各个方面,带你领略其强大的功能和魅力。

一、项目概述

1.1 项目简介

deepseek-opengauss-agent 是基于 deepseek-r1 开发的 openGauss 数据库优化智能助手。它借助大语言模型 deepseek 的能力,结合多种工具,能够对 openGauss 数据库进行 SQL 查询优化、性能诊断、索引建议、参数调优、SQL 执行等操作,帮助用户显著提升数据库的性能和管理效率。

1.2 环境说明

软件 配置
Windows11 16GB 内存 & 8GB 显存 ,个人笔记本电脑
DeepSeek - r1 14b & 32b,基于 ollama 部署的大模型
VMWare WorkStation 16 + 版本,用于创建虚拟机
openEuler20.03 LTS 华为开源的国产欧拉操作系统
openGauss5.0.0 华为开源的国产高斯数据库
Redis 基于 Key/Value 的内存数据库,用于存储历史对话信息
Python3.11.9 Python 解释器,该版本兼容性较好
PyCharm 社区版,用于编程的 IDE

1.3 项目代码结构

plaintext 复制代码
deepseek-opengauss-agent/
├── LICENSE
├── .gitignore
├── main.py
├── config.py
├── requirements.txt
├── database/
│   ├── __init__.py
│   ├── connector.py
│   └── schema.py
├── data/
│   ├── finance.sql
│   └── school.sql
├── driver/
│   └── openGauss - connector - python - pyog - master.zip
├── agent/
│   ├── __init__.py
│   ├── main_agent.py
│   ├── memory_manager.py
│   └── prompt_templates.py
├── web_ui/
│   ├── assets
│   │   ├── favicon.ico
│   ├── __init__.py
│   └── app.py
└── tools/
    ├── __init__.py
    ├── performance_diagnose.py
    ├── sql_executor.py
    ├── config_tuner.py
    ├── index_advisor.py
    ├── memory_manager.py
    └── sql_optimizer.py

二、系统架构剖析

2.1 架构图展示

输入请求 调用工具 调用工具 调用工具 调用工具 调用工具 操作 操作 操作 操作 操作 数据反馈 输出结果 记忆管理 调用模型 用户 OpenGaussOptimizationAgent SQL Optimizer Performance Diagnoser Index Advisor Config Tuner SQL Executor openGauss 数据库 Redis DeepSeek 模型

2.2 架构详细说明

  • 用户 :发起对 openGauss 数据库的操作请求,如 SQL 优化、性能诊断等。
  • OpenGaussOptimizationAgent :作为核心组件,接收用户请求,根据请求内容调用相应的工具进行处理。同时,它还负责与 Redis 进行记忆管理,以及调用 DeepSeek 模型获取专业的优化建议。
  • 工具集 :包括 SQL OptimizerPerformance DiagnoserIndex AdvisorConfig TunerSQL Executor,分别负责 SQL 查询优化、性能诊断、索引建议、参数调优和 SQL 执行等具体操作。
  • openGauss 数据库:存储和管理数据,工具集对其进行操作并获取反馈信息。
  • Redis :用于存储对话历史和相关信息,帮助 Agent 进行上下文感知和记忆管理。
  • DeepSeek 模型 :为 Agent 提供专业的数据库优化建议和知识支持。

三、系统功能模块解读

3.1 功能模块图展示

功能模块 功能模块 功能模块 功能模块 功能模块 OpenGaussOptimizationAgent SQL 查询优化 性能诊断 索引建议 参数调优 SQL 执行

3.2 功能模块详细说明

  • SQL 查询优化:分析用户提供的 SQL 查询语句,生成执行计划,识别潜在问题,并给出优化建议和优化后的 SQL 语句。
  • 性能诊断 :对 openGauss 数据库的整体性能进行诊断,识别系统状态、资源瓶颈和慢查询,并提供相应的优化建议。
  • 索引建议:根据用户指定的表名,分析现有索引情况,为表提供合适的索引优化建议。
  • 参数调优:根据用户提供的工作负载类型(如 OLTP、OLAP 或混合),对数据库的配置参数进行优化,给出当前配置和优化建议。
  • SQL 执行:直接执行用户提供的 SQL 语句,并返回执行结果。

四、系统数据流分析

4.1 数据流图展示

用户请求 调用工具请求 执行操作 操作结果 工具输出 处理结果 保存记忆 读取记忆 调用模型请求 模型响应 用户输出 OpenGaussOptimizationAgent 工具 openGauss 数据库 Redis DeepSeek 模型

4.2 数据流详细解释

  1. 用户输入 :用户向 OpenGaussOptimizationAgent 发送操作请求。
  2. Agent 处理Agent 解析用户意图,根据需求调用相应的工具,并将工具请求发送给工具集。
  3. 工具操作 :工具集对 openGauss 数据库进行操作,获取操作结果。
  4. 结果反馈 :工具将操作结果返回给 AgentAgent 对结果进行处理和分析。
  5. 用户输出Agent 将最终处理结果返回给用户。
  6. 记忆管理Agent 在处理过程中,将对话历史和相关信息保存到 Redis 中,以便后续使用。同时,也可以从 Redis 中读取记忆信息。
  7. 模型调用 :在需要专业知识和建议时,Agent 调用 DeepSeek 模型,获取模型的响应并应用到处理过程中。

五、核心技术组件工作原理揭秘

5.1 工作原理图展示

请求 解析意图 执行意图 优化意图 调用 SQL 执行器 调用 SQL 优化器 执行 SQL 优化 SQL 结果反馈 输出结果 记忆管理 调用模型 用户输出 OpenGaussOptimizationAgent 意图解析器 执行器 优化器 SQL Executor SQL Optimizer openGauss 数据库 Redis DeepSeek 模型

5.2 工作原理详细解释

  1. 意图解析Intent_Parser 对用户输入进行解析,判断用户的意图是执行 SQL 还是优化 SQL 等。
  2. 执行或优化 :根据解析结果,ExecutorOptimizer 分别调用相应的工具(如 SQL ExecutorSQL Optimizer)进行处理。
  3. 数据库操作 :工具对 openGauss 数据库进行操作,并将结果反馈给 Agent
  4. 结果输出Agent 将处理结果返回给用户。
  5. 记忆管理和模型调用 :在整个过程中,AgentRedis 进行记忆管理,同时在需要时调用 DeepSeek 模型获取专业建议。

六、关键代码深度解析

6.1 OpenGaussOptimizationAgent 类

python 复制代码
class OpenGaussOptimizationAgent:
    def __init__(self, session_id: str = "default"):
        # 初始化工具
        self.sql_optimizer = SQLOptimizer()
        self.performance_diagnoser = PerformanceDiagnoser()
        self.index_advisor = IndexAdvisor()
        self.config_tuner = ConfigTuner()
        self.sql_executor = SQLExecutor()

        # 创建工具集
        self.tools = [
            Tool(
                name="SQL Optimizer",
                func=self.optimize_sql,
                description="用于优化 SQL 查询语句。输入应该是一个完整的 SQL 查询。输出包含执行计划、问题分析和优化建议。",
            ),
            # 其他工具...
        ]

        # 初始化大语言模型
        self.llm = CustomOllamaLLM(
            model=DEEPSEEK_MODEL,
            temperature=0.3,
            endpoint=OLLAMA_ENDPOINT,
        )

        # 创建代理
        self.agent = create_react_agent(
            llm=self.llm,
            tools=self.tools,
            prompt=open_gauss_prompt_template,
        )

        # 初始化记忆管理器
        self.memory_manager = RedisMemoryManager(session_id)

        # 创建执行器
        self.agent_executor = AgentExecutor(
            agent=self.agent,
            tools=self.tools,
            verbose=True,
            handle_parsing_errors=True,
            memory=self.memory_manager.get_chat_history(APP_CONFIG["max_chat_history"]),
        )

    def run(self, user_input: str) -> str:
        # 解析用户意图
        user_intent, sql_query = self._parse_user_intent(user_input)

        if user_intent == "execute":
            # 执行 SQL
            result = self.execute_sql(sql_query)
            # 处理执行结果
            ...
        elif user_intent == "optimize":
            # 优化 SQL
            result = self.optimize_sql(sql_query)
            # 处理优化结果
            ...
        else:
            # 无法明确意图,使用 Agent 处理
            self.memory_manager.add_message("user", user_input)
            response = self.agent_executor.invoke({"input": user_input})
            if "output" in response:
                self.memory_manager.add_message("assistant", response["output"])
                return response["output"]
            return "抱歉,处理您的请求时出现问题。"

代码解释

  • __init__ 方法:初始化各种工具、大语言模型、代理、记忆管理器和执行器。这些组件协同工作,为用户提供数据库优化服务。
  • run 方法:解析用户意图,根据意图执行相应的操作(执行 SQL、优化 SQL 或使用代理处理),并返回处理结果。如果无法明确用户意图,则使用 Agent 进行处理。

6.2 analyze_execution_plan 方法

python 复制代码
def analyze_execution_plan(self, plan):
    # 初始化分析结果
    analysis = {"issues": [], "cost": 0, "warnings": []}

    # 尝试解析 JSON 字符串
    if isinstance(plan, str):
        try:
            plan = json.loads(plan)
        except json.JSONDecodeError as e:
            analysis["warnings"].append(f"执行计划 JSON 解析失败: {str(e)}")
            return analysis

    # 检查 plan 是否是列表
    if not isinstance(plan, list) or len(plan) == 0:
        analysis["warnings"].append(f"执行计划格式异常:预期为非空列表,但得到 {type(plan).__name__}")
        return analysis

    # 检查第一个元素是否包含 "Plan" 键
    root_plan = plan[0]
    if not isinstance(root_plan, dict) or "Plan" not in root_plan:
        analysis["warnings"].append(f"执行计划格式异常:缺少 'Plan' 键。类型: {type(root_plan).__name__}")
        return analysis

    # 提取总代价
    plan_node = root_plan["Plan"]
    total_cost = plan_node.get("Total Cost", 0)
    analysis["cost"] = total_cost

    def traverse_plan(node):
        # 检查节点类型并记录问题
        node_type = node.get("Node Type", "")
        if "Seq Scan" in node_type:
            table_name = node.get("Relation Name", "未知表")
            analysis["issues"].append({
                "type": "FULL_TABLE_SCAN",
                "table": table_name,
                "message": f"全表扫描表 {table_name},考虑添加索引"
            })
        elif "Sort" in node_type and node.get("Sort Method") == "external":
            analysis["issues"].append({
                "type": "EXTERNAL_SORT",
                "message": "外部排序操作,考虑增加 work_mem 参数或优化排序字段"
            })

        # 递归处理子节点
        if "Plans" in node:
            plans = node["Plans"]
            if not isinstance(plans, list):
                analysis["warnings"].append(f"'Plans' 字段类型异常:预期列表,但得到 {type(plans).__name__}")
                return
            for child in plans:
                if isinstance(child, dict):
                    traverse_plan(child)
                else:
                    analysis["warnings"].append(f"子计划格式异常:{type(child).__name__}")

    # 开始遍历执行计划
    traverse_plan(plan_node)

    return analysis

代码解释

  • 该方法用于分析 SQL 查询的执行计划,识别潜在的优化点。
  • 首先对执行计划进行格式检查和解析,然后提取总代价。
  • 递归遍历执行计划节点,根据节点类型记录潜在的问题,如全表扫描、外部排序等,并给出相应的优化建议。

七、使用说明与系统演示

7.1 使用说明

  1. 启动服务:运行 main.py 文件。
  2. 发起请求:通过命令行或其他方式向服务发送操作请求,如 SQL 查询、性能诊断等。
  3. 查看结果:服务将返回处理结果,包括执行计划、优化建议、性能诊断报告等。

7.2 系统演示效果

  • 系统首页 :在浏览器中输入 http://localhost:7860,正常打开如下图所示:

  • 执行 SQL 语句效果 :在对话框输入如下未经过优化的 SQL 语句(需要在 SQL 语句前添加 执行 sql:),让系统执行该 SQL 语句:

    sql 复制代码
    SELECT 
        c.c_id, 
        c.c_name, 
        c.c_phone, 
        b.b_number, 
        b.b_type 
    FROM 
        client c, 
        bank_card b 
    WHERE 
        c.c_id = b.b_c_id;

    执行结果如下:

    执行sql时,我在程序中添加了一些关键信息日志帮助理解:

    sql 复制代码
    INFO:root:检测到执行SQL意图...
    INFO:root:正在执行SQL查询: SELECT 
        c.c_id, 
        c.c_name, 
        c.c_phone,...
    ......
    解析SQL语句(获取语法树信息): {'tables': ['client'], 'columns': [], 'is_read_only': True, 'estimated_cost': 29.62}
    生成原始执行计划: [
      {
        "Plan": {
          "Node Type": "Hash Join",
          "Join Type": "Inner",
          ......
          "Actual Startup Time": 0.091,
          "Actual Total Time": 0.097,
          ......
          "Output": ["c.c_id", "c.c_name", "c.c_phone", "b.b_number", "b.b_type"],
          "Inner Unique": false,
          "Hash Cond": "(b.b_c_id = c.c_id)",
          "Plans": [......]
            }
          ]
        },
        "Triggers": [
        ],
        "Total Runtime": 0.238
      }
    ]
    ......
    分析执行计划并提取关键信息: {'scan_methods': ['Seq Scan', 'Seq Scan']......]}
    优化执行计划(调用优化器): SELECT 
        c.c_id, 
        c.c_name, 
        c.c_phone, 
        b.b_number, 
        b.b_type 
    FROM 
        client c, 
        bank_card b 
    WHERE 
        c.c_id = b.b_c_id;
    生成最终物理执行计划: [
      {
        "Plan": {
          "Node Type": "Hash Join",
          "Join Type": "Inner",
          "Startup Cost": 12.93,
          "Total Cost": 29.62,
          "Plan Rows": 220,
          "Plan Width": 514,
          "Actual Startup Time": 0.113,
          "Actual Total Time": 0.119,
          "Actual Rows": 20,
          "Actual Loops": 1,
          "Output": ["c.c_id", "c.c_name", "c.c_phone", "b.b_number", "b.b_type"],
          "Inner Unique": false,
          "Hash Cond": "(b.b_c_id = c.c_id)",
          "Plans": [
            {
              "Node Type": "Seq Scan",
              "Parent Relationship": "Outer",
              "Relation Name": "bank_card",
              "Schema": "public",
              "Alias": "b",
              "Startup Cost": 0.00,
              "Total Cost": 13.38,
              "Plan Rows": 338,
              "Plan Width": 212,
              "Actual Startup Time": 0.007,
              "Actual Total Time": 0.009,
              "Actual Rows": 20,
              "Actual Loops": 1,
              "Output": ["b.b_number", "b.b_type", "b.b_c_id"]
            },
            ......
          ]
        },
        "Triggers": [
        ],
        "Total Runtime": 0.289
      }
    ]
  • 优化 SQL 语句效果 :在对话框输入如下未经过优化的 SQL 语句(需要在 SQL 语句前添加 优化 sql:),让系统优化该 SQL 语句:

    sql 复制代码
    SELECT 
        c.c_name, 
        c.c_id_card, 
        p.pro_id, 
        p.pro_status, 
        p.pro_purchase_time 
    FROM 
        client c 
    INNER JOIN 
        property p 
    ON 
        c.c_id = p.pro_c_id 
    WHERE 
        p.pro_status = '可用';

    执行结果如下:

    优化sql时,我在程序中添加了一些关键信息日志帮助理解:

    sql 复制代码
    INFO:root:检测到优化SQL意图...
    INFO:root:正在优化SQL查询: SELECT 
        c.c_name, 
        c.c_id_card, 
        p.pro...
    [('finance', 'information_schema', 'tables', 'VIEW', None, None, None, None, None, 'NO', 'NO', None)]
    成功连接到openGauss数据库!
    用户输入: "优化sql:SELECT 
        c.c_name, 
        c.c_id_card, 
        p.pro_id, 
        p.pro_status, 
        p.pro_purchase_time 
    FROM 
        client c 
    INNER JOIN 
        property p 
    ON 
        c.c_id = p.pro_c_id 
    WHERE 
        p.pro_status = '可用';"
    "[\n  {\n    \"Plan\": {\n      \"Node Type\": \"Hash Join\",\n      \"Join Type\": \"Inner\",\n      \"Startup Cost\": 17.44,\n      \"Total Cost\": 29.24,\n      \"Plan Rows\": 2,\n      \"Plan Width\": 398,\n      \"Actual Startup Time\": 5.640,\n      \"Actual Total Time\": 5.649,\n      \"Actual Rows\": 3,\n      \"Actual Loops\": 1,\n      \"Output\": [\"c.c_name\", \"c.c_id_card\", \"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\"],\n      \"Inner Unique\": false,\n      \"Hash Cond\": \"(c.c_id = p.pro_c_id)\",\n      \"Plans\": [\n        {\n          \"Node Type\": \"Seq Scan\",\n          \"Parent Relationship\": \"Outer\",\n          \"Relation Name\": \"client\",\n          \"Schema\": \"public\",\n          \"Alias\": \"c\",\n          \"Startup Cost\": 0.00,\n          \"Total Cost\": 11.30,\n          \"Plan Rows\": 130,\n          \"Plan Width\": 306,\n          \"Actual Startup Time\": 0.006,\n          \"Actual Total Time\": 0.009,\n          \"Actual Rows\": 30,\n          \"Actual Loops\": 1,\n          \"Output\": [\"c.c_id\", \"c.c_name\", \"c.c_mail\", \"c.c_id_card\", \"c.c_phone\", \"c.c_password\"]\n        },\n        {\n          \"Node Type\": \"Hash\",\n          \"Parent Relationship\": \"Inner\",\n          \"Startup Cost\": 17.40,\n          \"Total Cost\": 17.40,\n          \"Plan Rows\": 3,\n          \"Plan Width\": 100,\n          \"Actual Startup Time\": 4.667,\n          \"Actual Total Time\": 4.667,\n          \"Actual Rows\": 3,\n          \"Actual Loops\": 1,\n          \"Output\": [\"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\", \"p.pro_c_id\"],\n          \"Hash Buckets\": 32768,\n          \"Original Hash Buckets\": 32768,\n          \"Hash Batches\": 1,\n          \"Original Hash Batches\": 1,\n          \"Peak Memory Usage\": 257,\n          \"Plans\": [\n            {\n              \"Node Type\": \"Seq Scan\",\n              \"Parent Relationship\": \"Outer\",\n              \"Relation Name\": \"property\",\n              \"Schema\": \"public\",\n              \"Alias\": \"p\",\n              \"Startup Cost\": 0.00,\n              \"Total Cost\": 17.40,\n              \"Plan Rows\": 3,\n              \"Plan Width\": 100,\n              \"Actual Startup Time\": 4.651,\n              \"Actual Total Time\": 4.657,\n              \"Actual Rows\": 3,\n              \"Actual Loops\": 1,\n              \"Output\": [\"p.pro_id\", \"p.pro_status\", \"p.pro_purchase_time\", \"p.pro_c_id\"],\n              \"Filter\": \"(p.pro_status = '\u53ef\u7528'::bpchar)\",\n              \"Rows Removed by Filter\": 1\n            }\n          ]\n        }\n      ]\n    },\n    \"Triggers\": [\n    ],\n    \"Total Runtime\": 5.866\n  }\n]"
    {
        "issues": [
            {
                "type": "FULL_TABLE_SCAN",
                "table": "client",
                "message": "\u5168\u8868\u626b\u63cf\u8868 client\uff0c\u8003\u8651\u6dfb\u52a0\u7d22\u5f15"
            },
            {
                "type": "FULL_TABLE_SCAN",
                "table": "property",
                "message": "\u5168\u8868\u626b\u63cf\u8868 property\uff0c\u8003\u8651\u6dfb\u52a0\u7d22\u5f15"
            }
        ],
        "cost": 29.24,
        "warnings": []
    }
    [
        {
            "priority": "HIGH",
            "action": "\u5728\u8868 client \u4e0a\u521b\u5efa\u7d22\u5f15",
            "sql": "CREATE INDEX idx_client_optim ON client(relevant_column);"
        },
        {
            "priority": "HIGH",
            "action": "\u5728\u8868 property \u4e0a\u521b\u5efa\u7d22\u5f15",
            "sql": "CREATE INDEX idx_property_optim ON property(relevant_column);"
        }
    ]

八、代码获取与配置

  • 8.1 代码下载:跳转到下载页面

  • 8.2 安装依赖:pip install -r requirements.txt

  • 8.3 配置环境变量:根据实际情况配置 config.py 文件。

九、注意事项

  • 请确保 openGauss 数据库正常运行,并且服务可以访问该数据库。
  • 请确保 redis 数据库正常运行,并且服务可以访问该数据库。
  • 在使用过程中,如果遇到问题,可以查看日志文件获取详细信息。

十、总结与展望

本文详细介绍了基于 DeepSeek 构建的 openGauss AI 智能优化助手的各个方面,包括项目概述、系统架构、功能模块、数据流、核心技术组件工作原理、关键代码、使用说明等。该智能优化助手为 openGauss 数据库的优化和管理提供了强大的支持,能够显著提升数据库的性能和管理效率。未来,随着技术的不断发展,相信这个智能优化助手将会不断完善和升级,为用户带来更多的惊喜。

相关推荐
杨小扩2 小时前
第4章:实战项目一 打造你的第一个AI知识库问答机器人 (RAG)
人工智能·机器人
whaosoft-1432 小时前
51c~目标检测~合集4
人工智能
雪兽软件2 小时前
2025 年网络安全与人工智能发展趋势
人工智能·安全·web安全
元宇宙时间3 小时前
全球发展币GDEV:从中国出发,走向全球的数字发展合作蓝图
大数据·人工智能·去中心化·区块链
小黄人20254 小时前
自动驾驶安全技术的演进与NVIDIA的创新实践
人工智能·安全·自动驾驶
CS创新实验室4 小时前
筑牢 AIGC 安全防线:警惕提示词注入攻击
安全·大模型·aigc·提示词·提示词注入
ZStack开发者社区5 小时前
首批 | 云轴科技ZStack加入施耐德电气技术本地化创新生态
人工智能·科技·云计算
X Y O6 小时前
神经网络初步学习3——数据与损失
人工智能·神经网络·学习
唯创知音6 小时前
玩具语音方案选型决策OTP vs Flash 的成本功耗与灵活性
人工智能·语音识别
Jamence6 小时前
多模态大语言模型arxiv论文略读(151)
论文阅读·人工智能·语言模型·自然语言处理·论文笔记