Preprint
Article

This version is not peer-reviewed.

On-Premise, RAG-Grounded Natural-Language-to-SQL for Regulated Batch Manufacturing

Submitted:

01 October 2026

Posted:

06 October 2026

You are already at the latest version

Abstract
Natural-language access to structured manufacturing data could let plant personnel query batch records without structured query language (SQL) expertise, yet realistic multi-table industrial schemas remain hard for text-to-SQL systems, and regulated environments demand data sovereignty, traceability, and validatable behavior that cloud-hosted models cannot satisfy. This study presents a fully on-premise large language model (LLM) system that translates questions into SQL over an ISA-88-aligned database built from a pharmaceutical tablet dataset of 1,005 batches. The pipeline combines schema-aware prompting, retrieval-augmented generation (RAG) over validated query examples, execution-based checking, confidence scoring, and human review. Evaluation on 48 questions across three complexity tiers compared a schema-only baseline with five enhancements: controlled vocabularies, retrieved examples, analytical views, execution-guided self-consistency, and schema-specialized fine-tuning. Retrieved examples roughly doubled execution accuracy for two local models, from 23–25% to 46–48%, without reducing accuracy on any question; gains concentrated in two- and three-table joins, where accuracy reached 80%. Fine-tuning a 7-billion-parameter code model on execution-validated synthetic queries was the only intervention that improved the hardest tier, and combined with retrieval it achieved the highest accuracy there. Results show that a lightweight, auditable local pipeline can support regulated manufacturing analytics while flagging outputs that require human validation.
Keywords: 
;  ;  ;  ;  ;  

1. Introduction

Pharmaceutical and other regulated manufacturers increasingly depend on data-driven decision-making [1,2], yet extracting timely insight from the large, complex process data generated on the manufacturing floor remains difficult. A single tablet-compression line, for instance, produces high-frequency sensor time series alongside raw-material attributes, in-process controls, and laboratory quality results for every batch [3]. Traditional analytics workflows require specialists to translate operational questions into SQL queries that span many interdependent tables, debug their syntax, and validate the results manually. Natural-language interfaces to databases have long been proposed to remove this barrier [4]. Recent shop-floor studies confirm that limited digital literacy and rigid interfaces still prevent operators from querying manufacturing data without external technical support [5]. This manual path can take hours or days, creates a dependency on a small pool of SQL-proficient staff, and delays the interventions that prevent costly batch failures and compliance issues.
Large language models (LLMs) could shorten this path. They are already being adapted to manufacturing tasks, from domain-specific fine-tuning [6] to conversational machine monitoring over real-time shop-floor data [5]. Cloud-hosted natural-language and LLM services, however, conflict with the data-sovereignty, real-time, and compliance requirements of regulated production. Sending prompts that contain proprietary process records to third-party providers exposes them to confidentiality and data-leakage risks that are well documented in the LLM security literature [7]. Standards such as ISA-88 for batch control emphasize structured data, traceable process flows, and validated reporting [8,9]. Generative models, by contrast, introduce the risk of hallucinations: outputs that are plausible but factually incorrect or unfaithful to their source [10,11]. For organizations operating under good manufacturing practice, sending batch data to external providers is frequently not permissible. Any model output that informs a regulated decision must also be traceable and verifiable, consistent with the ALCOA+ data-integrity principles and computerized-system requirements enforced by regulators [12,13,14]. Regulators have recently made this position explicit for generative AI. The draft EU GMP Annex 22 excludes LLMs from critical GMP applications and confines them to non-critical uses in which qualified personnel remain responsible for the suitability of the output [15].
These constraints motivate a locally deployed alternative. A schema-aware LLM can convert natural-language questions into SQL within client-controlled infrastructure if it is grounded in validated documentation through retrieval-augmented generation (RAG) [16] and constrained by a human-in-the-loop review step, in line with the human-centric orientation of Industry 5.0 [17]. We are careful not to overstate what such a system can achieve. On realistic, multi-table schemas, text-to-SQL is far from solved [18,19]. On the enterprise-grade Spider 2.0 benchmark, an agentic framework built on a frontier reasoning model solved only 21.3% of tasks, against 91.2% on the earlier Spider 1.0 [20], and locally hostable models trail cloud frontier systems on the hardest queries. The contribution of this work is therefore not state-of-the-art accuracy. It is a demonstration that a deliberately lightweight, auditable pipeline is feasible, usable, and reliable enough to be valuable in a setting where the realistic alternative is no AI assistance at all.
Our contributions are fourfold. First, the approach prioritizes local deployment and data sovereignty: the LLM, vector store, and database all run within client-controlled infrastructure, removing cloud dependencies and keeping sensitive manufacturing data inside the organization's controlled environment. Second, it employs a schema-aware, RAG-grounded pipeline that retrieves ISA-88 documentation, schema metadata, and validated query examples from a local vector database before generation, improving grounding for complex cross-table questions. Third, it incorporates reliability safeguards: per-query confidence scoring, execution-based fidelity checking against ground-truth results, and a human-in-the-loop review step. Together, these keep outputs advisory and auditable rather than prescriptive, as current regulatory guidance expects for generative models [15]. Finally, it provides an empirical evaluation under realistic constraints. A tiered 48-question benchmark over the ISA-88 schema compares three context configurations (schema-only, controlled vocabularies, and retrieved validated examples) across two locally hostable open-weight models. The evaluation also covers execution-guided self-consistency, an adaptation of self-consistency decoding [21] to SQL generation, and a schema-specialized fine-tuned model, establishing which interventions improve accuracy and which do not.
The remainder of the paper is organized as follows. Section 2 reviews related work across four dimensions and identifies the gap addressed here. Section 3 describes the system design and implementation. Section 4 defines the evaluation methodology and Section 5 reports the results. Section 6 discusses the findings against the literature, and Section 7 and Section 8 present limitations, future work, and conclusions.

3. System Design and Implementation

This section describes the architecture and approach used to design and implement a localized AI-driven analytical system for pharmaceutical manufacturing and quality contexts. It explains how the components translate natural-language questions into executable SQL over an ISA-88-aligned batch database, in a form suitable for regulated manufacturing. All components run on a local server under client control, preserving data sovereignty.
The architecture is intentionally lightweight rather than maximally accurate. State-of-the-art text-to-SQL systems achieve their results through multi-call agentic pipelines that iteratively explore the schema, execute candidate queries and self-correct, often issuing many model and database calls per question. In a validated, regulated environment these properties are liabilities as much as assets: each additional autonomous step expands the surface that must be qualified, monitored for drift and explained to an auditor, and non-deterministic search complicates reproducibility and change control. We therefore adopt a deterministic, single-pass generation step grounded by retrieval and bounded by an explicit human-in-the-loop confidence check, prioritizing predictability, traceability and ease of validation over benchmark accuracy; a multi-sample, execution-guided variant is evaluated separately as a controlled refinement (Section 4.5). For the same reason of deployability under client control, all models are open-weight and served entirely on-premise on a single workstation-class GPU, and a general-purpose model is compared with a code-specialized one of the same architecture, alongside a smaller model fine-tuned on the schema (Section 3.5). The aim is not to surpass cloud frontier systems on accuracy, which would be unrealistic given the gap reported between frontier and locally deployable models on complex queries, but to characterize the accuracy, reliability and usability that a fully on-premise, auditable pipeline can deliver.

3.1. System Overview

The system integrates natural-language processing, SQL generation and retrieval to improve data accessibility and accuracy while remaining compatible with ISA-88 batch-control practice. Altra Systems' experience in ISA-88 standards, MES integration and SQL-based data warehousing informed the selection of components so that AI-generated outputs remain consistent with established batch records and equipment models. As shown in Figure 1, the system comprises four main components. The LLM engine is a locally served open-weight model that receives user questions and, using schema-aware prompts, generates candidate SQL.
The retrieval layer augments the prompt with controlled domain vocabularies and a small number of validated worked examples, selected per question by lexical similarity from a curated store held out from the benchmark; this improves grounding and reduces hallucinations on complex questions. The SQL database layer is a locally hosted relational database containing the ISA-88-aligned dataset, against which generated queries are executed and benchmarked. Finally, the user interface is a lightweight dashboard where users submit questions and inspect the generated SQL, the confidence score and a plain-language result summary.
The interface sits at the top, the LLM and retrieval components in the middle logic layer, and the relational database and exemplar store at the bottom data layer. This separation supports modular tuning, such as improving prompts or retrieval without changing the interface, and keeps control over where regulated data resides.
While Figure 1 sets out the static component architecture, Figure 2 traces how these components act on a single query.
A user's natural-language question is first grounded by retrieval from the exemplar store; the retrieved schema metadata, controlled vocabularies and validated query patterns augment the prompt, and a locally served open-weight model then generates SQL that is execution-checked and returned with a confidence score for human review. The diagram thus shows how the elements described above combine into a single deterministic, retrieval-grounded pass from question to validated output.

