Rail-llm-based urban railway passenger flow analysis and prediction intelligent interaction method and system

CN122946418APending Publication Date: 2026-10-20BEIJING JIAOTONG UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611065626.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-17
Publication Date
2026-10-20

Smart Images

  • Figure FT_1
    Figure FT_1
  • Figure FT_2
    Figure FT_2
  • Figure FT_3
    Figure FT_3
Patent Text Reader

Abstract

This invention provides a smart interactive method and system for passenger flow analysis and prediction in urban rail transit based on RAIL-LLM, belonging to the field of railway passenger flow prediction technology. Addressing the semantic bias, business illusion, and data security issues inherent in LLM in vertical transportation domains, this invention integrates rule constraints, semantic alignment, expert prior injection, and logic synthesis into the interaction process through structured prompt word engineering. Without adjusting the underlying model parameters, it significantly improves instruction execution, semantic alignment, and expert attribution performance, while ensuring data security. A four-dimensional prompt word engineering framework comprising rule constraints, attribute alignment, insight injection, and logic synthesis is constructed, exploring a reliable interaction paradigm for large language models in specialized vertical scenarios, providing a reference for artificial intelligence technology research in complex vertical business scenarios.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of railway passenger flow forecasting technology, specifically to a smart interactive method and system for passenger flow analysis and forecasting in urban rail transit based on RAIL-LLM. Based on the Large Language Model (LLM) prompt word engineering framework, and targeting the scenario of passenger flow analysis and forecasting in urban rail transit, a large language model for passenger flow interaction in urban rail transit (RAIL-LLM) is constructed. A smart interactive method for passenger flow analysis and forecasting in urban rail transit based on RAIL-LLM is proposed, achieving deep alignment between LLM and professional knowledge of urban rail transit without changing the underlying model parameters. Background Technology

[0002] As human-computer interaction technology has evolved from command-line interfaces to intelligent semantic understanding, the intelligent interaction paradigm in the rail transit field has undergone four generations of development: from early keyword retrieval to graphical interfaces based on expert systems, then to semantic parsing based on deep learning, and finally to the current intelligent agent interaction based on LLM.

[0003] Early rail transit information systems primarily employed an interactive mode similar to traditional search engines, using keyword matching and conditional retrieval to query information. Users needed to input specific fields (such as station name, date, and indicator type), and the system would perform string matching based on a rule base to return results. While this interactive method overcame the limitations of paper reports, it lacked semantic understanding capabilities, could not handle complex natural language (NL) queries, and its retrieval results relied heavily on precise keyword input, resulting in poor error tolerance. As passenger flow data dimensions surged and query demands became more complex, this mode gradually gave way to graphical interactive systems.

[0004] Based on expert systems and fixed menus, the system at this stage features pre-defined business rules, fixed menu navigation, and visual reports as its core characteristics. Passenger flow analysis logic is encoded through expert systems, and users complete queries by selecting parameters through multi-level menus. Early research primarily focused on rail transit passenger flow monitoring and system platform implementation. Although big data and IoT technologies were introduced into the underlying architecture to improve computational efficiency, the interaction layer still relied on a passive data-finding model: depending on pre-defined menu levels, fixed report templates, and parameter configurations. When faced with sudden, unstructured analytical needs, managers had to retrieve data level by level and make manual inferences, resulting in a lengthy decision-making process. Furthermore, the system only provided data presentation and lacked the ability to automatically analyze passenger flow evolution mechanisms; the effectiveness of the analysis highly depended on the user's business experience.

[0005] With the development of Natural Language Processing (NLP) technology, researchers have begun to explore an interactive paradigm that directly transforms natural language into structured query language (NL2SQL). This paradigm, based on semantic parsing and Text2SQL interaction, can break down the interaction barriers of fixed menus. Although it has achieved a preliminary bridge between natural language and structured queries, its functional modules are limited and lack in-depth integration with the physical mechanisms of passenger flow evolution.

[0006] In recent years, Generative Artificial Intelligence (GenAI), with LLM (Limited Language Modeling) as its core technology, is driving the transformation of human-computer interaction from fixed-rule matching to semantic understanding. LLM, with its pre-trained scale of tens to hundreds of billions of parameters, possesses strong capabilities in text generation, intent recognition, and complex logical reasoning, and has already demonstrated significant application potential in general domains. Compared to traditional interaction methods based on template matching or expert systems, LLM can achieve more flexible human-computer dialogue through natural language understanding, providing a new technological path for the intelligent transformation of vertical industries. This stage of technology presents two main branches: one is agent collaboration for operation and maintenance testing, and the other is knowledge-enhanced generation for operational decision-making.

[0007] The field of rail transit applications for intelligent interaction has undergone four generations of technological evolution, from keyword retrieval, expert system graphical interfaces, Text2SQL semantic parsing to LLM intelligent agents. However, the interaction paradigm is mainly based on preset functions and passive responses, and the system architecture relies on traditional development frameworks, making it difficult to adapt to the dynamic semantic parsing requirements of complex scenarios.

[0008] In summary, existing technologies still suffer from the following shortcomings: First, fragmented application scenarios and functionalities. While LLM applications possess semantic understanding capabilities, existing research exhibits significant domain segmentation, lacking coverage of the core operational scenario of passenger flow analysis and prediction. Passenger flow management possesses complex characteristics, combining regular commuting cycles with external disturbances, requiring dynamic analysis by integrating real-time prediction data and physical mechanisms. However, existing LLM research has not yet established a reliable interaction mechanism for this scenario. Second, insufficient dynamic data fusion and coupling with professional mechanisms. Existing LLM research mainly relies on static knowledge base retrieval enhancement, with limited ability to fuse and process dynamic data such as real-time passenger flow prediction and weather changes, making it difficult to achieve a deep closed loop between the prediction model and the interaction system. Especially in the context of rail transit network integration, the evolution of urban railway passenger flow is affected by the coupling of multiple factors. Existing research lacks a methodology for transforming previously mined passenger flow physical mechanisms into LLM-understandable prior knowledge, leading to business illusions in professional scenarios. Third, a lack of professional constraints and interpretability. General-purpose LLMs face the risk of "black box" decision-making in highly constrained professional scenarios, while existing research in vertical fields has not yet established effective domain knowledge injection and constraint mechanisms. A significant information gap exists between managers and algorithmic models, and the prediction results lack a transparent transformation path from numerical values ​​to business logic, limiting the in-depth application of intelligent interactive systems in high-reliability operational decision-making. Summary of the Invention

[0009] The purpose of this invention is to provide a smart interactive method and system for passenger flow analysis and prediction of urban railways based on RAIL-LLM, so as to solve at least one of the technical problems existing in the background art.

[0010] To achieve the above objectives, the present invention adopts the following technical solution:

[0011] In a first aspect, the present invention provides an intelligent interactive method for passenger flow analysis and prediction of urban rail transit based on RAIL-LLM, comprising:

[0012] Obtain raw passenger flow transaction data, external influencing factor data, and natural language query requests input by users for the target route; preprocess the raw passenger flow transaction data to extract multi-dimensional feature vectors including historical time series features, time attribute features, and weather features;

[0013] Based on the pre-built RAIL-LLM prompt engineering framework, intent recognition and semantic parsing are performed on the natural language query request, transforming the natural language query request into a structured query instruction, and generating an analysis constraint rule set. The RAIL-LLM prompt engineering framework includes structured prompt templates in four dimensions: rule constraint dimension R-Rule, semantic alignment dimension A-Attribute, prior knowledge injection dimension I-Insight, and logical synthesis dimension L-Logic.

[0014] The target feature subset is extracted from the preprocessed passenger flow data using the structured query command. The target feature subset is then input into a pre-trained passenger flow prediction model to obtain a passenger flow prediction numerical sequence. Based on the set of analysis constraint rules, a large language model is invoked to perform attribution analysis on the passenger flow prediction numerical sequence, generating a structured analysis report that includes data notification, anomaly identification, mechanism attribution, and operational suggestions.

[0015] As a further limitation of the first aspect of the present invention, the R-Rule dimension prompt word template realizes intent recognition and boundary constraints in the following way: when the user is detected to have enabled manual selection mode, the processor determines the task type according to the fixed mapping table between the front-end control state and the back-end task type, and suspends the semantic parsing function of the large language model; when the user does not enable manual selection mode, the processor calls the large language model to perform intent classification. In the NL2SQL generation stage, the prompt word soft constraint limits the generation to only SELECT / WITH type query statements, and hard interception verification is performed through the back-end regular expression filter and syntax tree parser.

[0016] As a further limitation of the first aspect of the present invention, the prompt word template of the A-Attribute dimension achieves semantic alignment in the following way: establishing a field mapping dictionary from the original data field to the business semantics, wherein the field mapping dictionary includes English field names, Chinese business interpretations, statistical calibers and dimensional information.

[0017] As a further limitation of the first aspect of the present invention, the I-Insight dimension prompt word template achieves prior knowledge injection in the following ways: based on the mutual information feature correlation evaluation results, a high-impact feature priority analysis rule is established in the prompt words to guide the large language model to consider each influencing factor in the attribution analysis according to the priority sequence; the statistical feature indicators of passenger flow fluctuations are written into the prompt word constraint rules, and the corresponding prior rule text is automatically loaded when a specific extreme weather scenario is detected; based on the results of previous empirical research, a compliant explanation path for specific abnormal correlation scenarios is preset in the prompt words.

[0018] As a further limitation of the first aspect of the present invention, the L-Logic dimension prompt word template realizes logical synthesis in the following way: in complex query tasks involving multiple table associations, the prompt word instruction requires the large language model to generate a thought process containing logic tree derivation before outputting the SQL script. The backend execution engine identifies and strips the thought content within the reasoning tags, and extracts only the standard executable SQL structured statement.

[0019] As a further limitation of the first aspect of the present invention, the method further includes a dual-agent collaborative scheduling step: when the task involves highly sensitive data or complex nested logic, a locally deployed agent is scheduled to execute the task, wherein the locally deployed agent loads the complete large language model and performs inference in a closed loop within the intranet environment; when the task is a regular query, a cloud API collaborative agent is scheduled to execute the task, wherein the cloud API collaborative agent calls the cloud large language model interface through an encrypted channel; the locally deployed agent and the cloud API collaborative agent share a unified RAIL-LLM prompt word template set.

[0020] Secondly, the present invention provides an intelligent interactive system for passenger flow analysis and prediction of urban rail transit based on RAIL-LLM, comprising:

[0021] The acquisition module is used to acquire the original passenger flow transaction data, external influencing factor data, and natural language query requests input by the user for the target route; and to preprocess the original passenger flow transaction data to extract multi-dimensional feature vectors including historical time series features, time attribute features, and weather features.

[0022] The transformation analysis module is used to perform intent recognition and semantic parsing on the natural language query request based on the pre-built RAIL-LLM prompt engineering framework, transforming the natural language query request into a structured query instruction, and generating an analysis constraint rule set. The RAIL-LLM prompt engineering framework includes structured prompt templates in four dimensions: rule constraint dimension R-Rule, semantic alignment dimension A-Attribute, prior knowledge injection dimension I-Insight, and logical synthesis dimension L-Logic.

[0023] The predictive analysis module is used to extract a target feature subset from the preprocessed passenger flow data using the structured query instructions, input the target feature subset into a pre-trained passenger flow prediction model to obtain a passenger flow prediction numerical sequence; based on the analysis constraint rule set, it calls a large language model to perform attribution analysis on the passenger flow prediction numerical sequence to generate a structured analysis report containing data notification, anomaly identification, mechanism attribution, and operational suggestions.

[0024] Thirdly, the present invention provides a non-transitory computer-readable storage medium for storing computer instructions, which, when executed by a processor, implement the intelligent interactive method for urban railway passenger flow analysis and prediction based on RAIL-LLM as described in the first aspect.

[0025] Fourthly, the present invention provides a computer device including a memory and a processor, wherein the processor and the memory communicate with each other, the memory stores program instructions that can be executed by the processor, and the processor calls the program instructions to execute the intelligent interactive method for urban rail passenger flow analysis and prediction based on RAIL-LLM as described in the first aspect.

[0026] Fifthly, the present invention provides an electronic device, comprising: a processor, a memory, and a computer program; wherein the processor is connected to the memory, the computer program is stored in the memory, and when the electronic device is running, the processor executes the computer program stored in the memory to cause the electronic device to execute instructions for implementing the intelligent interactive method for urban rail passenger flow analysis and prediction based on RAIL-LLM as described in the first aspect.

[0027] The beneficial effects of this invention are as follows: Addressing the semantic bias, business illusion, and data security issues inherent in LLM (Language Modeling) within the vertical transportation domain, this invention integrates rule constraints, semantic alignment, expert prior injection, and logical synthesis into the interaction process through structured prompt word engineering. This significantly improves instruction execution, semantic alignment, and expert attribution performance without adjusting the underlying model parameters, while simultaneously ensuring data security. Furthermore, a four-dimensional prompt word engineering framework comprising rule constraints, attribute alignment, insight injection, and logic synthesis is constructed, exploring a reliable interaction paradigm for large language models in specialized vertical scenarios and providing a reference for artificial intelligence technology research in complex vertical business scenarios.

