Industrial Internet AI Data Insight Method and System Based on Dynamic Skill System

By building a dynamic skills system in the Industrial Internet, encapsulating business knowledge into independent skills files, and combining semantic table routing and three-layer security protection, the challenges of the Text2SQL solution in the Industrial Internet are solved, achieving accurate understanding and secure response to user intent, and improving data analysis efficiency and security.

CN122309579APending Publication Date: 2026-06-30GUANGDONG TENGYI TECH CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
GUANGDONG TENGYI TECH CO LTD
Filing Date
2026-06-01
Publication Date
2026-06-30

Smart Images

  • Figure CN122309579A_ABST
    Figure CN122309579A_ABST
Patent Text Reader

Abstract

This invention discloses an industrial internet AI data insight method and system based on a dynamic skill system, relating to the fields of artificial intelligence, natural language processing, and industrial internet technologies. The method includes: a skill registration step, encapsulating business knowledge into independent skill files and registering them to an intelligent agent toolset; an intent matching and skill loading step, analyzing user intent and dynamically loading the complete content of matching skills; a context injection step, injecting the skill content into the current dialogue context; and a reasoning execution step, performing reasoning to generate a response based on the complete context. This invention, through a dynamic skill on-demand loading mechanism, overcomes the limitation of traditional Text2SQL solutions where prompts cannot exhaustively cover all user question scenarios, achieving accurate understanding and secure responses to diverse questions.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of artificial intelligence, natural language processing, and industrial internet technologies. More specifically, it relates to an industrial internet AI data insight method and system based on dynamic skill systems. Background Technology

[0002] In the field of modern industrial internet, enterprise data insights are a core capability supporting intelligent manufacturing and precise decision-making. With the deepening of industrial development, manufacturing enterprises have accumulated massive amounts of multi-dimensional data on production, supply chain, and equipment operation. Enterprise managers need to quickly extract business insights from this data to support key business scenarios such as procurement decisions, production scheduling, and quality control.

[0003] Traditionally, enterprise data analysis has relied heavily on IT professionals writing SQL queries, making it difficult for business users to directly access the data they need. In recent years, Text2SQL (Natural Language to SQL) technology has emerged, allowing users to directly query databases using natural language, greatly lowering the barrier to data acquisition.

[0004] Current mainstream Text2SQL solutions primarily employ fixed prompt words, static semantic mapping rule bases, or end-to-end models. While these solutions perform well in simple, closed testing environments, they face significant challenges in real-world industrial internet scenarios. 1) The dilemma of exhaustive prompting scenarios: Industrial Internet users express their questions in extremely diverse ways, and the preset prompting words cannot cover all questioning methods, leading to model comprehension bias; 2) Static solidification of business knowledge: Business knowledge (such as table names and field meanings) is hard-coded in the prompt words. When adding new business scenarios or changing rules, the prompt words need to be modified and redeployed. It cannot flexibly adapt to the customized needs of different tenants and is difficult to deal with the problem of excessively long context caused by massive table structures. 3) Lack of context in multi-turn dialogues: There is a lack of effective management of context during multi-turn interactions, making it impossible to achieve a coherent "query-follow-up" data analysis experience; 4) Data security and execution security risks: Directly allowing AI to generate and execute SQL poses risks such as malicious operations, crashing production databases, and disrupting data isolation. Summary of the Invention

[0005] This invention addresses the aforementioned technical problems by constructing an intelligent data insight solution based on a dynamic skill system. This solution overcomes the limitation of exhaustive prompt word scenarios in traditional Text2SQL systems, enabling accurate understanding and secure responses to diverse user queries. The specific solution is as follows: An industrial internet AI data insight method based on dynamic skill systems, the method specifically includes: Skill registration steps: Business knowledge, workflows, and tool call logic for different data analysis scenarios are encapsulated into independent, hot-swappable skill files, and the registration information of each skill file is pre-placed in the system prompts of the intelligent agent; Intent matching and skill loading steps: Receive natural language questions input by the user, analyze the user's intent, and when it is determined that the user's intent matches any registered skill, dynamically load the complete content of the matched skill by calling the skill file reading tool; Context injection step: The complete content of the dynamically loaded skill is injected as a temporary instruction into the context window of the current dialogue; Reasoning execution steps: The agent performs reasoning based on the complete context after injecting skill content and calls the corresponding tools to perform operations, generating and outputting the response results to the user's question.

[0006] Business knowledge refers to domain experience and rules in data analysis scenarios; workflow refers to the standard operating steps required to complete a specific analysis task; and tool invocation logic refers to the external tools invoked to achieve the analysis goals and their invocation order. The method of encapsulating this into a skill file is as follows: write the above content into a SKILL.md file in a separate directory using Markdown format. The file header declares the skill name and description using YAML metadata, and the body defines the skill profile, core capabilities, SOPs, available tools, and invocation flow in chapters. This skill file can be dynamically read by an agent using the read_agent_skill_file tool, enabling hot-swapping.

[0007] "Skill file" is defined as in the skill registration steps; "registered skill" refers to a skill whose registration information has been pre-placed in the system prompt; "matching skill" refers to a registered skill that matches the user's intent as determined by the intent matching steps.

[0008] The specific format of the skill file is a Markdown-formatted SKILL.md file. "Registering a skill" refers to pre-installing the registration information of each skill file into the agent's system prompt, enabling the agent to recognize the existence of the skill upon startup. This is achieved by registering the skill directory to the toolset using the AGENT_SKILL_INSTRUCTION variable and the register_agent_skills function. "Matching a skill" refers to the registered skill that matches the user's intent as determined by the intent matching step. This skill is obtained by the agent analyzing the user's natural language question. When the agent determines that the user's intent matches the description of any registered skill, it dynamically loads the complete content of the SKILL.md file in the skill directory by calling the read_agent_skill_file tool.

[0009] Furthermore, the skill file adopts Markdown format, and its content includes at least a skill profile, core competencies, standard operating procedures, and definitions of available tools.

[0010] Taking the SKILL.md file for the Text2SQL skill as an example: The "Skill Profile" includes role settings (e.g., "Enterprise Database Architect & Supply Chain Data Analysis Expert") and objectives ("Transforming user natural language questions into secure, executable SQL queries"); the "Core Capabilities" list the key technical capabilities of this skill, such as dynamic metadata management, intelligent intent recognition, semantic table routing, and robust SQL generation; the "Standard Operating Procedures" define the sequence of steps when executing this skill; and the "Definition of Available Tools" lists the tools that this skill can call (e.g., get_table_schema, execute_sql_query, etc.) and their uses. The correspondence between the above content and "Business Knowledge, Workflow, and Tool Calling Logic" is as follows: the skill profile and core capabilities together carry business knowledge, the standard operating procedures correspond to the workflow, and the definition of available tools and the subsequent "Workflow (Tool Calling Order)" reflect the tool calling logic.

[0011] Those skilled in the art will understand that the skill file organizes the above information in Markdown format, and the intelligent agent can obtain the complete knowledge and operating procedures required to perform a specific data analysis task after reading it.

[0012] Furthermore, the reasoning execution step and the context injection step also include a semantic table routing step: pre-setting semantic mapping rules from business keywords to database tables, accurately routing one or more tables most relevant to the user's intent from a massive database table based on the business keywords in the user's question, and dynamically obtaining the structural information of the table to assist in the generation of the structured query language SQL, and injecting the structural information of the target table determined by the routing as part of the context, along with the complete content of the skill, into the context window of the current dialogue.

[0013] Furthermore, the inference execution step also includes three layers of security protection steps: The first layer, authentication and decryption: verify user requests with JWT signatures and decrypt them using a hybrid RSA-AES encryption mechanism to obtain user identity and tenant information; The second layer implements security restrictions: before executing an SQL query, it verifies whether it is a SELECT statement and applies row count limits and timeout controls. The third layer is code sandbox execution: static analysis and keyword blacklist checks are performed on the Python code to be executed, and then it is executed in a restricted sandbox environment.

[0014] Furthermore, the inference execution step is followed by a streaming response step: events such as text increments, thought processes, and tool call states generated during the agent's inference process are managed through a message queue and converted into server-sent event SSE streams, which are pushed to the client in real time. At the same time, incremental output deduplication is achieved by caching the sent content.

[0015] Furthermore, the semantic table routing step specifically includes: 1) A semantic mapping rule base for pre-configured business keywords to database tables, wherein the semantic mapping rule base supports exact matching, fuzzy matching and combined matching; 2) When the user's intent matches the Text2SQL skill, the business keywords in the user's question are parsed, and one or more tables most relevant to the user's intent are routed from multiple data tables in the database according to the semantic mapping rule base. 3) Dynamically obtain the structure information of the routed table, including field names, data types, and field descriptions, and inject the structure information of the table as part of the context, along with the complete content of the skill, into the context window of the current dialog to assist in the generation of Structured Query Language (SQL).

[0016] Furthermore, the inference execution step specifically includes: 1) The ReAct reasoning framework is adopted, enabling the agent to alternately execute the thinking process and tool calls in the "reasoning-action" cycle; 2) When the user's intent matches a data query skill and requires the execution of an SQL query, the SQL execution tool is invoked, and a second layer of security protection is triggered before execution to verify whether the SQL statement is a SELECT query, while imposing row limit and timeout control on the returned results; 3) When the user's intent matches a data analysis skill and data analysis code needs to be executed, the Python sandbox tool is invoked, and a third layer of security protection is triggered before execution. Static analysis and keyword blacklist checks are performed on the code, and execution is carried out in a restricted sandbox environment after verification. 4) Return the results of the tool execution to the agent for use in the next round of inference.

[0017] Furthermore, the streaming response steps specifically include: 1) When the inference execution step is started, a message queue is enabled for the current session, and text increments, thought process increments, and tool call state events generated during the agent's inference process are pushed into the message queue. 2) Start the streaming consumption loop, consume events one by one from the message queue, and perform incremental calculation and deduplication on the events through the StreamDeduplicator deduplication tool; 3) Convert the processed incremental events into the SSE format for server-sent events and push them to the client in real time via an HTTP connection; 4) When the final result event is received, push the final event and close the SSE connection.