3.2. Dataset

To evaluate the system on pharmaceutical data, we use the openly published tablet-manufacturing dataset of Žagar and Mihelič [3], comprising 1,005 production batches of a film-coated tablet collected over roughly thirty months, with incoming raw-material analyses, intermediate and final product quality, and tablet-compression process time series at ten-second resolution. Because the published data are delivered as flat files oriented to quality prediction, we transformed them into a normalized, ISA-88-aligned schema of sixteen interdependent tables spanning product and recipe, equipment hierarchy and sensors, material genealogy, procedural execution (a compression operation with start-up and production phases), process data and quality results; Appendix B (Figure B1) gives the full schema, organized into the ISA-88 sub-models with the batch table as the central hub.

3.3. Prompt Engineering and Query Pipeline

The pipeline converts a user question into executable SQL through controlled prompt steps. The model is first primed with schema information (table names, relationships, primary keys and key attributes) so it can reason about which tables and joins are relevant. Structured prompt templates then guide it to identify the required tables, construct a syntactically valid query, and avoid inventing columns or tables. Retrieval is treated as an experimental condition: in the schema-plus-RAG configuration, the system retrieves ISA-88 definitions, table descriptions and validated example patterns from the vector store and adds them to the prompt to clarify ambiguous terms (for example, batch outcome versus equipment failure); in the schema-only configuration this retrieval is disabled. After generation, the output is compared against analyst-validated reference SQL using both semantic similarity and execution-result comparison, and a confidence score is assigned (Section 4.4). Low-confidence or divergent outputs are flagged in the interface for review or rejection, keeping humans in the loop for critical decisions.

3.4. User Interface

The interface is a simple dashboard for engineers, quality specialists and managers who may not have programming backgrounds. Users enter a natural-language question and the dashboard displays the generated SQL, its confidence score and a short structured summary of the results side by side. When retrieval is active, it also lists the worked examples and vocabulary entries supplied to the prompt, increasing transparency. Review takes place in the same dashboard: users compare generated queries against pre-validated SQL and mark outputs as correct, partially correct or incorrect, and approved queries are added to the exemplar store for subsequent prompt tuning and retrieval adjustment.

3.5. Models Evaluated

To reflect current local-model practice, the system is evaluated with open-weight models that can be served entirely on-premise. The primary comparison uses two members of the Qwen3 30B-A3B family [44]: a general-purpose instruction model (Qwen3-30B-A3B-Instruct) and a code-specialized model of the same architecture (Qwen3-Coder-30B-A3B-Instruct). Both are mixture-of-experts models with 30.5 billion total but only about 3.3 billion active parameters per token, so that in 4-bit quantization they run on a single workstation-class GPU; sharing architecture and scale, they isolate the effect of code specialization. To probe schema adaptation, a smaller code model, Qwen2.5-Coder-7B-Instruct [45], is additionally fine-tuned on the schema (Section 4.6). All models are served under identical retrieval and prompting conditions, and serving and version details are given in Appendix A.

4. Evaluation Methodology

4.1. Datasets and Question Bank

The system is evaluated on the ISA-88-aligned relational database derived from the pharmaceutical tablet-manufacturing data of Žagar and Mihelič [3], comprising 1,005 production batches across 25 product sub-families. Over the pharmaceutical schema we constructed a benchmark of 48 natural-language questions reflecting realistic operational and quality queries, spanning batch genealogy, raw-material and product quality, process features, equipment and sensor relationships, campaign roll-ups, and temporal analysis. Each question is labelled with one of three complexity tiers: single-table or simple-aggregation (T1, n = 13), two- to three-table joins (T2, n = 15), and multi-join queries involving aggregation, filtering, temporal logic, or sub-queries (T3, n = 20). The full question bank, with per-question tier and category labels, is provided in Appendix B. The benchmark is deliberately domain-specific rather than drawn from generic corpora such as Spider or BIRD, because the contribution concerns querying ISA-88-structured batch records; it is extensible, and the released version provides the seed set used here.

4.2. Ground-Truth Construction

Each question is paired with a reference (gold) SQL statement authored against the schema and validated by execution: every reference query was run against the database and its returned result set inspected for correctness, and a programmatic verifier confirms that all 48 queries execute and return the intended rows. Because recent analysis has shown that text-to-SQL benchmark annotations frequently contain errors [46], this execution-based verification was treated as a required step rather than an afterthought. Where a quantity could not be reconstructed exactly from the raw time series without the original feature-extraction routines, the published per-batch values of the source dataset were taken as ground truth and the raw series retained separately (Section 3.2).

4.3. Metrics

The primary metric is execution accuracy: a generated query is correct if, when executed, it returns the same result set as the reference query. Result sets are compared as multisets of rows, insensitive to row and column order and with floating-point values rounded to four decimal places, so that a logically equivalent query phrased differently is still scored correct. As a partial-credit measure we report fidelity, the Jaccard overlap between the returned and reference row multisets. Each outcome is assigned to one category (exact match; value mismatch, where the query executes but returns different data; SQL or execution error, such as referencing a non-existent column or an invalid join; empty result; or no prediction) to support the failure-mode analysis in Section 5.

4.4. Confidence Scoring and Human Oversight

At inference the system assigns each generated query the confidence score defined in Section 3.3 and surfaces low-confidence outputs for human review, keeping the pipeline advisory and auditable. In the offline evaluation, execution-based comparison against ground truth provides the objective correctness signal, while the confidence mechanism is assessed by its agreement with that signal.

4.5. Models and Experimental Configurations

The system was evaluated with locally deployable, open-weight models so that every reported configuration could in principle run on-premise without a cloud dependency. The primary comparison used two members of the Qwen3 30B-A3B family: a general-purpose instruction model (Qwen3-30B-A3B-Instruct) and a code-specialized model of the same architecture (Qwen3-Coder-30B-A3B-Instruct). Both are mixture-of-experts models with 30.5 billion total but only about 3.3 billion active parameters per token, so that in 4-bit quantization they occupy on the order of 18 GB and run on a single workstation-class GPU. Using two models that share architecture, scale and active-parameter count and differ only in training emphasis isolates the effect of code specialization.
Three context configurations were compared, holding the model, prompt template and scoring constant and varying only the information supplied alongside the question. The schema-only configuration supplied the table, column and foreign-key definitions. The vocabulary configuration additionally supplied controlled domain vocabularies (the characteristic catalogue, the stage and statistic enumerations, the material codes, the product strengths and the process-feature names). The retrieval configuration additionally supplied a small number of validated worked examples retrieved per question from a held-out exemplar store by a lightweight lexical-similarity retriever, drawn from a pool disjoint from the evaluation set so that no benchmark answer was leaked. Two further refinements were evaluated as additions to the retrieval configuration. First, a set of curated analytical views was added to the database (one row per batch, with the entity-attribute-value quality measurements pivoted into named columns), present in both contexts while the reference queries continued to use the base tables. Second, an execution-guided self-consistency procedure was evaluated, in which several candidate queries were sampled, executed against the database, repaired when they raised an error or returned no rows, and resolved by majority vote over executed result sets, with the fraction of candidates agreeing on the selected result reported as a confidence score. All sampling used a temperature of zero for the deterministic first candidate and a moderate temperature for additional candidates, and the database, schema context and scoring were identical across configurations. Table 5 summarizes the models and context configurations evaluated. The fine-tuned model is described in Section 4.6.

4.6. Model Adaptation by Fine-Tuning