[0028] The advantages of additional aspects of the invention will be set forth more clearly in the following description or will be learned by practice of the invention. Attached Figure Description

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

[0030] Figure 1 This is a closed-loop flowchart of the multi-dimensional evolution of prompt words for the RAIL-LLM framework as described in an embodiment of the present invention.

[0031] Figure 2 This is a hierarchical architecture diagram of the urban railway passenger flow prediction and analysis system described in an embodiment of the present invention.

[0032] Figure 3 As described in the embodiments of the present invention Figure 3 A schematic diagram of the interactive interface of the cloud API collaborative intelligent agent (Edge-Agent).

[0033] Figure 4 Actual image of the ticket type distribution described in this embodiment of the invention. Detailed Implementation

[0034] Embodiments of the present invention are described in detail below, examples of which are shown in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and should not be construed as limiting the present invention.

[0035] To facilitate understanding of the present invention, the present invention will be further explained and described below with reference to the accompanying drawings and specific embodiments. However, the specific embodiments do not constitute a limitation on the embodiments of the present invention.

[0036] Those skilled in the art should understand that the accompanying drawings are merely schematic diagrams of embodiments, and the components in the drawings are not necessarily essential for implementing the present invention.

[0037] Example 1

[0038] This embodiment provides a smart interactive system for passenger flow analysis and prediction of urban rail transit based on RAIL-LLM, including: an acquisition module for acquiring raw passenger flow transaction data, external influencing factor data, and natural language query requests input by the user for the target line; preprocessing the raw passenger flow transaction data to extract multi-dimensional feature vectors including historical time series features, time attribute features, and weather features; and a transformation and analysis module for performing intent recognition and semantic parsing on the natural language query requests based on a pre-built RAIL-LLM prompt word engineering framework, converting the natural language query requests into structured query instructions, and generating a set of analysis constraint rules; the RAI... The L-LLM prompt word engineering framework includes structured prompt word templates in four dimensions: rule constraint dimension (R-Rule), semantic alignment dimension (A-Attribute), prior knowledge injection dimension (I-Insight), and logical synthesis dimension (L-Logic). The predictive analysis module extracts a subset of target features from preprocessed passenger flow data using the structured query instructions, inputs the subset of target features into a pre-trained passenger flow prediction model, and obtains a passenger flow prediction numerical sequence. Based on the analysis constraint rule set, it calls a large language model to perform attribution analysis on the passenger flow prediction numerical sequence, generating a structured analysis report containing data notifications, anomaly identification, mechanism attribution, and operational suggestions.

[0039] In this embodiment, the above-described system is used to implement an intelligent interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM. This includes acquiring raw passenger flow transaction data, external influencing factor data, and natural language query requests input by the user for the target line; preprocessing the raw passenger flow transaction data to extract multi-dimensional feature vectors, including historical time-series features, time attribute features, and weather features; performing intent recognition and semantic parsing on the natural language query request based on a pre-built RAIL-LLM prompt word engineering framework, converting the natural language query request into a structured query instruction, and simultaneously generating an analysis constraint rule set; the RAIL-LLM prompt word engineering framework includes prompt word templates in four dimensions: rule constraint dimension, semantic alignment dimension, prior knowledge injection dimension, and logical synthesis dimension; extracting a target feature subset from the preprocessed passenger flow data using the structured query instruction, inputting the target feature subset into a pre-trained passenger flow prediction model to obtain a passenger flow prediction numerical sequence; and, based on the analysis constraint rule set, calling a large language model to perform attribution analysis on the passenger flow prediction numerical sequence to generate a structured analysis report containing data notification, anomaly identification, mechanism attribution, and operational suggestions.

[0040] In this embodiment, the automated construction and iterative optimization method of the RAIL-LLM prompt word engineering framework is used to generate the RAIL-LLM prompt word template set used in the method described in the first aspect. The method includes: a zero-sample benchmark testing and failure mode exposure step: under the condition of only providing the raw database table structure metadata to the large language model and without injecting domain prior knowledge, by inputting test instructions under extreme scenarios, the benchmark model is triggered to exhibit logical errors and inference biases, and domain experts use a double-blind evaluation method to identify typical failure modes of the model in the vertical business of urban railways; a failure decoupling and attribution step based on the RAIL-LLM dimension: the identified failure modes are attributed to the RAIL-LLM dimension one by one according to the root cause of the problem. The LM framework comprises four dimensions: rule constraints (corresponding to permission out-of-bounds failures), semantic alignment (corresponding to semantic gap failures), prior knowledge injection (corresponding to mechanistic illusion failures), and logical synthesis (corresponding to deduction out-of-control failures). The structured compensation steps for domain knowledge involve extracting deterministic natural language patches from the underlying system protocols and traffic mathematical laws extracted earlier, injecting them into system prompts, including security defense compensation, semantic alignment compensation, mechanistic empirical compensation, and output standardization compensation. The rolling verification step involves re-entering the compensated new prompts into the blind test sample set for multiple rounds of verification, continuously iterating and optimizing the prompt content until the model's output accuracy, logical consistency, and format standardization meet preset standards.

[0041] The R-Rule dimension prompt word templates achieve intent recognition and boundary constraints in the following ways: when the user is detected to have enabled manual selection mode, the processor determines the task type based on a fixed mapping table between the front-end control state and the back-end task type, and suspends the semantic parsing function of the large language model; when the user has not enabled manual selection mode, the processor calls the large language model to perform intent classification. In the NL2SQL generation stage, the prompt word soft constraint limits the generation to only SELECT / WITH type query statements, while hard interception verification is performed through the back-end regular expression filter and syntax tree parser.

[0042] The prompt word templates for the A-Attribute dimension achieve semantic alignment in the following way: a field mapping dictionary is established from the original data fields to the business semantics. The field mapping dictionary includes English field names, Chinese business definitions, statistical standards, and dimensional information.

[0043] The I-Insight dimension prompt word template achieves prior knowledge injection in the following ways: based on the mutual information feature correlation evaluation results, a high-impact feature priority analysis rule is established in the prompt words to guide the large language model to consider each influencing factor in the attribution analysis according to the priority sequence; statistical feature indicators of passenger flow fluctuations are written into the prompt word constraint rules, and the corresponding prior rule text is automatically loaded when a specific extreme weather scenario is detected; based on the results of previous empirical research, a compliant explanation path for specific abnormal correlation scenarios is preset in the prompt words.

[0044] The L-Logic dimension prompt word template achieves logical synthesis in the following way: In complex query tasks involving multiple table joins, the prompt word instruction requires the large language model to generate a thought process containing logic tree derivation before outputting the SQL script. The backend execution engine identifies and extracts the thought content within the reasoning tags, extracting only standard executable SQL structured statements.

[0045] In this embodiment, the method further includes a dual-agent collaborative scheduling step: when the task involves highly sensitive data or complex nested logic, a locally deployed agent is scheduled to execute the task, and the locally deployed agent loads the complete large language model and performs inference in a closed loop in the intranet environment; when the task is a regular query, a cloud API collaborative agent is scheduled to execute the task, and the cloud API collaborative agent calls the cloud large language model interface through an encrypted channel; the locally deployed agent and the cloud API collaborative agent share a unified RAIL-LLM prompt word template set.

[0046] In this embodiment 1, a smart interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM is first provided. This method is executed by the processor of a computer device and includes the following steps:

[0047] Step S1: Obtain the original passenger flow transaction data and external influencing factor data for the target route.

[0048] The processor reads two types of data from the data support layer: (1) raw passenger flow transaction data, including ACC clearing center data and Internet ride code data. Each record contains card number / device ID, entry station number, entry timestamp, exit station number, exit timestamp and ticket type, with time accuracy at the second level; (2) external influencing factor data, including hourly meteorological data (temperature at 2 meters above the ground, relative humidity, precipitation, rainfall, and wind speed at 10 meters) and holiday calendar data obtained through the historical meteorological interface of the Open-Meteo platform, as well as national railway arrival and departure train data obtained through the national railway timetable database. Among them, for a small number of time slice gaps in passenger flow data caused by network delay or equipment failure, the processor uses the local mean method to fill them; for instantaneous outliers caused by abnormal card swiping, the processor uses the 3σ principle to identify and smooth them.

[0049] Step S2: Preprocess and feature engineering the original passenger flow transaction data to generate a multi-dimensional feature vector.

[0050] This step involves the processor performing the following feature building operations:

[0051] S2-1: Construction of Historical Time Series Features. The processor extracts three types of time series features from the original passenger flow time series: (a) lag features, including short-term lags (passenger flow values ​​in the previous 5 minutes, 1 hour, and 2 hours) and periodic lags (passenger flow values ​​in the same period in the previous 24 hours and 7 days), used to explicitly model the temporal correlation of passenger flow; (b) sliding window statistical features, which calculate the rolling mean (to eliminate random noise), rolling standard deviation (to quantify the intensity of passenger flow fluctuations), and rolling maximum value (to capture local peak pressure) within a preset time window; (c) difference features, which calculate the first-order difference of passenger flow between adjacent time points, used to characterize the rate of change of passenger flow surges or drops.

[0052] S2-2: Construction of Time Attribute Features. The processor extracts four types of time attribute features: (a) Discrete time coding features, including hour, day of the week, and classification identifiers for weekdays / weekends / holidays; (b) Periodic time coding features, which convert discrete classification variables such as hour and day of the week into continuous coordinates on the unit circle through sine and cosine mapping, preserving the continuity of time sequence; (c) Commuting peak features, which construct the morning peak period of 7:00-9:00 and the evening peak period of 17:00-19:00 as binary dummy variables.

[0053] S2-3: Weather Feature Construction. The meteorological features extracted by the processor include: air temperature (°C) at 2 meters above the ground, relative humidity (%), precipitation in the previous period (mm), rainfall in the previous period (mm), and wind speed (km / h) at 10 meters above the ground. In addition, the processor also constructs weather interaction features, including: peak-hour temperature impact features (multiplying the morning / evening peak hour markers by the temperature values) and weekend rainfall impact features (multiplying the weekend markers by the rainfall amounts), to capture the differentiated regulatory effects of meteorological factors on passenger flow under specific social activity intensities.

[0054] S2-4: For railway passenger hub stations, additional rail transit network integration features are constructed. Based on the national railway timetable database, the processor constructs two types of network integration features: (a) train arrival and departure data features, including the number of arrival and departure trains of D-series and G-series trains, their lag characteristics, and rolling average characteristics; (b) capacity structure features, including the total number of train arrivals, the ratio of EMU and high-speed trains, and the interaction features between train arrival times and weekdays.

[0055] S2-5: Feature Normalization. The processor uses Min-Max Normalization to map all feature values ​​to the [0,1] interval for the constructed features, as shown in the following formula:

[0056]

[0057] In the formula, x is the original feature value, and x_min and x_max are the minimum and maximum values ​​of the feature in the training set, respectively.

[0058] Step S3: Based on the pre-built RAIL-LLM prompt word engineering framework, perform intent recognition and semantic parsing on the natural language query request, and transform the natural language query request into a structured query instruction.

[0059] The RAIL-LLM prompt word engineering framework comprises structured prompt word templates across four dimensions: rule constraint (R-Rule), semantic alignment (A-Attribute), prior knowledge injection (I-Insight), and logical composition (L-Logic). The specific execution mechanisms for each dimension in this step are as follows:

[0060] S3-1 (R-Rule Dimension – Rule-Driven Intent and Boundary Constraints): The processor implements a dual constraint mechanism. Intent Recognition Deterministic Control: The processor maintains a fixed mapping table between front-end control states and back-end task types. When it detects that a user has enabled manual selection mode (i.e., the front-end control state flag is set to manual mode), the processor directly determines the task type based on the mapping table and pauses the semantic parsing function of the large language model. Only when the user has not enabled manual selection mode does the processor call the large language model to perform intent classification, determining whether the user's request is "historical passenger flow analysis" or "future passenger flow prediction." SQL Execution Boundary Protection Mechanism: In the NL2SQL generation stage, the processor's prompt word template explicitly limits the large language model to only generating query-type (SELECT / WITH) operation statements. Simultaneously, the back-end execution engine is configured with a regular expression filter to perform syntax tree parsing and blacklist instruction verification on the generated code (intercepting keywords such as DROP, DELETE, UPDATE, INSERT, etc.), constructing a dual protection mechanism of soft constraints at the prompt word level and hard interception at the code level.

[0061] S3-2 (A-Attribute Dimension – Semantic Alignment Strategy for Underlying Data): The processor establishes a three-layer mapping relationship. **Raw Fine-Grained Data Business Semantic Interpretation:** The processor abandons the traditional intermediate aggregation table design and directly exposes the finest-grained raw passenger flow data to the large language model. In the system prompts, the processor supplements each English field with a complete Chinese business interpretation, clarifying the statistical scope and dimensions of each field. For example, it explains to the large language model that "entry_station" corresponds to "entry station" and "ticket_type" corresponds to "ticket type". **Professional Derivative Indicator Semantic Standardization:** The processor pre-defines the definitions and calculation logic of industry-specific indicators for the urban rail transit sector in the prompts. Taking the time imbalance coefficient as an example, the pre-defined definition is "Time Imbalance Coefficient = Maximum Cross-Sectional Passenger Flow in One-Way Peak Hour ÷ Average Value of Maximum Cross-Sectional Passenger Flow in All Time Periods in That Direction"; the calculation logic is "First execute GROUP BY time window aggregation, then perform extreme value ratio calculation". **Line Spatial Topology Semantic Constraints:** The processor explicitly supplements the spatial structural attributes of the urban rail transit lines in the prompts. For example, we define "upward" as the direction towards Taizhou Railway Station and "downward" as the direction towards Chengnan Station, so that the large language model can map natural language queries such as "downward direction during morning rush hour" into filtering conditions with corresponding station IDs.

