A large model-based batch picking auditing formula automatic generation and automated sandbox testing method

By using a large-model-based automatic generation of batch release approval formulas and an automated sandbox testing method, the problems of low efficiency, high professionalism, poor understanding consistency, and insufficient test coverage in batch release approval have been solved. This has enabled an efficient and accurate batch release approval process, ensuring the compliance and regulatory compatibility of the formulas.

CN123178265APending Publication Date: 2026-11-27NAT INST FOR FOOD & DRUG CONTROL
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611333478.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-31
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing technologies suffer from low efficiency, high level of specialization, poor consistency in understanding, delayed response to standard changes, and insufficient test coverage, resulting in a large workload for batch release audits, inconsistent formula logic, and difficulty in quickly identifying potential defects.

Method used

A method based on a large model for automatically generating batch review formulas and automated sandbox testing is adopted. Through template parsing, schema management, prompt construction, large model inference, formula compilation and sandbox testing, parameterized formulas are generated and automated testing is performed. Risk assessment is carried out in conjunction with pharmacopoeia rules and historical review database.

Benefits of technology

It has achieved automation and efficiency in batch release review, ensured the accuracy and compliance of formulas, reduced the cost of repetitive configuration, improved regulatory adaptability and review credibility, and significantly reduced the rework rate.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178265A_ABST
    Figure CN123178265A_ABST
Patent Text Reader

Abstract

The present application relates to the field of artificial intelligence and drug management technology, more specifically to a batch review formula automatic generation and automatic sandbox test method based on a large model. The method comprises: parsing an Excel template to generate a template abstract syntax tree; fusing the template parsing result, field definition, and domain semantic rule library pre-built based on pharmacopoeia and variety standards to construct a formal Schema; constructing a Prompt containing domain constraints; mapping the semantic alignment result to a semantic type and a judgment mode through a lightweight classification model, instantiating the bound parameterized formula template directly when a hit is made, and generating a bottom line under domain constraints by a large model when a miss is made; compiling the formula into executable code; generating professional test cases based on pharmacopoeia limits, biological assay statistics, abnormal reporting, and numerical rounding rules; executing the test in an isolated sandbox, and performing risk-driven compliance judgment on formula missing items in combination with a historical batch review library and a regulation library.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of artificial intelligence and drug management technology, and more specifically to a method for automatically generating batch review formulas and automating sandbox testing based on a large model. Background Technology

[0002] Batch release is a mandatory pre-market review and inspection system implemented by the National Medical Products Administration (NMPA) for each batch of biological products (vaccines, blood products, in vitro diagnostic reagents, etc.). According to the "Administrative Measures for Batch Release of Biological Products," each batch of biological products must be reviewed and inspected by a designated drug testing institution before release. The review includes a summary of production records (i.e., batch release summary) and test reports.

[0003] The batch release summary has been converted from paper documents to Excel spreadsheets, containing basic product information, testing items, quality standards, and test results. It serves as the core basis for batch release review. The batch release review formula is manually entered by management personnel in Excel, row by row, using functions such as IF, AND, and VLOOKUP, based on pharmacopoeia standards, GMP regulations, and company procedures to determine whether the batch summary data complies with regulations.

[0004] In current batch release audit practices, auditors rely on manually reading the quality standard text in the review form and then manually writing audit formulas in the audit system or Excel to determine whether the result value meets the standard. This has the following technical drawbacks: 1. Inefficient and highly specialized: A single review form typically contains hundreds of review points, and the review rules for each type of product must be written from scratch. When dealing with multiple varieties, batches, and standard versions, the workload increases linearly, making it impossible to scale up. The writer must simultaneously understand quality standards, actual value data formats, Excel function syntax, and cell referencing rules, requiring extremely high professional and multidisciplinary skills.

[0005] 2. Poor consistency of understanding: Different auditors may have different understandings of the same quality standard text, resulting in inconsistent formula logic written by different people and creating systemic bias.

[0006] 3. Delayed response to standard changes: When quality standards are updated, existing formulas need to be reviewed manually to determine which rules are affected and then modified accordingly. This process typically takes weeks or even months, making it impossible to quickly respond to regulatory adjustments.

[0007] 4. Insufficient test coverage: The verification of traditional Excel formulas relies on manual sampling checks, usually selecting only 2-3 sets of typical data to verify the correctness of the formula, which is far from achieving systematic test coverage. This may result in a large number of potential defects being exposed only in formal audit scenarios.

[0008] Therefore, how to provide an automated method for generating batch review formulas and automating sandbox testing based on a large model is a problem that urgently needs to be solved by those skilled in the art. Summary of the Invention

[0009] In view of this, the present invention provides a method for automatically generating batch review formulas and automating sandbox testing based on a large model, aiming to solve the above-mentioned technical problems.

[0010] To achieve the above objectives, the present invention adopts the following technical solution: A method for automatically generating batch review formulas and automating sandbox testing based on a large model includes the following steps: S1. Parse the uploaded batch release summary review Excel template to generate a template abstract syntax tree and coordinate mapping information; S2. Integrate template parsing results, field definitions, and pre-built domain semantic rule base to construct a formal schema. The domain semantic rule base is built based on pharmacopoeia, variety standards, and historical batch extraction templates. The formal schema includes the data type, value range, precision requirements, association relationships of fields, and parameterized formula templates registered according to semantic type and judgment mode. S3. Construct a Prompt containing domain constraints based on the formal schema and domain semantic rules; S4. Input the Prompt into the large model for field semantic alignment. Map the semantic alignment result to semantic type and judgment mode through a lightweight classification model bound to the rule base version. When the judgment mode is hit and the confidence level reaches the threshold, directly instantiate the parameterized formula template bound to the judgment mode to generate the review formula. When the judgment mode is not hit, the confidence level is insufficient, or there is a conflict between multiple modes, the large model generates a candidate formula under the domain constraints. S5. Compile the generated audit formula into executable code. The compilation includes lexical and syntactic analysis to generate an abstract syntax tree, syntax tree optimization, and translation into executable code. S6. Generate test cases based on pharmacopoeia rules, batch release reporting characteristics, and drug testing value rounding specifications. The test cases include pharmacopoeia limit boundary test cases, bioassay statistical test cases, batch release reporting anomaly test cases, and rounding rule verification test cases. S7. Execute the test cases in the isolated sandbox environment and make a quality judgment on the audit formulas; for inspection items with blank formula columns, placeholders, or no calculation logic, search the historical batch review library and regulatory library to assess the batch risk status and the basis for exemption from inspection, and determine whether the inspection item can be exempted according to the approval and whether the evidence is complete. If the conditions are met, the test passes and the evidence chain is recorded; otherwise, the formula is missing and the judgment basis is output.

[0011] Furthermore, S1 specifically includes: Unzip the OPC package of the Excel template, parse the worksheet file, shared string file and style file, and extract the original cell data, style information and worksheet relationships; Generate a template abstract syntax tree to identify merged cells, conditional formatting, data validation rules, and existing formula expressions; The table header is detected by combining rule-based and lightweight classification models. The rules identify the visual features of cells, such as bolding, background color, and borders. The lightweight classification model performs semantic role labeling on the cell text, and the labeling categories include table header, data, formula target, and metadata. Establish a dual-track coordinate mapping table using A1 and R1C1 references to mark the candidate positions of the formula's target cell.

[0012] Furthermore, the semantic types of the domain semantic rule base described in S2 include quantitative limits, qualitative judgments, detection limit semantics, dilution conversion, ratios and relative quantities, biological potency judgments, date semantics, quantity semantics, and missing and exception semantics; each semantic type is registered with a judgment mode, and each judgment mode is bound to a parameterized Excel formula template and a filling rule. The formula template records parameter slots, applicable field types, unit requirements, and standard versions. Based on the current template schema and the loaded rule slices, construct a compatibility matrix between the schema, semantic type, decision mode and formula template to predict the matching risk of field types, units and template parameters; and analyze the calculation transmission path between template fields to generate a field dependency graph.

