Skip to content

BlueCodeAgent: a blue-team agent for code-generating AI driven by automated red teamingBlueCodeAgent: A Blue Teaming Agent Powered by Automated Red Teaming for CodeGen AI

arXiv· arXiv:2510.18131· ICML 2026· Chengquan Guo, Yuzhou Nie, Chulin Xie, Zinan Lin, Wenbo Guo, Bo LiUniversity of Chicago; University of California, Santa Barbara; University of Illinois Urbana-Champaign; Microsoft Research; Virtue AIIndexed by this site · 8 days ago· Originally publishedDefenses

Quick read

Defenses

Based on the paper PDF (AI-generated); refer to the original

The authors propose BlueCodeAgent, which uses automated red teaming to generate knowledge for a blue-team agent to perform code security defense; the authors state that with GPT-4o as the backbone, average F1 improves by 14.7% across four tasks.

Threat modelDefender's perspective: binary-classify input test cases as safe/unsafe. Risks cover the input/text layer (biased instructions, malicious instructions, prompt injection) and the output/code layer (code containing CWE vulnerabilities); unsafe samples come from red-team-generated data, and benign samples come from normal coding tasks in MBPP.

Questions
Code generation AI safety research leans toward red teaming (exposing risks), while blue-team defense is insufficient: existing methods align poorly with safety concepts, are over-conservative and produce many false positives, and do not fully cover unseen risks.
Methods
BlueCodeAgent first accumulates risk knowledge using multiple red-team strategies (strategy-driven generation, seed-prompt jailbreak optimization, knowledge-driven vulnerability generation), then retrieves similar knowledge and summarizes it into a constitution to guide defense decisions, and vulnerability detection additionally adds sandbox dynamic testing for verification.
Experiments and results
The authors report that F1 exceeds baselines such as Llama Guard, PurpCode, and LLM-ensemble on the four task types: bias, malicious instructions, prompt injection, and vulnerability detection; with a GPT-4o backbone, the average F1 across the four tasks improves by 14.7%, and dynamic testing reduces FP by an average of 19.3%.
Limitations and future work
Future directions listed by the authors: generalize to more code risk categories, extend to file and repository level, and extend to other modalities. Experiments mainly use a few backbone models such as GPT-4o, and the advanced red-teaming methods and harmful data are not publicly released.
Experimental setupGPT-4o、Meta-Llama-3-8B-Instruct et al. · BlueCodeEval-Bias、BlueCodeEval-Mal (RedCode-based / RMCbench-based) et al. · F1、TP/FP/TN/FN et al.
Evaluated models
GPT-4oMeta-Llama-3-8B-InstructQwen2.5-72B-Instruct-TurboClaude-3.7-Sonnet (Claude-3.7-Sonnet-20250219)
Benchmarks
BlueCodeEval-BiasBlueCodeEval-Mal (RedCode-based / RMCbench-based)SecCodePLTBlueCodeEval-PIMBPPBias-CBSMalicious-RMCOpen-Prompt-InjectionCWEval
Metrics
F1TP/FP/TN/FN平均延迟(秒)
AI summaryResearchers propose BlueCodeAgent, a blue-team agent for code-generating AI empowered by automated red teaming, to detect risks in AI-generated code. Its red-team component generates diverse risk instances, providing boundary examples and guidance for the subsequent blue-team process; the blue-team agent then performs multi-layer defense through constitution summarization and dynamic code analysis to detect seen and unseen risk scenarios. The authors' evaluation on four task types—biased instruction detection, malicious instruction detection, vulnerable code detection and prompt injection detection—shows that with GPT-4o as the base model, BlueCodeAgent improves average F1 by 14.7% over directly prompting the model; in the vulnerability detection task, combining dynamic analysis effectively reduces false positives, mitigating the base model's tendency to be overly conservative. Code and data are open-sourced at https://github.com/1mocat/BlueCodeAgent。

