Editor’s introduction
It compares human interventions required by existing tools—such as IDEs and general LLMs—against its own performance, measuring autonomy through the number of times humans must correct errors or provide design guidance. IDE tools require 5–17 interventions across tasks, primarily for architecture selection and preprocessing, highlighting their lack of domain-specific knowledge. Performance is measured via Dice scores for segmentation and classification accuracy, with results showing up to 0.90 Dice and 99% accuracy.
Introduction
The emergence of large language models (LLMs) has revolutionised the field of software engineering. Trained on massive code datasets, LLMs show impressive capabilities in natural language requirements comprehension, relevant codebases search, reasoning on software structures, and demonstrating substantial code generation capabilities. On function-level code generation benchmarks such as HumanEval and MBPP, state-of-the-art LLMs have achieved accuracy rates of 97.6% and 92.7%, respectively. On SWE-bench, a benchmark on solving real-world Github repository issues, LLMs have achieved a 76.8% resolution rate. These results highlight the significant potential of LLMs in software engineering.
However, these benchmarks only demonstrate the capability of LLM systems in small-scale code generation or code repair within existing repositories. When generating complex code from scratch, current LLMs face significant limitations: (1) For complex problems, users must provide highly detailed prompts encompassing all task-relevant background information to achieve satisfactory results; (2) Due to the hallucination problem inherent in LLMs and the lack of effective validation mechanisms, human intervention remains necessary during code generation; (3) Without built-in validation mechanisms, LLMs cannot maintain consistent context and memory across code generation projects, even when successfully generating complete code. Medical image processing code generation significantly exemplifies these challenges. Medical images exhibit complex properties with multimodal data (CT, MRI), 2D/3D volumetric structures, various intensity ranges, and specialised formats (NIfTI, DICOM), demanding domain expertise that significantly exceeds what can be conveyed through manual prompting. Domain reliability requirements mean that hallucinated preprocessing steps or incorrect architectural choices are unacceptable, necessitating rigorous validation throughout generation. Complete pipelines span multiple interdependent stages from data loading through inference, while recurring patterns across projects demand cross-project knowledge retention that standard LLMs cannot exploit. Automating this process would enable practitioners lacking deep learning expertise to deploy validated medical imaging pipelines, broadening access to AI-assisted diagnostics. Moreover, established benchmarking datasets with ground truth annotations and standardised metrics enable objective assessment of generated pipelines. Together, these properties make medical image processing both a practically impactful and methodologically rigorous domain for evaluating automated code generation in complex, real-world settings.
Although several approaches attempt to tackle these challenges, they remain insufficient. Existing code generation frameworks or tools lack domain-specific knowledge integration and systematic validation mechanisms, making human intervention indispensable for specialised domains. Recent AutoML and multi-agent approaches automate broader ML pipelines but remain confined or pre-defined datasets, requiring manual effort to extend to specialised domains or datasets. Medical imaging automation methods incorporate domain expertise but address only partial pipeline components without achieving fully automated generation. No existing approach combines comprehensive domain knowledge, systematic validation, and consistent context management to enable fully automated generation of complete, validated pipelines from scratch.
Automation in medical image processing
In the field of medical imaging, numerous automated algorithm design and optimization methods have been developed. NAS automatically discovers optimal network structures but requires predefined search spaces and manual pipeline implementation. nnU-Net automates segmentation pipeline configuration but requires manual environment setup and is restricted to segmentation tasks. Foundation models like SAM and MedSAM eliminate task-specific training but require interactive prompts during inference and address only segmentation. AutoML-Agent automates full-pipeline ML across diverse tasks but requires manually provided skeleton code for new task types and relies solely on prompt-based rather than execution-grounded verification. DS-Agent leverages case-based reasoning for data science automation but lacks medical imaging knowledge for generating appropriate pipelines, and its sole reliance on execution feedback can only guarantee runnable code without ensuring alignment with domain conventions. VoxelPrompt integrates a jointly-trained vision-language agent for end-to-end radiological analysis but focuses exclusively on inference-time task execution without addressing automated pipeline development or code generation. M3Builder automates medical imaging ML workflows through multi-agent coordination but restricts generation to pre-defined datasets with accompanying code templates, requiring manual preparation for new datasets. These approaches address only partial pipeline components, requiring substantial expertise for deployment, and none achieves fully automated generation of complete pipelines from scratch.
Agent Coordination Structure
Complex medical image processing tasks require comprehensive expertise over multiple domains, including medical image data analysis, library dependencies and APIs, data loading strategies, and neural network architecture design. A single-agent approach faces fundamental limitations: (1) simultaneously invoking knowledge across diverse domains creates confusion and inconsistent reasoning; (2) maintaining accurate context becomes increasingly difficult as context accumulates through planning, validation, and coding phases; (3) single-agent systems cannot exploit parallel execution for efficiency improvement.
AutoMedImg addresses these limitations through a multi-agent architecture organised as a router-subagent hierarchy with an independent Validation Layer. To distribute domain expertise, AutoMedImg employs specialised agents: the Planning Router invokes Dataset Analyser and Architect, while the Coding Router allocates multiple Coder subagents in parallel for concurrent module generation, each possessing focused knowledge rather than handling multiple domains simultaneously. Each agent maintains its own context window, with Shared Memory storing validated intermediate results that agents retrieve as needed, preventing context accumulation in a single window. Critically, the Verification Agent and Tester Agent operate within an independent Validation Layer rather than embedded within generating agents, eliminating self-validation bias. Routers coordinate workflow progression based on validation outcomes: only verified results advance to subsequent stages, while failures trigger automated correction loops with diagnostic feedback. This architecture addresses domain knowledge specialisation, phase-specific context management, and parallel execution requirements.
Agent Context Integration
Specific resource assignments vary by agent role. Planning Router and Coding Router employ orchestration Skills for workflow coordination: Planning Router sequentially invokes Dataset Analyser and Architect subagents, while Coding Router concurrently allocates multiple Coder subagents for parallel module generation. Dataset Analyser, Architect, and Coder each access specialised knowledge bases: The Dataset Analyser’s knowledge base is derived from nnU-Net dataset card specifications, capturing standardised medical imaging dataset properties; The Architect’s knowledge base is manually curated from leading neural network architectures on Grand Challenge, providing validated pipeline design patterns across diverse medical imaging tasks, with CSP# modeling Skill for converting architecture designs to formal specifications; The Coder’s knowledge base is extracted from official MONAI API documentation, supplying library-specific implementation templates. The Verification Agent’s knowledge base comprises manually summarised ISO/IEC 25023 modularity standards and IEC 62304 medical device software conventions, providing structured validation criteria and scoring rubrics for semantic assessment, CSP# interpretation knowledge base for understanding verification outputs, alongside Skills for invoking PAT tool for formal verification. Tester accesses the Testing Knowledge Base containing test case patterns and coverage criteria, while utilising static analysis tools (Pylint, Radon) and dynamic testing frameworks (Pytest) through MCP. All agents share access to shared memory for validated intermediate results and adaptive synthesis knowledge base for cross-project reference. Validation feedback from failed checks and tool execution results is incorporated during the fix-loop, enabling targeted corrections. This comprehensive context integration enables each agent to automatically construct domain-appropriate context without manual prompting.
Baseline Prompt Design and Configuration
To evaluate the fundamental limitations of existing code generation approaches on medical image processing tasks, all baseline methods receive carefully designed prompts that provide equivalent task structure and necessary tool access, enabling them to attempt the same four-stage pipeline as AutoMedImg: Dataset Analysis: Generate scripts to examine dataset file structure, image dimensions, modality characteristics and intensity distributions. Architecture Design: Design the complete pipeline architecture based on dataset analysis results, including preprocessing and data-loading strategies, neural network structure, training configurations, and inference workflow. Module Implementation: Implement individual modules according to the architecture design. Pipeline Assembly: Generate an assembly script integrating all modules into an executable end-to-end pipeline.
Baselines also receive command-line execution permissions and file system access where their architecture permits, enabling them to: (1) execute Python scripts for runtime debugging, (2) read/write files during code generation, (3) check and install required dependencies, and (4) attempt to iteratively refine code based on execution feedback. This configuration allows us to identify what types of errors and limitations emerge without AutoMedImg’s validation-based context engineering and multi-agent coordination.
Evaluation Criteria
We evaluate methods across three dimensions. To measure autonomy, we count human interventions (HI) — the number of times a human must intervene to correct errors or provide guidance that the system cannot autonomously resolve, including error correction, design guidance, and workflow instructions. HI takes three forms: direct prompt interactions (providing instructions, relaying error messages, or corrections), passing templates or skeleton code, and, rarely, manual script or configuration updates. For model performance, we use the Dice coefficient for segmentation and accuracy for classification, both measured on test sets using identical evaluation protocols. For implementation quality, we analyse structural designs including preprocessing strategies, data augmentation techniques, neural network architectures, and computational efficiency (GPU memory usage and training time). On selected datasets, we conduct detailed comparisons to assess whether generated pipelines adhere to medical imaging practices and properly handle volumetric data properties. All experiments are conducted with Pass@3, running each configuration three times and reporting the best-performing trial.
Limitations of Existing Code Generation Approaches
Proprietary IDE tools require 5–17 human interventions across all tasks, revealing a fundamental inability to autonomously handle domain-specific requirements. Interventions predominantly take the form of design guidance and preprocessing specification, such as selecting appropriate architectures, applying correct preprocessing, and accounting for volumetric data properties, as well as error correction for frequent execution failures. While these tools can generate syntactically correct code, they lack domain knowledge to make appropriate design decisions, such as selecting appropriate architectures, applying appropriate preprocessing, and accounting for volumetric data properties, leading to frequent failures that require human correction. Notably, Antigravity performs most competitively (0.6372–0.9938, fewer than 10 interventions) owing to its partial memory retention across sessions, indirectly suggesting the value of cross-project knowledge accumulation. Open-source LLMs exhibit severe limitations in both domain knowledge and autonomous error correction. Interventions span the broadest range, including domain design guidance, preprocessing specification, manual script execution, and error message relay. Without domain guidance, these models make critical preprocessing errors that break fundamental medical imaging properties. For example, GPT-oss applies unrestricted Resize instead of voxel-space Resample, corrupting physical scale information and causing near-zero segmentation performance (0.0067 Dice on FLARE22), yet lacks the validation mechanisms to detect and correct such errors autonomously. Proprietary LLMs demonstrate stronger baseline capabilities but still require 5–12 interventions with inconsistent performance across datasets (0.5058–0.9752 Dice), revealing that general coding ability alone is insufficient for full autonomy in specialised domains even with state-of-the-art models. Interventions are more mixed, spanning both domain design guidance and workflow instructions, reflecting stronger but still insufficient domain awareness. Answer to RQ1: Existing code generation tools and LLMs consistently fail on medical imaging tasks due to lack of domain knowledge and validation, with Antigravity’s partial memory retention suggesting cross-project knowledge accumulation as a promising direction.
Performance of AutoMedImg Against Advanced Multi-agent and AutoML Frameworks
Multi-agent frameworks demonstrate improved autonomy over baseline tools but still suffer from the identified fundamental limitations. CAMEL lacks domain-specific guidance, resulting in basic preprocessing and augmentation strategies. MetaGPT X still shows performance gaps on complex tasks (0.6845 Dice on BTCV, 0.7750 on ACDC), demonstrating that code generation quality alone is insufficient without domain validation. MaCTG achieves the lowest intervention counts (1–4) through intra-agent validation, yet without domain knowledge its validation fails on complex multi-organ segmentation (0.5104 on FLARE22, 0.5205 on BTCV) despite strong performance on simpler tasks, confirming that multi-agent architecture alone is insufficient without domain-specific validation. AutoML frameworks exhibit different but equally limiting constraints. AutoML-Agent requires a manually provided code skeleton for each new task type, fundamentally constraining its applicability, and its retrieval mechanism fetches neural network architectures while ignoring preprocessing requirements for complex medical data formats, increasing interventions on specialised tasks (5 on FLARE22, 4 on BTCV). M3Builder relies on manually provided dataset cards and fixed templates for segmentation and classification, lacking dynamic pipeline design capability. Its template-based approach causes hallucinations on task type selection and aborted executions on tasks outside template coverage, particularly semi-supervised segmentation (6 interventions on FLARE22). Its competitive BTCV performance (0.7392 Dice) stems from predefined template coverage and forced nnU-Net backbone rather than adaptive design capability.
AutoMedImg addresses the identified limitations across both framework categories. Domain-specific knowledge bases eliminate the need for manually provided skeletons or dataset cards, enabling fully automated generation from arbitrary datasets. Multi-stage validation prevents error propagation and hallucinations that cause framework abortions. Adaptive pipeline synthesis enables cross-project knowledge reuse without the rigidity of fixed templates. AutoMedImg achieves zero human interventions across all task types including semi-supervised segmentation, while maintaining competitive or superior performance compared to all frameworks.
Answer to RQ2: While multi-agent and AutoML frameworks partially address RQ1 limitations, they introduce their own constraints including manual input dependencies and fixed templates. AutoMedImg overcomes these through domain-specific knowledge, systematic multi-stage validation, and adaptive synthesis, achieving fully automated generation where existing frameworks still require human preparation.
Ablation Study
Planning Phase Validations. Dataset analysis semantic checking removal increases interventions by 0.10 with 3.3% performance degradation, as missing critical properties such as voxel spacing or intensity range lead to subtly incompatible downstream designs that only manifest as performance degradation rather than outright failures. Planning semantic validation removal has a more severe impact (+0.57 HI, -4.7%), reflecting the central role of architecture validation in the overall pipeline — without contextual validation, agents may select fundamentally incompatible architectures such as 2D networks for 3D volumetric data. Without formal semantic validation, occasional specification-level inconsistencies that contextual checks cannot detect go unresolved. While medical imaging pipelines follow straightforward sequential structures that rarely violate process ordering properties, formal verification provides an additional correctness guarantee that catches edge cases before implementation begins. Together, these two planning validation steps form a comprehensive correctness gate, preventing a combined +0.67 HI increase and significant performance degradation before implementation begins.
Coding Phase Validations. Code validations exhibit a strong impact on autonomy. Syntax check removal adds 0.67 interventions and increases generation time by 37.2 minutes, as downstream validations eventually catch syntax errors after attempting to execute malformed code. This result demonstrates that early-stage checks prevent costly downstream failures. Execution testing removal dramatically increases HI by 3.50 with 4.5% performance degradation, representing the most critical validation for automated generation. Without runtime verification, functional errors, such as tensor dimension mismatches or incorrect function calls, can propagate to later stages, requiring substantial human debugging. Assembly validation removal causes 2.50 additional interventions, confirming its necessity for detecting integration issues between individually validated modules.
Memory and Knowledge Components. Shared memory removal causes 2.4% performance degradation with a 16-minute time increase, indicating its role in maintaining context consistency across agents. Removing the knowledge base results in the largest performance degradation (-13.7%) with minimal increase in HI (+0.33), indicating that domain-specific knowledge primarily guides appropriate designs. Without medical imaging practices and conventions, agents generate syntactically correct but suboptimal pipelines, such as using torchvision transforms instead of MONAI medical imaging transforms, or applying a generic resize operation that breaks voxel spacing information. Adaptive synthesis removal results in 8.4% performance degradation and an over 37-minute time overhead, confirming that cross-project learning enables agents to adapt pipelines from previous projects rather than regenerate from zero. Without it, agents must generate solutions independently, resulting in slow generation and suboptimal designs.
Discussion
Qualitative Comparison with Code Generation Baselines. IDE tools and vanilla LLMs possess strong code generation capability but lack domain-specific conventions and built-in validation, resulting in suboptimal pipeline designs and substantial human correction overhead. Multi-agent frameworks provide effective inter-agent cooperation but lack systematic validation and domain grounding, limiting their effectiveness on complex domain-specific tasks. AutoML frameworks offer pipeline automation but require manually provided scaffolds for each new task type, constraining their applicability to predefined task coverage. AutoMedImg addresses these limitations by instantiating base models within a multi-agent architecture augmented with domain KBs and systematic step-wise validation, eliminating the need for manually provided scaffolds through a planning-validation workflow that dynamically synthesises task-appropriate pipelines. Furthermore, AutoMedImg distinguishes itself across all categories through cross-project knowledge accumulation via adaptive pipeline synthesis, enabling validated solutions to be retrieved and adapted for future tasks, a capability absent in all prior work.