[0013] Furthermore, constructing a Prompt in S3 includes: The Prompt is assembled according to a five-layer architecture: system layer, context layer, example layer, task layer, and constraint layer. The system layer sets the role of the large model as an Excel formula expert for drug batch release. The context layer injects the current template schema, field types, units, and formula target cell coordinates. The task layer specifies the field semantic alignment or fallback formula generation task. The constraint layer injects semantic types, judgment modes, formula template slots, filling rules, and output format constraints. Retrieve historical formula examples for similar scenarios from the historical template library, along with corresponding pharmacopoeia clauses, standard fragments for varieties, and template binding records. Sort by similarity and compatibility with standard versions and then inject into Prompt. Common formula error patterns and batch release reporting errors are encoded as negative examples and injected into Prompt. These common errors include omission of regional references, confusion between absolute and relative references, failure to convert units, and use of the wrong pharmacopoeia version. Under the token length limit, priority is given to retaining information on the task layer, constraint layer, hit rules, and template slots, while adaptively compressing the context layer and example layer.

[0014] Furthermore, the lightweight classification model described in S4 uses a lightweight Chinese semantic encoder with a two-level classification head. The first level predicts the semantic type, and the second level predicts the judgment pattern within the corresponding semantic type, outputting classification confidence, hit rule fragments, and standard version. The lightweight classification model is trained offline based on pharmacopoeia, variety standards, and historical batch templates during the system initialization phase. During training, the input features are field names, field meanings, quality standard clauses, units, limit expressions, result column text, and the context of adjacent cells. First, the semantic types and judgment modes are automatically pre-labeled by rules. Then, the gold standard samples are formed by domain experts. Samples not covered by the rules are supplemented by manual annotation and back-annotation of historical formulas. After training, the model is bound to the rule base version and released uniformly. During runtime, only inference is loaded, and no retraining is performed for individual Excel templates.

[0015] Furthermore, in S4, when candidate formulas are generated by the large model as a last resort, constraint bundle search decoding is used to check in real time whether the current prefix can be expanded into a valid Excel formula. If it cannot be expanded, the probability of the corresponding branch is set to negative infinity to prune illegal branches. Template binding instances are prioritized as candidates, and fallback candidates generated by multiple large models are filtered by both formula abstract syntax tree similarity and execution result consistency. Both template paths and fallback paths must pass field reference integrity, unit consistency and standard version consistency checks. A confidence score is formed by combining semantic classification confidence, template hit rate, model output probability, grammatical validity, field reference integrity, and boundary sensitivity. A low-rank adaptive adapter for the drug batch release field is loaded to enhance performance in professional scenarios.

[0016] Furthermore, the compilation described in S5 also includes: The abstract syntax tree is optimized by constant folding, dead code elimination and reference normalization. The reference normalization converts A1 references into R1C1 format to eliminate ambiguity between absolute and relative references. Map Excel functions to their corresponding functions in a data analysis library for translation into Python executable code; Validate whether all cell references in the formula are within the valid area defined by the template schema, and block outbound references and dangling references; Analyze the dependencies between formulas, generate a formula dependency graph and a data flow graph, and mark the risk of circular references.

[0017] Furthermore, generating test cases in S6 includes: Traverse the conditional branches in the formula abstract syntax tree to ensure that each Boolean subexpression has at least one true value and one false value; Based on the limit parameters in the pharmacopoeia and product standards, five types of numerical test cases are generated: lower limit critical value, lower limit non-compliant value, upper limit critical value, upper limit non-compliant value and normal value. Format boundary test cases are also constructed for unit mismatch, significant digit error, upper and lower limits reversed, and inconsistent limit text writing. For tests requiring parallel samples or multiple dose groups in potency and content determination, generate statistical test cases for bioassays, including critical values ​​for relative deviation of parallel samples, confidence limit exceedance, outlier removal, and abnormal dispersion of replicate wells. Generate text-based results covering untested, inapplicable, retested, compliant, and undetectable results, as well as abnormal reporting cases such as abbreviations of standard basis, incorrect pharmacopoeia versions, missing items, missing units, and inconsistencies between results and judgment columns. Based on the standard for rounding up drug testing values, test values ​​with different decimal places and boundary digits are generated to verify the rules of rounding to even numbers and not allowing continuous rounding. Fine-tuning input values ​​near pharmacopoeia limits, statistical thresholds, and text judgment boundaries to construct critical samples as adversarial samples; Ensure that each field referenced in the formula is explicitly set by the use case at least once, generate full path combinations for nested conditions, and use the Pair-Wise strategy to reduce and preserve pharmacopoeia boundaries, statistical judgment, and report abnormal paths when the combination size exceeds the threshold.

[0018] Furthermore, the batch risk status assessment in S7 includes: based on the large model, searching the historical batch review database, and combining information on the enterprise, product, batch number, production site, and standard version, determining whether the product in this batch is newly approved for market launch, whether there has been a change in the production site, whether there has been a major process change, whether the batch has not applied for batch release for two consecutive years, whether there are any previous batch release failures, whether there are any deviation complaints, adverse reactions, or regulatory risk signals, whether there are already approved exemptions from inspection, and whether the current product is in the full inspection, partial inspection, or dynamic adjustment stage. Based on the large model, the regulatory database is searched, the risk status of the batch is input, and the relevant regulatory clauses, approval documents, inspection stage requirements and evidence lists related to the current variety and test items are located to determine whether the test item meets the conditions for exemption from approval and with complete evidence.

[0019] Furthermore, the quality assessment described in S7 adopts a seven-layer quality threshold, namely, syntactic validity, reference integrity, type compatibility, boundary judgment correctness, exception handling robustness, performance compliance, and formula missing compliance. The system performs difference pattern induction on failed use cases, uses decision trees to summarize counterfactual conditions to generate formula repair suggestions, and outputs a list of supplementary formulas, approval basis or supporting materials for compliance failure projects. Formulas that pass the quality threshold and compliance verification will be written back to the Excel template copy in a non-destructive manner while retaining the original cell styles; formulas that fail the quality threshold will not be written back.

[0020] Compared to existing technologies, this invention transforms large models from freely generated to controlled semantic alignment through template binding and an LLM fallback mechanism, fundamentally suppressing illusions. A lightweight classification model achieves millisecond-level semantic mapping, and binding parameterized templates ensures 100% formula traceability. Continuous iteration of the domain rule base significantly improves formula accuracy and compliance while reducing repetitive configuration costs for enterprises. Breaking through the limitations of general testing frameworks, it constructs a nine-category professional scenario test case generation engine specifically for biological product testing. Four-dimensional coverage of pharmacopoeia limits, bioassay statistics, reporting anomalies, and rounding rules achieves 100% coverage of branches, fields, and paths. It accurately simulates high-frequency errors in real audits, exposing formula logic defects in advance and significantly reducing batch release audit rework rates. It upgrades static formula testing to dynamic compliance verification, automatically assessing batch risk status and the completeness of exemption criteria through LLM-based joint retrieval of historical audit and regulatory databases. It avoids one-size-fits-all omissions, misjudgments, or improper releases, ensuring that every missing formula item is supported by regulatory evidence. This forms a traceable chain of compliance judgment evidence, significantly improving regulatory adaptability and audit credibility. Attached Figure Description

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

[0022] Figure 1 This is a diagram illustrating the overall technical architecture of the present invention; Figure 2 This is an end-to-end business process diagram of the present invention. Detailed Implementation

[0023] The technical solutions in the embodiments of the present invention will be clearly and completely described below. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0024] The present application will now be described in further detail with reference to the accompanying drawings and specific embodiments.

[0025] The system proposed in this application comprises seven services: template parsing, schema management, prompt construction, large model inference, formula compilation, test case generation, and sandbox testing. Here, schema refers to the schema, and prompt refers to the prompt words. Each service exchanges Template AST, field schema, candidate formulas, test cases, and quality judgment results through standardized interfaces. Domain constraints and evidence support are provided by a domain semantic rule base, a historical batch summary review library, and a regulatory library. Specialized domain enhancement mechanisms are introduced in the three key stages of formula generation, test case construction, and test execution: formula generation adopts a dual-track formula generation mechanism of "template binding + LLM fallback" under domain semantic constraints; test case construction adopts a pharmacopoeia compliance-oriented specialized test case generation; and test execution adopts a risk-driven formula missing compliance judgment mechanism, thereby comprehensively improving the compliance and reliability of batch release review formulas. The technical architecture of this application is as follows: Figure 1 As shown.

[0026] The following provides a detailed description of the seven core services.