[0018] Furthermore, the inference execution step also includes a dynamic integration step for MCP remote tools: 1) Reserve the MCP remote tool interface in the agent's toolset to support dynamic loading of tools from a remote server that conforms to the Model Context Protocol (MCP); 2) When the skill matched by the user's intent requires the invocation of remote capabilities, the agent sends a tool invocation request to the remote server through the MCP remote tool interface; 3) Receive the tool execution results returned by the remote server, and push the tool call status and execution results to the client in real time through the SSE streaming response step; 4) The MCP remote tool supports two transmission protocols, streamable_http and SSE, enabling remote expansion and independent deployment of the tool's capabilities.

[0019] An industrial internet AI data insight system based on dynamic skill systems, the system specifically includes: The first module is used to encapsulate business knowledge, workflows, and tool call logic for different data analysis scenarios into independent, hot-swappable skill files, and pre-install the registration information of each skill file in the system prompts of the intelligent agent; The second module is used to receive natural language questions input by users, analyze user intent, and when it is determined that the user intent matches any registered skill, dynamically load the complete content of the matching skill by calling the skill file reading tool. The third module is used to inject the complete content of the dynamically loaded skill as a temporary instruction into the context window of the current dialogue. The fourth module is used by the agent to reason based on the complete context after injecting skill content, call the corresponding tools to perform operations, generate and output the response results to the user's question.

[0020] Compared with the prior art, the present invention has at least one of the following technical effects: 1. This invention encapsulates business knowledge, workflows, and tool invocation logic for different data analysis scenarios into independent, hot-swappable skill files. The complete content of the relevant skills is dynamically loaded only when the user's intent matches, achieving a "cold start for small prompts, dynamic injection of large skills" architecture. This allows the system to accurately understand diverse user question formats. Secondly, it enables hot-swappable skills. When adding new business scenarios or adjusting business rules, only the SKILL.md file in the skill directory needs to be created or modified; no modification to the core code or service restart is required for online implementation, significantly reducing system maintenance costs and iteration cycles. Thirdly, it significantly reduces token consumption and inference costs because the system loads the complete skill content only when needed, rather than pre-loading all business knowledge into system prompts. This avoids a large amount of irrelevant information occupying the context window, optimizing inference efficiency and cost. Fourthly, it supports customized needs from different enterprises and tenants. By configuring a dedicated skill package for each tenant, it enables flexible deployment of personalized data analysis capabilities, improving the system's scalability and commercial adaptability.

[0021] 2. The "dynamic skill on-demand loading" technical solution of this invention breaks through the fundamental limitations of traditional Text2SQL solutions, which restrict the length of system prompts and cannot exhaust all user question scenarios. Traditional solutions require pre-setting all information such as database schema, business rules, and SQL generation templates in system prompts. However, industrial internet users express their questions in extremely diverse ways. Scenarios such as different expressions of the same intent, colloquial expressions of business terminology, follow-up questions with implicit context, and complex combined queries cannot be completely covered by fixed prompts.

[0022] 3. In industrial internet scenarios, production databases often contain thousands of tables. Traditional solutions pre-load all table structure information into prompts, leading to excessively long contexts that exceed the context window limits of large models. This invention utilizes a semantic table routing mechanism to accurately identify user intent based on business keywords in user queries. It intelligently routes one or more of the most relevant tables from a massive table structure, dynamically acquiring and incorporating the structure information of the target table into SQL generation. This reduces the number of tables to be processed from thousands to single digits. For example, when a user asks "How many screws were produced last month?", the system accurately routes to the wide production table using keywords like "production" and "output," retrieving only a few dozen fields from that table instead of loading the metadata of all thousands of tables. This on-demand routing mechanism not only completely solves the problem of excessively long contexts and significantly reduces input token consumption in large models, but also significantly improves the accuracy of SQL generation. Because the model does not need to search through a massive number of unrelated table structures, it can focus on understanding the fields of relevant tables and constructing SQL, thus achieving more accurate and efficient data query responses.

[0023] 4. In industrial internet data analysis scenarios, users typically need multiple rounds of interaction to complete complex data analysis tasks. For example, they might first query the overall production situation, then inquire about specific data for a particular product category, and finally perform drill-down analysis by dimension. This invention, through a session-level state management mechanism, binds an independent intelligent agent instance and session lock to each user session. It uses the SessionRecord data structure to record session state, maintain session locks, and cache recent query results, achieving contextual coherence in multiple rounds of dialogue within the same session. When a user asks "Check last month's production situation" in the first round, and then inquires "How many screw products are there?" in the second round, the system understands that "screw products" is a filtering inquiry based on the previous production data. When the user requests "Check by workshop group" in the third round, the system understands that this is a secondary analysis of screw data. This coherent dialogue experience allows business personnel to refine their analysis needs naturally, as if conversing with a human analyst, without repeatedly entering complete query conditions. This significantly lowers the barrier to data analysis and improves the efficiency of gaining insights from data.

[0024] 5. In scenarios where AI directly generates and executes SQL, there are serious security risks such as malicious users inducing the generation of dangerous SQL, unrestricted queries crashing production databases, and difficulty in guaranteeing multi-tenant data isolation. This invention solves these problems by constructing a defense-in-depth system: The first layer of authentication protection ensures the legitimacy of the request source through JWT signature verification, protects the security of sensitive user identity and tenant information during transmission through RSA-AES hybrid encryption, and automatically parses tenant identifiers to achieve data isolation and attribution; the second layer of execution protection forces the SQL statement to start with SELECT before execution, rejects any dangerous operations such as DROP, DELETE, and UPDATE, and limits the number of rows returned to no more than 200 by default and controls the timeout to 30 seconds by default to prevent a large amount of data from crashing the production database; the third layer of code protection performs static analysis and AST syntax tree checks on Python code, establishes a keyword blacklist to block dangerous calls such as subprocess, os, and eval, and executes code in a restricted sandbox environment to prevent malicious code injection and system damage. The three layers of protection work together to ensure both the flexibility of data querying and the compliance of enterprise-level security requirements.

[0025] 6. In traditional Text2SQL solutions, users need to wait for the AI ​​to complete the entire reasoning process before seeing the results. For complex SQL queries and data aggregation tasks, the waiting time can be as long as tens of seconds, making it impossible for users to determine whether the system is working, resulting in a poor user experience. This invention uses a streaming response mechanism to push events such as text increments, thought processes, and tool call status generated during the agent's reasoning process to the front end in real time. Users can see the AI's reasoning progress without waiting for the complete results. Specifically, when a user asks a question, the front end immediately receives the thought process increment, showing that the AI ​​is analyzing the intent; then it receives the text increment, displaying the AI's generated response word by word; when the AI ​​calls the SQL execution tool, it pushes the tool call event showing "Executing SQL query"; after the tool completes execution, it continues to push the result analysis content. This real-time feedback mechanism allows users to clearly understand the system's processing progress and avoids interrupting operations due to waiting anxiety. At the same time, the StreamDeduplicator deduplication function calculates incremental content by caching sent text, avoiding duplicate sending, and deduplicates by message ID and tool call ID, ensuring the accuracy of the content displayed on the front end, significantly improving the smoothness of interaction and user experience. Attached Figure Description

[0026] To more clearly illustrate the technical solutions in the embodiments of this application, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0027] Figure 1 This is a flowchart illustrating an industrial internet AI data insight method based on a dynamic skill system, provided by an embodiment of the present invention. Figure 2 This is a schematic diagram of the structure of an industrial internet AI data insight system based on a dynamic skill system, provided by an embodiment of the present invention. Detailed Implementation

[0028] In the following description, specific details such as particular system architectures and techniques are set forth for illustrative purposes and not for limitation, in order to provide a thorough understanding of the embodiments of this application. However, those skilled in the art will understand that this application may also be implemented in other embodiments without these specific details. In other instances, detailed descriptions of well-known systems, apparatuses, circuits, and methods have been omitted so as not to obscure the description of this application with unnecessary detail.

[0029] It should be understood that, when used in this application specification and the appended claims, the term "comprising" indicates the presence of the described features, integrals, steps, operations, elements and / or components, but does not exclude the presence or addition of one or more other features, integrals, steps, operations, elements, components and / or a collection thereof.

[0030] It should also be understood that the term “and / or” as used in this application specification and the appended claims means any combination of one or more of the associated listed items and all possible combinations, and includes such combinations.

[0031] As used in this application specification and the appended claims, the term "if" may be interpreted, depending on the context, as "when," "once," "in response to determination," or "in response to detection." Similarly, the phrase "if determined" or "if detected [the described condition or event]" may be interpreted, depending on the context, as meaning "once determined," "in response to determination," "once detected [the described condition or event]," or "in response to detection [the described condition or event]."

[0032] Furthermore, in the description of this application and the appended claims, the terms "first," "second," "third," etc., are used only to distinguish descriptions and should not be construed as indicating or implying relative importance.

[0033] References to "one embodiment" or "some embodiments" as described in this specification mean that one or more embodiments of this application include a specific feature, structure, or characteristic described in connection with that embodiment. Therefore, the phrases "in one embodiment," "in some embodiments," "in other embodiments," "in still other embodiments," etc., appearing in different parts of this specification do not necessarily refer to the same embodiment, but rather mean "one or more, but not all, embodiments," unless otherwise specifically emphasized. The terms "comprising," "including," "having," and variations thereof mean "including but not limited to," unless otherwise specifically emphasized.

[0034] An industrial internet AI data insight method based on dynamic skill systems, the method specifically includes: Skill registration steps: Business knowledge, workflows, and tool call logic for different data analysis scenarios are encapsulated into independent, hot-swappable skill files, and the registration information of each skill file is pre-placed in the system prompts of the intelligent agent; Intent matching and skill loading steps: Receive natural language questions input by the user, analyze the user's intent, and when it is determined that the user's intent matches any registered skill, dynamically load the complete content of the matched skill by calling the skill file reading tool; Context injection step: The complete content of the dynamically loaded skill is injected as a temporary instruction into the context window of the current dialogue; Reasoning execution steps: The agent performs reasoning based on the complete context after injecting skill content and calls the corresponding tools to perform operations, generating and outputting the response results to the user's question.