[0062] S3-3 (I-Insight Dimension – Empirical Mechanisms and Prior Knowledge Injection): The processor transforms the previously mined physical mechanisms of passenger flow into prior constraints for the large language model. Pre-setting Priority Rules for Dominant Influencing Factors: Based on the previous mutual information feature correlation assessment results, the processor establishes high-impact feature priority analysis rules in the prompt word rule base. For example, it mandates that the large language model prioritize the core impact of temperature on the baseline passenger flow scale in passenger flow attribution analysis, guiding the model to strictly follow domain empirical rules. Passenger Flow Fluctuation Heterogeneity Illusion Suppression Constraints: The processor writes statistical characteristic indicators of passenger flow fluctuations into the prompt word constraint rules. For example, when the analysis scenario involves strong winds and extreme weather, the processor automatically loads the prior rule "The impact of wind speed on urban passenger flow has a high coefficient of variation across the entire range and is not a linear correlation" into the prompt words, guiding the model to fully consider the impact of environmental uncertainty. Anomaly Correlation Attribution Correction Mechanism: Based on previous empirical research results, the processor pre-sets a compliant explanatory framework for the model. For example, in response to the phenomenon that the arc elasticity of passenger flow on national railways and passenger flow on urban lines is significantly negative during certain periods on Taizhou S1 line, the prompt words are pre-set with reasonable explanations from multiple dimensions such as "fluctuations in urban passenger flow are dominated by urban commuting, the proportion of national railway connecting passenger flow is low, and off-peak travel during holidays", to avoid the model generating illusionary content with reversed causality.

[0063] S3-4 (L-Logic Dimension – Structured Logic Synthesis of Multi-Dimensional Temporal Features): The processor standardizes the inference logic and output format of the large language model. Implicit CoT Controllable Inference: In complex passenger flow data query tasks involving multiple table joins, the processor calls the large language model with native inference capabilities, forcing it to generate a thought process including logic tree derivation in the background before outputting the SQL script; then, the backend execution engine identifies and extracts the thought content within the inference tags, extracting only standard executable structured SQL statements. Standardized Generation of Analysis Reports: The processor forces the large language model to follow a standardized four-stage operational analysis format of "data overview report → anomaly feature identification → evolution mechanism tracing (combined with I-Insight dimension prior knowledge) → operational optimization suggestions" through prompts, strictly limiting the chapter level and expression specifications of the output content, and prohibiting the generation of chatty content unrelated to passenger flow analysis.

[0064] Step S4: Use the structured query command to extract the target feature subset from the preprocessed passenger flow data, and call the pre-trained passenger flow prediction model to make predictions.

[0065] The processor submits the structured query instructions (SQL statements) generated in step S3 to the database execution engine, queries the data support layer, and returns the target feature subset. Subsequently, the processor calls the pre-trained passenger flow prediction model to perform the prediction. The passenger flow prediction model uses a Random Forest (RF) model. In one specific implementation, the hyperparameters of the RF model are set to: n_estimators=300, max_depth=16. The RF model generates multiple training subsets through Bootstrap sampling, builds a decision tree on each training subset, and randomly selects a feature subset from the full feature set for optimal splitting feature selection when splitting nodes in each decision tree. Finally, the average of the prediction results from all decision trees is taken as the passenger flow prediction output. The passenger flow prediction model outputs a numerical sequence of predicted passenger flow for future periods at the target station or the entire line, with a prediction time granularity of 5 minutes.

[0066] Step S5: Based on the set of analytical constraint rules and the passenger flow prediction numerical sequence, call the large language model to perform attribution analysis and generate a structured report.

[0067] The processor combines the set of analytical constraint rules generated in step S3 (including prior knowledge rules injected from the I-Insight dimension and output format specifications defined from the L-Logic dimension) with the passenger flow prediction numerical sequence generated in step S4 to form the final prompt word. It then calls the large language model to perform the following processing: (a) Data Status Report: Read the predicted numerical sequence, calculate the maximum and minimum values ​​for key periods, and generate a data overview description text; (b) Abnormal Fluctuation Identification: Compare the predicted values ​​with historical baseline values ​​to identify and mark inflection points that significantly deviate from the baseline; (c) Traffic Mechanism Attribution: Combine the expert prior rules injected from the I-Insight dimension to provide a professional explanation of the causes of abnormal fluctuations; (d) Operational Recommendation Output: Based on the attribution analysis results, output optimization suggestions for operation management. Finally, the above four parts are combined into a structured analysis report conforming to industry standards and returned to the user through a multimodal interaction layer.

[0068] Example 2

[0069] This embodiment 2 provides a method for constructing and iteratively optimizing the RAIL-LLM prompt word template set as used in step S3 of embodiment 1. This method follows a closed-loop evolution process of "blind testing exposure → dimensionality reduction and decoupling → structured compensation → rolling verification," and is completed by experts in the field of computer-aided design. Specifically, it includes the following steps:

[0070] Step T1: Zero-sample initial compilation and extreme blind test exposure.

[0071] Initially, the processor only provides the large language model with basic database table structure information (table name, field name, field data type), without injecting any domain prior knowledge or business rules. The processor reads a pre-set set of extreme test instructions, covering various tasks such as basic queries (e.g., "query the number of passengers entering a station on a certain day"), complex associations (e.g., "compare the passenger and alighting volumes of two stations"), and anomaly attribution (e.g., "analyze the reasons why passenger flow increased but national railway arrivals and departures decreased during a certain period"). The processor assembles each test instruction with the table structure information into basic prompts, sends them to the large language model, and receives the model output. Domain experts use a double-blind evaluation method to review the output, identifying and recording typical failure modes of the model in the vertical business of urban railways.

[0072] Step T2: Failure decoupling and attribution based on RAIL-LLM dimensions.

[0073] Domain experts categorized the failures exposed in blind testing according to their root causes, classifying them one by one into the four dimensions of the RAIL-LLM framework:

[0074] (a) R dimension – Permission overstepping: The large language model has not established the role of a "read-only analysis expert" and is induced by natural language commands to generate high-risk database operation statements (such as DROP and DELETE), which is attributed to the lack of rule constraint dimension; (b) A dimension – Semantic discontinuity: The large language model has not identified the business definition of the special indicators of the urban railway and adopts a general semantic understanding method, which leads to the SQL query logic not matching the actual data retrieval requirements, which is attributed to the lack of semantic alignment dimension; (c) I dimension – Mechanism illusion: Faced with abnormal passenger flow fluctuations, the large language model lacks the support of local line empirical laws and only relies on general pre-trained knowledge to generate erroneous explanations that do not match the actual traffic mechanism, which is attributed to the lack of prior knowledge injection dimension; (d) L dimension – Uncontrolled inference: The large language model does not have the structured reasoning logic of standardized reports, and the output content is loose, redundant and disordered in format, which is attributed to the lack of logical synthesis dimension.

[0075] Step T3: Structured compensation of domain knowledge.

[0076] To address the shortcomings of the attribution identification in step T2, the underlying system protocols and traffic mathematical patterns extracted in the previous stage are refined into deterministic natural language patches and injected into system prompt words:

[0077] (a) Security Defense Compensation: An SQL operation blacklist mechanism is embedded in the prompt, explicitly limiting it to "You are an advanced database read-only analysis expert. When generating SQL, you must and are only allowed to generate query statements that begin with SELECT or WITH. It is strictly forbidden to include any form of DROP, DELETE, UPDATE, GRANT, or REPLACE instructions in the generated code." (b) Semantic Alignment Compensation: A field semantic mapping dictionary is built into the prompt, clarifying the correspondence between each English abbreviation field and business indicators, and unifying the logic of indicator calculation operators. For example, "Passenger flow = sum of entry records + transfer records, the generated SQL is strictly prohibited from containing the exit_station field" and "Passenger volume = UNION ALL merge entry and exit records and then COUNT". (c) Mechanism Empirical Compensation: The characteristics of multi-source heterogeneous influence and passenger flow evolution are transformed into executable decision rules and written into the prompt. For example, the prompt message states, "When analyzing Taizhou Railway Station or Wenling Railway Station, the arrival and departure of national railways have the greatest impact and exhibit a positive elastic response. However, during 14:00-15:00 or the evening peak, passenger flow shows a negative elastic response to the arrival and departure of national railways, and attribution to external transportation delays is strictly prohibited." (d) Output standardization compensation: The prompt message forces the model to follow a fixed three-part output structure of "data status report → abnormal fluctuation identification → traffic mechanism attribution → operation optimization suggestions," and prohibits the use of unnecessary format symbols such as Markdown.

[0078] Step T4: Scrolling verification.

[0079] After completing the structured compensation in step T3, the updated system prompts are re-entered into the blind test sample set for a new round of verification. The model outputs before and after compensation are compared to evaluate the instruction execution success rate, semantic alignment accuracy, and business logic acceptance. Steps T1 to T4 are continuously iterated until the model output meets the preset standards, ultimately resulting in a standardized RAIL-LLM prompt template set for use in step S3 of Example 1.

[0080] The theoretical framework of the RAIL-LLM urban rail passenger flow interaction prompts is shown in Table 2.

[0081] Table 2. Theoretical Framework of RAIL-LLM Urban Rail Transit Passenger Flow Interaction Prompt Terms

[0082]

[0083] Dimension 1: R-Rule: Rule-driven intentions and boundary constraints

[0084] The R-Rule dimension is executed in step S3 of the method of this invention. Through the dual mechanisms of intent recognition deterministic control and SQL execution boundary protection, a standardized constraint on LLM operation permissions is constructed.

[0085] (1) Deterministic control of intent identification

[0086] The processor implements the intent routing logic that allows the front end to manually select the priority through the query method.

[0087] First, the processor receives the mode parameter from the front-end interaction layer, which can take the values ​​'prediction' (passenger flow prediction), 'analysis' (passenger flow analysis), or None (not manually selected).

[0088] When mode='prediction', the processor first calls the _detect_prediction_request method to detect whether the user input contains a predicted intent. If the detection result is not a predicted intent, the processor returns a pattern conflict error and does not perform subsequent processing; if the detection result is consistent, it is routed to the prediction processing pipeline. When mode='analysis', symmetrical logic is used for pattern consistency verification. This mechanism is the "front-end hard constraint priority" principle—when the manual mode is activated, the task type path is directly locked, and the LLM autonomous semantic judgment is suspended. When mode is None, the processor calls the _detect_prediction_request method to perform automatic intent classification. This method adopts a two-level comprehensive strategy of keyword matching and LLM semantic judgment: first, the user input is matched with keywords using the prediction keyword list ['predict', 'estimate', 'future', 'next', 'after', 'will', 'tomorrow', 'next week']; at the same time, it checks whether the previous round of assistant response in the dialogue history contains prediction task-specific markers ("confidence", "estimate", "predict"). By combining keyword matching results with the context of the dialogue history, the type of task currently requested is determined.

[0089] (2) SQL execution boundary protection mechanism

[0090] Before submitting the LLM-generated code text to the database execution engine, the processor performs multi-layered security checks using the `_clean_and_validate_sql` method:

[0091] The first layer—format preprocessing—is performed sequentially by removing Markdown code block markers (``sql and ```), removing SQL comments (-- single-line comments and / * * / multi-line comments), and compressing redundant whitespace characters. The second layer—whitelist-based mandatory validation—converts the preprocessed SQL text to uppercase and checks if it begins with SELECT or WITH. If it doesn't, the processor throws a security interception exception, preventing the SQL from executing. The third layer—blacklist regular expression scanning—uses a list of regular expressions with word boundary recognition (\b) to scan the SQL text for the following dangerous keywords: DROP, DELETE, UPDATE, INSERT, ALTER, CREATE, TRUNCATE, RENAME, GRANT, REVOKE, REPLACE. If any blacklist keyword is matched, the processor throws a security interception exception and logs an alert. The fourth layer—multi-statement injection protection—checks if the SQL text contains a semicolon (;) before the end. If detected, it's considered a multi-statement concatenation injection attack, and a security interception exception is thrown.

[0092] Only after all four layers of verification pass can the processor submit the SQL statement to the database execution engine. At the soft constraint level of the prompt, the system prompt also embeds the role-identifying instruction "You are an expert-level MySQL programmer" and the SQL generation restriction "Only output SQL statements, without any textual explanation."

[0093] Dimension 2: A-Attribute: Semantic alignment strategy for underlying data

[0094] The A-Attribute dimension is executed in the NL2SQL generation stage and prediction parameter extraction stage of step S3 of the method described in Example 1. By establishing a virtual semantic mapping in the prompt words, it bridges the cognitive gap between the English abbreviation fields of the underlying physical database and the natural language of business personnel.

[0095] (1) Business semantic interpretation of raw data fields

[0096] In the system prompt, the processor injects complete field semantic descriptions into the LLM table by table. Taking the card_data table as an example, the processor explicitly states in the prompt: "The card_data table contains entry_station, entry_id, entry_time, exit_station, exit_id, and exit_time, with the time in DATETIME format and UTC time zone; it also contains card_number: card number, ticket_name: ticket type, and amount: amount." Taking the weather_holiday table as an example, it is specified that: "time: time (DATETIME format, UTC time zone), temperature_2m: temperature, relative_humidity_2m: relative humidity, precipitation: precipitation, rain: rainfall, snowfall: snowfall, snow_depth: snow depth, wind_speed_10m: wind speed, holiday: whether it is a holiday (1=yes, 0=no), weekend: whether it is a weekend (1=yes, 0=no), workday: whether it is a workday (1=yes, 0=no), event: whether there is a special event (1=yes, 0=no)".

[0097] This method does not modify the physical field names of the underlying database. Instead, it dynamically injects field definitions through prompts each time an LLM is called, thus avoiding the engineering risks of physically modifying tables.

[0098] (2) Standardized definition of the calculation logic of professional indicators

[0099] Within the same system prompt, the processor pre-sets the calculation logic for core indicators of urban rail passenger flow analysis. The calculated indicators are as follows:

[0100] 1) Basic Passenger Flow Analysis

[0101] a. Number of passengers entering the station

[0102] Station entry volume: The number of passengers using urban rail transit to enter and travel within the statistical period. In the formula: Indicates the number of passengers entering the station; This indicates the number of people whose tickets are checked at the station's entry gates, expressed in ten thousand people. This indicates the number of people entering the station using other credentials, expressed in tens of thousands of people.

[0103] Line entry volume: The number of passengers entering the station from this line during the statistical period.

[0104]

[0105] In the formula: Indicates the number of passengers entering the station; This indicates the number of passengers entering and exiting the station on this line, in ten thousand passengers. This indicates the number of passengers entering the station on this line and exiting on other lines, expressed in tens of thousands of passengers.

[0106] b. Outbound volume

[0107] Station exit volume: During the statistical period, the number of passengers who exit the city rail transit station from the paid area to the non-paid area using tickets, turnstiles, handheld ticket machines or other credentials.

[0108]

[0109] in, Indicates the number of passengers leaving the station; This indicates the number of passengers whose tickets are checked at the exit gates, in ten thousand people. This indicates the number of people exiting the station using other credentials, expressed in tens of thousands of people.

[0110] Line exit volume: The number of passengers who exit the station at this line during the statistical period.

[0111]

[0112] in, Indicates the number of passengers leaving the station; This indicates the number of passengers entering the station from other lines and exiting from this line, expressed in tens of thousands of passengers.

[0113] c. Passenger volume

[0114] Station passenger volume: During the statistical period, the number of passengers provided with entry and transfer services at urban rail transit operating stations is the sum of entry volume and transfer volume. ; Indicates station passenger volume;

[0115] Line passenger volume: During the statistical period, the total number of passenger trips carried by urban rail transit lines is the sum of the number of passengers entering the lines and the number of transfers. ; Indicates the passenger volume of the route

[0116] d. Station Passenger Volume: The total number of passengers who entered, transferred, or exited the urban rail transit operating stations during the statistical period. ; Indicates station passenger volume

[0117] e. Passenger flow

[0118] Total passenger volume: Passenger volume on the same route.

[0119] Average passenger flow: During the statistical period, the total number of passengers transported per hour on urban rail transit lines is the sum of the average hourly station entry volume and transfer volume. ;

[0120] in, Indicates average passenger flow; This indicates the operating time of the line, in hours (h).

[0121] f. Passenger Turnover: During the statistical period, the sum of the products of each passenger's trip and the corresponding travel distance on the operating routes, also known as passenger turnover. ;

[0122] in, Indicates the passenger turnover of the route; This indicates the travel distance for each passenger, expressed in ten-thousand-passenger-kilometers.

[0123] g. Cross-sectional passenger flow: The number of passengers passing between two adjacent stations in one direction within 1 hour on an operating line, also known as cross-sectional passenger volume.

[0124] Maximum cross-sectional passenger flow: The maximum passenger flow of the operating line cross-section under normal operating conditions.

[0125] h. Ticket type ratio: The proportion of a certain ticket type used to enter the station on urban rail transit out of the total number of passengers entering the station.

[0126] ;

[0127] in, Indicates the first Ticket type entry volume , Number of ticket types; Indicates the first The proportion of different ticket types;

[0128] i. Month-on-month: The ratio of changes in quantity over two consecutive statistical periods, expressed as the month-on-month growth rate. The formula is: ; Indicates the month-on-month growth rate; This indicates the data for this period; This indicates data from the previous period;

[0129] j. Year-on-year

[0130] Year-on-year comparison (YoY): The change in quantity this month compared to the same month in a previous year, expressed as the year-on-year growth rate. The formula is: ; Indicates the year-on-year growth rate; This indicates data for this month; This indicates data from the same month of a past year.

[0131] Daily year-on-year comparison: The ratio of the change in quantity today to the same day in a past week, expressed as the daily year-on-year growth rate. The formula is: ; Indicates the daily year-on-year growth rate; This indicates today's data; This indicates data from the same day of a past week.

[0132] 2) Congestion Analysis

[0133] a. Cross-sectional occupancy rate: The ratio of passenger flow to the corresponding capacity of a one-way cross-section of an operating line per unit time, also known as cross-sectional congestion. ; Indicates the cross-sectional load factor; This indicates the cross-sectional passenger flow, expressed in ten thousand people per hour (ten thousand people per hour). This indicates the cross-sectional transport capacity.

[0134] b. Peak-hour platform passenger volume per unit area: The ratio of the station's maximum passenger volume during peak hours to the platform area. ; This indicates the number of people served per unit area of ​​the platform during peak hours; This indicates the platform area, expressed in square meters (m2).

[0135] 3) Travel Characteristics Analysis

[0136] a. Commuter / Non-commuter ratio: The proportion of commuter / non-commuter passengers to the total number of passengers on urban rail transit during the statistical period on weekdays. , ; Indicates the commuting ratio; Indicates the proportion of non-commuting; Indicates the number of commuter passengers; This indicates the total number of commuter passengers.

[0137] b. Travel Origin / Outlet (OD) Popularity: Reflects the absolute scale and relative proportion of OD to passenger flow.

[0138] ;

[0139] in, Indicates the popularity of travel origin-destination (OD) routes; This represents the total daily passenger flow for the calculated OD pair; This represents the total daily passenger flow for the entire line's origin-destination (OD) pairs. This represents the maximum value of the entire line's OD (Original Departure) ratio relative to the total daily passenger flow. Indicates the weighting coefficient, and suggests , .

[0140] c. Travel time popularity: reflects the intensity of passenger flow during the travel period. ;

[0141] in, Indicates the popularity of travel time; Indicates the time period of the line Passenger volume within the city, of which A one-hour time period starting at any hour during the line's operating hours; This indicates the total daily passenger volume.

[0142] 4) Strength Analysis

[0143] a. Passenger traffic intensity of the route: The average daily passenger volume carried per unit operating mileage on the operating routes during the statistical period. ; Indicates the passenger traffic intensity of the route; The line's operating mileage is the length measured along the center of the main line from the center of the originating station to the center of the terminal station. , Indicates the distance from the starting point to the destination. This indicates the distance from the starting point to the end point of the downhill journey.

[0144] b. Line passenger flow density: The average daily passenger turnover per unit operating mileage of the operating line during the statistical period. ; This indicates the passenger flow density of the route.

[0145] c. Network travel intensity: The average daily passenger volume carried per unit operating mileage of the network during the statistical period. ; This indicates the intensity of travel on the rail network.

[0146] 5) Analysis of passenger flow imbalance

[0147] a. Temporal Imbalance: The ratio of the maximum cross-sectional passenger flow during peak hours in one direction to the average maximum cross-sectional passenger flow during all time periods in that direction. ; Indicates the time imbalance coefficient; This indicates the maximum cross-sectional passenger flow during different time periods, expressed in tens of thousands of people. This indicates the operating time of the line, in hours (h).

[0148] b. Cross-sectional imbalance: The ratio of the maximum passenger flow in one direction of the operating route to the average passenger flow in all cross-sections in that direction during the same period. ; Indicates the cross-sectional unevenness coefficient; This indicates the number of unidirectional cross sections, expressed in units of individual sections.

[0149] c. Direction imbalance: the ratio of the maximum section passenger flow in a single direction of the operational line to the average value of the maximum section passenger flow in both directions: ; represents the direction imbalance coefficient; represents the maximum up-direction section passenger flow, with the unit of ten thousand person-times; represents the maximum down-direction section passenger flow, with the unit of ten thousand person-times.

[0150] (3) Line spatial topology semantic constraint

[0151] The processor injects the complete spatial topology information of the line into the system prompt: station spacing mapping table (exact kilometer value of each section), operation duration, and number of sections. The direction determination rule is "down direction (en_id<ex_id); up direction (en_id>ex_id)".

[0152] (4) Time semantic mapping rule

[0153] In the prompt for prediction parameter extraction, the processor injects the mapping rules from NL time expressions to system parameters: "tomorrow" → time_period='24hours'; "next week" → time_period='7days'; "hour-level / minute-level / day-level" → convert according to the actual number (e.g. "9-minute-level" → '9min'); "every day" → granularity='24hours'. Meanwhile, the station name processing rule is injected: "It is strictly prohibited to overwrite a user-specified station name (including station names mentioned in history) to 'entire line'".

[0154] Dimension 3: I-Insight: Empirical mechanism and prior knowledge injection

[0155] The I-Insight dimension is executed in step S5 (attribution analysis report generation phase) of the method of the present invention. In the _build_analysis_prompt method, the processor concatenates the predefined traffic domain prior knowledge base TRAFFIC_EXPERT_KNOWLEDGE into the analysis prompt, so that the LLM is constrained by empirical rules when generating the attribution analysis text.

[0156] The prior knowledge base contains three empirical rules:

[0157] Rule 1 (Attribution Rule for Railway Passenger Hubs): "When analyzing railway stations, the arrival and departure of national railway lines has the greatest impact and exhibits a positive elasticity response. However, during fluctuations between 14:00-15:00 or the evening peak, passenger flow shows a negative elasticity response to national railway arrivals and departures, which can be interpreted as a 'masking effect of local life flow / commuter flow,' and attribution to external transportation delays is strictly prohibited." This rule is based on empirical evidence—the arc elasticity coefficient of hub stations is negative during the 14:00-15:00 period and the evening peak. The code transforms this empirical finding into a constraint rule text, clarifying the compliant interpretation path ("masking effect of local life flow / commuter flow") and the prohibited erroneous attribution direction ("attribution to external transportation delays is strictly prohibited").

[0158] Rule 2 (Priority of Temperature at Non-Hub Stations and Distinction Between Temperature and Morning Peak): "Temperature at other stations has the highest driving force on baseline passenger flow. When analyzing passenger flow deviating from the norm, priority should be given to checking whether the temperature has deviated from the comfort zone. However, when analyzing the morning peak, it is necessary to distinguish between 'time-driven' and 'environment-driven' factors. Although the temperature elasticity coefficient is high, it reflects the high sensitivity of passenger flow to comfort, rather than an absolute driving force. This can be interpreted as 'on the basis of essential commuting needs, small fluctuations in temperature significantly amplify the fluctuation increment of passenger flow by influencing the choice of travel mode.' It is strictly forbidden to attribute the peak commuting period entirely to temperature changes." This rule is based on empirical evidence—the temperature arc elasticity coefficient shows extremely high correlation sensitivity during the morning peak period; it also points out that "the surge in essential travel during the morning peak means that small fluctuations in temperature significantly amplify the fluctuation increment of passenger flow by influencing the choice of travel mode." The code translates this finding into an analytical criterion for distinguishing between "time-driven" and "environment-driven" factors.

[0159] Rule 3 (Different Interpretation of Humidity by Time of Day): "Increased humidity during the morning rush hour and evening serves as a signal of 'deteriorating travel environment,' triggering a shift in transportation modes. This is explained as 'as increased humidity foreshadows the risk of precipitation or physical discomfort, causing road users to shift to rail transit, resulting in marginal growth in passenger flow.' Increased humidity at other times serves as a signal of 'weakened travel intentions,' explained as 'high humidity inhibits non-essential travel, leading to a slight contraction in passenger flow.'" This rule is based on empirical evidence—relative humidity shows a positive correlation sensitivity during morning and evening rush hours, but becomes negatively sensitive during off-peak hours—explained as "during peak hours, rigid demand is driven by increased humidity foreshadowing the risk of precipitation or physical discomfort, causing road users to shift to rail transit."

[0160] In step S5, the processor uses the `_build_analysis_prompt` method to concatenate the three rule texts mentioned above into the "Transportation Domain Prior Knowledge Base" section of the analysis prompt, and adds the instruction "Please answer strictly based on data as a 'City Rail Passenger Flow Management Expert', and cite the [Transportation Domain Prior Knowledge Base] for attribution." When generating the attribution analysis text, LLM is constrained by the above rules and outputs professional explanations that conform to empirical patterns.

[0161] Dimension 4: L-Logic: Structured Logic Synthesis of Multidimensional Temporal Features

[0162] The L-Logic dimension is executed in steps S3-4 (SQL generation) and S5 (report generation) of the method of this invention. Through two mechanisms, implicit CoT controllable reasoning and output format normalization, the traceability of LLM reasoning logic and the availability of output content are guaranteed.

[0163] (1) Implicit CoT Controllability Inference

[0164] In the `_generate_sql_with_deepseek` method, the processor calls the DeepSeek-Reasoner model to generate the SQL. This model has native inference capabilities and performs inference before generating the final SQL. <think> ...< / think> The inference process is output within the label.

[0165] After receiving the complete text returned by the model, the processor uses a regular expression to extract the inference label content: `re.sub(r')` <think> .*?< / think> `', '', sql,flags=re.DOTALL)`, only retains the standard SQL statements outside the tags. The stripped inference content is discarded in this request, but the processing framework supports storing the inference content in a log system for subsequent query auditing and logical tracing.

[0166] (2) Standardized generation of analysis reports

[0167] The processor ensures the formatting of LLM output through two mechanisms: a formatting cleanup mechanism. The `_clean_markdown_formatting` method performs the following cleanup operations on the analyzed text returned by the LLM: removing bold markers (**text**→text), removing italic markers (*text*→text and _text_→text), removing inline code markers (`text`→text), removing Markdown heading markers (#), removing Markdown list markers (- and *), and cleaning up extra spaces and line breaks. This method ensures that the text ultimately returned to the user is in plain text format and does not contain any Markdown syntax symbols.

[0168] Content structure constraint mechanism: In the `_build_analysis_prompt` method, the processor injects explicit formatting instructions into the LLM: "Please use plain text format, do not use any Markdown syntax," "Respond directly to the user's original question," "Strictly answer based on data, and cite the [transportation domain prior knowledge base] for attribution," "If there are numerical results, highlight important numbers," and "Do not mention SQL or technical details." Simultaneously, by injecting `TRAFFIC_EXPERT_KNOWLEDGE` (the prior knowledge base of the I-Insight dimension) into the analysis prompt words, the LLM automatically integrates empirical patterns for attribution in the analysis report.

[0169] In predictive analytics scenarios, the `_build_prediction_analysis_prompt` method further injects format constraints specific to the prediction scenario: "The analysis must include: passenger flow fluctuation characteristics (identifying the peak and trough times), outlier identification, possible cause speculation, and final conclusions," "The use of any Markdown tags is strictly prohibited (the use of symbols such as **, ##, -, >, |, etc. is prohibited)," and "Please use plain text paragraphs and numbering (such as 1, 2, 3.) to organize the content."

[0170] Example 3

[0171] To address the issue of zero-sample general-purpose models easily generating business logic illusions and data misinterpretations in urban railway scenarios, this embodiment constructs a RAIL-LLM prompt word engineering framework based on a closed-loop process of "blind testing exposure—dimensionality reduction and decoupling—structured compensation—rolling verification." This process is processor-assisted, transforming the knowledge injection process from domain experts into a reproducible, iterative, and verifiable prompt word optimization pipeline. This evolution process is as follows: Figure 1 As shown.

[0172] Step T1: Zero-sample benchmarking and failure mode exposure.

[0173] In this step, the processor performs the following operations: First, the processor builds a benchmark testing environment. The processor reads the table structure metadata of the underlying database (including table names, field names, and field data types for the `card_data`, `transaction_data`, and `weather_holiday` tables), injecting only this metadata as database structure descriptions in the system prompts, without injecting any domain prior knowledge (i.e., no A-Attribute dimension field semantic mapping text, I-Insight dimension traffic prior rule text, R-Rule dimension SQL security constraint text, or L-Logic dimension output format specification text). Second, the processor automatically executes the test case set. The processor reads a pre-set set of test instructions covering three types of tasks: basic queries (e.g., "query the number of passengers entering a station on a certain day"), complex relationships (e.g., "compare the passenger and alighting volumes of two stations"), and anomaly attribution (e.g., "analysis of why passenger flow increased but national railway arrivals and departures decreased during a certain period"). The processor assembles each test instruction with the underlying table structure information into prompts, sending them one by one to the large language model, and receiving the SQL statements or analysis text output by the model. Then, domain experts conducted a double-blind evaluation of the model output for each test case, identifying and recording failure modes such as SQL syntax errors, privilege escalation (generating non-query statements), semantic errors (field retrieval logic does not match the query intent), analysis logic errors (attribution conclusions violate empirical traffic flow patterns), and disordered output format.

[0174] Step T2: Failure decoupling and attribution based on RAIL-LLM dimensions.

[0175] In this step, domain experts categorize the failure modes exposed in step T1 according to their root causes, assigning them one by one to the four dimensions of the RAIL-LLM framework: (a) Failures attributed to the R-Rule dimension: The LLM fails to establish a "read-only analysis expert" role, is induced by NL instructions to generate high-risk database operation statements (such as DROP, DELETE, UPDATE), or fails to correctly identify the user's query intent type (analysis / prediction pattern mismatch). The root cause of this type of failure lies in the lack of rule-driven intent and boundary constraints. (b) Failures attributed to the A-Attribute dimension: The LLM fails to identify the business definitions of urban rail-specific indicators, and uses a general semantic understanding method, resulting in SQL query logic that does not match the actual data retrieval requirements (such as incorrectly interpreting "passenger flow" as including exit records, and incorrectly interpreting "passenger volume" as only counting entry records). The root cause of this type of failure lies in the lack of semantic alignment information of the underlying data. (c) Failures at the I-Insight dimension: Faced with abnormal passenger flow fluctuations (such as the inverse relationship between passenger flow and national railway arrival / departure volume at railway passenger hubs during specific periods), LLM relies solely on general pre-trained knowledge to generate erroneous explanations that do not conform to actual traffic mechanisms (e.g., attributing a decrease in passenger flow at hubs to "national railway delays"). The root cause of this type of failure lies in the lack of empirical prior knowledge constraints in the field of urban rail transit. (d) Failures at the L-Logic dimension: The analytical content output by LLM exhibits logical jumps and chaotic formatting (e.g., the use of Markdown symbols, loose and redundant content), failing to directly generate structured analytical reports that meet operational management requirements. The root cause of this type of failure lies in the lack of standardized constraints on the tracing of reasoning logic and the output format.

[0176] Step T3: Structured compensation of domain knowledge.

[0177] In this step, to address the various deficiencies identified in step T2's attribution identification, the processor injects the previously extracted underlying system protocols and traffic mathematical patterns into the system prompt words as structured prompt word patches. The processor performs the following compensation operations:

[0178] (a) R-Rule security defense compensation. The processor embeds SQL operation security constraints into the system prompt of the _generate_sql_with_deepseek method—injecting whitelist rules ("The system only allows the execution of query commands SELECT / WITH") and blacklist rules ("Operations containing DROP, DELETE, UPDATE, INSERT, ALTER, CREATE, TRUNCATE, RENAME, GRANT, REVOKE, REPLACE are prohibited"). Simultaneously, a three-branch intent routing logic for the mode parameter is established in the query method to achieve intent control with "human intervention priority". This compensation corresponds to the failure attributed to the R-Rule dimension in step T2. (b) A-Attribute semantic alignment compensation. The processor injects complete field semantic explanations of three data tables, calculation formulas and operator logic for four sets of passenger flow analysis indicators, and line spatial topology information (station spacing mapping table and direction determination rules) into the system prompt, and injects time semantic mapping rules into the prediction parameter extraction prompt. This compensation corresponds to the failure attributed to the A-Attribute dimension in step T2. (c) I-Insight Mechanism Empirical Compensation. In the `_build_analysis_prompt` method, the processor injects the traffic domain prior knowledge base `TRAFFIC_EXPERT_KNOWLEDGE` (containing three rules: hub station attribution rules, temperature priority rules, and humidity time-segmentation interpretation rules) into the analysis prompt words. This compensation corresponds to the failure attributed to the I-Insight dimension in step T2. (d) L-Logic Output Standardization Compensation. The processor implements two levels of standardization processing: in the SQL generation stage, regular expressions are used to extract the DeepSeek-Reasoner model's... <think>Inference tags ensure that only pure SQL statements are extracted; during report generation, the `_clean_markdown_formatting` method removes all Markdown formatting symbols from the LLM output, while injecting plain text formatting instructions and content structure requirements into the analysis prompts. This compensation corresponds to the failure attributed to the L-Logic dimension in step T2.

[0179] Step T4: Scrolling verification.

[0180] In this step, the processor performs the following operations: The new system prompts generated after the structured compensation in step T3 (containing a complete set of prompt templates including R-Rule dimension security constraints, A-Attribute dimension field semantic mapping, I-Insight dimension prior knowledge base, and L-Logic dimension output format specifications) are re-entered into the test case set described in step T1, and all test cases are re-executed. The processor compares the test results under the new prompts with the test results of the baseline model (zero samples, no prior knowledge injection) in step T1, and calculates the improvement in each evaluation metric.

[0181] The process continues iteratively from step T1 to T4 until the model output accuracy, logical consistency, and format conformity all meet the preset application standards. This results in a standardized RAIL-LLM prompt word template set, which is the RAIL-LLM prompt word engineering framework called in step S3 of Example 1, for continuous use by the system in subsequent intelligent interaction for passenger flow analysis and prediction.

[0182] The core logic of the system is to transform the research findings presented above into practical engineering applications. Its hierarchical architecture is as follows: Figure 2 As shown:

[0183] Data Support Layer: The system's data foundation, responsible for storing various underlying data required for system operation, including raw passenger flow data (including ACC data and internet data) as well as holiday and weather data, providing a reliable and comprehensive basic data foundation for subsequent core processes such as passenger flow analysis and short-term forecasting. In the intelligent interactive mode, direct connection to raw data is achieved, using SQL intelligent agents for dynamic pivoting without intermediate tables, without pre-creating aggregated intermediate tables for specific analytical indicators. When the generated SQL query command is submitted to the data support layer, the database execution engine directly performs query operations on the following three raw data tables:

[0184] (1) card_data table: stores card transaction data of ACC clearing center. Fields include entry_station (entry station), entry_id (entry station number), entry_time (entry time, DATETIME format, UTC time zone), exit_station (exit station), exit_id (exit station number), exit_time (exit time), card_number (card number), ticket_name (ticket type), and amount (amount).

[0185] (2) transaction_data table: stores Internet ride code transaction data, fields include entry_station, entry_id, entry_time, exit_station, exit_id, exit_time (the meaning of the above fields is the same as that of card_data table), ticket_type (ticket type), payment_amount (payment amount).

[0186] (3) weather_holiday table: stores weather and calendar data, with fields including time (time, DATETIME format, UTC time zone), temperature_2m (temperature), relative_humidity_2m (relative humidity), precipitation (precipitation), rain (rainfall), snowfall (snowfall), snow_depth (snow depth), wind_speed_10m (wind speed), holiday (whether it is a holiday, 1=yes, 0=no), weekend (whether it is a weekend), workday (whether it is a workday), and event (whether there is a special event).

[0187] During SQL query execution, for statistical needs involving both ACC and internet data, the processor uses UNION ALL to merge the query results from the card_data and transaction_data tables in the generated SQL. For queries requiring the association of weather and calendar information, the processor uses the DATE_FORMAT function to align the time field of the passenger flow data with the time field of the weather_holiday table. Real-time SQL query instructions can be generated directly from the raw data, eliminating the need to pre-create redundant intermediate tables for different evaluation metrics, significantly reducing database maintenance costs and data redundancy.

[0188] Algorithm Engine Layer: The core unit for implementing complex calculations and model inference, mainly consisting of two modules: prediction engine and analysis engine.

[0189] (1) Prediction Engine - Passenger Flow Prediction Model Based on Random Forest

[0190] The core implementation of the prediction engine is in the `PassengerPredictionService` class (`prediction_service.py`), which uses a Random Forest (RF) regression model. The training and inference process of this model is as follows:

[0191] Step 1: Dynamic Bucket Aggregation of Historical Data. The processor constructs a dynamic SQL query using the `_get_historical_data_with_buckets` method. First, the processor parses the prediction granularity parameters (e.g., "5min", "15min", "1hour") and prediction span parameters (e.g., "24hours", "7days"), converting the granularity parameters into seconds (using regular expressions to extract numbers and units: min × 60, hour × 3600, day × 86400). Then, it constructs a dynamic aggregation SQL query, using the `FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(t) / interval in seconds)*interval in seconds)` function to aggregate the original transaction flow into time-segmented passenger flow by target granularity. Simultaneously, the `LEFT JOIN weather_holiday` table aligns the associated weather and calendar features using `DATE_FORMAT`. For single-station prediction mode, the SQL's `WHERE` condition is limited to `entry_station` equal to the target station name; for full-line prediction mode, no station filtering is applied. For inbound volume forecasting, only entry records are counted; for outbound volume forecasting, only exit records are counted; for passenger and passenger alighting volume forecasting, UNION ALL is used to merge inbound and outbound records.

[0192] Step 2: Feature Engineering. The processor performs feature construction on the aggregated historical data using the `_prepare_features` method. First, the time field is converted to datetime type, and the hour (hour, 0-23) and day (day of the week, 0-6) attributes are extracted. Then, the following features are constructed:

[0193] Time periodicity characteristics: Discrete hourly variables are transformed into continuous coordinates on the unit circle through sine and cosine mapping, preserving the temporal continuity between 0:00 and 23:00.

[0194] Peak hour feature: is_rush, which is 1 when the hour value is in {7,8,9,17,18,19}, and 0 otherwise. This feature is used to mark the rigid commuting periods of the morning peak (7:00-9:00) and the evening peak (17:00-19:00).

[0195] Lag feature: The passenger flow value from the previous time step is used, and backward padding is applied to the first time step of the sequence. This feature provides the model with reference information on the short-term continuity of passenger flow.

[0196] Calendar characteristics: holiday (whether it is a holiday) and workday (whether it is a working day), which are obtained from the weather_holiday table by the SQL aggregation phase.

[0197] The final extracted complete feature list is: ['hour_sin', 'hour_cos', 'dow', 'holiday', 'workday', 'is_rush', 'lag_1'], a total of 7 features. The target variable is the aggregated time-segmented passenger flow y.

[0198] Step 3: Random Forest Model Training. The processor is trained using RandomForestRegressor from the scikit-learn library, with hyperparameters set as follows: n_estimators=100 (number of decision trees), max_depth=12 (maximum tree depth), random_state=42 (random seed). The model constructs 100 decision trees by randomly sampling with replacement from historical data using Bootstrap sampling. For each decision tree, a subset of features is randomly selected from the full 7-dimensional feature set when splitting at a node to choose the optimal split point. After training, the model stores the structure and node parameters of all decision trees for subsequent inference.

[0199] Step 4: Rolling Prediction Inference. The processor performs predictions point-by-point on the target time point sequence generated by the `_generate_time_points` method. For each target time point: first, calculate `hour_sin` and `hour_cos` based on the `hour` value of the target time; determine `dow` based on the day of the week; determine `holiday` and `workday` values ​​based on whether it is a weekend; determine `is_rush` value based on whether `hour` is during peak hours; and take the predicted value of the previous time point as `lag_1`. Then, construct the above 7-dimensional features into a feature vector and input it into the trained RF model, calling `model.predict()` to obtain the passenger flow prediction value. Finally, apply a slight random perturbation to the prediction value (multiplied by N(0,0.02) normally distributed random numbers) to prevent the prediction sequence from degenerating into a straight line during multi-step recursion. The perturbed prediction value is also used as the input to `lag_1` for the next time point. The final output is a prediction sequence containing timestamps, predicted passenger flow values ​​(rounded down, minimum 0), and confidence scores (initially 0.9, decreasing by 0.005 each step, minimum 0.4).

[0200] (2) Analysis Engine - NL2SQL Intelligent Query and Explanatory Briefing Generation

[0201] The analysis engine is driven by an SQL agent, with its core implementation in the `_generate_sql_with_deepseek` and `_analyze_query_results` methods of the `DeepSeekSQLAgent` class. The NL2SQL processing flow is as follows: The processor first constructs a system prompt containing a data architecture description, metric calculation logic, SQL structure requirements, and standard code examples. This prompt is then concatenated with the dialogue history and the user's current input, and finally invoked on the `DeepSeek-Reasoner` model with parameters `temperature=0.1` and `max_tokens=2000`. The model returns a response containing... <think>After inferring the text of the tag, the processor uses the regular expression re.sub(r' <think> .*?< / think> The `sql` statement (`re.DOTALL`) is stripped of inference tags to extract pure SQL statements. Then, the `_clean_and_validate_sql` method performs four layers of checks: preprocessing (removing Markdown tags, comments, and extra whitespace), whitelist validation (checking for entries starting with `SELECT` or `WITH`), blacklist regular expression scanning (using `\b` word boundaries to detect 10 dangerous keywords: `DROP`, `DELETE`, `UPDATE`, `INSERT`, `ALTER`, `CREATE`, `TRUNCATE`, `RENAME`, `GRANT`, `REVOKE`, and `REPLACE`), and multi-statement injection protection. Only SQL statements that pass these checks are submitted to the database for execution. The explanatory briefing generation process: After the SQL execution returns data, the processor uses the `_analyze_query_results` method to call the `_build_analysis_prompt` method to construct analysis prompts. The prompt combines the actual query results returned by the database (the first 10 records), the TRAFFIC_EXPERT_KNOWLEDGE traffic prior knowledge base (containing three rules: hub station attribution rules, temperature priority rules, and humidity time-based interpretation rules), and formatting constraints ("Please use plain text format, do not use any Markdown syntax," "Strictly based on data, and referencing the traffic domain prior knowledge base for attribution," "Do not mention SQL or technical details"), and sends it to the DeepSeek-Chat model to generate analysis text. The text returned by the model is cleaned of Markdown formatting symbols using the _clean_markdown_formatting method and returned as an explanatory brief. The numerical conclusions of this brief are always based on the actual values ​​returned by the database, generated without LLM parameterized memory, effectively preventing numerical illusions.

[0202] Business logic layer: Implemented using the Flask web framework, with its core implementation in the `query` method of the `DeepSeekSQLAgent` class. This layer acts as the system's central task scheduler, responsible for three core functions: user request intent recognition, analysis / prediction process orchestration, and prediction result management.

[0203] (1) User request intent recognition

[0204] The processor implements a two-level intent recognition mechanism through the query method and the _detect_prediction_request method.

[0205] First level: The front-end mode parameter takes priority. The query method receives three parameters: user_input (the user's natural language query text), mode (the state of the front-end control, with values of 'prediction', 'analysis' or None), and conversation history. When mode is 'prediction' or 'analysis', it is the manual mode: the processor directly determines the task type according to the value of the mode parameter, and does not call the LLM for semantic discrimination, but before execution, it first detects through _detect_prediction_request whether the user input intention is consistent with mode: if mode='prediction' but the user input does not contain a prediction intention, a conflict error is returned (success=False, mode='conflict_error'); if mode='analysis' but the user input contains a prediction intention, a conflict error is also returned. Only when the mode and the detected inten Figure 1 tion are consistent, the request is routed to the corresponding processing pipeline.

[0206] Second level: Automatic intention classification. When mode is None (the user does not manually select a mode), the processor calls the _detect_prediction_request method to perform automatic intention recognition. This method adopts a two-step strategy of keyword matching and context reasoning: first, match the user input with the prediction keyword list ['prediction', 'estimate', 'future', 'next', 'later', 'will', 'tomorrow', 'next week']; at the same time, check whether the previous assistant reply in the conversation_history of the conversation history contains unique marks specific to prediction tasks — "confidence", "estimate", "prediction". If the keyword matching is successful, or the conversation history shows that the previous round is a prediction task and the current input is a short follow-up question (length < 8 and does not contain the word "figure"), it is determined as a prediction intention; otherwise, it is determined as an analysis intention. Recognition result: The task type is determined as one of "historical passenger flow analysis" or "future passenger flow prediction". The analysis task is routed to the _process_sql_flow method, and the prediction task is routed to the _handle_prediction_request method.

[0207] (2) Analysis / Prediction Process Orchestration

[0208] When the task type is determined as an analysis task, the processor calls the _process_sql_flow method to execute the following orchestration:

[0209] Step 1: Call the _generate_sql_with_deepseek method (the analysis engine at the algorithm engine layer) to generate an SQL query statement;

[0210] Step 2: If SQL generation fails (returns an empty string), return an error result;

[0211] Step 3: Call the _clean_and_validate_sql method to perform security checks on the SQL (see the algorithm engine layer for details);

[0212] Step 4: Call the DataVisualizer.execute_sql_and_visualize method to execute the SQL and obtain the data and visualization results;

[0213] Step 5: If the SQL execution fails, return an error result containing the SQL text for debugging purposes;

[0214] Step 6: Call the _analyze_query_results method (algorithm engine layer interpretive briefing generation) to analyze the query results and generate a natural language answer;

[0215] Step 7: Return the results containing the answer (analysis text), sql_query (executed SQL), visualization (visualized data), and mode='deepseek_smart'.

[0216] When the task type is determined to be a prediction task, the processor calls the _handle_prediction_request method to perform the following orchestration:

[0217] Step 1: Call the `_extract_prediction_params_with_deepseek` method to extract prediction parameters from the user input. This method outputs a parameter object in JSON format via the prompt word instruction LLM, containing `station_name` (target station name), `prediction_type` (prediction type: 'entry' for entry, 'exit' for exit, 'total' for total), `granularity` (prediction granularity: e.g., '9min', '15min', '1hour'), ​​and `time_period` (prediction span: e.g., '24hours', '7days'). The prompt words have pre-defined time semantic mapping rules: "tomorrow" → '24hours', "next week" → '7days'.

[0218] Step 2: Pass the extracted parameters into the prediction_service.predict_station_flow method, call the prediction engine (algorithm engine layer) to perform RF model training and rolling prediction inference, and obtain the predicted numerical sequence.

[0219] Step 3: If the prediction service fails (e.g., there are fewer than 5 historical data entries, see line 25 of prediction_service.py), return an error directly and do not perform subsequent LLM analysis.

[0220] Step 4: Call the `_build_prediction_analysis_prompt` method to construct the predictive analysis prompt. This prompt combines the prediction background (site name, data type, time granularity), the actual predicted data sequence (time-predicted value-confidence triples for the first 24 time points), and format constraints ("The analysis must include: passenger flow fluctuation characteristics, outlier identification, possible cause speculation, and final conclusions" "No Markdown tags allowed" "Please organize content using plain text paragraphs and numbering") and sends it to the LLM to generate the predictive analysis report.

[0221] Step 5: Call the _generate_prediction_chart method to use the matplotlib library to draw the prediction curve and return it in base64 encoding for direct rendering by the front end.

[0222] (3) Management of prediction results

[0223] Conversation history management: After each successful processing, the processor appends the user input and assistant response (including SQL text for context reference) to the `conversation_history` list. When the history length exceeds 10 entries (i.e., 5 rounds of conversation), it is automatically truncated to retain the most recent 10 entries, ensuring that the context window for subsequent LLM calls does not overflow.

[0224] Multimodal Interaction Layer: Constructs an interaction mode based on LLM intelligent interaction modalities to meet intelligent interaction needs. It is suitable for managers without business background, allowing them to directly initiate query and analysis requests via NL. Adopting a conversational design, it achieves WYSIWYG (What You Ask Is What You Get) functionality. Users can directly initiate query and analysis requests via natural language, and the system automatically generates professional visual charts. It also supports contextual follow-up questions based on historical dialogue memory, significantly reducing the operational threshold and cognitive load for managers, making it suitable for those without business background.

[0225] Based on the RAIL-LLM prompt word engineering framework proposed above, a private deployment experimental environment was constructed. To ensure the rigor of the model comparison, a distilled unified prompt word template was adopted. Based on the task orchestration capabilities of LLM, an intelligent interaction modality was constructed, driven by two mutually substitutable and scenario-adaptive agents, providing managers with logically interpretable decision support.

[0226] (1) Dual-agent cooperative architecture

[0227] To balance the depth of passenger flow analysis with real-time interactivity, the system is designed with dual intelligent agents that are functionally equivalent but have different deployments and computing power allocations. These agents can be switched according to the network environment, computing power requirements, and data sensitivity.

[0228] 1) Cloud API Collaborative Intelligent Agent (Edge-Agent)

[0229] By calling lightweight cloud APIs to execute high-frequency, low-latency tasks, agile interaction is achieved by leveraging the logical capabilities of public cloud large-scale models, without requiring large-scale local computing power. The deployment environment runs on a local scheduling workstation and communicates with remote servers through the requests library; the API bridge adopts a RESTful architecture and connects to DeepSeek-Chat / Reasoner cloud endpoints via HTTPS protocol; security authentication uses an encrypted storage of the API key in the .env environment file, and the identity credential is loaded during the __init__ initialization phase. At runtime, after receiving user input, intent detection is performed to identify "passenger flow prediction" or "passenger flow analysis" tasks, and the semantic parsing capabilities of the cloud model are used to complete parameter extraction and SQL logic draft generation.

[0230] This intelligent agent ensures timely responses to interactions, as shown in some interactive interfaces such as... Figure 3 As shown in the figure, the blue dialog box on the right represents the natural language query entered by the user, and the white dialog box on the left represents the answer output by the agent. Figure 3 The query was "Ticket distribution on June 5, 2024". The agent, by calling the cloud-based large language model API, performed semantic mapping of fields based on the A-Attribute dimension and security constraint verification based on the R-Rule dimension of the RAIL-LLM prompt word framework. It then converted the natural language query into standard SQL commands, queried the database, and formatted the returned numerical results into structured analysis text using the L-Logic dimension, and plotted related images. Figure 3 Taking the question as an example, the actual image of the question is as follows: Figure 4 As shown, this chart, generated based on real transaction records from the database, displays the passenger flow distribution for each ticket type, and provides a comparison. Figure 3 The output results were consistent, verifying Edge-Agent's semantic understanding accuracy and interactive response capabilities in routine passenger flow analysis query tasks.

[0231] 2) Super-Agent deployed locally on supercomputers

[0232] This intelligent agent loads a complete series of LLMs to perform complex data analysis tasks, providing a localized solution for privacy protection and heavy-load computing scenarios. Deployed on a high-performance computing platform, it supports large-scale parallel computing. Its underlying core is the locally deployed Qwen2.5 Coder 32B model, which is deeply optimized for code generation and SQL logic, exhibiting greater rigor when handling complex Text-to-SQL tasks. Utilizing llamafile technology, the model is encapsulated into a local interface conforming to OpenAI standards, enabling seamless switching from the Flask backend to the local model with consistent calling methods as the cloud API. In a supercomputing environment, on-demand GPU memory allocation is enabled via tf.compat.v1.ConfigProto, preventing the prediction engine from crashing due to default GPU memory saturation during large-scale model inference, thus achieving stable coexistence of model inference and passenger flow prediction algorithm engines. During runtime, the agent operates in a closed-loop environment within the intranet, ensuring no data leakage, and is responsible for generating complex SQL and performing in-depth causal analysis involving tens of millions of raw transaction flows. Qwen2.5 Coder 32B understands the high-level indicator definitions injected in the prompt words and generates MySQL code containing complex nesting and CASE WHEN logic.

[0233] This intelligent agent supports local deployment of different LLMs on the supercomputer to achieve model switching. The backend can add different LLMs according to business needs, and the frontend provides the switching function. The interactive interface of the supercomputing locally deployed intelligent agent (Super-Agent) asks the question "Predict the number of passengers entering Wenling First People's Hospital Station in the next hour for 5 minutes". Based on the A-Attribute dimension, it completes the spatial direction and professional indicator mapping. Based on the L-Logic dimension, it generates a MySQL statement containing multi-table JOIN and CASE WHEN nested logic using an implicit CoT inference mechanism. After the query results are returned, it performs automatic annotation and causal analysis based on the I-Insight dimension of prior knowledge, and finally provides an image and reasons for the prediction of the number of passengers entering a certain People's Hospital Station in the next hour for 5 minutes.

[0234] (2) Semantic routing logic control

[0235] The "Passenger Flow Analysis" and "Passenger Flow Prediction" dual-mode switch bar at the top of the chat bar constitutes the core semantic routing control layer of the intelligent interaction mode. It achieves precise user intent classification and dynamic alignment with the backend processing engine through explicit mode presets. This section contains two modes, including a "Passenger Flow Analysis" and "Passenger Flow Prediction" dual-mode switch button, forming the core semantic routing control layer of the intelligent interaction mode. It achieves precise user intent classification and dynamic alignment with the backend processing engine through explicit mode presets.

[0236] 1) Passenger flow analysis mode

[0237] Positioned as a retrospective data retrieval and indicator calculation engine, it handles complex queries based on historical facts. When this mode is activated, the agent first enters the SQL generation stream, using LLM to map natural language into MySQL query commands. This covers statistical analysis of basic passenger flow indicators, congestion indicators, travel characteristic indicators, intensity indicators, and various imbalance indicators. The visualization module automatically renders bar charts, line charts, etc., and provides logical interpretation of the data in conjunction with LLM.

[0238] 2) Passenger flow forecasting model

[0239] Positioned as a forward-looking time-series extrapolation and decision support engine, it reveals the evolution trend of passenger flow in future time periods. It triggers the intelligent agent parameter extraction logic to extract core metadata such as station name, prediction granularity, and prediction span from user input. The backend calls a passenger flow prediction algorithm based on dynamic bucketing optimization to perform feature engineering processing (cycle transformation, peak identification, etc.) on historical sequences to perform inference. It supports multi-dimensional prediction needs from "5-minute short-term high-frequency prediction" to "long-term trend prediction of the entire line next week".

[0240] 3) Dual-mode collaboration and conflict detection mechanism

[0241] To ensure the rigor of modal logic, the agent implements intention in the backend. Figure 1 Consistency check logic:

[0242] ① Following the principle of "human intervention first," the input stream is prioritized for classification to the mode path manually selected by the user. In the interactive process of "human intervention first," when the user manually selects the prediction mode and asks "hourly passenger flow at Chengnan Station for the next two days," the system determines and locks the task type as a prediction task, outputting the hourly passenger flow prediction image for Chengnan Station for the next two days and the reason. This principle ensures the uniqueness and stability of the scheduling instruction execution process.

[0243] ② If a user enters a predictive command in passenger flow analysis mode, or requests historical data queries in passenger flow prediction mode, a conflict error message is triggered on the interactive interface, requiring the user to adjust the mode or enter content. After manually selecting prediction mode, the user asks "Outbound volume of Huichuanwang Station on October 9, 2023". The agent judges this as an analytical command, and the system's intention... Figure 1 The consistency verification module detects a pattern conflict and triggers an interception, returning a preset error message on the interface, effectively preventing incorrect routing caused by pattern mismatch.

[0244] ③ In the default state where no mode is selected, the agent uses a logical discriminant function to perform autonomous intent recognition.

[0245] (3) Evaluation of agent performance differences

[0246] Based on the accuracy limit of the RAIL-LLM framework, and considering the attention mechanism and context window limitations of the locally deployed model in cross-platform comparative experiments, this study performs cue word distillation on expert rules: retaining the core semantic mapping (Attribute) and execution safety constraints (Rule), and structurally compressing the complex attribution logic (Insight), ensuring that the cloud and local models are compared under a consistent input environment, and truly reflecting the differences in the original capabilities of the models in handling traffic professional tasks.

[0247] Using a self-developed automated testing framework, 30 sets of standard test cases were specifically evaluated on a real dataset from the Taizhou S1 urban railway line. The passenger flow prediction algorithm adopts Randomized Randomized (RF), whose low inference latency ensures the smoothness of the agent's generation of test analysis reports, and the feature importance feedback mechanism provides logical support for the agent's physical semantics.

[0248] 1) Test plan and indicator system design

[0249] The evaluation covers five dimensions: basic query, business indicator calculation, passenger flow prediction parameter extraction, multi-turn dialogue memory, and security interception. It is assessed through the following core indicators:

[0250] Execution Success Rate (ESR): The percentage of models that generate executable code and receive feedback from the database.

[0251] Result Accuracy (RAR): Whether the generated SQL statements or analysis results fully meet the business logic requirements.

[0252] Response time: End-to-end time from when the user submits a command to when the agent responds (unit: seconds).

[0253] 2) Analysis of Task Completion Rate and Accuracy of Business Metrics

[0254] Through iterative testing of 30 test cases, the dual-agent system exhibited significant differences in performance across tasks of varying complexity. In basic tasks, both agents achieved near 100% accuracy, demonstrating the effectiveness of prompt word engineering in data architecture injection. In more complex tasks involving case-when logic, such as passenger turnover and cross-sectional imbalance coefficients, Super-Agent demonstrated more rigorous accuracy. This is attributed to the deep optimization of programming syntax and nested logic in the Coder series models, enabling accurate generation of MySQL statements that meet the requirement of accumulating 14 intervals. For multi-granularity prediction needs, Edge-Agent demonstrated stronger semantic induction capabilities, more acutely capturing colloquial temporal features and accurately mapping them into JSON-formatted prediction operators.

[0255] 3) Comparison of response timeliness

[0256] According to the recorded data, the average response time of Edge-Agent is about 48.42s, and its fluctuation is mainly affected by the queuing mechanism of public cloud API and network bandwidth; Super-Agent, under supercomputing environment, has an average response time of about 27.15s.

[0257] 4) Boundary security verification

[0258] In the SQL injection attack test, the built-in logic of the dual-agent modal backend successfully intercepted the commands containing DROP and DELETE and returned the preset error message, verifying the robustness of the modality in an open interactive environment.

[0259] Comprehensive test results show that Super-Agent has advantages in the rigor of business indicator calculation and response speed, making it suitable for high-intensity real-time scheduling analysis; while Edge-Agent excels in fuzzy semantic understanding and multi-granularity parameter extraction, making it more suitable as an interactive intelligent agent for junior managers. The dual-agent design provides flexible computing power redundancy for the intelligent interactive modality of urban railway passenger flow management, ensuring stable operation of the modality under different network environments and security level requirements.

[0260] Example 4

[0261] This embodiment 4 provides a non-transitory computer-readable storage medium for storing computer instructions. When the computer instructions are executed by a processor, they implement the RAIL-LLM-based intelligent interactive method for urban rail passenger flow analysis and prediction as described above. The method includes:

[0262] Step S1: Obtain the original passenger flow transaction data and external influencing factor data for the target route; wherein, the original passenger flow transaction data includes ACC clearing center card swipe transaction data (card_data table) and Internet ride code transaction data (transaction_data table), each record includes entry station, entry station number, entry time, exit station, exit station number, and exit time, with time precision at the second level, DATETIME format, and UTC time zone; the external influencing factor data includes weather data obtained through meteorological API (weather_holiday table), including temperature, relative humidity, precipitation, rainfall, wind speed, and calendar identifiers for holidays, weekends, weekdays, and special events;

[0263] Step S2: Preprocess and feature engineering the raw passenger flow transaction data to generate a multi-dimensional feature vector; wherein, the feature engineering includes: aggregating the raw transaction flow into time-segmented passenger flow according to the target prediction granularity using dynamic bucketing SQL, the aggregation method being FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(time field) / granularity in seconds)*granularity in seconds); extracting feature columns ['hour_sin', 'hour_cos', 'dow', 'holiday', 'workday', 'is_rush', The 'lag_1' has a total of 7 features, including hourly cycle features hour_sin=sin(2π×hour / 24) and hour_cos=cos(2π×hour / 24) encoded with sine and cosine, day of the week feature dow, holiday and weekend identifiers holiday and workday, peak time identifiers is_rush for morning peak 7:00-9:00 and evening peak 17:00-19:00, and passenger flow lag feature lag_1 for the previous moment;

[0264] Step S3: Based on the pre-built RAIL-LLM prompt word engineering framework, perform intent recognition and semantic parsing on the natural language query request input by the user; wherein, the RAIL-LLM prompt word engineering framework includes four dimensions of prompt word templates: (a) R-Rule constraint dimension—intent control is achieved through the three-branch routing logic of the mode parameter in the query method. When mode='prediction' or 'analysis', the task path is locked in manual mode. When mode is None, the prediction keyword list ['predict', 'estimate', 'future', 'next', 'after', 'will', ] is used. The intent is determined by a combination of matching 'tomorrow' and 'next week' and LLM contextual reasoning; the SQL generated by LLM is validated using the _clean_and_validate_sql method, starting with a whitelist of SELECT / WITH, scanning a blacklist of 10 dangerous keywords containing \b word boundaries (DROP / DELETE / UPDATE / INSERT / ALTER / CREATE / TRUNCATE / RENAME / GRANT / REVOKE / REPLACE), and a four-layer security check to ensure that only data query statements are submitted for execution; (b) A-Attribute semantic alignment dimension - injecting the field-level Chinese semantic interpretation of the three original data tables card_data, transaction_data and weather_holiday into the system prompt words, pre-setting the core indicator calculation logic, and "tomorrow" → t (c) I-Insight Prior Knowledge Injection Dimension—Injecting three empirical rules from the TRAFFIC_EXPERT_KNOWLEDGE prior knowledge base into the analysis prompts: Rule 1 stipulates that when analyzing a certain train station in Taizhou or Wenzhou, the passenger flow during the 14:00-15:00 or evening peak hours shows a negative elasticity response to the arrival and departure of the national railway, it is interpreted as a masking effect of local life flow / commuter flow and is strictly prohibited from being attributed to external traffic delays; Rule 2 stipulates that non-hub stations should prioritize checking whether the temperature has deviated from the comfort zone and must distinguish between time-driven and environment-driven during the morning peak hours; Rule 3 stipulates that increased humidity triggers the logic of mode of transportation shift during the morning and evening peak hours and triggers the logic of weakening travel intention during other times; (d) L-Logic Logic Composition Dimension—In the SQL generation stage, the regular expression re.sub(r' <think> .*?< / think> The code `', '', sql,flags=re.DOTALL` removes the inference labels from the DeepSeek-Reasoner model, extracting only the pure SQL statements. During report generation, the `_clean_markdown_formatting` method removes Markdown formatting symbols such as bold, italics, code markers, heading markers, and list markers. It also injects content structure constraints into the analysis prompts, including "Please use plain text format," "Strictly based on data answers, and referencing prior knowledge bases in the transportation domain for attribution," and "Analysis must include: passenger flow fluctuation characteristics, outlier identification, possible cause speculation, and final conclusions."