[0027] I. Template Parsing Service The template parsing service is the system's entry point, responsible for parsing user-uploaded Excel template files into a structured, machine-readable representation, providing input for the schema management service. Internally, the template parsing service includes an Excel file reader, a template structure builder, a header recognizer, and a coordinate mapper. The Excel file reader reads the Excel file, processes the internal structure of worksheets, shared strings, and styles, and converts the binary file into a structured data representation in memory. The template structure builder generates a template abstract syntax tree, identifying key structural features such as merged cells, conditional formatting, data validation, and existing formulas. The header recognizer analyzes the visual features of cells (boldness, background color, borders, etc.) to identify the semantic roles of header rows, data rows, and formula target areas. The coordinate mapper establishes a dual-track coordinate mapping relationship between A1 and R1C1, marking the candidate positions of formula target cells and providing spatial reference for subsequent formula location.

[0028] The input to the template parsing service is an Excel template file for batch release summary review uploaded by the user, which contains one or more worksheets. Each worksheet has a predefined header structure, data range, and cells to be filled with formulas.

[0029] The template parsing service processes the templates as follows: Step 1: Reading the OPC package structure. Unzip the Open Packaging Conventions (OPC) package of the Excel template, traverse and parse xl / worksheets / sheet.xml, xl / sharedStrings.xml, and xl / styles.xml to extract the original cell data, style information, and worksheet relationships.

[0030] Step 2: Template AST Construction. An Abstract Syntax Tree (AST) is generated, and the system identifies merged cells, conditional formatting, data validation rules, and existing formula expressions to establish a structured internal representation of the template.

[0031] Step 3: Header Detection. A detection algorithm combining rule-based and lightweight machine learning is used: the rule layer identifies visual features of cells such as bolding, background color, and borders; the machine learning layer uses a small semantic classifier to perform semantic role labeling on the cell text, with categories including but not limited to Header, Data, Formula Target, or Metadata.

[0032] Step 4: Coordinate Mapping. Establish a dual-track coordinate mapping table using A1 and R1C1 reference systems, marking the candidate positions of the formula's target cell to provide spatial reference for subsequent formula location.

[0033] Step 5: Output structured data. Serialize the Template AST into a JSON object, outputting a dictionary of cell coordinate mappings, a list of formula target area bounding boxes, and a snapshot of the original style.

[0034] The template parsing service outputs a Template AST object (JSON serialized), a dictionary of cell coordinate mappings, a list of formula target area bounding boxes, and a snapshot of the original style (for subsequent lossless write-back). This output is sent to the Schema management service via an internal interface.

[0035] II. Schema Management Service The Schema Management Service is the system's data contract and domain semantic constraint service. It integrates template parsing results, user field definitions, and knowledge from pharmacopoeias, drug standards, and historical templates to form a formalized schema and rule index that can be invoked by Prompt construction, formula generation, and formula compilation. Internally, the Schema Management Service includes a Schema Modeler, a Semantic Encoder, a Vector Retrieval Engine, a Domain Semantic Rule Base Builder, a Domain Semantic Type Registry, a Template and Filling Rule Registry, a Compatibility Analyzer, and a Dependency Graph Generator. The Schema Modeler defines the data type, value range, precision requirements, and relationships of fields, constructing a structured data description specification. The Semantic Encoder generates semantic embedding vectors for fields, supporting field understanding and matching based on semantic similarity. The Vector Retrieval Engine stores and provides approximate retrieval capabilities for similar schemas, supporting rapid reuse of historical knowledge across templates. The Domain Semantic Rule Base Builder gathers the main text of the Chinese Pharmacopoeia, general technical requirements and guidelines, the main text of pharmacopoeia drugs, approved drug registration standards and their revised versions, and historical batch release summary templates, completing clause extraction, version management, unit and limit standardization, and rule indexing. The domain semantic type registrar establishes a hierarchical semantic tagging system for batch release, covering at least categories such as quantitative limits, qualitative judgments, detection limits, dilution conversion, ratios and relative quantities, biopotency judgments, date semantics, quantity semantics, and missing and exception semantics, and registers the judgment modes under each type. The template and reporting rule registrar binds a parameterized Excel formula template and concise reporting format prompts to each "semantic type + judgment mode," recording the template ID, parameter slots, applicable standard versions, and enterprise reporting requirements for direct instantiation during formula generation. The compatibility analyzer defines the syntax rules for formula subsets, constructs a compatibility matrix between schemas, semantic types, and formula templates, and predicts type matching risks. The dependency graph generator constructs a dependency graph between fields, clearly expressing the computational transmission paths between each field.

[0036] The inputs to the Schema management service include the Template AST output by the template parsing service, user-provided field definitions (including quality standard fields, real value fields, field names and field meaning descriptions), the historical template Schema library, and the domain semantic rule library, semantic type and judgment mode registry, formula template and filling rule binding relationship pre-built and version-managed during the system initialization phase.

[0037] The processing steps for the Schema management service are as follows: Step 1: Schema Modeling. Convert the field definitions into a formal schema model (JSON Schema extension), and label each field with its data type (numeric, text, date, boolean), value range, precision requirements, and associated fields.

[0038] Step 2: Semantic Encoding. A semantic encoder is used to generate semantic embedding vectors for the fields, which are then stored in a vector database to enable semantic-based similar schema retrieval and reuse.

[0039] During the system initialization phase (a one-time process, not repeated with each individual Excel template), and upon system launch or rule version update, clauses are extracted, structurally cleaned, and version registered from the main text of the Chinese Pharmacopoeia, general technical requirements and guidelines, the main text of pharmacopoeia varieties, approved drug registration standards and their revised versions, and historical batch release summary templates, forming a traceable domain semantic rule base. Currently, when processing templates, only matching rule slices are loaded based on variety, standard version, and field semantics. A semantic labeling system for batch release should be established simultaneously, including at least: quantitation limits (greater than, less than, range, one-sided limit, two-sided limit); qualitative judgment (negative, positive, no abnormality, compliant, not detectable); detection limit semantics (distinguishing between "not detected", "0", "below quantitation limit", "less than reporting limit"); dilution conversion (conversion between detection value, dilution factor, stock solution concentration, and finished product concentration); ratios and relative quantities (recovery rate, relative potency, antigen content ratio, host cell protein residue ratio); biopotency judgment (combination of conditions such as parallel lines, dose-effect relationship, confidence interval, and replicate dispersion); date semantics (production date, inspection date, expiration date); quantity semantics (batch balance, repackaging quantity balance); and missing and exception semantics (not inspected, not applicable). Specific judgment modes should be further matched, such as setting quantitation limit types like S-LE (less than or equal to), S-RANGE (range), and S-BLTD (two-sided limit). Simultaneously complete the binding of templates and data entry rules, binding parameterized Excel formula templates and data entry rules to the judgment mode under each semantic type; the template records parameter slots, applicable field types, unit requirements and standard versions, and the data entry rules are used to guide enterprises to enter data in a compliant manner according to a unified format.

[0040] Step 3: Compatibility Matrix Construction. Based on the current template schema and the loaded pre-built rule slices, construct a compatibility matrix between the schema, semantic types, decision modes, and formula templates to predict the matching risks of field types, units, and template parameters.

[0041] Step 4: Dependency Graph Generation. Analyze the computational propagation paths between the current template fields and output a dependency graph (Directed Acyclic Graph, DAG) to clearly express the dependencies between each field.

[0042] The output of the Schema management service includes a formalized schema model, field semantic embedding vectors, field dependency graphs, domain rule slices matched by the current variety and standard version, semantic types and decision mode candidates, available formula templates and filling rules, and a schema version snapshot. This output provides a unified data contract and domain constraints for the Prompt construction service, formula generation, and formula compilation service.

[0043] III. Prompt Construction Service The Prompt Construction Service is the system's Prompt engineering service, responsible for transforming schemas, requirement descriptions, historical examples, domain semantic rules, and formula template constraints into high-quality input that the large model can understand. Internally, the Prompt Construction Service includes a hierarchical Prompt assembler, an example retrieval unit, a domain constraint injector, an adaptive truncation unit, and a negative example injector. The hierarchical Prompt assembler stacks five layers—system, context, example, task, and constraint—to assemble a clearly structured and complete Prompt. The example retrieval unit dynamically retrieves historical formulas for similar scenarios from the historical template library, providing relevant reference examples for the current task. The domain constraint injector injects the hit semantic type, decision mode, formula template parameter slots, filling rules, and pharmacopoeia clauses into the Prompt constraint layer, ensuring the large model completes its task only within a controlled semantic space. The adaptive truncation unit intelligently compresses the Prompt within length constraints, prioritizing task and constraint information while appropriately simplifying the context and examples. The negative example injector encodes common formula error patterns as counterexamples, enhancing the model's ability to identify and avoid typical errors.