To address the residual failures on the most complex queries (Section 5.4), a smaller open-weight model was fine-tuned on the schema. The base model was Qwen2.5-Coder-7B-Instruct, selected because a seven-billion-parameter model is inexpensive to fine-tune on a single 16 GB GPU and is straightforward to deploy on-premise, making it the most faithful artefact for the deployment setting.
The training set was generated synthetically and validated by execution. A library of parameterized templates spanning the schema's query patterns (single-table aggregates, two- and three-table joins, raw-material genealogy, the stage- and statistic-filtered quality measurements, process-feature filters, grouped aggregation with HAVING, sub-queries comparing a group to an overall average, conditional pass-rate calculations, stage comparisons, temporal grouping, and joins over the analytical views) was instantiated over real entities drawn from the database, so that each generated query was correct by construction; every query was then executed and retained only if it ran successfully. Each template was tagged by complexity tier, and generation enforced an intentionally compositional profile (approximately 10%, 35% and 55% for tiers T1, T2 and T3) rather than the distribution that is easiest to enumerate, because the complex T3 queries were the principal failure mode and therefore required over-representation; per-family balancing within each tier prevented high-cardinality lookup patterns from dominating. Natural-language diversity was increased by generating several meaning-preserving rewrites of each question with a language model while leaving the validated SQL unchanged, so that label correctness was retained. The 48 benchmark questions and the retrieval exemplars were excluded from the training set, and the data were formatted using the same prompt template employed at inference.
The model was adapted using QLoRA [47]: the base was loaded in 4-bit precision and low-rank adapters of rank 16 were trained on the attention and feed-forward projection matrices, with the loss computed only on the SQL completion. Training ran for two epochs with an effective batch size of eight; the validation loss decreased monotonically and plateaued below 0.01, indicating stable convergence on the synthetic distribution. The resulting adapter is a few tens of megabytes and is loaded on top of the open base model, so the adapted system remains fully self-hostable.

5. Results

This section reports the evaluation on the 48-question benchmark of Section 4.1. Execution accuracy is the primary metric: a generated query is correct when its executed result set matches that of the reference query, compared as an order-insensitive multiset with floating-point values rounded. Fidelity (the Jaccard overlap of result rows) and an outcome category (exact match, value mismatch, SQL error, empty result, or no prediction) support the failure analysis.

5.1. Effect of Retrieval Grounding

Table 6 reports execution accuracy for the two locally deployable models under the three context configurations. Supplying controlled vocabularies produced no meaningful improvement over the bare schema (one additional question for the general model, none for the code-specialized model). Retrieving validated worked examples, by contrast, approximately doubled execution accuracy for both models, from 23-25% to 46-48%. The improvement was statistically significant and free of regressions: a paired McNemar test on per-question correctness identified eleven questions that changed from incorrect to correct with example retrieval and none that regressed, for each model (exact two-sided p approximately 0.001). The two retrieval conditions thus differed in kind rather than degree: vocabulary lists indicate which entities exist, whereas worked examples demonstrate how to compose them, and only the latter affected accuracy on this schema.

5.2. Performance by Query Complexity

Table 7 decomposes the schema-only and retrieval configurations by complexity tier for the code-specialized model; the general model followed the same pattern. The benefit of retrieval was concentrated at the intermediate tier, where accuracy rose from 27% to 80%, recovering most two- and three-table join queries. Single-table queries (T1) were already handled moderately well and improved slightly, whereas the complex multi-join queries (T3) remained near the floor, rising only from zero to two of twenty. Accuracy therefore degraded sharply with structural complexity, and the residual difficulty was almost entirely confined to the most complex queries. Because two- and three-table joins of this kind, which link a batch to its product, material lots or process features, account for the bulk of routine operational and quality questions, the retrieval configuration answered roughly four-fifths of that tier and therefore handled most of the everyday queries a plant analyst would pose; its overall accuracy of 46-48% was held down by the hardest analytical queries (T3), so in practice the system is dependable for common look-ups and aggregations while the complex compositional queries remain the cases that require human review.

5.3. Model Specialization and Additional Refinements

Across all configurations the code-specialized model did not significantly outperform the general-purpose model of the same architecture and scale (48% versus 46% with retrieved examples; 25% versus 23% with the schema alone), and a paired McNemar test found no significant difference in either condition (p = 1.0). For natural-language-to-SQL over this schema, retrieval grounding rather than code specialization determined accuracy.
Two refinements were evaluated as additions to the retrieval configuration, and neither improved accuracy. Adding the curated analytical views reduced accuracy from 46-48% to 42% for both models. The mechanism was visible in the generated queries: the models adopted the convenience columns but frequently applied them incorrectly, selecting a column that was null for the requested metric or mismatching a view to a question, which raised the SQL-error rate in the schema-only condition to 19%, while the additional column names enlarged the prompt without commensurate benefit. Denormalizing the schema into wide reporting views was therefore counterproductive. Layering execution-guided self-consistency (five sampled candidates with up to two repair rounds) on the view-augmented configuration produced at most a negligible gain: accuracy changed from 20 to 21 of 48 for the code-specialized model and from 20 to 20 for the general model (a paired McNemar test found no question changing in either direction), while median per-query generation time increased three- to fivefold. Self-consistency and execution repair help only when failures are non-executable or inconsistent across samples, whereas the dominant residual failures here were executable and stable (Section 5.5), so the majority vote tended to agree on an incorrect result.
The confidence score produced by the voting procedure was, in both models, weakly but positively calibrated. Correct predictions carried higher mean confidence than incorrect ones (0.98 versus 0.88 for the code-specialized model; 1.00 versus 0.93 for the general model), and the point-biserial correlation between confidence and correctness was 0.36 and 0.22 respectively. However, both models assigned the maximum confidence to a large majority of questions, including many that were wrong, so the signal is usable as a soft indicator but does not by itself constitute a reliable correctness filter. This supports retaining human validation of low-confidence outputs while cautioning against treating model confidence as a guarantee.

5.4. Schema-Specialized Fine-Tuning

Table 8 reports the fine-tuned seven-billion-parameter model in two configurations, evaluated with the schema-only context it was trained on and with retrieved examples added at inference, against the strongest off-the-shelf configurations. Fine-tuning achieved the objective for which it was designed: with schema-only context it raised accuracy on the most complex queries from two to four of twenty (10% to 20%), and adding retrieved examples raised it further to five of twenty (25%), the highest T3 accuracy of any configuration evaluated, including the 30B-A3B model with retrieval. The deliberately T3-weighted training set thus improved performance precisely where the system had previously failed most, and the two interventions proved complementary: relative to the tuned model alone, adding retrieval recovered intermediate-tier accuracy (T2 from 9 to 11 of 15) while preserving the T3 gain (T3 from 4 to 5).
Figure 3 visualizes these configurations across the three complexity tiers. The fine-tuned model did not exceed the 30B-A3B retrieval configuration in overall accuracy (46% versus 48%).
Two observations qualify this parity in the tuned model's favor. First, it is a seven-billion-parameter model, roughly a quarter of the active size of the 30B-A3B model, so matching the larger model overall while surpassing it on the hardest tier is a favorable deployment trade-off. Second, the modest overall figure masks a redistribution: adding retrieval to the tuned model lowered single-table accuracy (T1 from 8 to 6 of 13), as the worked examples appear to distract the model on trivial queries, offsetting part of the gains at the higher tiers. The strongest configuration for complex analytical queries is therefore the fine-tuned model with retrieval, while the highest overall accuracy remains the larger model with retrieval; which to prefer depends on the query mix and the deployment constraints.

5.5. Failure Analysis

Categorizing every outcome clarified the accuracy ceiling. In the schema-only configuration the errors were dominated by two patterns rooted in the normalized schema: queries that omitted the stage and statistic filters required by the entity-attribute-value design of the quality table (the single largest cause, accounting for the entire set of measurement questions that require such filters), and queries that assumed a flatter schema than exists, for example treating an attribute stored in the characteristic catalogue as a direct column. Retrieving worked examples that demonstrate these patterns removed most of them, which is the source of the intermediate-tier recovery in Section 5.2. After retrieval, the residual failures were concentrated in a single category: value mismatches accounted for roughly twenty of the forty-eight questions for both models, while empty results and SQL errors each fell to five or fewer. These were queries that were syntactically valid, executed without error, and returned a plausible but incorrect result set, typically through an incorrect aggregation grain, a missing or over-broad join predicate, or a misreading of the intended grouping. Such errors are by construction invisible to execution-guided methods, because the database raises no error and independently sampled candidates tend to repeat the same misreading. The ceiling on this benchmark is therefore one of semantic rather than syntactic correctness, most pronounced on the complex queries that require multi-step compositional reasoning, and fine-tuning was the only intervention that moved it.
Recent text-to-SQL studies indicate that low-to-moderate execution accuracy is common once models are evaluated beyond simplified academic benchmarks. On BIRD, even GPT-4 reached only 54.89% execution accuracy against 92.96% human performance [18]. At the enterprise-workflow level, Spider 2.0 makes the difficulty starker still: the best agentic configuration solved only 21.36% of tasks, and traditional text-to-SQL methods dropped below 6% execution accuracy on Spider 2.0-Lite despite much higher results on Spider 1.0 and BIRD [20]. Even ReFoRCE, a state-of-the-art agentic framework using schema compression, self-refinement, consensus voting and column exploration, achieved only 35.83% and 36.56% execution accuracy on Spider 2.0-Snow and Spider 2.0-Lite respectively [38]. The semantic ceiling observed here is therefore in line with the difficulty these benchmarks report.