[0265] Step S4: Call the pre-trained passenger flow prediction model to make predictions and obtain a passenger flow prediction numerical sequence; wherein, the passenger flow prediction model adopts the RandomForestRegressor model, with hyperparameters set to n_estimators=100 and max_depth=12, taking the 7-dimensional features generated in step S2 as input, and outputting the passenger flow prediction values ​​for different time periods; the prediction adopts a rolling recursive method, after each prediction, the current prediction value is subjected to N(0,0.02) random perturbation and used as the lag_1 input for the next time point, and finally outputs a prediction sequence containing timestamps, predicted passenger flow values ​​and confidence scores;

[0266] Step S5: Call the large language model to perform attribution analysis on the passenger flow prediction numerical sequence and database query results based on the analysis constraint rule set, and generate a structured analysis report.

[0267] Example 5

[0268] This embodiment 5 provides a computer device, including a memory and a processor. The processor and the memory communicate with each other. The memory stores program instructions that can be executed by the processor. The processor calls the program instructions to execute the intelligent interactive method for urban rail passenger flow analysis and prediction based on RAIL-LLM as described above. The method includes:

[0269] Step S1: Obtain the original passenger flow transaction data and external influencing factor data of the target route; wherein, the memory of the computer device stores the card_data table (ACC card swipe transaction data), the transaction_data table (Internet ride code transaction data), and the weather_holiday table (weather calendar data); the processor reads the above data through a MySQL database connection;