[0035] Traditional data analysis tools (such as systems that convert natural language into SQL queries) have a major problem: they pre-write all possible business knowledge into prompts, but in practice, user questions are incredibly diverse, and some questions are not anticipated, leading to system misunderstandings. The core method of this invention to solve this problem is: first, package the knowledge, processes, and tools corresponding to different analysis tasks (such as checking production volume, calculating costs, and finding suppliers) into independent "skill files," like apps that can be installed and uninstalled at any time on a mobile phone; when the system starts, it only lets the agent know the names of the skills, without loading the full content; when a user asks a question, the agent first determines which skill the question belongs to (e.g., "What was the production volume last month?" matches the "check production volume skill"), then reads the complete usage instructions for that skill, temporarily placing these instructions as a work guide in the current dialogue context, and finally instructing the agent to reason, call tools, and provide the answer according to these instructions. This approach avoids cramming massive amounts of knowledge into prompts and can handle various question formats.

[0036] Business knowledge refers to domain experience and rules in data analysis scenarios; workflow refers to the standard operating steps required to complete a specific analysis task; and tool invocation logic refers to the external tools invoked to achieve the analysis goals and their invocation order. The method of encapsulating this into a skill file is as follows: write the above content into a SKILL.md file in a separate directory using Markdown format. The file header declares the skill name and description using YAML metadata, and the body defines the skill profile, core capabilities, SOPs, available tools, and invocation flow in chapters. This skill file can be dynamically read by an agent using the read_agent_skill_file tool, enabling hot-swapping.

[0037] "Skill file" is defined as in the skill registration steps; "registered skill" refers to a skill whose registration information has been pre-placed in the system prompt; "matching skill" refers to a registered skill that matches the user's intent as determined by the intent matching steps.

[0038] The specific format of the skill file is a Markdown-formatted SKILL.md file. "Registering a skill" refers to pre-installing the registration information of each skill file into the agent's system prompt, enabling the agent to recognize the existence of the skill upon startup. This is achieved by registering the skill directory to the toolset using the AGENT_SKILL_INSTRUCTION variable and the register_agent_skills function. "Matching a skill" refers to the registered skill that matches the user's intent as determined by the intent matching step. This skill is obtained by the agent analyzing the user's natural language question. When the agent determines that the user's intent matches the description of any registered skill, it dynamically loads the complete content of the SKILL.md file in the skill directory by calling the read_agent_skill_file tool.

[0039] In practice, the skill file adopts Markdown format, and its content includes at least a skill profile, core competencies, standard operating procedures, and definitions of available tools.

[0040] To ensure that intelligent agents can correctly understand and use skill files, this invention stipulates that skill files must be in a simple and easy-to-understand Markdown format and must contain at least four parts: a skill profile (e.g., the role setting of "I am a production data analysis expert"), core competencies (what this skill is good at), standard operating procedures (what to do in the first step, what to do in the second step), and available tools (which external tools can be called, such as tools for querying database table structures). In this way, the skill file acts like a detailed user manual, allowing the intelligent agent to understand how to complete the analysis task after reading it.

[0041] Taking the SKILL.md file for the Text2SQL skill as an example: The "Skill Profile" includes role settings (e.g., "Enterprise Database Architect & Supply Chain Data Analysis Expert") and objectives ("Transforming user natural language questions into secure, executable SQL queries"); the "Core Capabilities" list the key technical capabilities of this skill, such as dynamic metadata management, intelligent intent recognition, semantic table routing, and robust SQL generation; the "Standard Operating Procedures" define the sequence of steps when executing this skill; and the "Definition of Available Tools" lists the tools that this skill can call (e.g., get_table_schema, execute_sql_query, etc.) and their uses. The correspondence between the above content and "Business Knowledge, Workflow, and Tool Calling Logic" is as follows: the skill profile and core capabilities together carry business knowledge, the standard operating procedures correspond to the workflow, and the definition of available tools and the subsequent "Workflow (Tool Calling Order)" reflect the tool calling logic.

[0042] Those skilled in the art will understand that the skill file organizes the above information in Markdown format, and the intelligent agent can obtain the complete knowledge and operating procedures required to perform a specific data analysis task after reading it.

[0043] In specific implementation, the reasoning execution step and the context injection step also include a semantic table routing step: pre-setting semantic mapping rules from business keywords to database tables, accurately routing one or more tables most relevant to the user's intent from a massive database table based on the business keywords in the user's question, and dynamically obtaining the structural information of the table to assist in the generation of the structured query language SQL, and injecting the structural information of the target table determined by the routing as part of the context, along with the complete content of the skill, into the context window of the current dialogue.

[0044] In the Industrial Internet, a company's database may contain thousands of tables (such as production, procurement, and sales tables). Without proper processing, having an agent search for data in all these tables would overwhelm the context and prevent accurate table lookups. This invention adds a "semantic table routing" step between "loading skills" and "injecting skills into the context": a pre-built mapping database between business keywords and data tables (e.g., if a user mentions "screws," "output," or "production," it automatically corresponds to the "production wide table"); when a user asks a question, the system first quickly selects the most relevant one or a few tables from thousands based on the keywords in the question (e.g., "screw output"), then retrieves only the structural information (field names, data types, etc.) of these tables, and injects them along with the skill content into the context. This reduces the number of tables to be processed from thousands to single digits, solving the problem of excessively long contexts and making SQL generation more accurate.

[0045] The semantic table routing step is executed after intent matching and skill loading are complete, but before context injection. Its purpose is to accurately locate one or more tables most relevant to the user's intent from a massive database based on the business keywords in the user's query, and dynamically obtain table structure information to assist in subsequent SQL generation. The logical relationship between this step and the preceding and following steps is as follows: after skill loading, the target table to be queried is first determined through semantic table routing, and then the table structure information obtained from routing, along with the skill content, is injected into the context for use by the inference and execution steps.

[0046] In practice, the inference execution step also includes three layers of security protection steps: The first layer, authentication and decryption: verify user requests with JWT signatures and decrypt them using a hybrid RSA-AES encryption mechanism to obtain user identity and tenant information; The second layer implements security restrictions: before executing an SQL query, it verifies whether it is a SELECT statement and applies row count limits and timeout controls. The third layer is code sandbox execution: static analysis and keyword blacklist checks are performed on the Python code to be executed, and then it is executed in a restricted sandbox environment.

[0047] The three-layer security protection is not an additional step independent of the inference execution step, but is invoked during the inference execution process: the first layer is executed when a user request is received, the second layer is triggered before the SQL query is executed, and the third layer is triggered before the Python code is executed.

[0048] Allowing AI to directly generate and execute SQL or code poses significant security risks: users could potentially induce AI to perform deletion operations, or malicious code could attack the database. This invention embeds three layers of security protection into the inference and execution steps: First, user requests must undergo JWT signature verification and RSA-AES hybrid encryption to ensure legitimate identity and prevent the theft of tenant information; second, before executing SQL, a mandatory check ensures that only SELECT queries are allowed, strictly prohibiting dangerous operations such as DROP and DELETE, while limiting the number of rows returned to a maximum of 200 and setting a 30-second timeout to prevent database crashes; third, if Python code needs to be executed, static analysis and keyword blacklist checks are performed first (prohibiting dangerous calls such as subprocess, os, and eval), and then it is run in an isolated sandbox environment. These three layers of protection comprehensively safeguard enterprise data security from identity and SQL to code.

[0049] In practice, the inference execution step is followed by a streaming response step: events such as text increments, thinking processes, and tool call states generated during the agent's inference process are managed through a message queue and converted into server-sent event SSE streams, which are pushed to the client in real time. At the same time, incremental output deduplication is achieved by caching the sent content.

[0050] Traditional solutions often involve long waits for users to see complete results after submitting a question, leaving them unsure of the system's progress and resulting in a poor user experience. This invention adds a streaming response step after the inference execution step: any progress made by the agent during inference (such as "analyzing intent...", "generating SQL...", "executing query...") is pushed to the user in real time, like watching a live stream. The system manages these events through a message queue and converts them into SSE (Server Push Event) format before pushing them to the front end, while using caching to avoid duplicate content. This way, users don't have to wait passively; they can see the AI's thinking and operation process in real time, resulting in a smoother interaction.

[0051] In specific implementation, the semantic table routing step includes: 1) A semantic mapping rule base for pre-configured business keywords to database tables, wherein the semantic mapping rule base supports exact matching, fuzzy matching and combined matching; 2) When the user's intent matches the Text2SQL skill, the business keywords in the user's question are parsed, and one or more tables most relevant to the user's intent are routed from multiple data tables in the database according to the semantic mapping rule base. 3) Dynamically obtain the structure information of the routed table, including field names, data types, and field descriptions, and inject the structure information of the table as part of the context, along with the complete content of the skill, into the context window of the current dialog to assist in the generation of Structured Query Language (SQL).

[0052] This invention refines the specific implementation of semantic table routing: First, a semantic rule base is pre-established that supports exact matching (e.g., "purchase" → purchase table), fuzzy matching (e.g., "inventory" → purchase table), and combined matching. Second, when the user's intent matches the Text2SQL skill, business keywords are extracted from the user's question, and the most relevant one or more tables are selected from numerous data tables based on the rule base. Third, the structural information of these tables, such as field names, data types, and field descriptions, is dynamically obtained and provided to the subsequent SQL generation step. This ensures both the accuracy of routing and on-demand loading of table structures.

[0053] In specific implementation, the inference execution steps specifically include: 1) The ReAct reasoning framework is adopted, enabling the agent to alternately execute the thinking process and tool calls in the "reasoning-action" cycle; 2) When the user's intent matches a data query skill and requires the execution of an SQL query, the SQL execution tool is invoked, and a second layer of security protection is triggered before execution to verify whether the SQL statement is a SELECT query, while imposing row limit and timeout control on the returned results; 3) When the user's intent matches a data analysis skill and data analysis code needs to be executed, the Python sandbox tool is invoked, and a third layer of security protection is triggered before execution. Static analysis and keyword blacklist checks are performed on the code, and execution is carried out in a restricted sandbox environment after verification. 4) Return the results of the tool execution to the agent for use in the next round of inference.

[0054] Whether to execute an SQL query or data analysis code depends on the skill type matched to the user's intent and the agent's judgment in the ReAct inference loop: an SQL query is executed when the intent is a data query, and Python code is executed when the intent is data computation or analysis. Meanwhile, the "second layer of security" and the "third layer of security" refer to the execution security restrictions and code sandbox execution defined in claim 4.