6. Discussion

The evaluation yields a coherent and, in places, deliberately negative account of what does and does not improve natural-language-to-SQL on a realistic, ISA-88-aligned manufacturing database. The single largest lever was retrieval of validated query examples, which approximately doubled execution accuracy with a significant, regression-free effect and recovered most intermediate-complexity queries. Controlled vocabularies, code specialization, denormalized analytical views, and execution-guided self-consistency each added little or nothing, the last confirmed across both models, and the analytical views were mildly counterproductive. Targeted fine-tuning of a small model on a compositional, execution-validated synthetic dataset was the only intervention to improve the hardest tier, and it was complementary to retrieval: the fine-tuned seven-billion-parameter model combined with retrieved examples achieved the highest accuracy on complex analytical queries of any configuration while matching the much larger model overall, a favorable result for on-premise deployment even though absolute accuracy on the hardest queries remained limited. These findings are consistent with the broader text-to-SQL literature, in which accuracy on realistic enterprise schemas remains well below that on simpler academic benchmarks (Section 5.5), in which retrieval and in-context demonstrations are strong contributors, and in which locally deployable open-weight models trail frontier systems while remaining attractive where data cannot leave the premises; the limitations observed on the present ISA-88 benchmark are thus consistent with broader challenges in realistic deployment, particularly when schemas are large, normalized, domain-specific and require multi-step analytical reasoning.
For practice, the results suggest a pragmatic on-premise configuration: a single-GPU open-weight model grounded with retrieved validated examples answers the great majority of the routine two- and three-table operational queries that dominate day-to-day use (about four-fifths of that tier) with fully auditable behavior, even though overall accuracy (46-48%) is held down by the hardest analytical queries, and a small fine-tuned model extends reach on those complex queries while remaining inexpensive to host. Relative to the closest industrial neighbors, which provide natural-language access over sensor streams [27] or simulation output via knowledge graphs [28], the contribution here is executable SQL over hierarchical relational batch records with execution-based fidelity checking. The weak calibration of the model's confidence signal reinforces the design choice to keep a human in the loop: confidence is useful for triage but is not a substitute for validation, and the execution-based comparison against ground truth, rather than the model's self-assessment, is what provides an objective correctness signal.

7. Limitations and Future Work

Several limitations bound the claims of this study and should be read as design boundaries. The benchmark comprises 48 questions over a single production line, so absolute accuracies should be read as indicative rather than definitive, and broader benchmarks across plants and processes are needed. The fine-tuning data were synthetic; although every query was validated by execution and the human-curated benchmark was held out, the training distribution may not fully reflect the questions practitioners ask, and overfitting to the synthetic distribution remains a risk that a larger and more varied training set, or additional human-authored evaluation items, would mitigate.
Future work follows from these boundaries. The accuracy ceiling is semantic rather than syntactic, and closing it on complex compositional queries will require approaches beyond context engineering: richer and larger fine-tuning datasets, larger schema-adapted models, and query-decomposition or plan-then-generate strategies that target multi-step reasoning. Schema linking, which supplies fewer question-relevant columns rather than more, is a promising alternative to the denormalized views that proved counterproductive here. Validation on additional plants and processes would further strengthen external validity.

8. Conclusions

This study implemented and evaluated a fully on-premise, schema-aware, RAG-grounded LLM system that translates natural-language questions into SQL over an ISA-88-aligned batch-manufacturing database, with confidence scoring and human-in-the-loop validation. On a tiered 48-question benchmark, retrieving validated query examples was the decisive intervention, approximately doubling execution accuracy to 46-48% with a significant, regression-free effect, while code specialization, denormalized analytical views and execution-guided self-consistency added little; a small code model fine-tuned on a tier-balanced, execution-validated synthetic dataset was the only intervention to improve the most complex queries and, combined with retrieval, achieved the highest accuracy on them while a seven-billion-parameter model matched a far larger one overall. Rather than competing with cloud frontier systems on accuracy, the system demonstrates that a deliberately lightweight, auditable and sovereign pipeline is feasible and usable for regulated batch-manufacturing analytics, and it maps the query classes for which human review remains essential. The approach offers lessons for other regulated, data-rich industrial domains where data sovereignty and validatability outweigh raw model performance.

Author Contributions

Conceptualization, L.R., J.Z.-A., J.V., M.U., G.M., S.D. and E.G.-F.; Methodology, L.R. and J.Z.-A.; Validation, J.V. and E.G.-F.; Formal analysis, J.Z.-A.; Investigation, J.Z.-A., M.U., G.M. and S.D.; Writing—original draft preparation, L.R., J.Z.-A., M.U., G.M. and S.D.; Writing—review and editing, F.A., J.V. and E.G.-F.; Visualization, J.Z.-A.; Project administration, L.R.; Funding acquisition, F.A. All authors have read and agreed to the published version of the manuscript.

Funding

This research was funded by the Ongoing Research Funding Program (ORF-2026-1514), King Saud University, Riyadh, Saudi Arabia.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The publicly available pharmaceutical tablet-manufacturing data used in this study were published by Žagar and Mihelič and are available in Figshare at https://doi.org/10.6084/m9.figshare.c.5645578.v1. The ISA-88-aligned relational database used for the analyses was derived from these data, and the 48 benchmark questions are provided in Appendix B.

Acknowledgments

The authors would like to thank the Ongoing Research Funding Program (ORF-2026-1514), King Saud University, Riyadh, Saudi Arabia, for support this work.

Conflicts of Interest

The authors declare no conflicts of interest.

Appendix A. Prompt Templates and Configuration

A.1. Prompt Structure

Each query was generated from a single user prompt comprising three parts: a schema description (every table with its columns and foreign keys, the analytical views, and controlled domain vocabularies), a task instruction, and the question. In the retrieval condition, k = 3 validated worked examples (a natural-language question paired with its reference SQL), retrieved from a held-out store, were inserted before the task instruction. The template skeleton is as follows.
# Database schema (SQLite)
TABLE batch(batch_id, product_code, campaign_id, batch_size, ...)
... all tables with columns and foreign keys, plus the analytical views ...
# Domain hints (controlled vocabularies)
characteristic.name in: dissolution, hardness, thickness, ...
batch_quality.stage in: core, fct statistic in: min, max, av, rsd, single
# Worked examples (retrieval condition only; k = 3, held out)
Q: <natural-language question>
SQL: <validated reference query>
# Task
Write ONE SQLite query that answers the question. Use only the tables and
columns above. Return only the SQL statement.
Question: <user question>
SQL:

A.2. Models

The two primary models were Qwen3-30B-A3B-Instruct and Qwen3-Coder-30B-A3B-Instruct (mixture-of-experts, 30.5 billion total and about 3.3 billion active parameters); the fine-tuned model was Qwen2.5-Coder-7B-Instruct.

A.3. Retrieval

Worked examples were retrieved by a lightweight, dependency-free lexical-similarity ranker (token overlap weighted by inverse document frequency) over a held-out exemplar store disjoint from the 48 benchmark questions; the three highest-ranked examples were supplied per question.

A.4. Fine-Tuning

Adaptation used QLoRA [47] via the Unsloth library [48]: the base model was loaded in 4-bit precision and low-rank adapters of rank 16 (alpha 16, no dropout) were trained on the attention and feed-forward projection matrices, with the loss computed only on the SQL completion. Training ran for two epochs at learning rate 2e-4 with a linear schedule, an effective batch size of eight (per-device batch size two, gradient accumulation four), the adamw_8bit optimizer and a maximum sequence length of 2048, on a single 16 GB GPU. The training set was synthetic and execution-validated, tier-balanced to approximately 10/35/55 across T1/T2/T3, with language-model paraphrasing for natural-language diversity and the benchmark and retrieval exemplars excluded.

A.5. Execution-Guided Self-Consistency

