Know Thy Enemy: How Chain-of-Thought Fine-Tuning Defends LLMs Against Prompt Injection
From the publisher’s feed, collected in the ZeroLabs newsroom.
InstruCoT teaches language models to reason through every instruction before obeying.Made using notebookLMAn insurance claim processor receives a user query about the status of a disability claim. The system retrieves policyholder records, stitches them into the context window alongside a multi-turn conversation history, and gets to work. Woven between legitimate follow-up questions and retrieved policy data sits an injected instruction asking the model to extract and enumerate every data field it can access. The model complies. Social security numbers, policy identifiers, claim amounts, all exfiltrated through what looked like a normal workflow.This isn’t a hypothetical. It’s the kind of attack that current prompt injection defenses consistently miss, and it illustrates why a team from the Chinese Academy of Sciences and Nanyang Technological University built InstruCoT, a defense method that doesn’t just detect injections but teaches LLMs to reason about them. Averaged across four open-source models, it achieves defense rates of 92.5% for behavior deviation, 98.0% for privacy leakage, and 90.9% for harmful output, outperforming every baseline tested on average across all three dimensions.The idea is, before an LLM decides what to do, it should explicitly think through what it’s being asked and whether that conflicts with its actual job.Table of ContentsThe Two Problems with Current PI DefensesInstruCoT’s Three-Phase ArchitectureDiverse Data Synthesis: Coverage by DesignSituation Awareness for LLMsResults: Where InstruCoT Wins and Where It StrugglesThe CoT Tax and Open QuestionsWhat This Means for Production SecurityThe Two Problems with Current PI DefensesThe Multi-Vector ProblemOWASP ranks prompt injection as the number one security threat for LLM applications. The reason is structural: LLM-integrated applications don’t have a single input channel. They pull content from user messages, retrieved documents, tool outputs, conversation history, and memory systems. Each represents a potential injection vector, and each lands in a different region of the model’s context window.The InstruCoT paper formalizes this by tracing information flow from application frameworks through their functional components down to four fundamental context regions where adversarial content enters: User (user-provided content), Data (external data), User and Data (both simultaneously), and Empty (direct injection without prior context). This reduction is inspired by dataflow analysis from program analysis (Kildall, 1973), and it reveals something uncomfortable about current defenses. Methods like StruQ, SecAlign, and Meta-SecAlign only train against injections in the data region. ISE extends coverage to empty-context scenarios but still misses direct injections when user instructions or combined user-and-data contexts are involved. That’s a significant blind spot when real-world attacks target every available entry point.The Blurry Boundary ProblemEarly prompt injections were blunt: “Ignore all previous instructions and do X.” Semantically disjoint from the surrounding context, easy to catch. Modern attacks are far more sophisticated. TopicAttack inserts multiple rounds of topically relevant dialogue before the actual injection, creating a semantic gradient where the malicious instruction feels like a natural continuation of the conversation. The injected instruction stays within the system prompt’s domain, uses related terminology, and only subtly deviates from the model’s intended behavior.For defenses that rely on detecting role boundaries (“this is user content, that is data content”), these semantically blurred attacks are nearly invisible. StruQ introduces structured role separation between user and data sources. ISE encodes role hierarchy through learnable segment embeddings (system > user > data). MetaSec trains models to ignore instructions in the data region entirely. All useful, but they share a core assumption: that identifying the source of an instruction is enough to decide whether to follow it. When an injection lives in the user region and sounds like it belongs there, source identification alone doesn’t cut it. The average defense rate of existing methods against TopicAttack sits at a dismal 21.9% for ISE, highlighting exactly where boundary-based thinking breaks down.InstruCoT’s Three-Phase ArchitectureInstruCoT addresses both problems through three phases, diverse data synthesis, instruction-aware chain-of-thought generation, and supervised fine-tuning. The approach is a model enhancement method, meaning it modifies how the LLM itself processes inputs rather than adding external detection layers. This distinction matters because even when malicious instructions slip past external guardrails, an enhanced model can still produce safe outputs.Phase 1: Diverse Synthesis for Prompt InjectionRather than relying on a narrow set of injection patterns, InstruCoT generates training data across three threat scenarios: Behavior Deviation (instructions that shift the LLM away from its intended task), Privacy Leakage (instructions that extract sensitive information), and Harmful Output (instructions that induce dangerous content). For each scenario, injected instructions are generated at varying levels of sophistication and inserted into all four context regions identified by the reduction framework.Phase 2: Instruction-Aware CoT GenerationThis is the conceptual heart of the method. Instead of training models to recognize role boundaries, InstruCoT generates chain-of-thought reasoning that walks through every instruction in the context, analyzes each one for conflicts with the system prompt, and projects the appropriate response. More on this in the Situation Awareness section below.Phase 3: Supervised Fine-TuningThe generated CoT reasoning is prepended to training outputs, and the backbone LLM is fine-tuned on this augmented dataset using standard supervised learning. The model learns to produce structured reasoning before its final response, turning implicit instruction processing into explicit, auditable analysis. The training dataset totals 74,810 samples, combining both clean and adversarial examples (each augmented with CoT) to prevent over-refusal.Diverse Data Synthesis: Coverage by DesignGraduated Difficulty for Behavior DeviationMade using notebookLMOne of the more thoughtful design choices in InstruCoT is how it generates behavior deviation instructions. Rather than creating uniformly obvious injections, the method produces instructions at four deviation levels along two dimensions: domain alignment and topic relevance.Same Domain, Related Topic injections are the hardest to catch. The instruction stays within the system prompt’s domain and maintains topical relevance, but subtly exceeds the model’s defined responsibilities. A medical triage chatbot being asked for a specific diagnosis, for instance. Same Domain, Unrelated Topic keeps the domain but diverges in subject matter. Different Domain, Related Topic shifts domains while maintaining a weak topical thread. Different Domain, Unrelated Topic is the most obvious, departing entirely from both domain and topic.This graduated approach means the training data includes both easy cases that build baseline robustness and hard cases that sharpen the model’s decision boundaries. Existing baselines use homogeneous injection content without distinguishing deviation levels at all.Privacy Leakage Across Protection ScopesFor privacy attacks, InstruCoT targets three distinct protection scopes: user-level privacy (PII extraction), organization-level confidentiality (business data), and system-level secrets (system prompt extraction). The paper evaluates against 15 different prompt extraction attack strategies, which is notably more comprehensive than most defense evaluations.Harmful Output: Covering the Full SpectrumThe harmful output dimension follows the taxonomy proposed by Shen et al. (2024), spanning 13 categories: Illegal Activity, Hate Speech, Malware Generation, Physical Harm, Economic Harm, Fraud, Pornography, Political Lobbying, Privacy Violation, Legal Opinion, Financial Advice, Health Consultation, and Government Decision. This breadth matters because different categories present fundamentally different challenges. An LLM might easily refuse to generate malware but struggle with boundary cases in health consultation or financial advice where the line between helpful information and harmful guidance is genuinely blurry. InstruCoT’s training data covers all 13 categories, and the results show that while defense rates are highest for clear-cut categories like Illegal Activity (98.4%) and Fraud (95.0%), they dip for more ambiguous ones like Pornography (80.9%) and Health Consultation (80.9%). That pattern suggests the model has learned something real about intent analysis rather than just memorizing refusal triggers.The Context Reduction FrameworkImage taken from the research paper(Chang et al., 2026)The injection position strategy deserves attention. By mapping real-world LLM application architectures (RAG systems, multi-agent frameworks, tool-augmented LLMs, chatbots) down to their fundamental context regions, InstruCoT ensures training data covers all four injection positions rather than just the data region that most baselines focus on.Situation Awareness for LLMsEndsley’s Model as a Security FrameworkThe reasoning component of InstruCoT draws from an unexpected source: Mica Endsley’s Situation Awareness (SA) model, a framework from human factors research that describes decision-making as a three-level cognitive process. Level 1 is perception of environmental elements. Level 2 is comprehension of their meaning. Level 3 is projection of future states.The parallel to prompt injection defense is surprisingly clean. An LLM processing a complex context needs to first perceive all instructions present (not just the obvious ones), then comprehend whether each instruction conflicts with the system prompt’s defined scope, and finally project the appropriate response action for each. InstruCoT operationalizes this into three corresponding stages.Stage 1: Instruction PerceptionThe model identifies every instruction embedded in the input context. Two design principles govern this stage: exhaustiveness (no instruction can be missed, since a missed injection is a successful attack) and neutrality (instructions are perceived without premature judgment, preventing confirmation bias where the model might skip instructions that don’t match expected attack patterns).Stage 2: Violation ComprehensionEach perceived instruction undergoes a three-step analysis. Instruction Presentation isolates the specific instruction being examined. Binary Conflict Assessment determines whether it violates the system prompt with a clear yes/no decision, deliberately avoiding probabilistic hedging that would weaken the training signal. Reasoning Elaboration then explains the semantic basis for the determination, articulating how the instruction’s intent relates to the system prompt’s boundaries.The paper makes a strong case for why this instruction-by-instruction approach outperforms holistic judgment. When multiple instructions with varying intents coexist in a context, evaluating the entire context at once leads to inconsistent assessments. Consider a context containing three instructions: a legitimate user query, a benign follow-up, and a subtly injected privacy extraction request. Holistic analysis might assess the overall context as “mostly safe” and let the injection through. Instruction-level analysis forces the model to confront each one individually, making it far harder for a malicious instruction to hide behind the legitimacy of its neighbors. Fine-grained analysis enables precise conflict localization and reduces reasoning complexity.Stage 3: Response ProjectionThe final stage translates analysis into action, reject instructions that conflict with the system prompt, comply with those that align. This ensures the reasoning chain culminates in concrete behavioral outcomes rather than abstract analysis.The quality of this generated CoT is remarkably high. Across seven context region categories, the approach achieves an average F1 of 98.3% for instruction perception, 99.7% precision for violation comprehension, and 99.3% precision for response projection.Results: Where InstruCoT Wins and Where It StrugglesImage taken from the research paper(Chang et al., 2026)The Headline NumbersThe results are evaluated across four backbone LLMs: Llama3–8B, Llama3.1–8B, Qwen2.5–7B, and Qwen3–8B, using seven PI attack methods (Naive, Ignore, Escape-Character, Fake Completion, Combined, Multi-position, and TopicAttack). For behavior deviation, single-position and multi-position variants are evaluated separately, yielding ten distinct attack configurations.For Behavior Deviation, InstruCoT achieves 91.5% average defense rate against direct prompt injection and 93.4% against indirect injection, outperforming all baselines by 25.8% to 82.5%. For Privacy Leakage, it reaches 97.6% on ShareGPT and 98.4% on Unnatural datasets. For Harmful Output, it hits 90.9% across 13 harmful categories.Where the Gaps Reveal ThemselvesThe most telling results come from the breakdown by attack type. Against straightforward attacks like EscapeSP (escape character injection in single position), InstruCoT achieves a perfect 100.0% defense rate for direct injection. Against the more sophisticated TopicAttack, performance drops to 70.3% for direct injection and 87.7% for indirect. This is still dramatically better than ISE’s 22.5% and 21.4% on the same attack, but it shows that semantically blurred injections remain the hardest class of attacks to defend against.The MetaSec AsymmetryOne of the more revealing comparisons is MetaSec’s performance split between direct and indirect attacks. Because MetaSec’s entire training objective is to make LLMs distrust instructions within the data region, it performs reasonably well against indirect injections (85.9% average DR) but collapses against direct ones (51.0% average DR). When the injection arrives through the user channel rather than the data channel, MetaSec’s core assumption breaks. InstruCoT doesn’t have this asymmetry because it evaluates instruction intent rather than instruction source, achieving 91.5% and 93.4% for direct and indirect attacks respectively. This consistency across injection vectors is arguably more important than the raw numbers, because attackers will always target the weakest path.The CoT Ablation: Proof That Reasoning MattersThe CoT ablation is particularly revealing. InSFT, which is InstruCoT trained without the chain-of-thought component (same diverse data, no reasoning), achieves 53.5% and 60.1% average defense rates for direct and indirect behavior deviation attacks. Adding CoT pushes those to 91.5% and 93.4%. That’s a 38.0% and 33.4% improvement from the reasoning component alone, which is strong evidence that explicit instruction-level analysis isn’t just nice to have but fundamentally changes the model’s security posture. The privacy leakage dimension tells a similar story: InstruCoT achieves 15.7% higher average DR than InSFT, confirming that the reasoning framework generalizes across threat types rather than only benefiting one dimension.Model-Level VariationPerformance isn’t uniform across backbone LLMs either. Llama3–8B and Llama3.1–8B consistently achieve the highest defense rates after InstruCoT enhancement, with Llama3.1–8B reaching 94.8% average DR for direct behavior deviation. Qwen3–8B shows the most improvement from its baseline (jumping from 1.3% to 87.8% average DR for direct attacks) but still trails the Llama models in absolute terms. Qwen2.5–7B lands in between. These gaps suggest that the backbone model’s pre-existing instruction-following capabilities influence how effectively it can learn the CoT reasoning framework, though all four models achieve substantial gains.Utility Isn’t SacrificedA common concern with security-hardened models is degraded performance on legitimate tasks. InstruCoT achieves an average win rate of 82.9% on AlpacaEval across four LLMs, representing a 1.5% to 11.4% improvement over baselines. The model doesn’t just defend better; it actually performs better on normal tasks after alignment.The CoT Tax and Open QuestionsInference OverheadThe authors acknowledge that InstruCoT adds inference latency. The fine-tuned model generates chain-of-thought reasoning before every response, which means more tokens per interaction. The paper suggests mitigation strategies (speculative decoding, CoT distillation, selectively triggering CoT only for suspicious inputs), but these remain future work. For latency-sensitive production deployments, this overhead is a real consideration.Evaluation Dimension OverlapThe training data and evaluation benchmarks share the same three threat dimensions: behavior deviation, privacy leakage, and harmful output. While the specific instructions don’t overlap between training and test sets, the structural similarity leaves open the question of generalizability to novel threat categories. The authors note this as a limitation and plan to explore additional dimensions in future work.Detection-Based vs. Model EnhancementAn interesting subplot in the results is the performance of PromptArmor, a detection-based approach that uses GPT-4 as a guardrail. Its defense rates swing wildly across attack types, ranging from 14.4% to 93.2% for behavior deviation. This instability highlights the fundamental challenge with external detection: it’s only as good as the guardrail model’s ability to recognize each specific attack pattern. Notably, PromptArmor fares better in the harmful output dimension (70.8% average DR), where it actually outperforms ISE (67.8%). The paper attributes this to GPT-4’s safety alignment training, which equips it to catch overtly harmful instructions even when it struggles with subtler behavioral deviations. Model enhancement approaches like InstruCoT show more consistent performance because the defense is internalized. For anyone building production security layers, the implication is that detection and enhancement likely work best together, with external filters like antijection.com catching known patterns while enhanced models handle the novel or ambiguous cases that slip through.What This Means for Production SecurityInstruCoT represents a meaningful shift in how the field thinks about prompt injection defense. Instead of teaching models rigid rules about which input sources to trust, it teaches them a reasoning process for evaluating what they’re being asked to do. The Situation Awareness framing is more than a theoretical nicety. It produces measurable improvements, and the instruction-by-instruction analysis approach addresses a real failure mode in existing defenses.The practical takeaway for engineers building LLM applications is that role-level defenses have a ceiling. When attacks can live in trusted regions and mimic legitimate instructions, the model needs to reason about intent, not just source. InstruCoT’s approach, synthesizing diverse training data across all context regions and teaching explicit conflict analysis through chain-of-thought, offers a concrete path toward that capability.Whether the inference overhead is acceptable depends on the application. For high-stakes systems handling sensitive data or financial decisions, the additional latency is a reasonable trade. For chatbots where sub-second response times matter, it may not be. But the core insight, that LLMs should think before they obey, is one that should influence defense strategy regardless of whether this specific method fits every deployment.The dataset and code are publicly available for researchers looking to build on this work.ReferencesAcademic ResearchChang, Z., Li, M., Huang, Y., Jiang, Z., Jia, X., Xiong, Q., Wang, J., Li, Z., & Wang, Q. (2026). Know Thy Enemy: Securing LLMs Against Prompt Injection via Diverse Data Synthesis and Instruction-Level Chain-of-Thought Learning. arXiv preprint arXiv:2601.04666.Endsley, M. R. (1995). Toward a theory of situation awareness in dynamic systems. Human Factors, 37(1), 32–64.Chen, S., Piet, J., Sitawarin, C., & Wagner, D. A. (2025). StruQ: Defending against prompt injection with structured queries. 34th USENIX Security Symposium, 2383–2400.Chen, S., Zharmagambetov, A., Mahloujifar, S., Chaudhuri, K., Wagner, D. A., & Guo, C. (2025). SecAlign: Defending against prompt injection with preference optimization. ACM SIGSAC Conference on Computer and Communications Security (CCS 2025), 2833–2847.Wu, T., Zhang, S., Song, K., Xu, S., Zhao, S., Agrawal, R., Indurthi, S. R., Xiang, C., Mittal, P., & Zhou, W. (2025). Instructional Segment Embedding: Improving LLM Safety with Instruction Hierarchy. ICLR 2025.Wallace, E., Xiao, K., Leike, R., Weng, L., Heidecke, J., & Beutel, A. (2024). The instruction hierarchy: Training LLMs to prioritize privileged instructions. arXiv preprint arXiv:2404.13208.Chen, Y., Li, H., Li, Y., Liu, Y., Song, Y., & Hooi, B. (2025). TopicAttack: An indirect prompt injection attack via topic transition. EMNLP 2025.Shen, X., Chen, Z., Backes, M., Shen, Y., & Zhang, Y. (2024). “Do Anything Now”: Characterizing and Evaluating In-the-Wild Jailbreak Prompts on Large Language Models. ACM CCS 2024, 1671–1685.Shi, T., Zhu, K., Wang, Z., Jia, Y., Cai, W., Liang, W., Wang, H., Alzahrani, H., Lu, J., Kawaguchi, K., Alomair, B., Zhao, X., Wang, W. Y., Gong, N., Guo, W., & Song, D. (2025). PromptArmor: Simple yet effective prompt injection defenses. arXiv preprint arXiv:2507.15219.Security StandardsOWASP. (2023). OWASP Top 10 for LLM Applications.Know Thy Enemy: How Chain-of-Thought Fine-Tuning Defends LLMs Against Prompt Injection was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.