[0270] Step S2: Preprocess and feature engineering are performed on the original passenger flow transaction data to generate a multi-dimensional feature vector; wherein, the processor executes the _prepare_features method to extract 7-dimensional features from the dynamically bucketed and aggregated historical passenger flow data: hour_sin=sin(2π×hour / 24), hour_cos=cos(2π×hour / 24), down (day of the week), holiday (holiday identifier), workday (workday identifier), is_rush (peak hour identifier, 1 when hour∈{7,8,9,17,18,19}), and lag_1 (passenger flow lag feature of the previous moment);

[0271] Step S3: Based on the pre-built RAIL-LLM prompt word engineering framework, perform intent recognition and semantic parsing on the natural language query request input by the user; wherein, the processor executes the query method to perform intent splitting, executes the _generate_sql_with_deepseek method to generate SQL, executes the _clean_and_validate_sql method to perform security verification on the SQL with SELECT / WITH whitelist starting, 10 dangerous keyword blacklist regular expressions containing \b word boundaries, and multi-statement injection semicolon detection, executes the _build_analysis_prompt method to inject TRAFFIC_EXPERT_KNOWLEDGE traffic prior knowledge base into analysis prompt words, and executes the _clean_markdown_formatting method to remove Markdown formatting symbols;

[0272] Step S4: Call the pre-trained passenger flow prediction model to make predictions and obtain a passenger flow prediction numerical sequence; wherein, the processor executes the fit method of RandomForestRegressor(n_estimators=100, max_depth=12) to train the model and the predict method to perform rolling prediction inference. Each prediction value is multiplied by N(0,0.02) random perturbation and used as the input of the next time point lag_1.