[0044] The inputs to the Prompt construction service include a formal schema model, field dependency graph, user display requirements, historical formula examples, and rule fragments, semantic types and judgment patterns, formula template binding relationships, and reporting rules from the domain semantic rule base.

[0045] The steps for constructing the Prompt service are as follows: Step 1: Five-layer Prompt Assembly. The five-layer architecture—System, Context, Few-Shot, Task, and Constraint—is layered sequentially: The System layer defines the main model's role as an Excel formula expert for drug batch release; the Context layer injects the current template schema, field types, units, and formula target cell coordinates; the Few-Shot layer loads historical examples; the Task layer specifies field semantic alignment or fallback formula generation tasks; and the Constraint layer applies semantic type, judgment mode, formula template slots, filling rules, and output format constraints.

[0046] Step 2: Example Retrieval. Historical formula examples of Top-K similar templates are dynamically retrieved from the vector database, and pharmacopoeia clauses, standard fragments of the same or similar judgment patterns, and template binding records are simultaneously retrieved. These are then sorted by similarity and standard version compatibility and injected into the Prompt.

[0047] Step 3: Domain Constraint Injection. The semantic type, decision mode, available formula templates, parameter slot descriptions, unit requirements, and filling format hints of the current field candidate are written into the Constraint layer; for template-matching scenarios, the large model only performs field semantic alignment and parameter mapping, without directly rewriting the template logic.

[0048] Step 4: Adaptive Truncation. Implement an adaptive truncation strategy for the Token budget: prioritize retaining Task, Constraint, hit rules, and template slot information, dynamically compress the Context and Few-Shot layers, and strike a balance between length constraints and domain information integrity.

[0049] Step 5: Negative Example Injection. Common Excel formula error patterns and batch release reporting errors (such as missing area references, confusion between absolute and relative references, failure to convert units, and incorrect pharmacopoeia version) are used as Few-Shot negative examples to improve the model's ability to identify and avoid typical errors.

[0050] The output of the Prompt construction service includes an optimized Prompt string, a list of Few-Shot example pairs, domain rule evidence, semantic types and decision pattern candidates, formula template parameter descriptions, reporting rule hints, constraint specifications, and an expected output format template. This output is submitted to the large model inference service via the model gateway.

[0051] IV. Large-scale model inference service The large-model inference service is the core generation service of the system, employing a dual-track mechanism of "template binding + LLM fallback" under domain semantic constraints: the large model first undertakes field semantic alignment, while the lightweight classification model maps the recognition results to semantic types and judgment patterns; when the rule base is hit, the formula template is directly instantiated and bound; only when the rule base is not hit does the large model generate a fallback under constraints, thus suppressing the illusion caused by free generation. The large-model inference service internally includes a model gateway, template semantic recognizer, lightweight semantic classifier, formula template binder, LLM fallback generator, constraint decoder, multi-model voting unit, and confidence scorer. The model gateway uniformly connects to multiple large language models, providing standardized model invocation and routing capabilities. The template semantic recognizer performs semantic alignment of field names, field meanings, quality standards, true values, units, limits, and result columns based on Prompt, outputting a structured semantic description. A lightweight semantic classifier loads a lightweight classification model trained offline based on pharmacopoeia, variety standards, and historical batch templates. It maps semantic descriptions to semantic types and decision patterns, outputting label confidence and hit evidence. The model is bound to the rule base version, preventing retraining for individual templates at runtime. The formula template binder, when a decision pattern is hit and the confidence level is met, reads the bound parameterized Excel formula template, maps parameter slots such as quality standard, true value, upper and lower limits, dilution factor, and batch size to template cells, and instantiates the formula, while simultaneously returning rule suggestions. The LLM fallback generator, for scenarios with no hits, insufficient confidence, or multi-pattern conflicts, calls the large model to generate candidate formulas based on retrieved rule fragments, schema constraints, and negative examples, prohibiting free interpretation outside the domain rules. The constraint decoder employs a bundle search strategy combined with real-time syntax validation to ensure the grammatical validity of the generated content and prunes illegal branches in real-time. The multi-model voting unit participates in syntax tree comparison and execution result verification with template instances and LLM candidates; template binding paths take priority, and LLM candidates must pass consistency voting and reference integrity checks. The confidence scorer integrates semantic classification confidence, template hit rate, output probability, syntactic validity, field reference integrity, and boundary sensitivity to quantify the credibility of the generated results.

[0052] The inputs to the large model inference service include optimization prompts, field schemas, descriptions of comparison rules between quality standards and true values, formula target cell coordinates, expected formula type, domain semantic rule base, semantic type and judgment mode registry, formula template binding relationships, and filling rules.

[0053] The processing steps for large model inference services are as follows: Step 1: Field Semantic Alignment. The large model identifies the correspondence between field names, field meanings, quality standards, actual values, units, limits, result columns, and formula target areas in the Excel template based on the Prompt, and outputs a structured semantic object that clarifies the role of each parameter in the formula and its source cell.

[0054] Step Two: Semantic Type and Judgment Pattern Classification. The lightweight classification model takes structured semantic objects as input, first predicts the primary semantic type, then predicts the secondary judgment pattern, and outputs classification confidence, hit rule fragments, and standard versions. The training corpus for the classification model comes from a rule base constructed from pharmacopoeia, variety standards, and historical batch excerpt templates. The model training method is offline one-time training, updated according to rule versions: during the system initialization phase, training samples are constructed based on pharmacopoeia, variety standards, and historical batch excerpt templates, and the field semantic recognition results of the large model on historical templates and manually corrected labels are collected. Using field names, field meanings, quality standard clauses, units, limit expressions, result column text, and the context of adjacent cells as input features, the semantic type and judgment pattern are first automatically pre-labeled by rules, and then reviewed by domain experts to form the gold standard samples; for samples not covered by the rules, they are supplemented by manual annotation and back-annotation using historical formulas. The model adopts a lightweight Chinese semantic encoder with a two-level classification head. The first level predicts nine semantic types, and the second level predicts judgment patterns such as S-LE, S-RANGE, and S-BLTD within the corresponding type. Once training is complete, the model is bound to the rule base version and released uniformly. At runtime, only inference is loaded, and no retraining is performed for individual Excel templates.

[0055] The specific values ​​for the model base, training data size, classification accuracy metric, and confidence threshold of the lightweight semantic classifier are shown in the table below:

[0056] The above thresholds are determined according to the following rules: when the confidence level of the judgment pattern reaches θ_bind, it enters the template binding path; when it is between 0.70 and θ_bind, the template instance is not considered a priority candidate and must be reviewed by multi-model voting with LLM candidates; when it is below 0.70, the classification result is deemed unreliable and directly enters the LLM fallback path, with a low-confidence risk label marked in the output. Two additional red lines are set for batch release operations: First, safety tests (sterility tests, abnormal toxicity tests, pyrogen or bacterial endotoxin tests, etc.) are not subject to confidence level exemptions; even if the confidence level is ≥ θ_bind, the template binding result must still be reviewed by multi-model voting before output; Second, during the transition period of the Chinese Pharmacopoeia revision, θ_bind is temporarily increased to 0.90, and will be restored after the revision is completed and version verification is performed.

[0057] Step 3: Formula Template Binding and Instantiation. When the judgment pattern is hit and the confidence level reaches the threshold, the system directly reads the parameterized Excel formula template bound to the pattern, maps the upper and lower limits, true values, dilution ratios, stock solution concentrations, finished product concentrations, batch sizes, and other slots to the target template coordinates, generates a traceable Excel formula, and synchronously returns the corresponding reporting rule prompts.

[0058] Step 4: LLM misses the fallback. When the rule base is not covered, the classification confidence is insufficient, or there are multiple conflicting candidate patterns, the system enters the fallback loop: the large model can only generate candidate formulas based on the schema, rule fragments, negative examples, and output constraints in the Prompt, and use structured JSON to explain the formula logic, field mapping, and basis, and then convert it into an Excel formula string.

[0059] Step 5: Constrained Beam Search Decoding. Enable Constrained Beam Search on the fallback generation path to check in real time whether the current prefix can be expanded into a valid Excel formula; if it cannot be expanded, set the logits of the branch to negative infinity to ensure that the output syntax is valid.

[0060] The set of syntax validation rules upon which the constraint search is based is shown in the table below:

[0061] The specific logic for pruning illegal branches is as follows: (1) In each step of the beam search, retain the beam width B=4 candidate prefixes and sort them according to the cumulative log probability; (2) Each time a token is expanded, the verification of rules R1 to R4 is triggered. If any violation occurs, the subsequent logits of that branch are set to negative infinity, and the reason for pruning is recorded. (3) When the subexpression is closed, R5 is triggered and when the formula is closed, R6 is triggered. The illegal branch is backtracked to the nearest recoverable decision point. The candidate pool is replenished according to the suboptimal path to ensure that the bundle width is not occupied by illegal branches. (4) If the candidate pool has no expandable branch for 3 consecutive steps, it is determined that the constraint of the field cannot be satisfied, and it is transferred to the manual confirmation queue. It is prohibited to downgrade to unconstrained free generation. (5) Record the pruning log (branch ID, violation rule number, recovery path) throughout the process, and output it with the test report to support traceability of the generation process; (6) The pruning log and the (prompt hash + model version + rule base version) triple are included in the batch release audit working paper archive to support the review and traceability of the formula generation process during regulatory verification.

[0062] Step Six: Multi-model Integration Voting and Path Determination. Template-bound instances are prioritized candidates, and fallback candidates generated from multiple heterogeneous models are filtered by both formula AST similarity and execution result consistency. Both template paths and LLM paths must pass field reference integrity, unit consistency, and standard version consistency checks.

[0063] Step 7: Confidence Score and Domain Adaptation. A 0-1 score is generated by combining semantic classification confidence, template hit rate, model output probability, syntactic validity, field reference integrity, and boundary sensitivity. A LoRA adapter for the drug batch release domain is then loaded to enhance performance in professional scenarios.

[0064] Large model selection scope: The model gateway is routed from the candidate set {Qwen2.5-72B-Instruct, Jiutian Language Large Model (13.9B), DeepSeek-R1-Distill-Qwen-32B} based on four constraints: domestic large model, private deployment, Chinese long text understanding capability, and structured output stability. The default main generation model is Qwen2.5-72B-Instruct, and the voting models are DeepSeek-R1-Distill-Qwen-32B and Jiutian Language Large Model (13.9B).

[0065] LoRA fine-tuning dataset and strategy: The domain LoRA adapter is fine-tuned on the main generative model base with rank r=16, scaling factor α=32, and dropout=0.05, applied to the four attention projection layers q / k / v / o; the fine-tuning dataset consists of 8,400 batch-issued domain instruction samples, including 3,600 field semantic alignment samples, 3,200 formula generation samples with standard answers and rule basis, and 1,600 negative error correction samples; cosine annealing is used, with the learning rate decreasing from 1e-4 to 1e-5, trained for 3 epochs, with a batch size of 32; the adapter is released in tandem with the rule base version, and only incremental fine-tuning is performed when the rule base is upgraded, without retraining the base.

[0066] The inference hyperparameter configurations are shown in the table below:

[0067] The output of the large model inference service is an Excel formula string (e.g., =IF(AND(B2>=C2,B2<=D2),“Pass”,“Fail”)), generation path identifier (template binding or LLM fallback), semantic type and judgment mode, hit template ID and rule basis, filling rule prompts, confidence score, model version identifier, and multi-model voting records. This output is submitted to the formula compilation service for further processing.

[0068] V. Formula Compilation Service The formula compilation service is the system's compilation and transformation service, responsible for compiling Excel formulas generated from large models into optimized Python executable code, providing executable objects for the test case generation service and sandbox testing service. Internally, the formula compilation service includes a syntax parser, an AST optimizer, a code transpiler, a reference validator, and a dependency graph generator. The syntax parser performs lexical and syntactic analysis on the formulas, generating an abstract syntax tree covering arithmetic, logical, comparison, text, and lookup reference function types. The AST optimizer performs optimizations on the syntax tree, such as constant folding, dead code elimination, and reference normalization, improving code execution efficiency. The code transpiler maps Excel functions to Python executable code, establishing an execution mapping between Excel functions and the data analysis library. The reference validator verifies that all cell references are within the legal area defined by the template schema, ensuring reference integrity. The dependency graph generator analyzes the dependencies between formulas, identifying and marking potential circular reference risks.

[0069] The inputs to the formula compilation service include the original Excel formula string output by the large model, the generation path identifier, the semantic type and judgment mode, the template or rule basis, the template schema, the target cell coordinates, and the formula dependency graph.

[0070] The processing steps of the formula compilation service are as follows: Step 1: Syntax Analysis. The syntax parser performs lexical and syntactic analysis on Excel formulas, generating an Abstract Syntax Tree (AST) that covers five core function categories: arithmetic, logical, comparison, text, and lookup / reference.

[0071] Step 2: AST optimization. Perform constant folding, dead code elimination, and reference normalization (convert A1 references to R1C1 format to eliminate ambiguity between absolute and relative references).

[0072] Step 3: Python Translate. Translate the optimized AST into executable Python code, and establish a mapping table from Excel functions to Python (openpyxl / pandas / numpy), such as mapping IF to np.where, AND to np.logical_and, and VLOOKUP to pd.merge.

[0073] Step 4: Reference Validation. Verify that all cell references in the formula exist within the valid area defined in the template schema, blocking out-of-bounds references and dangling references.

[0074] Step 5: Dependency Graph Generation. Analyze the dependencies between formulas, generate a formula dependency graph and a data flow graph, and mark the risk of circular references.

[0075] The output of the formula compilation service includes optimized Excel formulas, Python executable function objects, formula dependency graphs, and a compilation report (including a list of optimization items, reference verification results, generation path, and risk warnings based on rules). This output provides executable objects for the test case generation service and the sandbox testing service.

[0076] VI. Test Case Generation Service The test case generation service is the system's test data service. Based on general branch, field, and path coverage, it has been restructured into a dedicated test case generation engine for biopharmaceutical testing. The system generates test suites that closely match real-world audit scenarios based on pharmacopoeia rules, batch release reporting characteristics, and drug testing numerical rounding specifications. Internally, the test case generation service includes a branch analyzer, a pharmacopoeia limit boundary test case generator, a bioassay statistics test case generator, a batch release reporting anomaly test case generator, a rounding rule verification test case generator, a field and path coverer, and an adversarial example generator. The branch analyzer traverses the conditional branches in the formula syntax tree, ensuring that the true and false paths for each condition are covered at least once. The pharmacopoeia limit boundary test case generator automatically generates five types of numerical test cases—lower limit critical values, lower limit non-compliant values, upper limit critical values, upper limit non-compliant values, and normal values—based on limit parameters in the pharmacopoeia and product standards, and covers format boundaries such as unit mismatch and incorrect significant digits. The Bioassay Statistical Test Case Generator generates test cases for items requiring parallel samples or multiple dose groups, such as potency and content determination, generating professional scenarios such as relative deviation thresholds for parallel samples, confidence limit exceedances, and outlier removal to verify the compliance of formula statistical logic. The Batch Release Reporting Anomaly Test Case Generator covers text-based results such as "Not Tested," "Not Applicable," "Retest," "Compliant," and "Not Detectable," as well as frequently occurring errors in real audits, such as abbreviations of standard bases, incorrect pharmacopoeia versions, and missing entries. The Rounding Rule Verification Test Case Generator has built-in drug testing numerical rounding specifications, automatically generating test values ​​that need rounding to verify whether the formula follows professional requirements such as "rounding to even numbers" and "no consecutive rounding." The Field and Path Coverer ensures that all fields referenced by the formula are explicitly set and covers nested conditional paths; it uses a Pair-Wise strategy for reduction when paths explode. The Adversarial Sample Generator constructs critical samples near pharmacopoeia limits, statistical thresholds, and text judgment boundaries to verify the robustness of the formula under boundary perturbations.

[0077] The inputs to the test case generation service include compiled Python executable functions, template schema, field value ranges, formula dependency graphs, semantic types and decision patterns, pharmacopoeia and variety standard limit parameters, batch release reporting rules and coverage requirements (100% branch coverage, 100% field coverage, and 100% boundary coverage).

[0078] The processing steps for the test case generation service are as follows: Step 1: Branch Coverage Analysis. Traverse all conditional branches (IF, AND, OR) in the formula AST, ensuring that each Boolean subexpression has at least one true value and one false value.

[0079] Step 2: Precise Use Case Generation for Pharmacopoeia Limit Boundaries. Based on the limit parameters in the pharmacopoeia and product standards, five types of numerical use cases are automatically generated: "lower limit critical value, lower limit non-compliant value, upper limit critical value, upper limit non-compliant value, and normal value". At the same time, format-related boundary scenarios such as unit mismatch, incorrect significant digits, inverted upper and lower limits, and inconsistent limit text writing are constructed.

