1. Introduction
Graph databases have become an important technology for managing highly interconnected data because they represent entities as nodes and relationships as edges, enabling expressive modeling and efficient traversal of complex relational structures [
1,
2,
3]. These capabilities make graph databases well suited for domains such as social network analysis [
4], biomedical knowledge graphs [
5], and cybersecurity [
6], where answering multihop and relationship-centric queries is often essential. More recently, graph databases have also been integrated with Retrieval-Augmented Generation (RAG) techniques, often referred to as graph RAG, to support reasoning over structured and heterogeneous knowledge sources [
7,
8,
9,
10].
In parallel, natural language interfaces to databases have emerged as a promising mechanism for democratizing access to complex data systems and supporting advanced Business Intelligence (BI) applications [
11]. Such interfaces allow users to express information needs in natural language, which are then translated into formal query languages such as SQL or Neo4j Cypher [
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23]. In the graph database setting, text-to-Cypher systems translate natural language questions into executable Cypher queries, thereby reducing the technical barrier for interacting with graph-structured data [
17].
Despite their practical potential, LLM-based text-to-Cypher systems introduce security risks that remain insufficiently addressed. In particular, because these systems accept untrusted natural language input and convert it into executable database queries, they are vulnerable to prompt injection attacks. A malicious user may embed adversarial instructions into an otherwise valid question, causing the model to generate unsafe operations, semantically divergent queries, or queries that expose sensitive information. These risks are especially important in graph database environments, where generated queries may traverse rich relational structures and access sensitive or governance-restricted information.
This paper addresses these challenges by proposing a retrieval-augmented and feedback-guided architecture for secure text-to-Cypher generation. A training-free, feedback-guided RAG architecture is proposed for improving robustness of text-to-Cypher systems against direct prompt injection attacks. The proposed approach first employs a training-free RAG architecture that retrieves semantically similar question–query examples to improve Cypher generation without fine-tuning. We then extend this architecture with a validator-guided feedback loop, in which a separate LLM agent evaluates generated Cypher candidates and provides corrective feedback when potentially malicious, unsafe, or divergent outputs are detected. This design aims to improve adversarial robustness while preserving the deployment advantages of training-free LLM-based systems.
This paper makes the following main contributions:
Retrieval-Augmented Text-to-Cypher Generation: We propose a training-free RAG-based text-to-Cypher architecture that retrieves semantically similar examples to improve Cypher query generation without supervised fine-tuning.
Feedback-Guided Prompt Injection Defense: We introduce a feedback loop architecture in which a validator LLM detects malicious, unsafe, or divergent Cypher candidates and provides corrective feedback to the generator for self-correction.
Synthetic Prompt Injection Dataset: We develop a systematic procedure for constructing a text-to-Cypher prompt injection dataset covering multiple attack categories, including instruction override, role confusion, output-format manipulation, misleading prompts, chained instructions, and obfuscated attacks.
Security-Oriented Evaluation Framework: We evaluate the proposed architectures using both generation-quality metrics and robustness-oriented metrics, including Google-BLEU, semantic similarity, attack success rate, and unsafe operation rate. We employ an ensemble-based, LLM-as-a-jury evaluation methodology in which multiple LLMs act as independent classifiers to detect erroneous (faithful, malicious, diverged) Cypher query candidates.
Multimodel Evaluation: We conduct experiments across multiple foundation models, including GPT-4o, Claude 3.5 Sonnet, DeepSeek R1, Amazon Nova Pro, and Qwen 2.5 Coder 32B Instruct, and compare the proposed feedback-guided architecture with training-free prompt injection defense baselines. We also compare the proposed approach with Gemma-3-27B-Instruct fine-tuned for text-to-Cypher translation.
The remainder of the paper is organized as follows.
Section 2 reviews related work on text-to-SQL, text-to-Cypher, RAG-based generation, prompt injection attacks, and robust LLM-based architectures.
Section 3 presents the proposed RAG and feedback-loop-enhanced text-to-Cypher architectures, together with the synthetic prompt injection dataset and evaluation framework.
Section 4 reports the experimental setup and quantitative results, including comparisons with baseline and ablation variants and evaluation of the LLM-as-a-jury ensemble.
Section 5 discusses the design rationale and architecture-level analysis, given the experimental results.
Section 6 discusses deployment and scalability implications of the findings, and
Section 7 concludes the paper, discusses limitations and outlines future research directions.
4. Experimental Results and Evaluation
In this section the experimental results and findings are discussed. First the technical details of the experimental setup are discussed, then the FF RAG architecture’s CQL query generation capability is evaluated. This evaluation examines the text-to-Cypher translation task on a standard dataset under non-adversarial conditions (no prompt injection attacks). It is demonstrated that the RAG architecture design pattern can improve the CQL query generation capability of foundation models. Then we discuss the performance of the FF- and FB-enhanced RAG systems under prompt injection attacks using the syntactically generated text-to-Cypher prompt injection dataset. It is shown that the feedback-enhanced system achieves consistently improved adversarial robustness across all the employed foundation models. We performed experiments by comparing the proposed solution to various training-free prompt injection defense mechanisms and ablation variants. In order to assess the reliability of the proposed LLM-as-a-jury ensemble, we performed experiments using inter-rater reliability and entropy-driven metrics.
All reported experiments were repeated three times using the same prompt templates, retrieval index, and model instance configurations. Across repeated runs, the observed variation in the reported metrics was consistently small, with deviations on the order of 10−3, and the relative ordering of the compared methods remained unchanged. Therefore, the main tables report averaged values, while separate hypothesis tests were not included because the run-to-run stochasticity was negligible and did not affect the experimental conclusions. This observation suggests that the reported improvements are stable under repeated execution of the evaluation pipeline.
4.1. Experimental Setup
In our technical evaluation the AWS cloud platform was employed. In terms of LLMs, we used Amazon Bedrock to gain access to foundation models, in particular, DeepSeek R1, Amazon Nova Premier, Amazon Nova Pro, Amazon Nova Lite, Claude 3.5 Sonnet, Llama 3.1 70B, and Pixtral Large 25.02. SageMaker AI was used to host Qwen 2.5 Coder 7B Instruct and Qwen 2.5 Coder 32B Instruct model variants. The OpenAI platform was employed to integrate GPT-4o and GPT-4o-mini models.
In order to provide a model-independent, generalistic evaluation across all the employed LLMs, we did not perform model-specific prompt engineering. In addition, there was no model-specific system prompt configured. While custom prompt engineering and system prompts can result in improved model performance, in our study it was of paramount importance to create a framework which is model-agnostic and generic across all the foundation models involved.
The prompt templates employed by the LLM agents and the LLM-as-a-jury architecture are listed in
Appendix B.
We employed an Amazon-managed, provisioned OpenSearch vector database with a dedicated K-NN type index to support approximate nearest neighbor search. The Faiss engine with the Hierarchical Navigable Small World (HNSW) algorithm was configured. It is defined with a dimensionality of 1024 and utilized the l2 distance metric as the underlying similarity measure. The vector database and RAG architecture used Cohere Embed Multilingual v3 as an embedding model in all the experiments. The number of documents returned by the K-NN search was set to 2, while the k parameter of the algorithm was set to 20.
Since the vector database was proposed to contain vectorized representation of input natural language questions and they are brief sentences, we vectorized the input questions in one pass without applying a specific chunking strategy.
The Feedback (FB)-loop-based AI architecture was configured to execute a maximum of 3 feedback loops, then it returns the last CQL query candidate generated by the code generator LLM agent.
4.2. Evaluation of RAG-Based Text-to-Cypher
In this section the CQL query generation capability is evaluated for the proposed RAG-based architecture. The Google-BLEU score is used to evaluate syntactic (structural, lexical) similarities of reference and generated CQL queries. The Google-BLEU score is a widely used metric adapted in the text-to-Cypher scientific literature for quantitative evaluation [
17]. Note that the feedback architecture is not discussed in this section.
Figure 6 depicts the non-adversarial evaluation results on the feedforward RAG architecture. Results indicate that the standard RAG architecture consistently outperforms the No-RAG baseline across all evaluated models. For instance, GPT-4o-mini improves from a Google-BLEU score of 0.5675 (No-RAG) to 0.6871 (RAG), and Nova Lite from 0.4757 to 0.6780, reflecting improvements deltas of +0.1196 and +0.2023, respectively. The best-performing model under the RAG configuration, GPT-4o, achieved a BLEU score of 0.699.
Table 3 presents the Google-BLEU score improvements achieved by integrating the feedforward RAG architecture compared to the No-RAG baseline. The obtained delta values highlight the relative improvement of CQL query generation quality for each foundation model. Nova Lite shows the most substantial gain of +0.2023, indicating strong dependence on semantically relevant retrieved support. GPT-4o-mini and GPT-4o exhibit similar performance gains of +0.1196 and +0.1129, respectively, reinforcing the consistency of RAG benefits across different model sizes. Nova Pro and Nova Premier also show meaningful improvements exceeding +0.11 BLEU points. These deltas are especially significant given that no fine-tuning was involved in the feedforward RAG setup. Instead, performance was enhanced purely through external semantic context retrieval. This validates RAG as a lightweight yet effective alternative to fine-tuning, suitable for practical deployments. Furthermore, the tight clustering of improvement scores suggests stable and generalizable benefits across architectures. Overall, the feedforward RAG approach offers a robust mechanism for elevating text-to-Cypher generation performance across diverse foundation models. We note that fine-tuning can result in better Google-BLEU scores compared to the proposed feedforward RAG architecture [
17], however, the disadvantages of fine-tuning makes the proposed RAG-based feedforward text-to-Cypher architecture an attractive alternative. In particular, the following disadvantages of fine-tuning can be addressed by the proposed approach:
Slow training and preprocessing procedures: LLM customization can take significant time (GPU time, data labeling, model training pipelines, longer development cycles), but the RAG alternative does not require training of any model.
Cost of training: training requires GPU-intensive custom infrastructure resources which can be of high cost.
Custom model hosting: hosting customized models for inference requires specific (e.g., GPU-intensive) infrastructure resources which can be of high cost.
Data access and governance: the proposed RAG-based solution architecture can guarantee data access control authorization architecture, however, there is no theoretical guarantee that a foundation model does not return sensitive data, and in this way a robust security framework can be realized (see
Figure 2).
4.3. Ablation Study of the Feedforward-RAG-Based Text-to-Cypher
We performed ablation study on the feedforward RAG architecture in order to evaluate the impact of the retrieval (RAG) component by comparing it with a random-sampling-based approach. For each input NL question in the test dataset [
17], instead of RAG-based retrieval, we performed random sampling to obtain samples from the training set of [
17]. Note that in the RAG architecture the same training split is used to compose the vector database. The random-sampling-based approach serves as a control to assess the importance of retrieving semantically relevant data instances. Results indicate that replacing the RAG retriever with random sampling led to a substantial decrease in Google-BLEU scores across all evaluated models.
Figure 7 compares the feedforward RAG and the random-sampling-based performance. Google-BLEU score degradation of the random-sampling-based approach confirms that the retriever is critical for providing contextually relevant information to the CQL query generator, thereby improving syntactic correctness. In contrast, the full feedforward RAG architecture consistently delivered the highest fidelity outputs in terms of Google-BLEU score.
4.4. Feedback-Loop-Based RAG System
Table 4 evaluates the proposed RAG architecture design patterns with respect to its CQL query generation capabilities under prompt injection attacks. In order to simulate prompt injection attacks, we make use of the synthetic dataset proposed in the previous section. The feedforward RAG baseline (FF) and the feedback-enhanced RAG architecture (FB) are evaluated and compared based on the Google-BLEU score and two embedding-model-based semantic similarity scores. It is important to note that both scoring approaches are proposed to compare the generated CQL queries with the corresponding reference queries: the Google-BLEU score quantifies syntactic (lexical, structural) similarity, while embedding-based similarity measures capture semantic similarity. Regarding semantic similarity evaluation, the all-MiniLM-L6-v2 and the Cohere Embed Multilingual v3 models are employed as embedding models [
62]. The all-MiniLM-L6-v2 and Cohere Embed Multilingual models produce dense embedding vectors with dimensionalities of 384 and 1024, respectively. Semantic similarity is calculated based on the cosine distance function for each pair of reference CQL query and generated CQL query. Finally, the average of the individual similarity scores is calculated. In
Table 4, Semantic Similarity 1 and Semantic Similarity 2 indicate all-MiniLM-L6-v2 and Cohere Embed Multilingual, respectively.
The FF Google-BLEU scores indicate that the adversarial attacks—simulated by the synthetic prompt injection dataset—significantly reduced syntactic similarity (increased lexical and structural errors). In particular, in the case of GPT-4o the FF RAG architecture achieved 0.699 while the adversarial attacks resulted in a score of 0.55828 (see
Figure 1 for the Google-BLEU scores under non-adversarial conditions).
Across all evaluated models, the FB design pattern results in systematic gains in all three metrics. The delta (Δ) values are defined by subtracting the feedback scores from the respective feedforward scores: FF − FB, positive delta values indicating consistent improvements when the feedback loop is enabled. The Google-BLEU delta values indicate that FB reduces lexical/structural error relative to FF for every model, with the largest improvements observed for Amazon Nova Pro and Claude 3.5 Sonnet, followed closely by GPT-4o-mini and DeepSeek R1. The smallest BLEU delta appears for GPT-4o.
The semantic similarity deltas (both all-MiniLM-L6-v2 and Cohere Embed Multilingual) are uniformly positive as well, indicating that the feedback loop not only improves token-level fidelity but also reduces semantic drift under adversarial inputs. The most pronounced all-MiniLM-L6-v2 gains are observed for Claude 3.5 Sonnet, Amazon Nova Pro, and DeepSeek R1, while Cohere Embed Multilingual similarity gains are particularly strong for Claude 3.5 Sonnet, Amazon Nova Pro, and Qwen 2.5 Coder 32B. These patterns suggest that the validator-guided refinement preferentially enhances semantic meaning preservation, even when BLEU changes are modest.
Table 5 provides a comparative analysis of the feedforward RAG (FF) and feedback-enhanced RAG (FB) architectures in terms of metrics with respect to robustness against prompt injection attacks. Two key metrics are evaluated: Attack Success Rate (ASR) and Unsafe Operation Rate (UOR), with Δ defined as FF − FB.
Across all models, the FB architecture yields substantially lower attack success rates than the respective FF baseline. The most significant reductions are observed for DeepSeek R1 and Amazon Nova Pro, indicating that the feedback loop consistently blocks adversarial manipulations more effectively than the feedforward variant. We note that even models with strong baseline performance, such as GPT-4o and GPT-4o-mini, benefit from robust feedback architecture design. The attack success rate was calculated using the LLM-as-a-jury ensemble model consisting of five independent Foundation Models (FMs).
Similarly, the rate of unsafe operations—that is, the number of outputs containing predefined harmful instructions—indicates consistent improvement with the FB architecture. DeepSeek R1 and Amazon Nova Premier demonstrate the largest reductions. These results confirm that the feedback mechanism systematically suppresses unsafe behaviors by validating and refining intermediate outputs.
The combined improvement across attack success rate and rate of unsafe operations highlights the effectiveness of the validator–feedback loop and self-correction mechanism as a robust security enhancement against prompt injection attempts. The magnitude of the Δ values suggests that this mechanism is especially impactful for models that are more susceptible to prompt injection attacks in the feedforward setting (e.g., Amazon Nova Pro), while still providing measurable gains for higher-performing models such as GPT-4o.
Figure 8 depicts the distribution of the individual LLM judges generated as part of the LLM-as-a-jury evaluation ensemble. The diagrams clearly demonstrate the improved adversarial robustness of the feedback-enhanced RAG (FB) architecture over the Feedforward (FF) RAG design pattern. Across all evaluated models, the FB architecture consistently reduced the proportion of malicious and diverged classifications while increasing the share of faithful outputs. These improvements indicate that the validator–feedback mechanism effectively detects and mitigates prompt injection attempts, thereby reducing unsafe operations and attack success rate. The observed trends are consistent across models of varying size and baseline performance, underscoring the generalizability of the approach. Overall, the feedback loop enhances the stability and reliability of text-to-Cypher query generation under adversarial conditions. Note that we provide a dedicated evaluation section for the LLM-as-a-jury ensemble.
We note that, in this study, the feedforward RAG architecture serves as the primary baseline for evaluating the proposed feedback-enhanced approach. To the best of our knowledge, no prior work has introduced a dedicated defense mechanism tailored specifically for securing text-to-Cypher CQL query generation against prompt injection attacks. Consequently, a direct competitive defense baseline does not exist in the literature, as existing prompt injection defenses focus on general LLM agents or text-to-SQL systems with different structural requirements. The feedforward RAG configuration quantifies the incremental benefit of the proposed feedback-loop-based architecture for adversarial robustness in the exact problem setting considered.
4.5. Comparative Analysis of the Feedback-Based RAG System
In this section we discuss our experimental results and provide comparative analysis on the proposed feedback-based RAG architecture against training-free approaches and a fine-tuned LLM variant.
We compared the RAG system to multiple training-free prompt injection defense methods.
Table 6 depicts the comparison of the proposed FB RAG solution to various prompt injection defense techniques. For each training-free defense method, the respective prompt was customized specifically to the defense technique. For the customized prompt templates, see
Appendix B.
The experimental results are depicted in
Table 6. In each defense technique, we employed dynamic information retrieval—similar to the FB and FF RAG methods—to augment the custom prompt with text-to-Cypher samples. The proposed method outperformed the training-free defense techniques across three text-to-Cypher model configurations. In particular, in the cases of the following model configurations the proposed approach outperformed all the defense techniques: GPT-4o-mini, Nova Pro, Deepseek R1. In the case of GPT-4o model configuration, the Spotlighting delimiting defense and the In-context defense methods outperformed the FB RAG method, however, the FB RAG outperformed all the other defense methods. We note that the FB RAG architecture is a system-design level defense technique which allows for the further customization of the underlying prompt templates. This way the FB RAG defense method can be augmented with all the examined training-free defense techniques discussed. This provides an opportunity for further study.
We evaluated the security vulnerability—in terms of the attack success rate metric—of the proposed approach on an LLM for which a fine-tuned variant is available. In [
17] the authors fine-tuned the open source Gemma-3-27B-Instruct model on the publicly available text-to-Cypher dataset of [
55]. Note that the training set in [
17] is the same dataset that we employed to build our vector database for the RAG pipeline of the proposed method. We used the same test set as the paper [
17] for validation purposes. Our experimental results are summarized in
Table 7. It is indicated that the proposed feedback RAG approach outperformed the fine-tuned model variant.
4.6. Evaluation on German Language Prompt Injection Dataset
In order to quantify the robustness of the proposed method against non-English prompt injection data, we created a synthetic German prompt injection dataset. The original text-to-Cypher dataset from Huggingface was used as the baseline [
55]. The input questions of the test set of the original dataset were translated to German. The input questions of the original training set were translated to German. The German variants of the training set’s input questions were embedded and indexed in the vector database. Note that in the original (English) experimental setup the training set was used to create the vector database for retrieval-augmented generation while the test set was used for validation. The Cohere Embed Multilingual v3 embedding model was employed across all the experiments throughout the paper. In the experiments the German input questions were embedded (vectorized) to find semantically meaningful German questions and augment the German-language-based text-to-Cypher generator prompts.
We employed Amazon Translate to implement the English-to-German translation as this is a traditional translation service implemented before the rise of large language models. We selected this translation function to intentionally make the translation model independent of foundation models employed as part of this experimental study.
Table 8 depicts the resulting attack success rates, and it is indicated that the FB RAG approach outperformed the training-free prompt injection defense mechanisms and the feedforward method (FF RAG).
4.7. Analysis of the Validator Module of the FB RAG System
This section evaluates and quantifies the performance of the validator module of the FB RAG architecture with respect to its reliability and failure modes. We observed the final output of the validator module and compared it to the output of the LLM-as-a-jury ensemble responsible for validating the final outcome. Note that the validator module is an internal component of the FB RAG text-to-Cypher architecture while the LLM-as-a-jury ensemble model is an external evaluator employed to quantify the performance of the proposed solution. We employed the following rules:
TN: the evaluator indicates no issue, the system returns the result without additional feedback loop execution. The LLM-as-a-jury ensemble indicates that the generated question is FAITHFUL.
FN: the evaluator indicates no issue, the system returns the result without additional feedback loop execution. The LLM-as-a-jury ensemble indicates that the generated question is either MALICIOUS or DIVERGED.
TP: the evaluator indicates an issue in the final iteration and returns the CQL query. The LLM-as-a-jury ensemble indicates that the generated question is either MALICIOUS or DIVERGED.
FP: the evaluator indicates an issue in the final iteration and returns the CQL query. The LLM-as-a-jury ensemble indicates that the generated question is FAITHFUL.
Note that the FB RAG text-to-Cypher system is configured with a maximum of three iterations throughout the paper, and in this way the system returns the CQL query after three iterations independent of the validator module. In our observation we compared the final outcome returned by the validator module and compared it to the output of the jury ensemble.
Table 9 depicts the classification-related performance metrics of the validator module. It is shown that the accuracy is consistently above 0.912 under all the text-to-Cypher LLM configurations. In our problem statement recall is of particularly high importance as it incorporates False Negative (FN) cases accounting for prompt injection attempts not captured by the validator. We observe that recall is consistently high (>0.8) across all the LLM configurations. GPT-4o and DeepSeek R1 provide us with the highest recall, implying that they identify the most prompt injection attacks.
The feedback loop introduces additional computational overhead through the repeated LLM invocations, since each iteration performs one text-to-Cypher generation pass followed by an LLM-based validation pass. With a maximum of three iterations, the pipeline executes between two calls (best case: FAITHFUL on the first attempt) and six calls (worst case: three generate–validate cycles), so latency and cost scale approximately linearly with the number of iterations. Assuming 2 s for an LLM inference request on average, the best case scenario and worst case scenario give computational overhead of 4 s and 12 s respectively.
4.8. Ablation Study of the Feedback-Based RAG System Under Prompt Injection Attacks
In this section we discuss the ablation studies proposed to validate the FB-based RAG system under prompt injection attacks. The attack success rate was employed to quantify the performance of the proposed solution against ablation variants. We compared the robustness against the following scenarios:
Static feedback.
Validator without explanation.
Dynamic feedback without classification.
Fixed evaluator models using either GPT-4o, GPT-4o-mini, Amazon Nova Lite, or Llama 3.1 8B Instruct.
Experimentation with varying feedback loop count.
Experimentation with varying document counts retrieved from the vector database in the RAG pipeline.
In the
static feedback case, the system feeds back constant plain text feedback to the text-to-Cypher module. The static feedback is hardcoded to indicate that the generated Cypher query might contain harmful components as a result of a prompt injection attack at the input. Note that in this case there is no LLM-based validator module employed to analyze the generated Cypher query candidate, but static feedback is sent back to the text-to-Cypher module independent of the generated candidate. The variant is configured to perform three feedbacks iteratively before sending the final Cypher query for evaluation to the LLM-as-a-jury ensemble. Note that the static-feedback-based ablation variant can be considered as the adoption of the zero-shot self-correction method proposed in [
49] with the following extensions: the query generation process is extended with a RAG component and the self-corrective procedure is executed multiple times (three iterations are configured throughout our experiments).
In the validator without explanation case, the evaluator model is employed to perform the classification to distinguish benign and harmful query candidates, but instead of a dynamically generated explanation, in the feedback an empty string is fed back to the system. This way the CQL generator model is triggered to re-generate the query, but it does not receive information on the potential harmful or malicious component of the previous iteration. The experiment was configured for at most three iterations. In the dynamic feedback case the validator module is implemented by a foundation model, but it is simplified to analyze the Cypher query and generate plain text feedback based on which the text-to-Cypher module can improve the generated query. Note that this ablation variant is performing self-correction, but the validator LLM is not prompted to perform classification. The variant is configured to perform three feedbacks independent of the validator’s output.
In the scenario of fixed evaluator models we used a fixed LLM for realizing the evaluator component independent of the query generator model. Note that, in the original architecture design and experimental setup, the Cypher query generator LLM is the same as the LLM of the evaluator. In this scenario, the evaluator model is configured independent of the query generator.
We note that all the ablation variants included the RAG component.
The static feedback template and dynamic-feedback-related prompt are detailed in
Appendix B. The experimental results are summarized in
Table 10. The FB RAG solution consistently outperforms all the ablation variants.
Figure 9 illustrates the impact of the maximum number of allowed feedback loops on the Attack Success Rate (ASR). We repeated the experiments with different values of the maximum feedback loop parameter n and computed the corresponding ASR for each configuration. Across the evaluated models, we consistently observe that increasing the number of allowed feedback loops reduces the ASR, indicating improved robustness against direct prompt injection attacks. The most substantial reduction is observed between
n = 0 and
n = 1, where
n = 0 corresponds to the Feedforward (FF) RAG architecture without feedback. The reductions between
n = 1 and
n = 2, and between
n = 2 and
n = 3, remain relatively pronounced, suggesting that the first few feedback iterations provide meaningful corrective capability.
Starting from n = 3, the ASR values begin to saturate, and additional feedback iterations do not lead to a significant further decrease. Based on this observation, we employed the elbow method to select the feedback loop parameter used throughout the experiments and set n = 3 as the default maximum number of feedback iterations. This value provides a favorable trade-off between adversarial robustness and computational overhead.
It is also important to note that, for Amazon Nova Pro and DeepSeek R1, the ASR values slightly increase between n = 8 and n = 10. This indicates that increasing the number of feedback loops does not necessarily improve robustness indefinitely. One possible explanation is context degradation, or context rotting, where repeated feedback iterations increase the amount of information included in the query generator (user) prompt, thereby increasing the number of input tokens and potentially reducing the model’s ability to focus on the original user intent and the relevant corrective signal. This observation further supports the choice of n = 3, since it achieves most of the robustness gains while avoiding the degradation effects observed at larger feedback loop depths.
Figure 10 illustrates the effect of the number of retrieved documents on the Attack Success Rate (ASR) for GPT-4o. We repeated the experiments with different values of the retrieved document count parameter, denoted by
k. The case
k = 0 corresponds to the non-RAG setting, where no reference document is retrieved and injected into the prompt. As
k increases from 0 to 5, the ASR consistently decreases, indicating that incorporating retrieved text-to-Cypher examples into the generation prompt improves robustness against direct prompt injection attacks.
For k > 5, the ASR begins to increase, suggesting that excessive retrieved context can degrade the defensive effect of the RAG pipeline. One explanation is context degradation, or context rotting, where too many retrieved examples increase prompt length and introduce additional contextual complexity, making it harder for the model to focus on the original user intent and the most relevant retrieval signals. These results indicate that the retrieved document count is an important design parameter: too few retrieved examples provide limited grounding, whereas too many may introduce noise and reduce robustness. In our experiments, k = 2 provides a favorable trade-off: although k = 5 yields a slightly lower ASR, the reduction from k = 2 to k = 5 is limited, whereas using k = 2 substantially reduces the number of retrieved examples included in the prompt. This choice therefore helps minimize input-token usage and improves cost efficiency while preserving most of the observed robustness gains.
4.9. Evaluation of the LLM-as-a-Jury Ensemble
We assessed the LLM-as-a-jury as a multiclass ensemble evaluator using three metrics: Inter-Rater Reliability (IRR), Leave-One-Model-Out (LOMO) stability, and entropy-based ambiguity rates. These metrics quantify the consistency and robustness of jury judgments. Note that they are not intended to estimate the accuracy of the ensemble model.
Observed IRR values are depicted in
Table 11. Across five text-to-Cypher model configurations (GPT-4o, GPT-4o-mini, Nova Premier, Nova Pro, DeepSeek R1) we calculated the respective Fleiss Kappa and BP coefficient values. Fleiss Kappa ranges from 0.607 to 0.671, indicating substantial agreement among the five LLM jurors. This suggests that the LLM-as-a-jury produces coherent labels well above chance levels [
63,
64].
Since Fleiss Kappa can be sensitive to class imbalance, we additionally report the Brennan–Prediger (BP) coefficient. BP values are consistently high (0.7987–0.8627), supporting the conclusion that agreement remains strong even under an imbalance-robust IRR model. In particular, the consistently high BP scores indicate that the jury’s agreement is not an artifact of skewed label frequencies [
65].
To test whether the evaluation is overly dependent on any single judge model, we conducted Leave-One-Model-Out (LOMO) experiments, recomputing ASR after removing one model from the jury at a time. Observed results are depicted in
Table 12. Five different text-to-Cypher model configurations were used. The observed attack success rate differences (ΔASR) are generally small across all configurations. Removing one judge at a time yields small changes in ASR (ΔASR typically ≤ ~0.03) across all configurations. ΔASR values are depicted in
Table 13. LOMO results indicate that the LLM-as-a-jury ensemble’s evaluation outcome is stable under perturbations of jury membership, which is important for scientific credibility in settings where individual LLMs may have differing alignment behavior. Removing one model does not materially alter the aggregate conclusions. This supports the claim that LLM-as-a-jury functions as a real ensemble rather than a single-model proxy.
We quantified the item-level uncertainty using the normalized entropy of individual votes (individual classification outcomes within the LLM-as-a-jury ensemble) and the ambiguity rate. For the sake of simplicity, in the sequel we denote ambiguity rate by P(). The results are summarized in
Table 14. Entropy-based ambiguity rates show that juries are highly decisive: ~72–82% of items are unanimous (
), and the high-uncertainty tail (
) is consistently small across all the examined LLM configurations. Thus, disagreement (high item-level entropy) is localized to a limited subset of items, which is consistent with expected ensemble behavior.
Across models, the LLM-as-a-jury framework exhibits high agreement, compositional robustness, and interpretable uncertainty, providing a consistent and reliability-aware approach for multiclass classification in text-to-Cypher robustness evaluation.
5. Architecture-Level Analysis and Design Rationale
The experimental results suggest that the robustness gains of the proposed feedback-enhanced RAG architecture arise from its system-level design rather than from any single model-specific property.
The RAG component provides task-specific grounding by retrieving semantically similar text-to-Cypher examples and injecting their associated schema and reference-query patterns into the generator prompt. This supports constrained generation toward valid Cypher structures and schema-consistent graph traversal patterns. RAG acts as a contextual anchor that reduces the likelihood of syntactically invalid or semantically unrelated Cypher candidates. In the experimental studies and ablation experiments it is observed that augmenting the generator prompt with samples improved the qualitative performance of the system in the case of FF RAG, FB RAG and fine-tuned RAG configurations.
Figure 10 indicates that the introduction of RAG resulted in reduced attack success rate, indicating improved robustness against direct prompt injection attacks. However, we note that the number of documents retrieved in the RAG pipeline is an important design parameter as excessive numbers of retrieved documents result in context degradation (context rotting).
Direct prompt injection attacks introduce an intent conflict between the legitimate user question and the malicious injected instruction. A feedforward generator must resolve this conflict in a single step, which increases the risk that the generated query follows the injected instruction. The feedback-enhanced architecture mitigates this risk by introducing an explicit validation checkpoint between query generation and acceptance. The validator evaluates whether the generated Cypher candidate is faithful to the original user intent and whether it contains unsafe, malicious, or divergent behavior, thereby separating query synthesis from security assessment.
Figure 9 suggests that the introduction of feedback results in reduced attack success rate consistently across all the model configurations, indicating its advantage in secure RAG pipeline design. We note that the maximum number of allowed feedback iterations is an important design parameter of the proposed architecture, and in
Figure 9 it is depicted that increasing the number of maximum iterations cannot reduce the ASR metric indefinitely. We suggested that repeating the feedback multiple times can increase the total token count of the generator prompt which can result in context degradation.
Experimental results suggest that the proposed architecture improves the security posture of text-to-Cypher generation through three complementary mechanisms: RAG-based task grounding, validator-based security checking, and feedback-guided self-correction. However, this analysis should be interpreted as an architectural explanation rather than proof of complete security. The validator may still produce false negatives, the feedback loop introduces additional cost and latency, and indirect prompt injection through retrieved RAG content remains an important direction for future work.
6. Latency, Scalability and Deployment Feasibility
The feedback-enhanced RAG architecture introduces additional overhead relative to the feedforward baseline, since each rejected Cypher candidate may require one additional validator call and one corrective generator call. In our implementation, models were accessed through Amazon Bedrock on-demand endpoints, so end-to-end latency is mainly determined by the number of sequential LLM invocations, prompt length, output length, and model-specific inference time.
Let f denote the average number of feedback loops per query. Since the initial pass requires one generator and one validator call, and each feedback loop adds one corrective generator and one validator call, the expected number of LLM invocations is:
In our experiments, f = 1.3, yielding:
Thus, the proposed architecture requires approximately 4.6 LLM calls per query on average. Assuming an average Bedrock invocation latency of approximately 4 s, the expected end-to-end latency is:
excluding minor vector-retrieval and deterministic post-processing overhead. This indicates that the feedback mechanism improves robustness at the cost of increased latency and token usage; however, the average feedback count of 1.3 shows that most queries do not reach the maximum feedback loop limit, supporting the use of three iterations as a practical upper bound.
The proposed solution architecture does not require continued pre-training, fine-tuning or other model customization steps since foundation models are employed in the architecture. This can significantly reduce the deployment and maintenance complexity of the solution while training is not required. This way the solution architecture has lower engineering cost and reduced time-to-deploy compared to text-to-Cypher architectures incorporating fine-tuned models. It is important to note that custom model deployments involve model maintenance debt (e.g., re-training, model and data drift handling) which can be reduced in the case of foundation model integration. As a practical deployment approach, we add that foundation models can be integrated from cloud providers leveraging on-demand consumption models, and essentially this translates LLM integration to API integration. The scalability of the solution architecture is determined by the integrated LLMs and vector database components. Runtime processing is dominated by stateless LLM inference and database execution, which enables horizontal scaling and elastic capacity provisioning. Note that the evaluation component (LLM-as-a-jury) can be operated offline as part of regression testing, decoupling it from production latency and allowing parallel batch processing.
7. Conclusions
In this paper, we introduced a feedback-guided RAG architecture to improve the robustness of LLM-based text-to-Cypher generation against direct prompt injection attacks. The proposed approach combines retrieval-augmented Cypher generation with a validator-driven feedback loop, where intermediate Cypher candidates are validated and, when necessary, refined before final acceptance. The results show that this self-corrective architecture can substantially reduce attack success rate and unsafe operation rate compared with feedforward generation, demonstrating the value of explicit validation and iterative correction in security-sensitive text-to-Cypher pipelines.
The experimental evaluation further shows that the proposed FB RAG architecture is generally competitive with, and in many model configuration cases superior to, training-free prompt injection defenses and ablation variants. However, the results do not indicate uniform dominance across all English-language settings: in particular, Spotlighting and In-context delimiting defense techniques achieve lower ASR than the proposed method in some English experiments. In contrast, in the German-language evaluation, no examined training-free defense outperformed the proposed FB RAG architecture. These findings suggest that feedback-guided RAG provides a strong and robust architectural defense pattern.
We also introduced a synthetic direct prompt injection dataset and an evaluation framework for assessing text-to-Cypher robustness under adversarial inputs. Generation quality was evaluated using Google-BLEU and semantic similarity metrics, while security robustness was quantified using attack success rate and unsafe operation rate. In addition, the validator module and LLM-as-a-jury ensemble were analyzed using classification and inter-rater reliability metrics, supporting the reliability of the proposed evaluation methodology.
Finally, we note improvement opportunities with respect to the proposed feedback-based RAG architecture:
The validator LLM agent acts as a binary classifier. Instead, it is worth considering the possibility of using a small model customized specifically to capture prompt injection attempts, leveraging publicly available prompt injection datasets.
The FB-enhanced AI architecture was configured with a static upper limit on the number of consecutive loop executions. Instead, it is worth exploring innovative design patterns for dynamically configuring the feedback loop executions.
While the study was focused on user-input-based (direct) prompt injection attacks, it does not discuss and evaluate indirect, data-poisoning attacks where the malicious instructions originate from retrieved RAG content. It is worth exploring the application of feedback-loop-based self-corrective architectures against indirect data-poisoning attacks from a security point of view.
The limited availability of public text-to-Cypher benchmark datasets confined broader validation across custom, domain-specific graph schemas and enterprise-scale graph databases. It is an important direction for future work in the field of knowledge graphs.
Future work should include a more detailed analysis of validator false negatives, since these cases represent direct prompt injection attacks that bypass the internal validation step and therefore define the residual security risk of the architecture.
The adversarial benchmark dataset employed in this study is synthetically generated. Therefore, it might not fully capture the diversity, ambiguity, and adaptivity of real-user attacks observed in deployed production systems.
The evaluation does not include execution-based validation of generated Cypher queries against live or sandboxed graph databases, and the use of LLM-based evaluators can introduce model-specific bias despite the ensemble-based LLM-as-a-jury design. In future research incorporating real-user based (red teaming) evaluation can be considered.