Where evaluated, five candidates were sampled (the first at temperature zero, the remainder at temperature 0.6); each was executed, and candidates that raised an error or returned no rows were repaired by returning the execution feedback to the model for up to two rounds; the answer was selected by majority vote over executed result sets, and the fraction of candidates agreeing on the selected result was reported as a confidence score.

A.6. Metrics

Execution accuracy counts a query correct when its executed result set equals that of the reference query, compared as an order- and column-order-insensitive multiset with floating-point values rounded to four decimal places. Fidelity is the Jaccard overlap of result rows. Each outcome is categorized as exact match, value mismatch, SQL error, empty result, or no prediction. Paired configurations are compared with an exact two-sided McNemar test on per-question correctness.
Table A1. Key configuration parameters.
Table A1. Key configuration parameters.
Component Setting
General / coder models Qwen3-30B-A3B-Instruct; Qwen3-Coder-30B-A3B-Instruct
Fine-tuned model Qwen2.5-Coder-7B-Instruct (QLoRA adapter)
Quantization (deployment) 4-bit, single workstation-class GPU
Decoding (single-shot) temperature 0 (deterministic)
Retrieval lexical similarity, top-3 held-out examples
LoRA rank / alpha / dropout 16 / 16 / 0
LoRA target modules q, k, v, o, gate, up, down projections
Epochs / learning rate / schedule 2 / 2e-4 / linear
Effective batch / max sequence length 8 / 2048
Self-consistency 5 samples, up to 2 repair rounds, majority vote
Benchmark 48 questions, three tiers (13 / 15 / 20)

Appendix B. Database Schema

B.1. Relational Schema

The relational schema is organized into the ISA-88 sub-models, with the batch table as the central hub through which almost every join passes. Figure B1 shows the sub-models and their relationship to the hub, and Table B1 lists the sixteen tables with their primary keys and roles. The product-and-recipe, physical-equipment and procedural-execution layers are modelled in alignment with ISA-88 from domain knowledge, whereas the material-genealogy, process-data and quality layers are populated directly from the source dataset. Quality results are stored in long (entity-attribute-value) form keyed by a shared characteristic catalogue, with the stage and statistic columns distinguishing core from film-coated measurements and identifying the reported summary statistic; convenience views such as v_batch_quality_wide pivot this table into one row per batch for readability (Section 5). Full data-definition statements are provided with the released code.
Figure B1. ISA-88-aligned database schema. The six sub-models (product and recipe, physical equipment, material genealogy, procedural execution, process data, and quality) are organized around the central batch table, through which almost every join passes.
Figure B1. ISA-88-aligned database schema. The six sub-models (product and recipe, physical equipment, material genealogy, procedural execution, process data, and quality) are organized around the central batch table, through which almost every join passes.
Preprints 236196 g0b1
Table B1. Tables of the ISA-88-aligned schema, by sub-model.
Table B1. Tables of the ISA-88-aligned schema, by sub-model.
ISA-88 sub-model Table Primary key Role and key relationships
Product and recipe product product_code Product sub-family: strength, batch size and normalization factor.
campaign campaign_id Plant-wide production campaign, derived from the time series.
Central hub batch batch_id One manufactured batch; links to product and campaign and is referenced by the genealogy, quality, procedural and process tables.
Physical equipment unit unit_id Process unit (ISA-88 unit).
equipment_module module_id Equipment module within a unit (FK unit_id).
sensor sensor_id Measured parameter on a module (FK module_id); parameter_code matches a time-series column.
Material genealogy material material_id Material type (API, SMCC, lactose, starch).
material_lot lot_id Incoming lot of a material (FK material_id).
batch_genealogy (batch_id, lot_id) Which lots a batch consumed (FK batch_id, FK lot_id).
Quality characteristic characteristic_id Catalogue of measured properties (applies_to raw_material, intermediate or final); shared by lot_test and batch_quality.
lot_test lot_test_id Incoming-material test result (FK lot_id, FK characteristic_id).
batch_quality result_id Intermediate and final product results in long form (FK batch_id, FK characteristic_id; stage, statistic, value).
Procedural execution operation operation_id Operation on a batch at a unit (FK batch_id, FK unit_id), e.g. compression.
phase phase_id Phase within an operation (FK operation_id): start-up or production.
Process data batch_feature feature_id Per-batch process feature (FK batch_id, optional FK phase_id; feature_name, value).
timeseries reading_id Ten-second compression sensor readings (FK batch_id); wide columns, long form via a view.

B.2. Benchmark Question Bank

This appendix lists the 48 natural-language questions that constitute the evaluation benchmark introduced in Section 4.1. Each question is assigned to one of three complexity tiers, reflecting the structural complexity of its reference (gold) SQL rather than the surface form of the question: single-table or simple-aggregation queries (T1, n = 13); two- to three-table join queries (T2, n = 15); and multi-join queries involving aggregation, filtering, temporal logic, or sub-queries (T3, n = 20). Each question is additionally tagged with the data theme it targets, following the breakdown in Section 4.1: genealogy (product, recipe, batch and material-lot structure and lineage; 14 questions), quality (incoming raw-material and intermediate or final product quality measurements; 14), process (compression-process features such as press speed, compression force, ejection and waste; 5), equipment/sensor (equipment-module and sensor relationships and readings; 3), campaign (campaign-level roll-ups; 6), and temporal (analysis by weekday/weekend, month or year; 6). Each question is paired with an execution-validated reference query as described in Section 4.2; the questions are reproduced here, and the reference SQL and result sets accompany the released benchmark.
Table B2. The 48-question evaluation benchmark, grouped by complexity tier, with data-theme category.
Table B2. The 48-question evaluation benchmark, grouped by complexity tier, with data-theme category.
ID Tier Main category Natural-language question
q01 T1 Genealogy How many batches were produced for each product code?
q02 T1 Quality What is the overall average final-product dissolution?
q03 T1 Genealogy List each product strength with its batch size and normalization factor.
q04 T1 Temporal How many batches were run on weekends versus weekdays?
q05 T1 Campaign How many distinct campaigns are in the dataset?
q19 T1 Genealogy How many distinct product strengths are there?
q20 T1 Genealogy What is the total number of tablets produced across all batches?
q21 T1 Quality What are the minimum and maximum final-product dissolution values recorded?
q22 T1 Genealogy List product codes with their normalization factors, highest first.
q23 T1 Genealogy How many material lots are recorded in total?
q24 T1 Quality How many batches had a final batch yield below 90%?
q25 T1 Process What is the average production tablet-press speed across all batches?
q26 T1 Campaign How many batches are assigned to a campaign?
q06 T2 Quality For each product strength, what is the average final tablet hardness?
q07 T2 Quality Which five lactose lots had the highest water content?
q08 T2 Genealogy How many batches consumed API lot number 170?
q09 T2 Quality List the ten batches with the lowest final dissolution, with their product code.
q10 T2 Genealogy For each material, how many lots exist and how many batches consumed them?
q27 T2 Equipment/sensor How many sensors are mapped to each equipment module?
q28 T2 Genealogy How many batches were produced per product strength?
q29 T2 Quality Which five API lots have the highest assay content?
q30 T2 Quality For each product code, what is the average final tablet tensile strength?
q31 T2 Quality Which five SMCC lots have the lowest bulk density?
q32 T2 Campaign Which ten campaigns contained the most batches?
q33 T2 Genealogy How many distinct API lots did each product code use?
q34 T2 Process List the ten batches with the highest start-up waste, with their product code.
q35 T2 Quality What is the average final residual solvent per product strength?
q36 T2 Quality What is the average API assay content per product strength?
q11 T3 Genealogy Which API lots are associated with the lowest average final dissolution (lots used in at least five batches)?
q12 T3 Process What is the mean production-phase main compression force per product strength?
q13 T3 Campaign Per campaign, how many batches exceeded 4000 start-up rejected tablets, and what was their average final total-impurity content?
q14 T3 Genealogy For batches whose tablet-core average hardness was below 50 N, what was the assay content of the API lots they used?
q15 T3 Temporal What was the average production tablet-press speed by month of manufacture?
q16 T3 Quality Which batches had a final dissolution below 90%, and in which campaign did they occur?
q17 T3 Equipment/sensor For the first batch of product code 1, what was the average ejection force recorded by the ejection-station sensor, and on which equipment module?
q18 T3 Temporal Compare average final tablet tensile strength for weekend versus weekday batches, per product strength.
q37 T3 Process Per product strength, give the average production main-compression force and the average final dissolution.
q38 T3 Genealogy Which five API lots were used in the most batches, and what was their average assay content?
q39 T3 Temporal For batches manufactured in 2020, what was the average final dissolution by month?
q40 T3 Temporal Compare average final tablet hardness for weekend versus weekday batches, per product strength.
q41 T3 Campaign Which campaigns had an average final total-impurity content above the overall average?
q42 T3 Quality For each product strength, what fraction of batches had a final dissolution of at least 95%?
q43 T3 Genealogy List batches whose final dissolution was below 85%, with the assay content of the API lot they used.
q44 T3 Process Rank product strengths by their average maximum ejection force during production.
q45 T3 Equipment/sensor For the first batch of product code 1, give the average value recorded by each sensor and the module it sits on.
q46 T3 Temporal How many batches were produced for each combination of product strength and weekend/weekday?
q47 T3 Campaign Rank the ten campaigns that produced the most tablets in total.
q48 T3 Quality For each product strength, compare the average tablet-core hardness with the average film-coated hardness.