[0080] Step 3: Generation of Statistical Use Cases for Bioassays. For tests requiring parallel samples or multiple dose groups, such as potency and content determination, use cases that conform to the statistical laws of bioassays are automatically generated. These include specialized scenarios such as critical values ​​for relative deviation of parallel samples, exceeding confidence limits, outlier removal, and abnormal dispersion of replicates, verifying the statistical logic compliance of the formulas.

[0081] Step 4: Generate batch release reporting exception cases. This covers text-based results such as "not tested," "not applicable," "retested," "compliant," and "not detectable," as well as high-frequency errors in real audits, such as abbreviations of standard basis, incorrect pharmacopoeia versions, missing items, missing units, and inconsistencies between results and judgment columns, verifying the error tolerance and accuracy of the formula.

[0082] Step 5: Rounding rule verification test case generation. The built-in drug testing numerical rounding specification automatically generates test values ​​at different decimal places and boundary digits to verify whether the formula follows professional requirements such as "rounding to even numbers" and "no consecutive rounding".

[0083] Step Six: Field and Path Coverage. Ensure that each field referenced in the formula is explicitly set at least once by the use case, and generate full path combinations for nested conditions; when the combination size exceeds the threshold, use the Pair-Wise strategy for scientific reduction, while retaining high-value paths such as pharmacopoeia boundaries, statistical judgments, and reporting anomalies.

[0084] Step 7: Adversarial Example Generation. Fine-tune the input values ​​around pharmacopoeia limits, statistical thresholds, and textual decision boundaries to construct test samples that bring the formula output to a critical decision state, verifying the robustness of the formula under small perturbations.

[0085] The output of the test case generation service includes a set of test cases (containing test case IDs, professional type tags, input data, expected results, and judgment criteria), a test data Excel worksheet, a pharmacopoeia limit boundary coverage report, a bioassay statistical scenario coverage report, an anomaly reporting coverage report, a rounding rule verification report, and branch, field, and path coverage statistics. This output is submitted to the Excel sandbox testing service for verification.

[0086] VII. Sandbox Testing Service The Sandbox Testing Service is a system verification and execution service. Besides executing templates with embedded formulas in an isolated environment, it also introduces a risk-driven compliance assessment for missing formulas in inspection items. For items with blank formula fields, " / ", or simply marked "compliant", the system does not simply classify them as missed inspections or allow them to proceed directly. Instead, it considers the company's batch status, historical batch review records, and regulatory basis to determine if there is approved and fully supported evidence for exemption from inspection. The Sandbox Testing Service internally includes a process sandbox, a formula execution engine, a result comparator, a quality assessor, a formula missing identifier, a batch risk status assessor, a historical review and regulatory retrieval tool, an exemption compliance assessor, a difference analyzer, and a formula rewrite tool. The process sandbox constructs a secure execution environment through process isolation and a system call whitelist mechanism, preventing external influences and malicious operations. The formula execution engine loads Excel templates and recalculates formula results, supporting execution by calculation engines based on the Python ecosystem. The result comparator performs multi-dimensional comparisons of execution results, supporting tolerance-based comparisons for numerical results, standardized matching for text results, and equivalence judgments for Boolean results. The quality assessment system establishes a seven-layer quality assessment framework, verifying formula quality layer by layer from syntax, citation, type, boundary, anomalies, performance to formula missing compliance. The formula missing identifier identifies blank formula fields, " / ", only "compliant", or other placeholder content without calculation logic, transferring them to the compliance assessment chain instead of directly entering a missed inspection or release conclusion. The batch risk status assessor, based on LLM, searches the historical batch review database to determine the registration, changes, historical batch releases, quality signals, and exemption / reduction status of the company's current batch of products. The historical review and regulatory retrieval tool jointly searches the historical batch review database and the regulatory database to locate the approval basis, applicable clauses, and evidentiary requirements related to the current product, company, and inspection item. The exemption / reduction compliance assessor determines whether the test item is "approved for exemption and the evidence is complete"; if the condition is met, the test passes; otherwise, it prompts "formula missing" and outputs the assessment basis. The difference analyzer summarizes the difference patterns of failed test cases, generates repair suggestions, and assists in problem localization and repair. The formula writeback tool writes back a set of Excel formulas that have been validated through sandbox testing to a copy of the Excel template in a non-destructive manner.

[0087] The inputs to the sandbox testing service include a set of test cases, a copy of an Excel template with embedded formulas to be tested, a test data worksheet and a set of expected results, basic information of the company's products in this batch, a historical batch review database retrieval interface, and a regulatory database retrieval interface.

[0088] The processing steps for sandbox testing services are as follows: Step 1: Isolate Execution. Load the test template into an isolated Python process and build a secure execution environment through a system call whitelist mechanism to prevent external influence and malicious operations.

[0089] The process sandbox implements a system call whitelist based on seccomp-BPF. The whitelist range is shown in the table below. System calls outside the whitelist are rejected by default.

[0090] The resource isolation granularity is shown in the table below:

[0091] Specific measures for malicious code protection include: (1) Static scanning: Formula translation code and plug-in scripts undergo AST-level static checks before execution to intercept dangerous nodes such as importos / sys / subprocess, __import__, eval / exec calls and double underscore attribute access; (2) Escape the injected load: Before the test data is written to the cell, text content starting with "=", "+", "-" and "@" is forcibly escaped to prevent the formula injected load from being activated when the template is recalculated; (3) Runtime fallback: System calls outside the whitelist are directly returned to EPERM by seccomp-BPF and an audit log is generated. If the same session is triggered 3 times, the template session will be isolated and transferred to manual review. (4) Write-back area whitelist: Formula write-back is only allowed to be written to Formula Target cells. The electronic signature area, the signatory and reviewer signature columns and audit trail metadata in the template are read-only locked to prevent the write-back process from damaging the integrity of the batch issuance summary signature and the reliability of the data.

[0092] Step Two: Formula Missing Pre-check. Before executing test cases, scan the formula target area to identify blank formula fields, " / ", fields containing only "compliant", or other placeholder content without calculation logic. Such items are not directly judged as "missed" or allowed to proceed immediately; instead, they are transferred to a risk-driven compliance assessment process.

[0093] Step 3: Batch Risk Status Search. Based on the LLM search of the "Historical Batch Release Review Database," and combined with information such as enterprise, product, batch number, production site, and standard version, determine whether the product in this batch is newly approved for market launch; whether there has been a change in the production site; whether there has been a major process change; whether no batch release application has been submitted for two consecutive years; whether there are any previous batch release failures; whether there are any deviations, complaints, adverse reactions, or regulatory risk signals; whether there is already approved exemption from inspection; and whether the current product is in the full inspection, partial inspection, or dynamic adjustment stage.

[0094] Step 4: Regulatory Basis Search. Based on the LLM search of the "regulatory database," input the risk status of the batch mentioned above, locate the relevant regulatory clauses, approval documents, inspection stage requirements, and evidence lists related to the current variety and testing items, and determine whether the testing item meets the condition of "approval exemption and complete evidence."

[0095] Step 5: Formula Execution and Result Comparison. For items with formulas, use openpyxl to load the template and fill the corresponding cells with test data one by one. Call the calculation engine to recalculate the formula. Compare the actual output with the expected result from multiple dimensions: for numerical data, use floating-point comparison with tolerance; for text data, use standardized matching; and for Boolean data, use equivalence judgment.

[0096] Step Six: Quality Threshold Assessment. Perform a seven-layer quality threshold assessment: L1 Syntax Validity, L2 Reference Integrity, L3 Type Compatibility, L4 Boundary Decision Correctness, L5 Exception Handling Robustness, L6 Performance Compliance, and L7 Formula Missing Compliance.

[0097] Step Seven: Formula Missing Compliance Adjudication. For missing formula items identified in the pre-inspection, if the regulatory search and historical audit evidence jointly prove that it is "approved for exemption and the evidence is complete," then the test for this item passes, and the approval basis, applicable clauses, and chain of evidence are recorded; otherwise, a "formula missing" message is displayed, specifying the reason for non-approval, and providing the corresponding regulatory clauses, historical audit records, or missing evidence.

[0098] Step 8: Difference Analysis. Summarize the difference patterns of failed use cases, use decision trees to summarize counterfactual conditions, and generate formula repair suggestions; for compliance-failed projects, output a list of supplementary formulas, approval documents, or supporting materials.