[0273] Step S5: Call the large language model to perform attribution analysis on the passenger flow prediction numerical sequence and database query results based on the analysis constraint rule set, and generate a structured analysis report.

[0274] Example 6

[0275] This embodiment 6 provides an electronic device, including: a processor, a memory, and a computer program; wherein, the processor is connected to the memory, and the computer program is stored in the memory. When the electronic device is running, the processor executes the computer program stored in the memory, so that the electronic device executes instructions to implement the intelligent interactive method for urban rail passenger flow analysis and prediction based on RAIL-LLM as described above. The method includes:

[0276] Step S1: Obtain the original passenger flow transaction data and external influencing factor data of the target route; wherein, the memory stores a computer program, and when the processor executes the computer program, it reads the original data from the card_data table, transaction_data table and weather_holiday table through a database connection;

[0277] Step S2: Preprocess and feature engineering are performed on the original passenger flow transaction data to generate a multi-dimensional feature vector; wherein, the processor aggregates the original transaction data into time-segmented passenger flow through dynamic bucketing SQL (FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(time field) / granularity in seconds)*granularity in seconds)) and extracts a total of 7-dimensional features ['hour_sin', 'hour_cos', 'dow', 'holiday', 'workday', 'is_rush', 'lag_1'].

[0278] Step S3: Based on the pre-built RAIL-LLM prompt word engineering framework, perform intent recognition and semantic parsing on the natural language query request input by the user; wherein, the RAIL-LLM prompt word engineering framework includes: (a) R-Rule dimension—three-branch routing of the mode parameter ('prediction' / 'analysis' / None) and four-layer SQL security verification; (b) A-Attribute dimension—semantic mapping of three table fields, passenger flow indicator calculation logic (including 15 station ID-cumulative distance mapping table and direction determination rules), and time semantic mapping rules; (c) I-Insight dimension—three traffic prior knowledge rules (attribution of hub station masking effect, priority of non-hub station temperature, and time-time differentiated interpretation of humidity); (d) L-Logic dimension— <think>Inference tag regular expression stripping and Markdown format cleanup;