References

  1. Tao, F.; Qi, Q.; Liu, A.; Kusiak, A. Data-Driven Smart Manufacturing. J. Manuf. Syst. 2018, 48, 157–169. [Google Scholar] [CrossRef]
  2. Arden, N. S.; Fisher, A. C.; Tyner, K.; Yu, L. X.; Lee, S. L.; Kopcha, M. Industry 4.0 for Pharmaceutical Manufacturing: Preparing for the Smart Factories of the Future. Int. J. Pharm. 2021, 602, 120554. [Google Scholar] [CrossRef] [PubMed]
  3. Žagar, J.; Mihelič, J. Big Data Collection in Pharmaceutical Manufacturing and Its Use for Product Quality Predictions. Sci. Data 2022, 9, 99. [Google Scholar] [CrossRef] [PubMed]
  4. Affolter, K.; Stockinger, K.; Bernstein, A. A Comparative Survey of Recent Natural Language Interfaces for Databases. VLDB J. 2019, 28(5), 793–819. [Google Scholar] [CrossRef]
  5. Jeon, J.; Sim, Y.; Lee, H.; Han, C.; Yun, D.; Kim, E.; Nagendra, S. L.; et al. ChatCNC: Conversational Machine Monitoring via Large Language Model and Real-Time Data Retrieval Augmented Generation. J. Manuf. Syst. 2025, 79, 504–514. [Google Scholar] [CrossRef]
  6. Xia, L.; Li, C.; Zhang, C.; Liu, S.; Zheng, P. Leveraging Error-Assisted Fine-Tuning Large Language Models for Manufacturing Excellence. Robot. Comput.-Integr. Manuf. 2024, 88, 102728. [Google Scholar] [CrossRef]
  7. Yao, Y.; Duan, J.; Xu, K.; Cai, Y.; Sun, Z.; Zhang, Y. A Survey on Large Language Model (LLM) Security and Privacy: The Good, the Bad, and the Ugly. High-Confid. Comput. 2024, 4(2), 100211. [Google Scholar] [CrossRef]
  8. ISA (International Society of Automation). ANSI/ISA-88.00.01-2010; Batch Control Part 1: Models and Terminology. Research Triangle Park, NC: ISA, 2010.
  9. Virta, J.; Seilonen, I.; Tuomi, A.; Koskinen, K. SOA-Based Integration for Batch Process Management with OPC UA and ISA-88/95. In Proceedings of the 15th IEEE International Conference on Emerging Technologies and Factory Automation (ETFA 2010); IEEE: Piscataway, NJ, 2010; pp. 1–8. [Google Scholar] [CrossRef]
  10. Ji, Z.; Lee, N.; Frieske, R.; Yu, T.; Su, D.; Xu, Y.; Ishii, E.; Bang, Y. J.; Madotto, A.; Fung, P. Survey of Hallucination in Natural Language Generation. ACM Comput. Surv. 2023, 55(12), 1–38. [Google Scholar] [CrossRef]
  11. Huang, L.; Yu, W.; Ma, W.; Zhong, W.; Feng, Z.; Wang, H.; Chen, Q.; et al. A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions. ACM Trans. Inf. Syst. 2025, 43(2), 1–55. [Google Scholar] [CrossRef]
  12. US FDA (Food and Drug Administration). Data Integrity and Compliance with Drug CGMP: Questions and Answers; Guidance for Industry; US Department of Health and Human Services: Silver Spring, MD, 2018. [Google Scholar]
  13. European Commission. EudraLex Volume 4: Good Manufacturing Practice (GMP) Guidelines, Annex 11: Computerised Systems; European Commission: Brussels, 2011. [Google Scholar]
  14. Kavasidis, I.; Lallas, E.; Leligkou, H. C.; Oikonomidis, G.; Karydas, D.; Gerogiannis, V. C.; Karageorgos, A. Deep Transformers for Computing and Predicting ALCOA+ Data Integrity Compliance in the Pharmaceutical Industry. Appl. Sci. 2023, 13(13), 7616. [Google Scholar] [CrossRef]
  15. European Commission. EudraLex Volume 4: Good Manufacturing Practice (GMP) Guidelines, Annex 22: Artificial Intelligence; Consultation draft, July 7, 2025; European Commission, Directorate-General for Health and Food Safety: Brussels, 2025. [Google Scholar]
  16. Lewis, P.; Perez, E.; Piktus, A.; Petroni, F.; Karpukhin, V.; Goyal, N.; Küttler, H.; et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. In Advances in Neural Information Processing Systems; Curran Associates: Red Hook, NY, 2020; Volume 33, pp. 9459–9474. [Google Scholar]
  17. Xu, X.; Lu, Y.; Vogel-Heuser, B.; Wang, L. Industry 4.0 and Industry 5.0—Inception, Conception and Perception. J. Manuf. Syst. 2021, 61, 530–535. [Google Scholar] [CrossRef]
  18. Li, J.; Hui, B.; Qu, G.; Yang, J.; Li, B.; Li, B.; Wang, B.; et al. Can LLM Already Serve as a Database Interface? A BIg Bench for Large-Scale Database Grounded Text-to-SQLs. In Advances in Neural Information Processing Systems; Curran Associates: Red Hook, NY, 2023; p. 36. [Google Scholar] [CrossRef]
  19. Hong, Z.; Yuan, Z.; Zhang, Q.; Chen, H.; Dong, J.; Huang, F.; Huang, X. Next-Generation Database Interfaces: A Survey of LLM-Based Text-to-SQL. IEEE Trans. Knowl. Data Eng. 2025, 37(12), 7328–7345. [Google Scholar] [CrossRef]
  20. Lei, F.; Chen, J.; Ye, Y.; Cao, R.; Shin, D.; Su, H.; Suo, Z.; et al. Spider 2.0: Evaluating Language Models on Real-World Enterprise Text-to-SQL Workflows. The Thirteenth International Conference on Learning Representations (ICLR 2025), 2025; Available online: https://openreview.net/forum?id=XmProj9cPs.
  21. Wang, X.; Wei, J.; Schuurmans, D.; Le, Q.; Chi, E.; Narang, S.; Chowdhery, A.; Zhou, D. Self-Consistency Improves Chain of Thought Reasoning in Language Models. The Eleventh International Conference on Learning Representations (ICLR 2023), 2023. [Google Scholar]
  22. Salami, H.; Smith-Goettler, B.; Yadav, V. How Can Language Models Assist with Pharmaceuticals Manufacturing Deviations and Investigations? Int. J. Pharm. 2025, 669, 125100. [Google Scholar] [CrossRef] [PubMed]
  23. Kadi, H.; Abdellatif, A.; Kemajou Njamen, D. I.; Pereme, F. Automatic Extraction of SmPC Document for IDMP Data Model Construction Using Foundation LLM and RAG. Front. Med. 2025, 12, 1598979. [Google Scholar] [CrossRef] [PubMed]
  24. Kim, J.; Hur, M.; Min, M. From RAG to QA-RAG: Integrating Generative AI for Pharmaceutical Regulatory Compliance Process. In Proceedings of the ACM Symposium on Applied Computing; ACM: New York, 2025; pp. 1293–1295. [Google Scholar] [CrossRef]
  25. Vieira-Vieira, C. H.; Kulkarni, S. S.; Zalewski, A.; Loffler, J.; Munch, J.; Kreuchwig, A. From Data Silos to Insights: The PRINCE Multi-Agent Knowledge Engine for Preclinical Drug Development. Front. Artif. Intell. 2025, 8, 1636809. [Google Scholar] [CrossRef] [PubMed]
  26. Taskiran, N. P.; Tsai, C. E. J.; Huang, S.; Chakraborty, A.; Venkatasubramanian, V. A Knowledge-Graph-Based Pharmaceutical Engineering Chatbot for Drug Discovery. Comput. Chem. Eng. 2025, 203, 109318. [Google Scholar] [CrossRef]
  27. González-Potes, A.; Martínez-Castro, D.; Paredes, C. M.; Ochoa-Brust, A.; Mena, L. J.; Martínez-Peláez, R.; Félix, V. G.; Félix-Cuadras, R. A. Hybrid AI and LLM-Enabled Agent-Based Real-Time Decision Support Architecture for Industrial Batch Processes: A Clean-in-Place Case Study. AI 2026, 7(2), 51. [Google Scholar] [CrossRef]
  28. Thogaru, H.; Gopalakrishnan, S.; Ahmad, Z.; Deodhar, A. Intelligent Human-Machine Partnership for Manufacturing: Enhancing Warehouse Planning through Simulation-Driven Knowledge Graphs and LLM Collaboration. arXiv 2025, arXiv:2512.18265. [Google Scholar] [CrossRef]
  29. Wan, Y.; Chen, Z.; Liu, Y.; Chen, C.; Packianather, M. Empowering LLMs by Hybrid Retrieval-Augmented Generation for Domain-Centric Q&A in Smart Manufacturing. Adv. Eng. Inform. 2025, 65, 103212. [Google Scholar] [CrossRef]
  30. Oyekan, J.; Turner, C.; Bax, M.; Graf, E. From Ontologies to Knowledge-Augmented Large Language Models for Automation: A Decision-Making Guidance for Achieving Human-Robot Collaboration in Industry 5.0. Comput. Ind. 2025, 171, 104329. [Google Scholar] [CrossRef]
  31. Wang, T.; Zhang, B.; Jiang, D.; Li, D. A Multimodal Large Language Model Framework for Intelligent Perception and Decision-Making in Smart Manufacturing. Sensors 2025, 25(10), 3072. [Google Scholar] [CrossRef] [PubMed]
  32. Mahmud, T.; Azharul Hasan, K. M.; Ahmed, M.; Chak, T. H. C. A Rule Based Approach for NLP Based Query Processing. In Proceedings of the 2nd International Conference on Electrical Information and Communication Technologies (EICT 2015); IEEE: Piscataway, NJ, 2016; pp. 78–82. [Google Scholar] [CrossRef]
  33. Fan, W.; Ding, Y.; Ning, L.; Wang, S.; Li, H.; Yin, D.; Chua, T.-S.; Li, Q. A Survey on RAG Meeting LLMs: Towards Retrieval-Augmented Large Language Models. In Proceedings of the 30th ACM SIGKDD Conference on Knowledge Discovery and Data Mining; ACM: New York, 2024; pp. 6491–6501. [Google Scholar] [CrossRef]
  34. Zhou, Q.; Zhou, Z.; Johnson, M.; Ngo, M.; Ferrari, F.; Ma, J. ClinicalRAG: Automating Pharmaceutical Label Quality Control with Hierarchical RAG and Large Language Models. Proc. AAAI Conf. Artif. Intell. 39(28), 29736–29738, 2025. [CrossRef]
  35. Choi, H.; Jeong, J. A Conceptual Framework for a Latest Information-Maintaining Method Using Retrieval-Augmented Generation and a Large Language Model in Smart Manufacturing. Machines 2025, 13(2), 94. [Google Scholar] [CrossRef]
  36. Mohammadjafari, A.; Maida, A. S.; Gottumukkala, R. From Natural Language to SQL: Review of LLM-Based Text-to-SQL Systems. arXiv:2410.01066, 2025. Available online: https://arxiv.org/abs/2410.01066.
  37. Kumar, A.; Nagarkar, P.; Nalhe, P.; Vijayakumar, S. Deep Learning Driven Natural Language Text to SQL Query Conversion: A Survey. arXiv:2208.04415, 2022. Available online: https://arxiv.org/abs/2208.04415.
  38. Deng, M.; Ramachandran, A.; Xu, C.; Hu, L.; Yao, Z.; Datta, A.; Zhang, H. ReFoRCE: A Text-to-SQL Agent with Self-Refinement, Consensus Enforcement, and Column Exploration. arXiv 2025, arXiv:2502.00675. [Google Scholar] [CrossRef]
  39. Li, B.; Zhang, J.; Fan, J.; Xu, Y.; Chen, C.; Tang, N.; Luo, Y. Alpha-SQL: Zero-Shot Text-to-SQL Using Monte Carlo Tree Search. In Proceedings of the 42nd International Conference on Machine Learning, PMLR 267: 36810–36830, 2025; Available online: https://proceedings.mlr.press/v267/li25dt.html.
  40. Yan, L.; Wan, Q.; Liu, C.; Duan, S.; Han, P.; Xu, Y. SPS-SQL: Enhancing Text-to-SQL Generation on Small-Scale LLMs with Pre-Synthesized Queries. Pattern Recognit. Lett. 2025, 196, 45–51. [Google Scholar] [CrossRef]
  41. Murali, T.; Anu Priya, A. Production Enhancement and Process Analysis for Pharmaceutical Industries. In Proceedings of the 4th International Conference on Electronics and Sustainable Communication Systems (ICESC 2023); IEEE: Piscataway, NJ, 2023; pp. 156–161. [Google Scholar] [CrossRef]
  42. Vichev, S.; Marchev, A. RAGSQL: Context Retrieval Evaluation on Augmenting Text-to-SQL Prompts. In Proceedings of the 2024 IEEE International Conference on Intelligent Systems (IS 2024); IEEE: Piscataway, NJ, 2024; pp. 1–6. [Google Scholar] [CrossRef]
  43. Dogruluk, E.; Acikgoz, H. Edge-Centric Federated Learning for LLMs in Smart Manufacturing: Architectures, Challenges, and Opportunities. In Proceedings of the 4th International Conference on Innovative Mechanisms for Industry Applications (ICIMIA 2025); IEEE: Piscataway, NJ, 2025; pp. 1250–1256. [Google Scholar] [CrossRef]
  44. Qwen Team. Qwen3 Technical Report. arXiv 2025, arXiv:2505.09388. [Google Scholar] [CrossRef]
  45. Hui, B.; Yang, J.; Cui, Z.; Yang, J.; Liu, D.; Zhang, L.; Liu, T.; et al. Qwen2.5-Coder Technical Report. arXiv 2024, arXiv:2409.12186. [Google Scholar] [CrossRef]
  46. Jin, T.; Choi, Y.; Zhu, Y.; Kang, D. Text-to-SQL Benchmarks Are Broken: An In-Depth Analysis of Annotation Errors. In Proceedings of the 16th Annual Conference on Innovative Data Systems Research (CIDR ’26), Chaminade, CA, January 18–21, 2026; Available online: https://www.vldb.org/cidrdb/papers/2026/p5-jin.pdf.
  47. Dettmers, T.; Pagnoni, A.; Holtzman, A.; Zettlemoyer, L. QLoRA: Efficient Finetuning of Quantized LLMs. Adv. Neural Inf. Process. Syst. 2023, 36(NeurIPS 2023). [Google Scholar] [CrossRef]
  48. Unsloth, A.I. Unsloth. Computer software. GitHub. 2024. Available online: https://github.com/unslothai/unsloth.