[0099] Step Nine: Formula Write-Back. Create a copy to avoid modifying the user's original file. Write formulas that have passed sandbox testing and compliance verification into the corresponding cells, while retaining the original cell styles. Formulas that have not passed the quality threshold will not be written back, but will only be listed in the report.

[0100] The output of the sandbox testing service includes a sandbox test report (including test case pass rate, failure details, coverage statistics, and anomaly logs), batch risk status assessment results, regulatory basis search results, formula missing compliance determination and evidence chain, quality threshold determination results (pass / warning / failure), formula repair suggestions (difference analysis and correction prompts for failed test cases), and an Excel template file with verified pass formulas.

[0101] The end-to-end business process covers the entire chain from user uploading Excel templates to obtaining formula templates and test reports, and integrates controlled formula generation under domain semantic constraints, professional test case generation guided by pharmacopoeia compliance, and risk-driven compliance determination of missing formulas. Figure 2 As shown.

[0102] Taking the batch release summary template for recombinant hepatitis B vaccine (worksheet "Batch Release Summary") as an example, three test items are selected from the same template: line 7 "pH value" triggers the template binding path, line 9 "potency test" triggers the LLM fallback path, and line 11 "abnormal toxicity test" triggers the formula missing compliance judgment path. The following is a complete end-to-end implementation process from template parsing to formula rewriting.

[0103] (1) Template parsing and coordinate mapping. After uploading the template file, the template parsing service identifies the 5th row as the header row, and the coordinate mapper marks the target cells F7 and F9 of the formula and the placeholder cell F11. The legal area boundary is C7:F7, C9:F9 and the auxiliary area H9:J9. The semantic role recognition results of the cells in the three check rows are shown in the table below:

[0104] (2) Schema modeling and field semantic alignment. The schema management service labels C7, D7, E7, C9, D9, E9 and H9:J9 as numerical (pH value precision to one decimal place, relative potency to two decimal places), F7 and F9 as text-based judgment output, and E11 and F11 as missing and exception semantics; the large model inference service completes field semantic alignment and outputs structured semantic objects {pH value: lower limit → C7, upper limit → D7, measured value → E7, result column → F7} and {potency test: lower limit → C9, upper limit → D9, mean potency → E9, duplicate well monomer value → H9:J9, result column → F9}.

[0105] (3) Semantic classification and dual-track path decision (core protection point 1). The classification results and path decisions of the lightweight semantic classifier for the three items are shown in the table below:

[0106] (4) Template binding path instantiation (pH value). The formula template binder reads the hit template T-QTY-RANGE-01, completes the parameter slot mapping {value→E7, lower→C7, upper→D7, pass_text→“compliant”, fail_text→“non-compliant”}, the hit basis is the text of this variety in the 2025 edition of the Chinese Pharmacopoeia, Volume III, which states that "pH value should be 5.5~7.2", instantiates the following formula, and returns the reporting rule prompt "pH value is determined according to General Rule 0631, and the result is retained to one decimal place": =IF(AND(E7>=C7,E7<=D7),“Compliant”,“Uncompliant”) (5) LLM fallback path generation and constraint bundle search (efficacy test). In the S-POTENCY-CV mode, there is no bound formula template in the rule base. The system enters the fallback path: Prompt injects schema constraints, fragments of the "Statistical Methods for Bioassays" clause in the General Rules of the Chinese Pharmacopoeia (the coefficient of variation of multiple wells should not be greater than 20.0%), and negative examples. The main generation model Qwen2.5-72B-Instruct generates candidates under constraint bundle search. The pruning log is shown in the table below:

[0107] The final generated formula is as follows, with the limit constant 0.2 derived from the injected pharmacopoeia general clause fragment and the basis marked in the structured output; this candidate passed the consistency vote between DeepSeek-R1-Distill-Qwen-32B and the Jiutian Language Model by 3:0, with a comprehensive confidence score of 0.81. =IF(AND(E9>=C9,E9<=D9,STDEV(H9:J9) / AVERAGE(H9:J9)<=0.2),“Compliant”,“Disagree”) (6) Formula compilation. The two formulas were translated into Python executable code after syntax parsing, AST optimization and reference verification (all references are located in the corresponding legal area). No circular references were found. The compilation report marked the generation path as "template binding" and "LLM fallback (rule fragment based on: general bioassay statistical method)".

[0108] (7) Pharmacopoeia Compliance-Oriented Test Case Generation and Sandbox Execution. The test case generation service generates 13 test cases based on pharmacopoeia limit parameters, bioassay statistical laws, numerical rounding specifications, and reporting anomaly patterns. The sandbox testing service fills in, recalculates, and compares the test cases one by one in the isolated process. The results are shown in the table below:

[0109] (8) Risk-driven formula missing compliance determination (abnormal toxicity test). The formula missing identifier detects F11 as a placeholder " / ", and does not directly determine whether it is a missed detection or release, but transfers to the compliance determination link: based on the LLM joint search of the historical batch summary review library and the regulatory library, the batch risk status assessment and evidence chain are shown in the table below:

[0110] The exemption compliance assessment tool, taking into account the above evidence, determines that the test item "can be exempted according to the approval and the evidence is complete," and the L7 assessment is passed. The evidence chain is archived with the test report. If the number of consecutive qualified batches does not meet the approval requirements or there are unregistered site changes, the tool will prompt "formula missing" and output the corresponding regulatory clauses and a list of missing evidence (this branch was not triggered in this example).

[0111] (9) Quality Judgment Summary and Formula Rewrite. The results and handling of the seven-layer quality threshold judgment are shown in the table below:

[0112] In this embodiment, the branch coverage, field coverage, and boundary coverage are all 100%; the dual-track mechanism makes the template binding path results reproducible, and the LLM fallback path is subject to dual control by constraint-bound search and multi-model voting; the pharmacopoeia compliance-oriented use case system verifies the accuracy of the formula in the scenarios of limit boundaries, rounding rules, bioassay statistics, and abnormal reporting; risk-driven judgment avoids misjudging approved exemption items as missed detections.

[0113] Compared with the closest prior art, the beneficial effects of the present invention are as follows: Through the "template binding + LLM fallback" mechanism, large models are transformed from free generation to controlled semantic alignment, fundamentally suppressing illusions; lightweight classification models achieve millisecond-level semantic mapping, and binding parameterized templates ensures 100% traceability of formulas; the domain rule base is continuously iterated, significantly improving formula accuracy and compliance, while reducing the cost of repetitive configuration for enterprises.

[0114] Breaking through the limitations of general testing frameworks, a test case generation engine for nine professional scenarios is built for biological product testing; it provides four-dimensional coverage of pharmacopoeia limits, biological testing statistics, reporting anomalies, and rounding rules, achieving 100% coverage of branches, fields, and paths; it accurately simulates high-frequency errors in real audits, exposes formula logic defects in advance, and significantly reduces the rework rate of batch release audits.

[0115] The static formula testing is upgraded to dynamic compliance verification. By jointly searching the historical audit database and the regulatory database through LLM, the risk status of batches and the completeness of the basis for exemption are automatically assessed. This avoids "one-size-fits-all" omissions, misjudgments, or improper releases, and ensures that each missing formula item is supported by regulatory evidence. This forms a traceable chain of evidence for compliance determination, which significantly improves regulatory adaptability and audit credibility.

[0116] The various embodiments in this specification are described in a progressive manner, with each embodiment focusing on the differences from other embodiments. The same or similar parts between the various embodiments can be referred to each other.

[0117] The above description of the disclosed embodiments enables those skilled in the art to make or use the invention. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the invention. Therefore, the invention is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features disclosed herein.

Claims