[0055] This invention further details how the agent performs reasoning: it employs the ReAct framework, iteratively looping between "reasoning and action"—first thinking, then invoking tools, and finally considering the next step based on the results. Specifically, in industrial scenarios: when data needs to be retrieved, the agent invokes an SQL execution tool, automatically triggering the second layer of security protection (SELECT validation, row limit, and timeout) before execution; when complex data analysis is required (such as writing Python code for calculation), it invokes a Python sandbox tool, automatically triggering the third layer of security protection (static analysis, blacklist checking, and sandbox execution) before execution. The results of each tool execution are returned to the agent for use in the next round of reasoning until the final answer is obtained. This achieves secure and controllable multi-step reasoning.

[0056] In specific implementation, the streaming response steps include: 1) When the inference execution step is started, a message queue is enabled for the current session, and text increments, thought process increments, and tool call state events generated during the agent's inference process are pushed into the message queue. 2) Start the streaming consumption loop, consume events one by one from the message queue, and perform incremental calculation and deduplication on the events through the StreamDeduplicator deduplication tool; 3) Convert the processed incremental events into the SSE format for server-sent events and push them to the client in real time via an HTTP connection; 4) When the final result event is received, push the final event and close the SSE connection.

[0057] This invention further details the implementation of streaming responses: When inference execution begins, the system creates a message queue for the current session, pushing text increments, thought process increments, and tool call state events generated during the agent's inference process into this queue; then, a consumption loop is started, retrieving events one by one from the queue and using a deduplicator (StreamDeduplicator) to calculate the increment content, avoiding duplicate sending; afterwards, the processed increment events are converted into SSE format and pushed to the client in real time via an HTTP long connection; when the final result event is received, a "final" event is pushed and the connection is closed. In this way, the front end can display the AI's response and thought process word by word and sentence by sentence.

[0058] In specific implementation, the inference execution step also includes a dynamic integration step of the MCP remote tool: 1) Reserve the MCP remote tool interface in the agent's toolset to support dynamic loading of tools from a remote server that conforms to the Model Context Protocol (MCP); 2) When the skill matched by the user's intent requires the invocation of remote capabilities, the agent sends a tool invocation request to the remote server through the MCP remote tool interface; 3) Receive the tool execution results returned by the remote server, and push the tool call status and execution results to the client in real time through the SSE streaming response step; 4) The MCP remote tool supports two transmission protocols, streamable_http and SSE, enabling remote expansion and independent deployment of the tool's capabilities.

[0059] The MCP remote tool dynamic integration step is invoked during inference execution. MCP remote tool integration is implemented at the agent's toolset level. When a skill matching the user's intent requires the invocation of remote capabilities, the remote tool is invoked through the MCP tool manager during the inference execution step. This invention clarifies the invocation relationship between the MCP step, the inference execution step, and the streaming response step.

[0060] Enterprise data analysis often requires calling external services (such as third-party predictive models and remote data sources). Traditional methods require modifying system code for integration, which is inflexible. This invention introduces MCP (Model Context Protocol) for dynamic integration of remote tools: First, an MCP interface is reserved in the agent's toolset, allowing new tools to be loaded from remote servers conforming to the MCP protocol at any time. When a user's matched skill requires calling remote capabilities, the agent sends a tool call request to the remote server through the MCP interface during inference execution. After receiving the result, the tool call status and result are pushed to the user in real time through the aforementioned SSE streaming response. The MCP tool supports both streamable_http and SSE transport protocols, allowing tool capabilities to be deployed independently and dynamically expanded without modifying the main system code.

[0061] This invention provides an industrial internet AI data insight method based on a dynamic skill system. The method is based on the following system architecture, including: HTTP API Layer: Built on FastAPI, it provides an SSE streaming response interface for creating sessions, streaming chat, and ending sessions.

[0062] Session management layer: Includes AgentSessionManager, which is responsible for session creation, lifecycle management, concurrency control (session lock), and SSE event stream transformation and deduplication.

[0063] The core layer of the intelligent agent includes ReActAgent (inference-action intelligent agent) and its Toolkit. The toolkit includes an SQL execution tool (execute_sql_query), a schema query tool (get_table_schema), a table listing tool (list_database_tables), a time tool (get_current_time), a Python sandbox tool (safe_execute_python), a skill file reading tool (read_agent_skill_file), and a dynamically loadable MCP remote tool.

[0064] Dynamic Skills Layer: Contains a Skills Directory, such as Text2SQL_Skill (SQL generation skill), intelligent_dispatching (intelligent dispatching skill), quantity_skill (quantity query skill), etc. Each skill is an independent directory containing a SKILL.md file.

[0065] Security Authentication Layer: Includes Security Manager, which is responsible for JWT signature verification (RS256), RSA-AES hybrid encryption and decryption, and tenant / user identity resolution.

[0066] Data execution layer: contains SQL Server Executor, which is responsible for SQL security verification (only SELECT is allowed), row limit (default 200 rows), timeout control (default 30 seconds) and data serialization processing.

[0067] The dynamic skill system is the core innovation of this invention. Its core idea is to split fixed prompt words into multiple independent skill files and load them on demand according to user intent, so as to realize the architecture of "cold start of small prompt words + dynamic injection of large skills".

[0068] Skill file structure: Each skill is a separate directory containing a SKILL.md file that defines the complete knowledge of the skill. For example, the content of the SKILL.md file for the Text2SQL skill is as follows: text ---name: text2SQL Description: Enterprise database query skills, converting natural language into T-SQL queries. --- # Enterprise Intelligence Data Analyst (Text2SQL) Skills Document ## 1. Skill portrait - Role: Enterprise Database Architect & Supply Chain Data Analytics Expert - Objective: To translate user natural language questions into secure, executable SQL queries. ## 2. Core Competencies ### 2.1 Dynamic Metadata Management ### 2.2 Intelligent Intent Recognition ### 2.3 Semantic Table Routing ### 2.4 Robust SQL Generation ## 3. Key Workflows (SOPs) ## 4. Available Tools ## 5. Workflow (Tool Call Order) The above text defines a skill file named text2SQL, which guides the agent to transform users' natural language questions into secure and executable T-SQL queries. The YAML metadata section at the beginning of the file declares the skill name as text2SQL and describes it as an enterprise database query skill. The skill profile in the main body sets the agent's role as an enterprise-level database architect and supply chain data analysis expert, with the goal of transforming natural language questions into secure and executable SQL queries. The core capabilities section lists the four key capabilities of this skill, including dynamic metadata management for flexibly obtaining the structure information of database tables, intelligent intent recognition for accurately understanding the user's query intent, semantic table routing for accurately locating relevant data tables based on business keywords, and robust SQL generation for producing correct and reliable query statements. The subsequent key workflows, available tools, and workflow sections define the specific operation steps and tool call order when the skill is executed, enabling the agent to complete the entire task from user query to SQL generation according to a standardized process.

[0069] Skill registration and loading mechanism: First, skill registration is performed when the Agent starts. The registration information of the skill files is injected into the system prompt word via the AGENT_SKILL_INSTRUCTION variable, and the skill catalog specified in ENABLED_SKILL_DIRS is registered to the toolset via the register_agent_skills function.

[0070] Python AGENT_SKILL_INSTRUCTION = ( "# Agent Skills\n" "The agent skills are folders of instructions and resources thatimprove " "performance on specialized tasks. Each registered skill has a " "`SKILL.md` file that defines how to use it.\n" "If a user's request matches a registered skill, you must call " "`read_agent_skill_file` first and read the full `SKILL.md` before" "using that skill. Do not guess or paraphrase unread skillcontent." ) ENABLED_SKILL_DIRS = ("quantity_skill", "intelligent_dispatching", "Text2SQL_skill") def register_agent_skills(toolkit: Toolkit): for directory_name in ENABLED_SKILL_DIRS: toolkit.register_agent_skill(str(base_path / directory_name)) The code above implements the skill registration mechanism of the dynamic skill system: First, `AGENT_SKILL_INSTRUCTION` is a pre-defined instruction text in the agent system's prompts, informing the agent that skills are collections of instructions and resources stored in folders. Each skill contains a `SKILL.md` file defining its usage. When a user requests to match a skill, the agent must first call the `read_agent_skill_file` tool to read the complete skill file content, and must not guess or paraphrase unread skill content. Then, `ENABLED_SKILL_DIRS` is a tuple configuration that lists the three skill directories enabled by the system (quantity query skills, intelligent dispatch skills, and Text2SQL skills). Finally, the `register_agent_skills` function iterates through each directory name in the tuple and registers the complete path of the corresponding skill directory to the agent's toolset, enabling the agent to identify these skills at runtime and load their complete content as needed. This achieves the core architecture of "cold start with small prompts, dynamic injection of large skills," solving the fundamental problem in traditional solutions where prompts cannot exhaustively cover all user question scenarios.

[0071] When a user message is received, the agent analyzes the intent. If a skill (such as text2sql) is matched, the read_agent_skill_file tool is called to dynamically load the skill content and inject it into the current dialogue context. Finally, inference is performed based on the complete context.

[0072] Python async def process_user_message(user_message: str): intent = await agent.analyze_intent(user_message) if intent.matches_skill("text2SQL"): skill_content = await toolkit.call_tool( "read_agent_skill_file", skill_name="text2SQL" ) context.add_skill_instruction(skill_content) response = await agent.reason(user_message) return response The code above implements the core processing flow of intent matching and skill loading in the dynamic skill system: First, after receiving the user's natural language question, the agent calls the `analyze_intent` method to analyze the user's intent and identify the type of task the user wants to complete. Next, the `matches_skill` method determines whether the user's intent matches the skill named "text2SQL". If the match is successful, the `call_tool` method in the toolset is called to execute the `read_agent_skill_file` tool, passing in the skill name "text2SQL" to dynamically load the complete content of the `SKILL.md` file in the skill's directory. Then, the loaded skill content is injected into the context of the current dialogue using the `add_skill_instruction` method, enabling the agent to obtain the business knowledge, workflow, and tool usage specifications contained in the skill. Finally, the agent executes the `reason` method to infer based on the complete context after injecting the skill content, generating and returning the final response result to the user's question. The entire process embodies the core idea of ​​this invention: "on-demand loading and dynamic injection." The complete content of the relevant skill is only loaded when the user's intent matches, which avoids the problem of excessively long system prompts and ensures that the intelligent agent can accurately understand the diverse ways users ask questions.