Figure 1. System architecture for the local LLM-driven manufacturing analytics tool, showing the flow from the user interface, through the LLM and retrieval components, to the locally hosted ISA-88 SQL database and the exemplar store.
Figure 1. System architecture for the local LLM-driven manufacturing analytics tool, showing the flow from the user interface, through the LLM and retrieval components, to the locally hosted ISA-88 SQL database and the exemplar store.
Preprints 236196 g001
Figure 2. RAG-grounded pipeline for the local LLM-driven manufacturing analytics tool. A user's natural-language question (1) triggers retrieval (2) from a curated store, held out from the benchmark, of schema metadata, controlled domain vocabularies and validated worked examples for the 16-table ISA-88-aligned pharmaceutical tablet database. The retrieved context augments the schema-aware prompt (3); a locally served open-weight model (4) then generates SQL, which is execution-checked and returned with a confidence score for human review (5).
Figure 2. RAG-grounded pipeline for the local LLM-driven manufacturing analytics tool. A user's natural-language question (1) triggers retrieval (2) from a curated store, held out from the benchmark, of schema metadata, controlled domain vocabularies and validated worked examples for the 16-table ISA-88-aligned pharmaceutical tablet database. The retrieved context augments the schema-aware prompt (3); a locally served open-weight model (4) then generates SQL, which is execution-checked and returned with a confidence score for human review (5).
Preprints 236196 g002
Figure 3. Execution accuracy by configuration (schema-only, retrieval, and fine-tuned variants) and by complexity tier.
Figure 3. Execution accuracy by configuration (schema-only, retrieval, and fine-tuned variants) and by complexity tier.
Preprints 236196 g003
Table 1. Main contributions: LLMs as natural-language interfaces for industrial and pharmaceutical analytics.
Table 1. Main contributions: LLMs as natural-language interfaces for industrial and pharmaceutical analytics.
Article Main approach Tools / techniques Core contribution
Wan et al. [29] Domain-centric Q&A via hybrid RAG Knowledge graphs, vector embeddings, hybrid RAG, semantic constraints, prompt engineering LLMs as effective NL interfaces for smart-manufacturing analytics when grounded with domain knowledge
Salami et al. [22] Generative extraction + similarity search GPT-family LLMs, embedding models, cosine similarity, OCR preprocessing NL access to deviation reports for investigation support and knowledge reuse in pharma manufacturing
Oyekan et al. [30] Decision-guidance framework Ontologies, knowledge graphs, LLM prompting, inference-speed/accuracy metrics Positions LLMs as NL interfaces for human-robot collaboration and industrial reasoning
Wang et al. [31] Multimodal LLM framework Multimodal transformers, dynamic semantic tokenization, cross-modal alignment Extends NL interfaces to multimodal factory data for perception and decision-making
González-Potes et al. [27] Agent-based real-time decision support LLM analytics agent, RAG, deterministic agents, human operators NL access over batch-process sensor streams (clean-in-place); not text-to-SQL over relational records
Thogaru et al.
[28]
KG-grounded NL interface Knowledge graphs, LLM agents, iterative reasoning NL querying of manufacturing simulation output with human oversight
Mahmud et al. [32] Rule-based NL query processing Rule-based NLP parsing, handcrafted grammar, SQL generation Early baseline for NL access to industrial databases without LLMs
Table 2. Main contributions: hallucinations, retrieval-augmented generation, and hybrid architectures.
Table 2. Main contributions: hallucinations, retrieval-augmented generation, and hybrid architectures.
Article Main approach Tools / techniques Core contribution
Wan et al. [29] Hybrid KG-vector RAG Knowledge graphs, vector search, hybrid retrieval orchestration, constraint-based alignment Mitigates hallucinations and context loss by combining symbolic reasoning with scalable retrieval
Fan et al. [33] RA-LLM survey Sparse/dense retrieval, RAG architectures, retrieval-generation coupling Establishes RAG as a core strategy to reduce hallucination and stale knowledge
Kim et al. [24] QA-RAG (dual-track retrieval) Dual-track retrieval, RAG pipelines, generative answer reformulation Improves robustness in regulatory tasks by retrieving with queries and generated answers
Zhou et al. [34] Hierarchical RAG (ClinicalRAG) Hierarchical retrieval, statement decomposition, table-based verification, self-consistency Controls hallucinations via statement-level verification against structured evidence
Salami et al. [22] Empirical LLM evaluation Prompt-based extraction, embedding similarity, manual ground-truth validation Demonstrates the reasoning-hallucination trade-off in real manufacturing data
Table 3. Main contributions: text-to-SQL, ISA-88, and structured batch manufacturing data.
Table 3. Main contributions: text-to-SQL, ISA-88, and structured batch manufacturing data.
Article Main approach Tools / techniques Core contribution
Virta et al. [9] Standards-based integration OPC UA, SOA middleware, ISA-88/95 models, MES-PCS integration Interoperable structured batch-data architectures enabling analytics and AI access
Vichev and Marchev [42] RAG-enhanced text-to-SQL Embedding models, sentence-transformer fine-tuning, RAG context selection Retrieval-based context augmentation improves NL-to-SQL accuracy
Hong et al. [19] Text-to-SQL survey LLM-based SQL generation, schema linking, benchmark datasets Synthesizes architectures, datasets and evaluation for NL database interfaces
Mohammadjafari et al. [36] Review of LLM text-to-SQL Schema-aware prompting, retrieval-augmented prompting, schema linking Identifies schema linking and hallucination control as open challenges
Deng et al. [38] Agentic text-to-SQL (Spider 2.0 SOTA) Schema exploration, self-correction, voting/refinement Frontier accuracy via heavyweight multi-call pipelines; low auditability
Yan et al. [40] Small-model text-to-SQL Query pre-synthesis, few-shot prompting, code-specialized 7B model Competitive accuracy from locally hostable small models
Kumar et al. [37] Deep-learning text-to-SQL survey CNN/RNN/transformer models, benchmark datasets, exact-match metrics Historical baselines and dataset limitations for NLIDB systems
Table 4. Main contributions: AI in regulated environments.
Table 4. Main contributions: AI in regulated environments.
Article Main approach Tools / techniques Core contribution
Zhou et al. [34] Verification-centric RAG Hierarchical RAG, table QA, UI-supported human review Safe LLM use for pharmaceutical label QC with explicit evidence checking
Kim et al. [24] QA-RAG for compliance RAG pipelines, generative reformulation, compliance-oriented retrieval Addresses regulatory change and traceability via enhanced retrieval
Kadi et al. [23] Structured extraction + expert review LLM extraction, IDMP schema mapping, expert-in-the-loop validation Converts SmPC documents into IDMP-compliant data with human validation
Kavasidis et al. [14] Compliance-prediction modelling Transformer architectures, compliance-scoring models Predicts ALCOA+ data-integrity compliance using deep learning
Salami et al. [22] Risk-aware LLM deployment Prompting strategies, embedding similarity, human-validation workflows Highlights governance and hallucination risks in regulated manufacturing
Table 5. Locally deployable models and context configurations evaluated.
Table 5. Locally deployable models and context configurations evaluated.
Element Setting
General model Qwen3-30B-A3B-Instruct (30.5B total, ~3.3B active)
Code-specialised model Qwen3-Coder-30B-A3B-Instruct (same architecture)
Fine-tuned model (Section 4.6) Qwen2.5-Coder-7B-Instruct, QLoRA-adapted
Schema-only context table, column and foreign-key definitions
+ vocabulary + controlled domain vocabularies
+ retrieval + validated worked examples (held out from the benchmark)
Refinement: analytical views wide reporting views, present in both contexts
Refinement: self-consistency sample, execute, repair, majority vote, confidence score
Table 6. Execution accuracy by context configuration (out of 48 questions).
Table 6. Execution accuracy by context configuration (out of 48 questions).
Configuration Qwen3-30B-A3B (general) Qwen3-Coder-30B-A3B
Schema only 11 (23%) 12 (25%)
Schema + vocabulary 12 (25%) 12 (25%)
Schema + retrieved examples 22 (46%) 23 (48%)
Table 7. Execution accuracy by complexity tier (Qwen3-Coder-30B-A3B).
Table 7. Execution accuracy by complexity tier (Qwen3-Coder-30B-A3B).
Tier Schema only Schema + retrieved examples
T1 (n = 13) 8 (62%) 9 (69%)
T2 (n = 15) 4 (27%) 12 (80%)
T3 (n = 20) 0 (0%) 2 (10%)
Table 8. Execution accuracy across the principal configurations (out of 48), with per-tier detail. The first three rows are the 30B-A3B code-specialized model; the last two are the fine-tuned Qwen2.5-Coder-7B.
Table 8. Execution accuracy across the principal configurations (out of 48), with per-tier detail. The first three rows are the 30B-A3B code-specialized model; the last two are the fine-tuned Qwen2.5-Coder-7B.
Configuration Overall T1 (13) T2 (15) T3 (20)
Schema only (30B) 12 (25%) 8 4 0
Schema + retrieved examples (30B) 23 (48%) 9 12 2
Retrieval + views + self-consistency (30B) 21 (44%) 9 10 2
Fine-tuned 7B (schema only) 21 (44%) 8 9 4
Fine-tuned 7B + retrieved examples 22 (46%) 6 11 5
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.