Researchers propose BlueCodeAgent, a blue-team agent for code-generating AI empowered by automated red teaming, to detect risks in AI-generated code. Its red-team component generates diverse risk instances, providing boundary examples and guidance for the subsequent blue-team process; the blue-team agent then performs multi-layer defense through constitution summarization and dynamic code analysis to detect seen and unseen risk scenarios. The authors' evaluation on four task types—biased instruction detection, malicious instruction detection, vulnerable code detection and prompt injection detection—shows that with GPT-4o as the base model, BlueCodeAgent improves average F1 by 14.7% over directly prompting the model; in the vulnerability detection task, combining dynamic analysis effectively reduces false positives, mitigating the base model's tendency to be overly conservative. Code and data are open-sourced at https://github.com/1mocat/BlueCodeAgent。

Paper analysis

6 questions; open one to read the full answer

  1. What problem does this paper attempt to solve?

    Blue-team defense research for code generation AI is insufficient; the authors propose BlueCodeAgent, an end-to-end blue-team agent powered by automated red teaming.

    Core problem: CodeGen AI safety research concentrates on red teaming (exposing risks), while progress on the blue-team defense side is limited, and there is a lack of effective defenses that perform in-depth safety analysis of tasks and edge cases.

    • Problem scenario: As LLM code generation capabilities grow, they may be misused to generate malicious code or biased code with discriminatory logic, or may unintentionally produce vulnerable code containing injection and other vulnerabilities while completing normal tasks (Introduction).
    • Shortcomings of existing defenses (according to the paper): (1) poor alignment with safety concepts, with directly adding safety prompts being ineffective; (2) over-conservatism, especially in vulnerable code detection, where patched code is also flagged as vulnerable, producing many false positives and reducing developer trust; (3) incomplete risk coverage, making it difficult to handle subtle or unseen risks without safety knowledge and edge cases.
    • Core observation/hypothesis: The authors believe that better red-team knowledge can remedy the above shortcomings; they draw on ideas such as GuardAgent, Vul-RAG, and Constitutional AI that use risk knowledge to enhance defense, but manually collecting large-scale high-quality safety principles is unrealistic, so automated red teaming is used to generate them.
    • Proposed solution: BlueCodeAgent, an end-to-end blue-team agent powered by automated red teaming: the red-team component generates diverse risk instances as knowledge, and the blue-team component uses them for constitution summarization and dynamic code analysis, covering four detection task types: biased instructions, malicious instructions, vulnerable code, and prompt injection.
    • Threat model (defender's perspective):
      • Defense goal: binary-classify input test cases as safe or unsafe, and give a corresponding message (refusal, yes/no, or explanation).
      • Risk scope: input/text-layer risks (biased instructions, malicious instructions, prompt injection) and output/code-layer risks (code containing CWE vulnerabilities).
      • Sources of unsafe samples: red-team-generated biased/malicious/injection instructions and code containing CWEs; benign samples are normal coding tasks from MBPP.
      • Victim system: an LLM-backed code generation system, with BlueCodeAgent as its front-end defense.
  2. What related research exists?

    Related work is divided into two groups: red-team evaluation and blue-team defense; the authors state that this paper is the first end-to-end agent defense solution for CodeGen AI risks.

    Red-Team Research on CodeGen AI

    • Benchmark category: RedCode (Guo et al., 2024) and RMCbench (Chen et al., 2024) evaluate whether models generate malicious code in response to unsafe prompts; Huang et al. (2025) study biased code generation; Nie et al. (2024), Pearce et al. (2021), and Peng et al. (2025) evaluate code outputs along the CWE dimension.
    • Methods and adversarial inputs: Bhatt et al. (2024) and Mazeika et al. (2024) stress-test LLMs with adversarial inputs; red-team methods such as Jenko et al. (2025) and He & Vechev (2023) aim to induce unsafe behavior. The paper notes that most of these works only expose risks and do not use the knowledge they discover to improve defenses.

    Blue-Team Research on CodeGen AI

    • Guardrails and vulnerability detection: Kang et al. (2025) report that the best-performing guardrail models perform poorly in cyber and code generation scenarios; Ullah et al. (2024) and Ding et al. (2024) find that existing models struggle to reliably reason about security defects, and that over-conservatism is widespread, with patched code still judged as vulnerable, producing high false positives—the paper uses this to argue for runtime verification such as dynamic testing.
    • Knowledge-enhanced defenses: Vul-RAG (Du et al., 2025) performs retrieval augmentation on a CVE database; the paper notes that it relies on existing CVE code and does not support diverse automated red-team processes. PurpCode (Liu et al., 2025) uses red teaming to generate training prompts; the paper states that this work is complementary to it, using an agentic approach to dynamically leverage red-team knowledge and integrate runtime testing.

    Baselines and Benchmarks of This Paper

    • Baseline methods: Llama Guard 3-8B, LlamaFirewall, PurpCode-14b-RL, LLM-ensemble (voting by O3, DeepSeek-V3, Claude-3.7-Sonnet), direct prompting and two levels of safety reminders, Vul-RAG, static analysis tools (CodeQL, Semgrep, Bandit), and Hybrid of LLM+static tools.
    • Benchmarks/datasets: the self-built BlueCodeEval-Bias, BlueCodeEval-Mal (two subsets, RedCode and RMCbench), BlueCodeEval-PI, plus SecCodePLT (vulnerable code) and MBPP (benign samples); Appendix B additionally uses Bias-CBS, Malicious-RMC, Open-Prompt-Injection, and CWEval for external generalization evaluation.

    The authors' positioning of this paper: The authors state that, to their knowledge, this is the first work to provide an end-to-end agentic solution for mitigating CodeGen AI safety risks; compared with red-team work, it uses knowledge for defense, and compared with Vul-RAG and PurpCode, it emphasizes dynamic use of red-team knowledge and runtime testing.

  3. How does the paper address this problem?

    The red-team pipeline generates risk knowledge; the blue-team agent retrieves the knowledge, summarizes it into a constitution, and performs principle-level defense; vulnerability detection additionally adds sandbox dynamic testing.

    Overall approach: first use a diverse red-team pipeline to automatically generate the risk knowledge base BlueCodeKnow, then have BlueCodeAgent retrieve similar knowledge at inference time and summarize it into an executable constitution to guide safety decisions; vulnerable code detection additionally introduces dynamic testing to reduce false positives.

    Problem Setting and Formalization

    • The blue-team task is formalized as binary classification: determine whether an input test case x is safe or unsafe, written as d = BlueCodeAgent(x, t ∣ K), where t is the task type and K is the knowledge base.
    • The output d contains a binary judgment (obtained by keyword matching statistics) and a task-related message mt: in biased/malicious instruction tasks, mt is compliance or refusal plus explanation; in prompt injection tasks, mt is yes/no; in vulnerable code tasks, mt is the judgment rationale.
    • Four risk definitions: biased instructions (coding requests containing discriminatory intent), malicious instructions (requests to generate malware), prompt injection (embedding injection semantics to steer a safety task toward unsafe), and vulnerable code (code containing CWEs) are all judged unsafe; normal coding requests in MBPP are judged safe.

    Diverse Red Teaming: Knowledge Accumulation

    • Strategy-driven instance generation: Collect safety/ethical policies, enumerate combinations of biased groups and application scenarios into risk definitions, and use the uncensored model Orenguteng/Llama-3-8B-Lexi-Uncensored to generate diverse instructions that violate the policies; for prompt injection tasks, policies are formulated using the two injection categories of Liu et al. (2024) before generating instances.
    • Seed-driven adversarial prompt optimization: For simple malicious seeds that are easily refused, the red-team agent adaptively calls jailbreak tools such as GCG, AmpleGCG, AutoDAN, and Advprompter to query the victim model multiple times, optimizing the prompt until the attack success rate is relatively high; the authors state that new tool-combination attack vectors were discovered in the process.
    • Knowledge-driven vulnerability generation: Using MITRE CWE knowledge and SecCodePLT's coding scenarios and safety policies, GPT-4o is used to accumulate a pair of unsafe/safe code samples for each CWE.
    • The red-team data is split into two parts: the knowledge part BlueCodeKnow (four subsets: Bias/Mal/Vul/PI) and the test part BlueCodeEval; the risk categories of the two do not overlap (Appendix A lists the specific category division).

    Knowledge-Enhanced Blue-Team Agent

    • Retrieval and constitution summarization: For each test instance, embedding similarity is computed with text-embedding-3-small, the top-k (K=3) knowledge entries are retrieved from K, and a summarization model M induces them into a high-level constitution: C = M(Top-k(x, K)). The authors state the motivation is that knowledge or a constitution can help identify more unseen unsafe scenarios.
    • Principled-Level Defense: Inspired by Constitutional AI, red-team knowledge is summarized into executable rules and principles, and the model makes safety decisions according to them when facing unseen adversarial inputs.
    • Nuanced-Level Analysis: The authors observe that providing knowledge or a constitution makes the model more sensitive/conservative, so dynamic testing tools are added to vulnerable code detection: code is executed in an isolated Docker sandbox to verify whether the vulnerabilities reported by the LLM actually trigger, thereby reducing false positives.

    Dynamic Analysis Procedure (Algorithm 1)

    1. The static analyzer analyzes the specific vulnerability type in the test code T under the guidance of constitution C.
    2. If no vulnerability is found, a safe judgment is returned directly.
    3. Otherwise, the dynamic analyzer generates executable test code, runs it in the sandbox, and captures the output.
    4. The final analyzer integrates the static analysis, test code, execution results, and constitution to give the final judgment J.

    Key Parameters and Models

    • Retrieval: text-embedding-3-small, K=3; the default constitution summarization model is GPT-4o (Appendix D ablation compares Qwen3-0.6B to 8B, GPT-4o, GPT-5).
    • Dynamic analyzer: Claude-3.7-Sonnet-20250219, which the paper states is because of its stable code generation capability.
    • The red-team process is performed offline, and blue-team inference is online (Appendix C).
  4. What experiments did the paper conduct?

    BlueCodeAgent's F1 exceeds multiple baselines on four task types; ablation shows greater gains from seen risk knowledge, and dynamic testing mainly reduces false positives.

    Experimental setup

    • Backbone models tested: Bias/malicious/prompt injection tasks use Qwen2.5-72B-Instruct-Turbo, Meta-Llama-3-8B-Instruct, GPT-4o; vulnerable code detection uses GPT-4o and Claude-3.7-Sonnet.
    • Benchmarks: BlueCodeEval-Bias, BlueCodeEval-Mal (RedCode-based and RMCbench-based), SecCodePLT, BlueCodeEval-PI, with benign samples drawn from MBPP; the risk categories of knowledge and test do not overlap to simulate unseen risks.
    • Baselines: Llama Guard 3-8B, LlamaFirewall, PurpCode-14b-RL, LLM-ensemble (O3, DeepSeek-V3, Claude-3.7-Sonnet initial judgment + majority vote after discussion), direct prompting, generic/fine-grained safety reminders; the vulnerable code task additionally has Vul-RAG, CodeQL, Semgrep, Bandit, and Hybrid (LLM+static tools).
    • Metric: F1 with unsafe as the positive class; the vulnerable code task additionally reports TP/FP/TN/FN.
    • Evaluation method: Judgments are derived from the model's own output via keyword matching; the paper does not report an independent judge model or human evaluation.
    • Sample sizes and repetitions: The main text does not give the size of each test set or the number of repetitions; Appendix B gives external benchmark sizes (Bias-CBS 668, Malicious-RMC 272, PI-OpenPI 200, CWEval 57 entries), and Appendix C uses 280 vulnerability detection cases for latency evaluation.

    Main results

    Table 1 (text tasks on backbones such as GPT-4o, F1) and Table 2 (SecCodePLT vulnerable code detection, F1):

    Swipe horizontally to read the table

    MethodBiasMal(RedCode)Mal(RMC)PISource
    Llama Guard 3-8B0.190.180.790.71Table 1
    LlamaFirewall0.000.010.250.08Table 1
    LLM-ensemble (Disc.)0.750.920.900.60Table 1
    PurpCode-14b-RL0.580.890.890.70Table 1
    BlueCodeAgent0.981.000.990.99Table 1

    Vulnerable code detection (Table 2): direct prompting GPT-4o 0.64, Claude 0.75; Vul-RAG GPT-4o 0.63, Claude 0.76; PurpCode-14b-RL 0.67; static tools CodeQL 0.01, Semgrep 0.13, Bandit 0.22; BlueCodeAgent constitution+dynamic testing GPT-4o 0.68, Claude 0.77. Table 1 does not specify the backbone model used for each column; the main text states that BlueCodeAgent achieves F1 close to 1.0 on three backbones (Figure 3).

    • The authors state: when knowledge and test categories differ (unseen risks), BlueCodeAgent can still use seen risks for effective defense, and applies to both open-source and commercial backbones.
    • The authors state: generic or fine-grained safety reminders are insufficient for effective defense, attributed to models' difficulty in applying abstract safety concepts to unseen scenarios.
    • The authors report: with GPT-4o as backbone, average F1 across four tasks improves by 14.7% over direct prompting (abstract).

    Seen vs unseen risk knowledge (Table 3)

    • What was tested: Samples of the same risk category are split into disjoint knowledge and test sets (seen setting), and the F1 improvement is compared with the unseen setting of the main experiments.
    • Results: Improvements are larger with seen knowledge—bias 0.38 vs 0.31, malicious(RMC) 0.34 vs 0.23, malicious(RedCode) 0.15 vs 0.12, prompt injection 0.35 vs 0.32, vulnerable code 0.09 vs 0.04.
    • Authors' interpretation: Seen risk knowledge yields greater gains; the unseen setting still requires cross-category generalization (e.g., different CWEs), which the authors describe as already non-trivial cross-type generalization.

    Complementarity of constitution and dynamic testing (Table 4)

    • What was tested: Decomposes the contributions of constitution and dynamic testing to TP/FP/TN/FN on GPT-4o and Claude backbones.
    • Results: GPT-4o direct prompting has FP 116, FN 19; after constitution, TP rises to 129 and FN drops to 11; adding dynamic testing further reduces FP to 109, F1 0.68. On the Claude backbone, BlueCodeAgent(code example) has F1 0.78, the highest in that row, and constitution+dynamic testing is 0.77. Dynamic testing alone without constitution yields limited improvement (GPT-4o F1 0.64).
    • Authors' interpretation: Constitution mainly raises TP and lowers FN, while dynamic testing mainly lowers FP through runtime verification; the two are complementary; the authors also state that dynamic testing reduces FP by an average of 19.3% compared with directly using the base model (introduction).

    External knowledge base and external benchmark generalization (Appendix B)

    • SecEval as knowledge base (Tables 6, 7, GPT-4o): Bias 0.95, malicious-RMC 0.99, malicious-RedCode 1.00, comparable to BlueCodeKnow; prompt injection only 0.80, lower than the safety prompt baseline of 0.96, which the authors explain as SecEval lacking injection-specific knowledge.
    • External benchmarks (Tables 8, 9, GPT-4o): On Bias-CBS, BlueCodeAgent 0.92 (direct testing 0.04, safety prompt 0.61); Malicious-RMC 0.99; PI-OpenPI 0.40 (still the highest among methods); on CWEval, constitution+dynamic testing 0.73, slightly above PurpCode-14B's 0.72.

    Other ablations and analyses

    • Latency (Table 10): End-to-end 28.73 seconds, 25.93 seconds after caching the constitution; LLM-Ensemble 78.99 seconds serial, 42.93 seconds parallel; dynamic testing module alone 21.07 seconds.
    • Constitution model scale (Appendix D, Figure 4, Table 11): Qwen3-1.7B to 8B perform close to GPT-4o, and GPT-5 gives no additional gain; GPT-5-generated constitutions average 2034.20 characters and 33.74 seconds each, versus 1619.22 characters and 7.31 seconds for GPT-4o.
    • Case study (Figure 1, Appendices E/F): Appendix F shows a code snippet labeled Safe that the baseline and constitution judge as CWE-862, and after all dynamic tests pass it is finally judged vulnerability-free.
  5. What are some points that can be further explored?

    The authors list three future directions: more risk categories, file/repository-level extension, and multimodal extension; experimental coverage is mainly based on a small number of backbone models.

    Limitations and Future Directions Noted by the Authors

    • Generalize to more risk categories (§6 Conclusion and Future Works): The authors state that it is worth exploring generalizing the end-to-end framework to code generation risks beyond bias, malicious instructions, prompt injection, and vulnerable code, which may require designing new red-team strategies and building corresponding benchmarks.
    • Extend to file and repository level (§6): The authors state that extending BlueCodeAgent to the file and repository level could enhance practicality, requiring stronger context retrieval tools and memory components.
    • Extend to other modalities (§6): The authors state that, beyond code generation, the method should also be extended to text, image, video, audio, and multimodal applications.
    • Risk control of the red-team process (Impact Statement): The authors state that advanced red-team methods and potentially harmful data are not publicly released, and that released components come with documentation for research use—this is the authors' statement about the scope of release rather than a methodological limitation.

    Scope of Experimental Coverage

    • There are 5 backbone models tested: 3 for text tasks (Qwen2.5-72B-Instruct-Turbo, Meta-Llama-3-8B-Instruct, GPT-4o), and 2 for vulnerable code detection (GPT-4o, Claude-3.7-Sonnet).
    • Defense evaluation covers four task types: biased instructions, malicious instructions (two subsets, RedCode and RMCbench), prompt injection, and vulnerable code (SecCodePLT); external generalization covers four benchmarks: Bias-CBS, Malicious-RMC, Open-Prompt-Injection, and CWEval.
    • The sample size of the main test sets (the BlueCodeEval subsets) and the number of repetitions per condition are not reported in the paper; the external benchmark sizes are 668, 272, 200, and 57 entries (Appendix B).
    • Judgments are obtained by keyword matching on model outputs; the paper does not report independent LLM judging or human evaluation or agreement.
    • Adaptive attacks (bypass attacks designed against BlueCodeAgent's defense itself) do not appear in the paper's experiments; red teaming is used only to generate knowledge data.
  6. Summarize the main content of the paper

    BlueCodeAgent uses automated red-team knowledge to enhance blue-team defense, with F1 exceeding multiple baselines on four types of code security tasks.

    A defense paper for code generation AI: addressing insufficient blue-team defense research and the over-conservatism and incomplete coverage of existing methods, it proposes BlueCodeAgent, an end-to-end blue-team agent powered by automated red teaming.

    • Method highlights: On the red-team side, three pipelines accumulate a risk knowledge base: strategy-driven generation, seed-prompt jailbreak optimization (GCG, AutoDAN, and other tools), and CWE knowledge-driven vulnerability generation; on the blue-team side, the top-3 similar knowledge entries are retrieved and summarized by GPT-4o into a constitution to guide safety decisions, and vulnerable code detection then has Claude-3.7-Sonnet generate test code for dynamic verification in a Docker sandbox.
    • Main results: The authors report that with GPT-4o as the backbone, the average F1 across the four tasks improves by 14.7% over direct prompting; in Table 1, BlueCodeAgent's F1 on bias, malicious (RedCode), malicious (RMC), and prompt injection is 0.98, 1.00, 0.99, and 0.99, respectively, higher than baselines such as Llama Guard, PurpCode, and LLM-ensemble.
    • Vulnerable code detection (Table 2): with the GPT-4o backbone, constitution+dynamic testing F1 is 0.68 (direct prompting 0.64), and with the Claude backbone 0.77 (direct prompting 0.75); the authors state that dynamic testing reduces FP by an average of 19.3%.
    • Ablation: The F1 improvement from seen-risk knowledge is greater than from unseen risks (e.g., bias 0.38 vs 0.31, Table 3); the constitution mainly improves TP and dynamic testing mainly reduces FP, and the two are complementary (Table 4).
    • Generalization: Switching to the SecEval knowledge base performs comparably on bias and malicious tasks, but prompt injection drops to 0.80; on the external benchmarks, F1 is 0.92 on Bias-CBS and 0.73 on CWEval (Appendix B).
    • Authors' conclusion: The authors state that comprehensive red teaming can effectively empower blue-team defense, and they plan to extend the framework to more risk categories, file/repository level, and other modalities.

Related papers

Show 3 more papers
Read originalICML 2026