[0073] Semantic table routing: Semantic table routing is one of the core capabilities of Text2SQL, used to solve the problem of "how users know which table to query." Business semantic mapping rules are pre-defined in the SKILL.md file of the Text2SQL skill. text ### 2.3 Semantic Table Routing Logic: Select one or more most relevant tables from the metadata index based on business keywords and context.

[0074] Exact matching rules: - Purchasing / Inventory / Suppliers → Ads_Purchase_WideTable- Sales / Ships / Customers → Ads_SalesOutbound_WideTable- Production / Completion / Output → Ads_Production_WideTable- Issuance / Consumption / Dispensing of Materials → Ads_Production_Material_Issuance_WideTable Full-process traceability rules: - When users mention "batch", "traceability", "lifecycle", or "incoming material destination" - Force selection of all tables containing BatchNo. The above text describes the core rule design of semantic table routing: its logic is to intelligently select one or more data tables most relevant to the user's intent from the metadata index based on the business keywords and contextual information in the user's query; the exact matching rule defines the mapping relationship between specific business keywords and data tables. When the user mentions "purchasing," "receiving goods," or "supplier," the routing is to the purchasing wide table; when the user mentions "sales," "shipping," or "customer," the routing is to the sales outbound wide table; when the user mentions "production," "completion," or "output," the routing is to the production wide table; and when the user mentions "requisition," "consumption," or "material input," the routing is to the production material requisition wide table. The full-process traceability rule stipulates that when the user mentions keywords such as "batch," "traceability," "lifecycle," or "material destination," the system will forcibly select all data tables containing batch number fields to support complete material traceability queries. Thus, by combining exact matching with forced table selection, the problem of exact matching between user queries and massive database tables is solved.

[0075] Based on the routing results, the table structure information is dynamically obtained using the get_table_schema tool to assist in SQL generation.

[0076] Python async def get_table_schema(table_name: str, schema: str = "dbo"): """Retrieves the structure information of a specified table""" schema_sql = f""" SELECT c.column_name, c.data_type, c.character_maximum_length, c.is_nullable, c.column_default, ep.value AS column_description FROM INFORMATION_SCHEMA.COLUMNS c LEFT JOIN sys.extended_properties ep ON ep.major_id = OBJECT_ID('{schema}.{table_name}') AND ep.minor_id = c.ordinal_position AND ep.name = 'MS_Description' WHERE c.table_schema = '{schema}' AND c.table_name = '{table_name}' ORDER BY c.ordinal_position; """ return await execute_query(schema_sql) The code above implements the core functionality of semantic table routing: First, based on the business keywords and contextual information in the user's query, it selects one or more data tables most relevant to the user's intent from the metadata index using pre-defined semantic table routing rules. The exact match rule maps keywords such as "purchase," "inbound," and "supplier" to the purchase wide table; "sales," "shipping," and "customer" to the sales outbound wide table; "production," "completion," and "output" to the production wide table; and "requisition," "consumption," and "material input" to the production material requisition wide table. The full-process traceability rule mandates that when a user mentions keywords such as "batch," "traceability," "lifecycle," or "material destination," all data tables containing a batch number field are forcibly selected to support complete material traceability queries. Then, based on the target table name determined by the routing, the `get_table_schema` function is called to dynamically obtain the detailed structure information of the table. This function obtains metadata such as the table's field names, data types, maximum length, nullability, and default values ​​by querying the database's system information view `INFORMATION_SCHEMA.COLUMNS`. At the same time, it obtains the Chinese description information of the fields by left-joining the system extended property view `sys.extended_properties`. Finally, it returns the complete table structure information in field order for use in subsequent SQL generation steps. This solves the problem of excessively long context caused by massive table structures in the production database and achieves accurate matching between user queries and database tables.

[0077] Multi-turn dialogue context management: To enable coherent multi-turn dialogues, the system implements session-level state management and concurrency control. The SessionRecord data class records the state, locks, and most recent results for each session.

[0078] Python @dataclass class SessionRecord: Runtime records for a single session session_id: str agent: Any # ReActAgent instance lock: asyncio.Lock # Session-level lock, ensuring serial execution status: str = "idle" # idle / running / interrupted updated_at: datetime running_task: asyncio.Task | None = None last_result: dict | None = None # Recent result cache The code above defines the data structure for session runtime records, used to implement context management and concurrency control for multi-turn dialogues: `SessionRecord` is a data class used to record all state information of a single user session during runtime. The `session_id` field uniquely identifies the session; the `agent` field stores the `ReActAgent` agent instance bound to the session, ensuring each session has an independent agent execution environment; the `lock` field is an asynchronous lock used to ensure that multiple requests within the same session are executed serially, preventing data corruption caused by concurrent operations; the `status` field records the current state of the session, including idle, running, or interrupted states, with idle being the default; the `updated_at` field records the last update time of the session, used for session expiration cleanup and status monitoring; the `running_task` field stores the currently executing asynchronous task object, facilitating support for session interruption operations; and the `last_result` field caches the result of the most recent query, enabling users to respond quickly based on context when conducting follow-up questions and drill-down analysis in multi-turn dialogues. Through this session-level state management mechanism, the system can effectively maintain the continuity of multi-turn dialogues and support users in a seamless interactive experience of "searching data → asking follow-up questions → drilling down for analysis".

[0079] In the stream_chat method, session locks are used to ensure that requests within the same session are executed serially, and state management is performed to support users in a coherent interaction of "querying data → asking follow-up questions → drilling down for analysis".

[0080] Three layers of security protection: First layer: JWT+RSA-AES dual authentication: The get_decrypted_principal function first verifies the JWT signature, and then performs RSA-AES hybrid decryption on the encrypted fields to obtain key information such as tenant ID and user ID.

[0081] The second layer: SQL execution security restrictions: In the execute_query method, the SQL statement must be validated to start with "SELECT", otherwise execution will be refused; and the max_rows parameter is used to limit the number of rows returned to prevent a large amount of data from crashing the database.

[0082] The third layer: Python sandbox execution: Through the SafePythonExecutor class, static analysis is performed on Python code generated by users or AI to check code length, keyword blacklist (such as subprocess, os, eval, etc.) and imported module blacklist. After verification, it is executed in a safe environment.

[0083] SSE Streaming Response: The system implements SSE streaming responses through message queues and a streaming deduplicator. The StreamDeduplicator class caches sent text and only encapsulates incremental content (delta) as assistant_chunk events for sending. It also deduplicates tool call events to prevent the front-end from receiving duplicate content. Supported event types include assistant_chunk (text increment), thinking_chunk (thinking process), tool_call (tool call), mcp_trace (MCP tool tracing), and final (final result), enabling real-time display of the reasoning process.

[0084] System Deployment and Skills Expansion: The system can be deployed as a multi-instance cluster, distributing requests through a load balancing layer and sharing a data storage layer (such as SQL Server, Redis, LiteLLM Gateway).

[0085] When adding a new skill (such as "device failure prediction"), you only need to create a new folder and SKILL.md file in the skill directory and add the directory name in ENABLED_SKILL_DIRS to achieve hot-swapping without modifying the core code or restarting the service.

[0086] Technical Performance Comparison: Compared to traditional Text2SQL solutions, this invention demonstrates significant advantages in scenario coverage, methods for adding new scenarios, security protection, multi-turn dialogue capabilities, response experience, scalability, and multi-tenancy support. This invention achieves accurate understanding of diverse user queries through a dynamic skill system; solves the table location problem under massive table structures through semantic table routing; enables coherent multi-turn dialogues through session-level management; ensures enterprise-level data security through a three-layer security protection system; and optimizes user experience through SSE streaming response, showcasing high technological advancement and practical value.

[0087] Based on the above, we can summarize the industrial internet AI data insight method based on dynamic skill systems. (See appendix) Figure 1 The method specifically includes: Skill registration steps: Business knowledge, workflows, and tool call logic for different data analysis scenarios are encapsulated into independent, hot-swappable skill files, and the registration information of each skill file is pre-placed in the system prompts of the intelligent agent; Intent matching and skill loading steps: Receive natural language questions input by the user, analyze the user's intent, and when it is determined that the user's intent matches any registered skill, dynamically load the complete content of the matched skill by calling the skill file reading tool; Context injection step: The complete content of the dynamically loaded skill is injected as a temporary instruction into the context window of the current dialogue; Reasoning execution steps: The agent performs reasoning based on the complete context after injecting skill content and calls the corresponding tools to perform operations, generating and outputting the response results to the user's question.

[0088] In practice, the skill file adopts Markdown format, and its content includes at least a skill profile, core competencies, standard operating procedures, and definitions of available tools.

[0089] In specific implementation, the reasoning execution step and the context injection step also include a semantic table routing step: pre-setting semantic mapping rules from business keywords to database tables, accurately routing one or more tables most relevant to the user's intent from a massive database table based on the business keywords in the user's question, and dynamically obtaining the structural information of the table to assist in the generation of structured query language SQL.

[0090] In practice, the inference execution step also includes three layers of security protection steps: The first layer, authentication and decryption: verify user requests with JWT signatures and decrypt them using a hybrid RSA-AES encryption mechanism to obtain user identity and tenant information; The second layer implements security restrictions: before executing an SQL query, it verifies whether it is a SELECT statement and applies row count limits and timeout controls. The third layer is code sandbox execution: static analysis and keyword blacklist checks are performed on the Python code to be executed, and then it is executed in a restricted sandbox environment.

[0091] In practice, the inference execution step is followed by a streaming response step: events such as text increments, thinking processes, and tool call states generated during the agent's inference process are managed through a message queue and converted into server-sent event SSE streams, which are pushed to the client in real time. At the same time, incremental output deduplication is achieved by caching the sent content.

[0092] In specific implementation, the semantic table routing step includes: 1) A semantic mapping rule base for pre-configured business keywords to database tables, wherein the semantic mapping rule base supports exact matching, fuzzy matching and combined matching; 2) When the user's intent matches the Text2SQL skill, the business keywords in the user's question are parsed, and one or more tables most relevant to the user's intent are routed from multiple data tables in the database according to the semantic mapping rule base. 3) Dynamically obtain the structure information of the routed table, including field names, data types, and field descriptions, and provide the table structure information as context to the SQL generation step.