[0279] Step S4: Call the pre-trained passenger flow prediction model to make predictions and obtain the passenger flow prediction numerical sequence; wherein, the passenger flow prediction model uses RandomForestRegressor (n_estimators=100, max_depth=12), takes the 7-dimensional features as input, and outputs the prediction sequence in a rolling recursive manner;

[0280] Step S5: Call the large language model to perform attribution analysis on the passenger flow prediction numerical sequence and database query results based on the analysis constraint rule set, and generate a structured analysis report.

[0281] More detailed steps of the above method implemented when the computer program is executed by the processor are as described in Example 1.

[0282] In summary, this invention primarily proposes a RAIL-LLM-based intelligent interactive method for urban railway passenger flow analysis and prediction, optimizing the semantic drift, execution boundary violations, and logical illusion problems encountered by LLM in this vertical scenario. Addressing the semantic bias, business illusion, and data security issues of LLM in the vertical transportation domain, structured prompt word engineering integrates rule constraints, semantic alignment, expert prior injection, and logical synthesis into the interaction process. The experimental evaluation section sets up two sets of comparative models: the baseline model is the DeepSeek-Chat / Reasoner cloud endpoint that only provides the original database structure and does not impose RAIL-LLM framework constraints; the enhanced RAIL-LLM model is the same version of the cloud endpoint applying the prompt word set of this study. Evaluation relies on a self-developed automated testing framework, running 30 standard test cases on a real urban railway dataset from a certain city, covering three types of tasks: basic query, complex association, and anomaly attribution. The evaluation metrics include three items: SQL execution success rate (EX), which refers to the proportion of generated SQL that can be executed without errors and return results; semantic alignment accuracy (SA), which measures whether the results accurately match traffic semantics such as "entering the station," "exiting the station," and "section" in the user's needs; and business logic acceptance (LA), which is evaluated by traffic experts on a scale of 1 to 5 based on the attribution conclusions, assessing the accuracy of the application of traffic mechanisms. The experimental results are shown in Table 1, which compares the task performance under different prompt word frameworks. The experiment demonstrates that this framework significantly improves instruction execution, semantic alignment, and expert attribution effects without adjusting the underlying model parameters, while also ensuring data security.

[0283] Table 1

[0284]

[0285] While the specific embodiments of the present invention have been described above in conjunction with the accompanying drawings, this is not intended to limit the scope of protection of the present invention. Those skilled in the art should understand that, based on the technical solutions disclosed in the present invention, various modifications or variations that can be made by those skilled in the art without creative effort should be included within the scope of protection of the present invention.< / think> < / think> < / think>

Claims

1. A smart interactive method for passenger flow analysis and prediction in urban rail transit based on RAIL-LLM, characterized in that, include: Obtain raw passenger flow transaction data, external influencing factor data, and natural language query requests entered by users for the target route; The original passenger flow transaction data is preprocessed to extract a multi-dimensional feature vector, including historical time series features, time attribute features, and weather features; Based on the pre-built RAIL-LLM prompt engineering framework, intent recognition and semantic parsing are performed on the natural language query request, transforming the natural language query request into a structured query instruction, and generating an analysis constraint rule set. The RAIL-LLM prompt engineering framework includes structured prompt templates in four dimensions: rule constraint dimension R-Rule, semantic alignment dimension A-Attribute, prior knowledge injection dimension I-Insight, and logical synthesis dimension L-Logic. The target feature subset is extracted from the preprocessed passenger flow data using the structured query command. The target feature subset is then input into a pre-trained passenger flow prediction model to obtain a passenger flow prediction numerical sequence. Based on the set of analysis constraint rules, a large language model is invoked to perform attribution analysis on the passenger flow prediction numerical sequence, generating a structured analysis report that includes data notification, anomaly identification, mechanism attribution, and operational suggestions.

2. The intelligent interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM as described in claim 1, characterized in that, The R-Rule dimension prompt word templates achieve intent recognition and boundary constraints in the following ways: when the user is detected to have enabled manual selection mode, the processor determines the task type based on a fixed mapping table between the front-end control state and the back-end task type, and suspends the semantic parsing function of the large language model; when the user has not enabled manual selection mode, the processor calls the large language model to perform intent classification. In the NL2SQL generation stage, the prompt word soft constraint limits the generation to only SELECT / WITH type query statements, while hard interception verification is performed through the back-end regular expression filter and syntax tree parser.

3. The intelligent interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM as described in claim 1, characterized in that, The prompt word templates for the A-Attribute dimension achieve semantic alignment in the following way: a field mapping dictionary is established from the original data fields to the business semantics. The field mapping dictionary includes English field names, Chinese business definitions, statistical standards, and dimensional information.

4. The intelligent interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM as described in claim 1, characterized in that, The I-Insight dimension prompt word template achieves prior knowledge injection in the following ways: based on the mutual information feature correlation evaluation results, a high-impact feature priority analysis rule is established in the prompt words to guide the large language model to consider each influencing factor in the attribution analysis according to the priority sequence; statistical feature indicators of passenger flow fluctuations are written into the prompt word constraint rules, and the corresponding prior rule text is automatically loaded when a specific extreme weather scenario is detected; based on the results of previous empirical research, a compliant explanation path for specific abnormal correlation scenarios is preset in the prompt words.

5. The intelligent interactive method for passenger flow analysis and prediction of urban railways based on RAIL-LLM as described in claim 1, characterized in that, The L-Logic dimension prompt word template achieves logical synthesis in the following way: In complex query tasks involving multiple table joins, the prompt word instruction requires the large language model to generate a thought process containing logic tree derivation before outputting the SQL script. The backend execution engine identifies and extracts the thought content within the reasoning tags, extracting only standard executable SQL structured statements.

6. The intelligent interactive method for passenger flow analysis and prediction of urban rail transit based on RAIL-LLM according to any one of claims 1 to 6, characterized in that, It also includes a dual-agent collaborative scheduling step: when the task involves highly sensitive data or complex nested logic, the locally deployed agent is scheduled to execute the task, and the locally deployed agent loads the complete large language model and performs inference in a closed loop in the intranet environment; when the task is a regular query, the cloud API collaborative agent is scheduled to execute the task, and the cloud API collaborative agent calls the cloud large language model interface through an encrypted channel; the locally deployed agent and the cloud API collaborative agent share a unified RAIL-LLM prompt word template set.

7. A smart interactive system for passenger flow analysis and prediction of urban rail transit based on RAIL-LLM, characterized in that, include: The acquisition module is used to acquire raw passenger flow transaction data, external influencing factor data, and natural language query requests input by the user for the target route. The original passenger flow transaction data is preprocessed to extract a multi-dimensional feature vector, including historical time series features, time attribute features, and weather features; The transformation analysis module is used to perform intent recognition and semantic parsing on the natural language query request based on the pre-built RAIL-LLM prompt engineering framework, transforming the natural language query request into a structured query instruction, and generating an analysis constraint rule set. The RAIL-LLM prompt engineering framework includes structured prompt templates in four dimensions: rule constraint dimension R-Rule, semantic alignment dimension A-Attribute, prior knowledge injection dimension I-Insight, and logical synthesis dimension L-Logic. The predictive analysis module is used to extract a target feature subset from the preprocessed passenger flow data using the structured query instructions, input the target feature subset into a pre-trained passenger flow prediction model to obtain a passenger flow prediction numerical sequence; based on the analysis constraint rule set, it calls a large language model to perform attribution analysis on the passenger flow prediction numerical sequence to generate a structured analysis report containing data notification, anomaly identification, mechanism attribution, and operational suggestions.

8. A non-transitory computer-readable storage medium, characterized in that, The non-transitory computer-readable storage medium is used to store computer instructions, which, when executed by a processor, implement the intelligent interactive method for urban railway passenger flow analysis and prediction based on RAIL-LLM as described in any one of claims 1-6.

9. A computer device, characterized in that, The system includes a memory and a processor, which communicate with each other. The memory stores program instructions that can be executed by the processor, and the processor calls the program instructions to execute the intelligent interactive method for passenger flow analysis and prediction of urban rail transit based on any one of claims 1-6.

10. An electronic device, characterized in that, include: The electronic device includes a processor, a memory, and a computer program; wherein the processor is connected to the memory, the computer program is stored in the memory, and when the electronic device is running, the processor executes the computer program stored in the memory to cause the electronic device to execute instructions that implement the intelligent interactive method for passenger flow analysis and prediction of urban rail transit based on any one of claims 1-6.