1. A method for automatically generating batch review formulas and automating sandbox testing based on a large model, characterized in that, Includes the following steps: S1. Parse the uploaded batch release summary review Excel template to generate a template abstract syntax tree and coordinate mapping information; S2. Integrate template parsing results, field definitions, and pre-built domain semantic rule base to construct a formal schema. The domain semantic rule base is built based on pharmacopoeia, variety standards, and historical batch extraction templates. The formal schema includes the data type, value range, precision requirements, association relationships of fields, and parameterized formula templates registered according to semantic type and judgment mode. S3. Construct a Prompt containing domain constraints based on the formal schema and domain semantic rules; S4. Input the Prompt into the large model for field semantic alignment, and map the semantic alignment result into semantic type and judgment mode through a lightweight classification model bound to the rule base version. When the judgment pattern is hit and the confidence level reaches the threshold, the parameterized formula template bound to the judgment pattern is directly instantiated to generate the review formula; when it is not hit, the confidence level is insufficient, or there is a conflict between multiple patterns, the large model generates candidate formulas as a fallback under the domain constraints. S5. Compile the generated audit formula into executable code. The compilation includes lexical and syntactic analysis to generate an abstract syntax tree, syntax tree optimization, and translation into executable code. S6. Generate test cases based on pharmacopoeia rules, batch release reporting characteristics, and drug testing value rounding specifications. The test cases include pharmacopoeia limit boundary test cases, bioassay statistical test cases, batch release reporting anomaly test cases, and rounding rule verification test cases. S7. Execute the test cases in the isolated sandbox environment and make a quality judgment on the audit formulas; for inspection items with blank formula columns, placeholders, or no calculation logic, search the historical batch review library and regulatory library to assess the batch risk status and the basis for exemption from inspection, and determine whether the inspection item can be exempted according to the approval and whether the evidence is complete. If the conditions are met, the test passes and the evidence chain is recorded; otherwise, the formula is missing and the judgment basis is output.

2. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... S1 specifically includes: Unzip the OPC package of the Excel template, parse the worksheet file, shared string file and style file, and extract the original cell data, style information and worksheet relationships; Generate a template abstract syntax tree to identify merged cells, conditional formatting, data validation rules, and existing formula expressions; The table header is detected by combining rule-based and lightweight classification models. The rules identify the visual features of cells, such as bolding, background color, and borders. The lightweight classification model performs semantic role labeling on the cell text, and the labeling categories include table header, data, formula target, and metadata. Establish a dual-track coordinate mapping table using A1 and R1C1 references to mark the candidate positions of the formula's target cell.

3. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... The semantic types of the domain semantic rule base described in S2 include quantitative limits, qualitative judgments, detection limit semantics, dilution conversion, ratios and relative quantities, biological potency judgments, date semantics, quantity semantics, and missing and exception semantics. Each semantic type has a registered judgment mode, and each judgment mode is bound to a parameterized Excel formula template and a filling rule. The formula template records parameter slots, applicable field types, unit requirements, and standard versions. Based on the current template schema and the loaded rule slices, construct a compatibility matrix between the schema, semantic type, judgment mode and formula template to predict the matching risk of field type, unit and template parameter; It also analyzes the computational propagation paths between template fields and generates a dependency graph between fields.

4. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... Constructing a Prompt in S3 includes: The Prompt is assembled according to a five-layer architecture: system layer, context layer, example layer, task layer, and constraint layer. The system layer sets the role of the large model as an Excel formula expert for drug batch release. The context layer injects the current template schema, field types, units, and formula target cell coordinates. The task layer specifies the field semantic alignment or fallback formula generation task. The constraint layer injects semantic types, judgment modes, formula template slots, filling rules, and output format constraints. Retrieve historical formula examples for similar scenarios from the historical template library, along with corresponding pharmacopoeia clauses, standard fragments for varieties, and template binding records. Sort by similarity and compatibility with standard versions and then inject into Prompt. Common formula error patterns and batch release reporting errors are encoded as negative examples and injected into Prompt. These common errors include omission of regional references, confusion between absolute and relative references, failure to convert units, and use of the wrong pharmacopoeia version. Under the token length limit, priority is given to retaining information on the task layer, constraint layer, hit rules, and template slots, while adaptively compressing the context layer and example layer.

5. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... The lightweight classification model described in S4 uses a lightweight Chinese semantic encoder with a two-level classification head. The first level predicts the semantic type, and the second level predicts the judgment pattern within the corresponding semantic type, outputting the classification confidence, hit rule fragments, and standard version. The lightweight classification model is trained offline based on pharmacopoeia, variety standards, and historical batch templates during the system initialization phase. During training, the input features are field names, field meanings, quality standard clauses, units, limit expressions, result column text, and the context of adjacent cells. First, the semantic types and judgment modes are automatically pre-labeled by rules. Then, the gold standard samples are formed by domain experts. Samples not covered by the rules are supplemented by manual annotation and back-annotation of historical formulas. After training, the model is bound to the rule base version and released uniformly. During runtime, only inference is loaded, and no retraining is performed for individual Excel templates.

6. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... In S4, when candidate formulas are generated from the large model, constraint bundle search decoding is used to check in real time whether the current prefix can be expanded into a valid Excel formula. If it cannot be expanded, the probability of the corresponding branch is set to negative infinity to prune illegal branches. Template binding instances are prioritized as candidates, and fallback candidates generated by multiple large models are filtered by both formula abstract syntax tree similarity and execution result consistency. Both template paths and fallback paths must pass field reference integrity, unit consistency and standard version consistency checks. A confidence score is formed by combining semantic classification confidence, template hit rate, model output probability, grammatical validity, field reference integrity, and boundary sensitivity. A low-rank adaptive adapter for the drug batch release field is loaded to enhance performance in professional scenarios.

7. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... The compilation described in S5 also includes: The abstract syntax tree is optimized by constant folding, dead code elimination and reference normalization. The reference normalization converts A1 references into R1C1 format to eliminate ambiguity between absolute and relative references. Map Excel functions to their corresponding functions in a data analysis library for translation into Python executable code; Validate whether all cell references in the formula are within the valid area defined by the template schema, and block outbound references and dangling references; Analyze the dependencies between formulas, generate formula dependency graphs and data flow graphs, and mark the risk of circular references.

8. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... In S6, test cases are generated including: Traverse the conditional branches in the formula abstract syntax tree to ensure that each Boolean subexpression has at least one true value and one false value; Based on the limit parameters in the pharmacopoeia and product standards, five types of numerical test cases are generated: lower limit critical value, lower limit non-compliant value, upper limit critical value, upper limit non-compliant value and normal value. Format boundary test cases are also constructed for unit mismatch, significant digit error, upper and lower limits reversed, and inconsistent limit text writing. For tests requiring parallel samples or multiple dose groups in potency and content determination, generate statistical test cases for bioassays, including critical values ​​for relative deviation of parallel samples, confidence limit exceedance, outlier removal, and abnormal dispersion of replicate wells. Generate text-based results covering untested, inapplicable, retested, compliant, and undetectable results, as well as abnormal reporting cases such as abbreviations of standard basis, incorrect pharmacopoeia versions, missing items, missing units, and inconsistencies between results and judgment columns. Based on the standard for rounding up drug testing values, test values ​​with different decimal places and boundary digits are generated to verify the rules of rounding to even numbers and not allowing continuous rounding. By fine-tuning the input values ​​near pharmacopoeia limits, statistical thresholds, and text judgment boundaries, critical samples are constructed as adversarial samples. Ensure that each field referenced in the formula is explicitly set by the use case at least once, generate full path combinations for nested conditions, and use the Pair-Wise strategy to reduce and preserve pharmacopoeia boundaries, statistical judgment, and report abnormal paths when the combination size exceeds the threshold.

9. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... The S7 assessment of batch risk status includes: searching the historical batch approval database based on a large model, and combining information on the enterprise, product, batch number, production site, and standard version to determine whether the product in this batch is newly approved for market launch, whether there has been a change in the production site, whether there has been a major change in the process, whether the batch has not applied for batch release for two consecutive years, whether there are any previous batch release failures, whether there are any deviation complaints, adverse reactions, or regulatory risk signals, whether there are already approved exemptions from inspection, and whether the current product is in the full inspection, partial inspection, or dynamic adjustment stage. Based on the large model, the regulatory database is searched, the risk status of the batch is input, and the relevant regulatory clauses, approval documents, inspection stage requirements and evidence lists related to the current variety and test items are located to determine whether the test item meets the conditions for exemption from approval and with complete evidence.

10. The method for automatically generating batch review formulas and automating sandbox testing based on a large model, as described in claim 1, is characterized in that... The quality assessment described in S7 adopts a seven-layer quality threshold, namely, syntactic validity, reference integrity, type compatibility, boundary judgment correctness, exception handling robustness, performance compliance, and formula missing compliance. The system performs difference pattern induction on failed use cases, uses decision trees to summarize counterfactual conditions to generate formula repair suggestions, and outputs a list of supplementary formulas, approval basis or supporting materials for compliance failure projects. Formulas that pass the quality threshold and compliance verification will be written back to the Excel template copy in a non-destructive manner while retaining the original cell styles; formulas that fail the quality threshold will not be written back.