[0093] In specific implementation, the inference execution steps specifically include: 1) The ReAct reasoning framework is adopted, enabling the agent to alternately execute the thinking process and tool calls in the "reasoning-action" cycle; 2) When an SQL query needs to be executed, the SQL execution tool is invoked, and a second layer of security protection is triggered before execution to verify whether the SQL statement is a SELECT query, and at the same time, the number of rows returned and timeout control are applied. 3) When data analysis code needs to be executed, the Python sandbox tool is invoked, and a third layer of security protection is triggered before execution. Static analysis and keyword blacklist checks are performed on the code, and execution is carried out in a restricted sandbox environment after verification. 4) Return the results of the tool execution to the agent for use in the next round of inference.

[0094] In specific implementation, the streaming response steps include: 1) When the inference execution step is started, a message queue is enabled for the current session, and text increments, thought process increments, and tool call state events generated during the agent's inference process are pushed into the message queue. 2) Start the streaming consumption loop, consume events one by one from the message queue, and perform incremental calculation and deduplication on the events through the StreamDeduplicator deduplication tool; 3) Convert the processed incremental events into the SSE format for server-sent events and push them to the client in real time via an HTTP connection; 4) When the final result event is received, push the final event and close the SSE connection.

[0095] In specific implementation, the inference execution step also includes a dynamic integration step of the MCP remote tool: 1) Reserve the MCP remote tool interface in the agent's toolset to support dynamic loading of tools from a remote server that conforms to the Model Context Protocol (MCP); 2) When the skill matched by the user's intent requires the invocation of remote capabilities, the agent sends a tool invocation request to the remote server through the MCP remote tool interface; 3) Receive the tool execution results returned by the remote server, and push the tool call status and execution results to the client in real time through the SSE streaming response step; 4) The MCP remote tool supports two transmission protocols, streamable_http and SSE, enabling remote expansion and independent deployment of the tool's capabilities.

[0096] See appendix Figure 2 As another embodiment of the present invention, corresponding to the above method, an industrial internet AI data insight system based on a dynamic skill system is obtained, the system specifically including: The first module is used to encapsulate business knowledge, workflows, and tool call logic for different data analysis scenarios into independent, hot-swappable skill files, and pre-install the registration information of each skill file in the system prompts of the intelligent agent; The second module is used to receive natural language questions input by users, analyze user intent, and when it is determined that the user intent matches any registered skill, dynamically load the complete content of the matching skill by calling the skill file reading tool. The third module is used to inject the complete content of the dynamically loaded skill as a temporary instruction into the context window of the current dialogue. The fourth module is used by the agent to reason based on the complete context after injecting skill content, call the corresponding tools to perform operations, generate and output the response results to the user's question.

[0097] AI Model Call Interface Design: The core intelligent agent (ReActAgent) in this invention interacts with large language models through a unified model call interface, supporting flexible switching between various mainstream model backends (such as OpenAI, Azure OpenAI, AnthropicClaude, locally deployed models, etc.).

[0098] Model call interface definition: Python from typing import List, Dict, Any, Optional from enum import Enum from dataclasses import dataclass import aiohttp import json class ModelProvider(Enum): """Supported model provider enumeration""" OPENAI = "openai" AZURE_OPENAI = "azure_openai" ANTHROPIC = "anthropic" LITELLM = "litellm" LOCAL = "local @dataclass class ModelConfig: Model configuration parameters provider: ModelProvider model_name: str api_base: Optional[str] = None api_key: Optional[str] = None temperature: float = 0.1 max_tokens: int = 4096 timeout: int = 60 class LiteLLMGateway: """ LiteLLM gateway interface, providing unified management of all model calls. LiteLLM is an open-source model gateway that provides a unified API interface for calling various large language models. """ def __init__(self, config: ModelConfig): self.config = config self.session = None self.base_url = config.api_base or "http: / / localhost:4000" #LiteLLM default port async def initialize(self): Initialize HTTP session self.session = aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=self.config.timeout), headers={ "Content-Type": "application / json", "Authorization": f"Bearer {self.config.api_key}" ifself.config.api_key else "" } ) async def chat_completion( self, messages: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None, tool_choice: Optional[str] = None, stream: bool = True ) ->Any: """ Call the model to complete the dialogue Args: messages: A list of conversation messages, formatted as [{"role": "user", "content":"..."}]. tools: A list of tool definitions that conform to the OpenAI function call specification. tool_choice: Tool selection strategy, "auto", "none", or specify the tool name. stream: Whether to enable streaming output Returns: Model response (streaming or non-streaming) """ payload = { "model": self.config.model_name, "messages": messages, "temperature": self.config.temperature, "max_tokens": self.config.max_tokens, "stream": stream } if tools: payload["tools"] = tools payload["tool_choice"] = tool_choice or "auto" # Calling the model via LiteLLM gateway async with self.session.post( f"{self.base_url} / v1 / chat / completions", json=payload (as response:) if stream: return self._handle_stream_response(response) else: return await response.json() async def _handle_stream_response(self, response): "Processing streaming responses, producing data block by block." async for line in response.content: if line: line = line.decode('utf-8').strip() if line.startswith("data: "): data = line[6:] if data == "[DONE]": break try: yield json.loads(data) except json.JSONDecodeError: continue async def close(self): """Close HTTP Session""" if self.session: await self.session.close() The code above implements a unified AI model invocation gateway interface: First, the ModelProvider enumeration defines the types of model providers supported by the system, including OpenAI, Azure OpenAI, Anthropic Claude, LiteLLM gateway, and locally deployed models. The ModelConfig data class is used to configure various parameters for model invocation, including provider type, model name, API address, authentication key, temperature parameter to control output randomness, maximum number of output tokens, and timeout. The LiteLLMGateway class encapsulates the interaction logic with the LiteLLM open-source model gateway. Its __init__ method receives model configuration and sets the base URL, the initialize method creates an asynchronous HTTP session and configures request headers, and the chat_completion method is the core invocation interface, receiving a message list, tool definition, tool selection strategy, and streaming output flags, constructing a request payload conforming to the OpenAI API specification, and transmitting it via HTTP. The POST request is sent to the chat / completions endpoint of the gateway. The stream parameter determines whether to return a streaming or non-streaming response. The _handle_stream_response method is used to process the streaming response, parse the SSE format data line by line, filter heartbeat packets, and produce JSON data block by block for upper layer consumption. The close method is responsible for closing the HTTP session and releasing resources. This enables the ability to call multiple different large language models with a unified interface, providing flexible model backend switching support for upper layer intelligent agents.

[0099] Intelligent agent model invocation integration: Python class ReActAgent: """ Inference-action intelligent agent, integrating model invocation interface """ def __init__(self, model_gateway: LiteLLMGateway, toolkit:Toolkit): self.model_gateway = model_gateway self.toolkit = toolkit self.system_prompt = self._build_system_prompt() self.message_queue = None # Streaming message queue self.msg_queue_enabled = False def _build_system_prompt(self) ->str: """Construct system prompts, including registration information for skill files""" prompt = """You are an enterprise-level industrial internet data analysis expert assistant. You can use the following tools to help users solve problems: - execute_sql_query: Executes an SQL query - get_table_schema: Retrieves the database table structure. - read_agent_skill_file: Reads the skill file - safe_execute_python: Execute Python code When a user's question requires a specific skill, the skill file must first be read by calling read_agent_skill_file.

[0100] """ # Add registration information for skill files prompt += AGENT_SKILL_INSTRUCTION return prompt async def reason(self, user_message: str) ->str: """ Execute the ReAct inference loop Use the Reasoning-Action loop: 1. Call the model to generate inference and actions. 2. If the model decides to invoke the tool, execute the tool. 3. Return the tool results to the model. 4. Repeat until the model gives the final answer. """ messages = [ {"role": "system", "content": self.system_prompt}, {"role": "user", "content": user_message} ] max_iterations = 10 iteration = 0 while iteration <max_iterations: iteration += 1 # Calling the model tools = self.toolkit.get_openai_tool_definitions() response = await self.model_gateway.chat_completion( messages=messages, tools=tools, stream=self.msg_queue_enabled ) # Processing responses (streaming or non-streaming) if self.msg_queue_enabled: # Streaming processing pushes content into a message queue. assistant_message=await self._process_stream_response(response) else: assistant_message=await self._process_sync_response(response) messages.append(assistant_message) # Check if tools need to be invoked tool_calls = assistant_message.get("tool_calls", []) if not tool_calls: # No tools were called, returning the final answer. return assistant_message.get("content", "") # Execution tool call for tool_call in tool_calls: tool_name = tool_call["function"]["name"] tool_args = json.loads(tool_call["function"]["arguments"]) # Execution tools tool_result = await self.toolkit.execute_tool(tool_name, tool_args) # Add tool results to messages messages.append({ "role": "tool", "tool_call_id": tool_call["id"], "content": json.dumps(tool_result) }) The system returned "Maximum number of iterations reached, unable to generate an answer". async def _process_stream_response(self, response_generator): """Process streaming responses by pushing incremental content into the message queue."" assistant_message = { "role": "assistant", "content": "", "tool_calls": [] } async for chunk in response_generator: if "choices" in chunk and chunk["choices"]: delta = chunk["choices"][0].get("delta", {}) # Processing incremental text if "content" in delta and delta["content"]: assistant_message["content"] += delta["content"] # Push into message queue await self.message_queue.put({ "type": "assistant_chunk", "text": delta["content"], "is_last": False }) # Process the thought process (if the model supports it) if "reasoning_content" in delta: await self.message_queue.put({ "type": "thinking_chunk", "text": delta["reasoning_content"] }) # Processing tool call if "tool_calls" in delta and delta["tool_calls"]: # Accumulated tool call information Pass # Push final event await self.message_queue.put({ "type": "final", "result": assistant_message}) return assistant_message The code above implements the complete functionality of the ReAct inference-action agent: During initialization, the ReActAgent class receives a model gateway and toolset instance, calls the `_build_system_prompt` method to construct system prompts containing role location, a list of available tools, and skill registration instructions; the core `reason` method uses the ReAct inference loop framework. First, it constructs a message list containing system prompts and user messages, sets a maximum number of iterations to prevent infinite loops, and in each iteration, retrieves the OpenAI format definitions of all tools from the toolset and calls the model gateway's `chat_completion` method to obtain the response. Depending on whether streaming output is enabled, it calls either `_process_stream_response` or `_process_sync_response` to process the response. The system adds the assistant messages returned by the model to the message history, checks whether the messages contain tool calls, and returns the final answer if no tool calls are found. If tool calls are found, it iterates through and executes each tool, using the unified `execute_tool` method of the toolset to execute the tools and adding the execution results as tools to the message history for use in the next round of inference. The `_process_stream_response` method is specifically designed to handle streaming responses, parsing the incremental data returned by the model block by block, extracting the incremental text and appending it to the accumulated messages, and pushing it into the message queue in real time for front-end display. It also processes incremental thinking process information and tool call information. After all content is processed, it pushes the final result event, thereby realizing the alternating execution of "reasoning-action", supporting complex task processing, and displaying the agent's reasoning process in real time through the streaming response mechanism, which significantly improves the user interaction experience.

[0101] MCP Remote Tool Integration Solution: This invention supports dynamic integration of remote tools that conform to the Model Context Protocol (MCP). MCP is an open-source protocol that defines a unified standard for interaction between AI applications and external tools / data sources.

[0102] MCP Protocol Overview The MCP protocol uses JSON-RPC 2.0 as its communication foundation and supports two transmission methods: SSE (Server-Sent Events): Applicable to pushing tool call results from the server to the client; stdio: Suitable for local inter-process communication; HTTP with SSE (streamable_http): Suitable for remote HTTP services; MCP client implementation: Python import asyncio import json import uuid from typing import Dict, Any, Optional, Callable from enum import Enum import aiohttp import sseclient class MCPTransportType(Enum): """MCP transport type""" SSE = "sse" STREAMABLE_HTTP = "streamable_http" STDIO = "stdio" class MCPTool: """MCP tool definition""" def __init__(self, name: str, description: str, input_schema:Dict[str, Any]): self.name = name self.description = description self.input_schema = input_schema def to_openai_tool_definition(self) ->Dict[str, Any]: """Convert to the OpenAI tool call format""" return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.input_schema } } class MCPClient: """ MCP protocol client, used for communication with remote MCP server Conforms to the Model Context Protocol specification: - Supports tool discovery (tools / list) - Supports tool calls (tools / call) - Supports both SSE and streamable_http transport methods """ def __init__(self, server_url: str, transport_type: MCPTransportType= MCPTransportType.SSE): self.server_url = server_url.rstrip(' / ') self.transport_type = transport_type self.session = None self.event_source = None self.request_id = 0 self._pending_requests: Dict[int, asyncio.Future] = {} async def initialize(self): Initialize MCP connection self.session = aiohttp.ClientSession() if self.transport_type == MCPTransportType.SSE: # SSE mode: Establish a long connection and receive push notifications from the server. await self._init_sse_connection() elif self.transport_type == MCPTransportType.STREAMABLE_HTTP: # Streamable_http mode: Use HTTP streaming responses pass # Send initialization request await self._send_request("initialize", { "protocolVersion": "2024-11-05", "clientInfo": { "name": "BlueValley-AI-Insight", "version": "1.0.0" } }) async def _init_sse_connection(self): """Initialize the SSE long connection""" sse_url = f"{self.server_url} / sse" response = await self.session.get(sse_url, headers={"Accept":"text / event-stream"}) self.event_source = sseclient.SSEClient(response) # Start the background task to process SSE events asyncio.create_task(self._process_sse_events()) async def _process_sse_events(self): """Process the SSE event stream""" for event in self.event_source: if event.event == "message": data = json.loads(event.data) request_id = data.get("id") if request_id in self._pending_requests: future = self._pending_requests.pop(request_id) future.set_result(data.get("result", {})) elif event.event == "error": print(f"MCP error: {event.data}") async def _send_request(self, method: str, params: Dict[str, Any]) ->Dict[str, Any]: Sending a JSON-RPC request. self.request_id += 1 request = { "jsonrpc": "2.0", "id": self.request_id, "method": method, "params": params } future = asyncio.Future() self._pending_requests[self.request_id] = future # Send request if self.transport_type == MCPTransportType.SSE: # In SSE mode, send requests via POST async with self.session.post( f"{self.server_url} / message", json=request as resp: if resp.status != 202: # 202 Accepted is expected in SSE mode return await resp.json() else: # Streamable_http mode, directly POST and wait for the streaming response. async with self.session.post( f"{self.server_url} / message", json=request as resp: if resp.headers.get("content-type") == "text / event-stream": # Handling streaming responses return await self._process_streamable_response(resp) else: return await resp.json() # Waiting for SSE's response return await asyncio.wait_for(future, timeout=30) async def _process_streamable_response(self, response): """Handling Streamable HTTP Responses"" result = {} async for line in response.content: line = line.decode('utf-8').strip() if line.startswith("data: "): data = json.loads(line[6:]) if "result" in data: result = data["result"] elif "error" in data: raise Exception(f"MCP error: {data['error']}") return result async def list_tools(self) ->list[MCPTool]: """Get a list of remote tools""" response = await self._send_request("tools / list", {}) tools = [] for tool_def in response.get("tools", []): tools.append(MCPTool( name=tool_def["name"], description=tool_def.get("description", ""), input_schema=tool_def.get("inputSchema",{}) )) return tools async def call_tool(self, tool_name: str, arguments: Dict[str, Any])->Dict[str, Any]: """ Call remote tool Args: tool_name: Tool name arguments: Tool arguments Returns: Results of tool execution """ response = await self._send_request("tools / call", { "name": tool_name, "arguments": arguments }) return response.get("content", []) async def close(self): """Close the connection""" if self.session: await self.session.close() The code above implements a client conforming to the Model Context Protocol (MCP) for communicating with a remote MCP server and dynamically integrating remote tools. First, it defines three transport types—SSE, streamable_http, and stdio—through the MCPTransportType enumeration. The MCPTool class defines the data structure of the remote tool and provides methods for converting it to the OpenAI tool call format. The MCPClient class is the core MCP protocol client. In the initialize method, it establishes a connection based on the transport type. In SSE mode, it calls _init_sse_connection to establish a long-lived connection and starts the background task _process_sse_events to continuously receive events pushed from the server. The _send_request method constructs a JSON-RPC-compliant request. The 2.0 specification requests objects are sent to the server's message endpoint via POST. In SSE mode, a Future object is created to asynchronously wait for the response and push it back via SSE. In streamable_http mode, the HTTP streaming response is waited for directly. The _process_streamable_response method parses the SSE format data line by line to extract the results. The list_tools method sends a tools / list request to obtain all tool definitions provided by the remote server and parses them into a list of MCPTool objects. The call_tool method sends a tools / call request, passing in the tool name and parameters to execute the remote tool and return the execution result. This enables dynamic discovery and invocation of remote tools, allowing the system to integrate remotely deployed tool capabilities without modifying the server-side code.

[0103] MCP tool dynamic integration mechanism: class MCPToolManager: """ MCP Tool Manager, responsible for dynamically loading and managing remote MCP tools. """ def __init__(self): self.mcp_clients: Dict[str, MCPClient] = {} self.remote_tools: Dict[str, MCPTool] = {} async def register_mcp_server(self, server_id: str, server_url:str, transport_type: MCPTransportType =MCPTransportType.SSE): """ Register MCP server Supports dynamic registration at runtime, without requiring a service restart. """ client = MCPClient(server_url, transport_type) await client.initialize() # Get a list of tools provided by the server tools = await client.list_tools() self.mcp_clients[server_id] = client # Register all tools For tool in tools: self.remote_tools[tool.name] = tool print(f"MCP tool registered: {tool.name} from {server_id}") async def unregister_mcp_server(self, server_id: str): "Deregister the MCP server and dynamically remove the tools it provides." if server_id in self.mcp_clients: await self.mcp_clients[server_id].close() del self.mcp_clients[server_id] # Remove all tools provided by this server # In actual implementation, it is necessary to maintain the mapping from server_id to tool. pass async def execute_tool(self, tool_name: str, kwargs) ->Dict[str,Any]: """ Execute MCP remote tools Find the corresponding MCP client based on the tool name and invoke the remote tool. """ # Find the MCP client to which the tool belongs for server_id, client in self.mcp_clients.items(): tools = await client.list_tools() if any(tool.name == tool_name for tool in tools): # Push tool calls status to message queue await self._push_tool_event(tool_name, "started") try: result = await client.call_tool(tool_name, kwargs) await self._push_tool_event(tool_name, "completed", result) return {"success": True, "result": result} except Exception as e: await self._push_tool_event(tool_name, "error",str(e)) return {"success": False, "error": str(e)} return {"success": False, "error": f"Tool {tool_name} notfound"} async def _push_tool_event(self, tool_name: str, status: str,data: Any = None): "Push tool calls events to message queue (for SSE streaming responses)" # This method is called by the agent's message queue. pass def get_openai_tool_definitions(self) ->List[Dict[str, Any]]: """Retrieve OpenAI format definitions for all remote tools""" return [tool.to_openai_tool_definition() for tool inself.remote_tools.values()] The code above implements the MCP tool manager, responsible for dynamically loading and managing remote MCP tools: The MCPToolManager class creates an empty dictionary during initialization to store MCP client instances and remote tool definitions. The `register_mcp_server` method supports runtime dynamic registration of MCP servers without restarting the service. This method creates an MCP client of the corresponding transport type and initializes the connection, calls the client's `list_tools` method to retrieve a list of all tools provided by the server, stores the client instance in the `mcp_clients` dictionary, and registers each tool in the `remote_tools` dictionary for quick later lookup. The `unregister_mcp_server` method is used to dynamically unregister the server, close client connections, remove them from the dictionary, and simultaneously remove the server. All provided tools; the `execute_tool` method is the unified entry point for executing remote tools. It iterates through all registered MCP clients to obtain their tool lists, finds the server where the target tool is located, and once found, first calls `_push_tool_event` to push the tool call start status to the message queue for real-time display in SSE streaming response. Then, it executes the tool call through the client, pushes the completion or error status based on the execution result, and returns the corresponding result. The `get_openai_tool_definitions` method iterates through all registered remote tools and converts them into OpenAI-compatible function call format, which is passed as tool definitions when the agent calls the model. This enables dynamic discovery, registration, execution, and status tracking of remote tools, allowing the system to flexibly extend the capabilities of external tools without modifying the core code.

[0104] Toolset Integration (Update): class Toolkit: """ Intelligent Agent Toolset, integrating local tools and MCP remote tools """ def __init__(self): self.local_tools: Dict[str, Callable] = {} self.mcp_manager: MCPToolManager = MCPToolManager() def register_local_tool(self, name: str, func: Callable, description: str, parameters: Dict[str, Any]): Register a local tool self.local_tools[name] = { "func": func, "description": description, "parameters": parameters } async def register_mcp_server(self, server_url: str, transport_type: MCPTransportType =MCPTransportType.SSE): "Dynamically register MCP remote server" await self.mcp_manager.register_mcp_server( server_id=f"server_{len(self.mcp_manager.mcp_clients)}", server_url=server_url, transport_type=transport_type ) async def execute_tool(self, tool_name: str, kwargs) ->Dict[str,Any]: "Unified execution tool (local or remote)" # Prioritize executing local tools if tool_name in self.local_tools: try: result = await self.local_tools[tool_name]["func"]( kwargs) return {"success": True, "result": result} except Exception as e: return {"success": False, "error": str(e)} # Attempt to execute MCP remote tool return await self.mcp_manager.execute_tool(tool_name, kwargs) def get_openai_tool_definitions(self) ->List[Dict[str, Any]]: """Get OpenAI format definitions for all tools (local + remote)""" definitions = [] # Add local tool definition for name, tool in self.local_tools.items(): definitions.append({ "type": "function", "function": { "name": name, "description": tool["description"], "parameters": tool["parameters"] } }) # Add MCP remote tool definition definitions.extend(self.mcp_manager.get_openai_tool_definitions()) return definitions The code above implements an agent toolset for unified management of local and MCP remote tools: The Toolkit class creates an empty dictionary to store local tools during initialization and instantiates an MCPToolManager to manage remote tools. The `register_local_tool` method registers the locally implemented tool functions, along with their descriptions and parameter definitions, into the local tool dictionary. The `register_mcp_server` method dynamically adds remote MCP servers by calling the MCP tool manager's registration interface, automatically generating a server ID and passing in the server address and transmission type. The `execute_tool` method is the unified tool execution entry point. It first checks if the tool name exists in the local tool dictionary; if it does, it calls the local function and returns the result; if it doesn't exist, it delegates the execution of the remote tool to the MCP tool manager. Both methods handle exceptions and return a unified success or error response format. The `get_openai_tool_definitions` method iterates through all local tools and all remote tools obtained through the MCP manager, converting them into OpenAI-compatible function call formats and generating a complete tool definition list for the agent to pass when calling the large language model. This achieves transparent and unified management of local and remote tools, enabling the agent to call various tools in the same way without distinguishing their origin.

[0105] MCP server configuration example: # mcp_servers.yaml # MCP server configuration file, supports dynamic loading servers: # External data source server - id: "external_data_source" url: "https: / / mcp.example.com / data-source" transport: "sse" enabled: true # Predictive Model Server - id: "prediction_service" url: "http: / / localhost:8080 / mcp" transport: "streamable_http" enabled: true # Enterprise Internal Tools Server - id: "enterprise_tools" url: "http: / / internal-mcp.company.com" transport: "sse" enabled: true The code above is a YAML-formatted MCP server configuration file used to define a list of remote MCP servers that need to be dynamically loaded. The configuration file defines three server instances through the servers node. Each server contains a unique identifier id to distinguish different servers in the system. The url field specifies the access address of the MCP service, and the transport field specifies the communication transmission protocol type. The external data source server and the enterprise internal tool server use the SSE transmission protocol to establish a long connection to receive server pushes. The prediction model server uses the streamable_http transmission protocol to support HTTP streaming responses. The enabled field controls whether the server is enabled. When the system starts, it automatically loads all enabled MCP servers according to this configuration file, dynamically obtains the list of tools they provide, and registers them into the intelligent agent toolset. This enables remote expansion and independent deployment of tool capabilities. External data sources, prediction models, and enterprise internal business tools can be integrated on demand without modifying the server-side code.

Claims

1. An industrial internet AI data insight method based on dynamic skill systems, characterized in that, The method specifically includes: Skill registration steps: Business knowledge, workflows, and tool call logic for different data analysis scenarios are encapsulated into independent, hot-swappable skill files, and the registration information of each skill file is pre-placed in the system prompts of the intelligent agent; Intent matching and skill loading steps: Receive natural language questions input by the user, analyze the user's intent, and when it is determined that the user's intent matches any registered skill, dynamically load the complete content of the matched skill by calling the skill file reading tool; Context injection step: The complete content of the dynamically loaded skill is injected as a temporary instruction into the context window of the current dialogue; Reasoning execution steps: The agent performs reasoning based on the complete context after injecting skill content and calls the corresponding tools to perform operations, generating and outputting the response results to the user's question.

2. The industrial internet AI data insight method based on dynamic skill systems as described in claim 1, characterized in that, The skill files are in Markdown format and include at least a skill profile, core competencies, standard operating procedures, and definitions of available tools.

3. The industrial internet AI data insight method based on dynamic skill systems as described in claim 2, characterized in that, The reasoning execution step and the context injection step also include a semantic table routing step: pre-setting semantic mapping rules from business keywords to database tables, accurately routing one or more tables most relevant to the user's intent from a massive database table based on the business keywords in the user's question, and dynamically obtaining the structural information of the table to assist in the generation of the structured query language SQL, and injecting the structural information of the target table determined by the routing as part of the context, along with the complete content of the skill, into the context window of the current dialogue.

4. The industrial internet AI data insight method based on dynamic skill systems as described in claim 1, characterized in that, The inference execution step also includes three layers of security protection: The first layer, authentication and decryption: verifies user requests with JWT signatures and decrypts them using a hybrid RSA-AES encryption mechanism to obtain user identity and tenant information; The second layer implements security restrictions: before executing an SQL query, it verifies whether it is a SELECT statement and applies row count limits and timeout controls. The third layer is code sandbox execution: static analysis and keyword blacklist checks are performed on the Python code to be executed, and then it is executed in a restricted sandbox environment.

5. The industrial internet AI data insight method based on dynamic skill systems as described in claim 2, characterized in that, Following the inference execution step, there is also a streaming response step: the text increments, thought processes, and tool call state events generated during the agent's inference process are managed through a message queue and converted into server-sent event SSE streams, which are pushed to the client in real time. At the same time, incremental output deduplication is achieved by caching the sent content.

6. The industrial internet AI data insight method based on dynamic skill systems as described in claim 3, characterized in that, The semantic table routing steps specifically include: 1) A semantic mapping rule base for pre-configured business keywords to database tables, wherein the semantic mapping rule base supports exact matching, fuzzy matching and combined matching; 2) When the user's intent matches the Text2SQL skill, the business keywords in the user's question are parsed, and one or more tables most relevant to the user's intent are routed from multiple data tables in the database according to the semantic mapping rule base. 3) Dynamically obtain the structure information of the routed table, including field names, data types, and field descriptions, and inject the structure information of the table as part of the context, along with the complete content of the skill, into the context window of the current dialog to assist in the generation of Structured Query Language (SQL).

7. The industrial internet AI data insight method based on dynamic skill systems as described in claim 4, characterized in that, The inference execution steps specifically include: 1) The ReAct reasoning framework is adopted, enabling the agent to alternately execute the thinking process and tool calls in the "reasoning-action" cycle; 2) When the user's intent matches a data query skill and requires the execution of an SQL query, the SQL execution tool is invoked, and a second layer of security protection is triggered before execution to verify whether the SQL statement is a SELECT query, while imposing row limit and timeout control on the returned results; 3) When the user's intent matches a data analysis skill and data analysis code needs to be executed, the Python sandbox tool is invoked, and a third layer of security protection is triggered before execution. Static analysis and keyword blacklist checks are performed on the code, and execution is carried out in a restricted sandbox environment after verification. 4) Return the results of the tool execution to the agent for use in the next round of inference.

8. The industrial internet AI data insight method based on dynamic skill systems as described in claim 5, characterized in that, The streaming response steps specifically include: 1) When the inference execution step is started, a message queue is enabled for the current session, and the text increment, thought process increment, and tool call state event generated during the agent's inference process are pushed into the message queue; 2) Start the streaming consumption loop, consume events one by one from the message queue, and perform incremental calculation and deduplication on the events through the Stream Deduplicator; 3) Convert the processed incremental events into the SSE format for server-sent events and push them to the client in real time via an HTTP connection; 4) When the final result event is received, push the final event and close the SSE connection.

9. The industrial internet AI data insight method based on dynamic skill systems as described in claim 1, characterized in that, The inference execution step also includes a dynamic integration step of MCP remote tools: 1) Reserve the MCP remote tool interface in the agent's toolset to support dynamic loading of tools from a remote server that conforms to the Model Context Protocol (MCP); 2) When the skill matched by the user's intent requires the invocation of remote capabilities, the agent sends a tool invocation request to the remote server through the MCP remote tool interface; 3) Receive the tool execution results returned by the remote server, and push the tool call status and execution results to the client in real time through the SSE streaming response step; 4) The MCP remote tool supports two transmission protocols, streamable_http and SSE, enabling remote expansion and independent deployment of the tool's capabilities.

10. An industrial internet AI data insight system based on a dynamic skill system, characterized in that: The system specifically includes: The first module is used to encapsulate business knowledge, workflows, and tool call logic for different data analysis scenarios into independent, hot-swappable skill files, and pre-install the registration information of each skill file in the system prompts of the intelligent agent; The second module is used to receive natural language questions input by users, analyze user intent, and when it is determined that the user intent matches any registered skill, dynamically load the complete content of the matching skill by calling the skill file reading tool. The third module is used to inject the complete content of the dynamically loaded skill as a temporary instruction into the context window of the current dialogue. The fourth module is used by the agent to reason based on the complete context after injecting skill content, call the corresponding tools to perform operations, generate and output the response results to the user's question.