Automating Medical Coding Safely: Combining Deterministic Orchestration with Agentic AI Workflows

The intersection of artificial intelligence and safety-critical administrative systems has reached a pivotal juncture, particularly within the healthcare and pharmaceutical sectors. Medical coding—the meticulous process of translating free-text clinical terms, patient symptoms, and adverse event descriptions into standardized dictionaries like MedDRA and WHODrug—remains an indispensable yet highly repetitive operational bottleneck. Historically, skilled clinical data managers have reviewed these verbatims line by line to ensure regulatory compliance and data integrity. Even minor errors in signal routing can cascade into substantial downstream regulatory reporting flaws. Consequently, organizations have sought robust technological solutions to automate high-confidence cases while maintaining absolute deterministic control over the underlying workflows.
A newly published technical reference architecture from cloud computing leader Amazon Web Services (AWS) addresses this exact operational challenge. The solution demonstrates how enterprises can successfully combine deterministic orchestration with bounded, agentic artificial intelligence reasoning. By leveraging AWS Step Functions alongside the Amazon Bedrock AgentCore harness integration, the architecture establishes a division of labor where the workflow engine strictly governs sequencing, compliance rules, and approval gates, while generative AI agents are restricted to reasoning within isolated, highly bounded execution steps.
Core Architectural Principles and the Division of Labor
In conventional AI implementations, handing an entire business process over to an autonomous large language model (LLM) introduces non-deterministic runtimes, making execution paths exceptionally difficult to review, audit, or replay. For highly regulated medical environments where every operational decision must be fully explainable to compliance officers and auditors, this lack of predictability poses an unacceptable risk.
To mitigate these concerns, the AWS reference design adheres to a strict foundational principle: deploy the cheapest, most deterministic mechanism capable of handling a given task with complete confidence, and escalate to more expensive, probabilistic AI models only when ambiguous judgment is genuinely required.
This multi-tiered escalation ladder is intentionally structured to protect system integrity and optimize operational expenditures. When a clinical verbatim enters the pipeline, it encounters a sequence of progressively sophisticated evaluation filters:
- Safety Block-Lists: Before any machine learning model or LLM is ever invoked, incoming terms pass through an immediate security filter. Certain high-risk or excessively broad medical terms—such as unspecific references to hemorrhaging where the anatomical location dictates the appropriate classification code—are intercepted by a hard-coded safety block-list. A match immediately halts automated processing, leaving the term open for human expert review. Because this safety rule operates entirely ahead of any model call, it cannot be bypassed or "prompted away" by prompt injection or model hallucination.
- Direct Lexical and Synonym Matching: Following the safety evaluation, a high-performance database function executes a case-insensitive exact match against the target medical dictionary and curated synonym lists (such as mapping "Hypothyroid" directly to "Hypothyroidism"). In benchmark test workloads, a significant portion of incoming verbatims—exceeding one-third of the dataset—is successfully resolved at this stage for the negligible cost of an indexed database query, bypassing the AI agent entirely.
- Agentic Semantic Search and Contextual Reasoning: Only when direct lookup methods fail to achieve an exact match does the system invoke the Amazon Bedrock AgentCore harness integration. Even at this stage, the agent operates under strict operational boundaries. It is granted access to a carefully curated set of Model Context Protocol (MCP) tools via an AgentCore Gateway, including a semantic dictionary search powered by Amazon Titan Text Embeddings V2 and pgvector, as well as a study-specific protocol information retrieval tool.
Context-Aware Decision-Making and Clinical Nuance

The true utility of bounded agentic reasoning becomes apparent when handling ambiguous terms that require external protocol context to categorize accurately. A compelling illustration of this capability involves the processing of the verbatim "cramps" across two entirely different clinical trial environments.
When evaluated within an oncology trial where muscle spasms represent an adverse event of special interest, the AI agent queries the specific study protocol metadata, determines the appropriate clinical endpoint, and maps the term to "muscle spasms" with high confidence. Conversely, when processing the exact same verbatim within a gastrointestinal study where muscular events are not a primary safety endpoint but abdominal discomfort is prevalent, the agent appropriately routes the term toward "abdominal pain."
Crucially, the agent does not unilaterally determine the final workflow routing or write the code directly to the production record. Instead, it assigns a granular confidence score accompanied by a concise, one-sentence natural language rationale for its decision.
The Step Functions state machine then evaluates this score against predefined, auditable thresholds. Scores at or above 0.90 automatically trigger a validated write-back to the database. Scores falling between 0.70 and 0.90 are systematically routed to a human review queue, while scores dropping below 0.70 are left open for manual triage. This ensures that human oversight remains a first-class operational outcome rather than an exceptional error state.
Security, Infrastructure, and Compliance Considerations
Deploying automated data pipelines in clinical research requires stringent adherence to healthcare compliance frameworks, data privacy regulations, and proprietary licensing agreements. Controlled medical dictionaries such as MedDRA (managed by the MSSO on behalf of the IFPMA) and WHODrug (maintained by the Uppsala Monitoring Centre) are proprietary, licensed assets requiring valid institutional subscriptions for commercial deployment.
The underlying cloud infrastructure utilized in the reference sample—including Amazon Aurora PostgreSQL-Compatible Edition (Serverless v2) and Amazon Bedrock—is fully HIPAA-eligible when deployed under a signed AWS Business Associate Addendum (BAA). Furthermore, the sample dataset provided in the public GitHub repository has been meticulously scrubbed of any Protected Health Information (PHI), utilizing entirely generated study identifiers and de minimis illustrative dictionary entries.
From a data persistence standpoint, the architecture eliminates the operational complexity of managing a synchronized external vector database. By utilizing Amazon Aurora Serverless v2 equipped with the pgvector extension, reference data and their corresponding vector embeddings are stored within a single, unified relational database engine. This design significantly streamlines infrastructure management, reduces latency, and simplifies backup and recovery procedures.

Implications and Broader Industrial Applications
The architectural pattern established in this reference implementation extends far beyond clinical trial medical coding. Across numerous highly regulated industries—including financial services claims triage, legal document classification, automated medical case narrative summarization, and laboratory test results adjudication—organizations face a common architectural tension: balancing the unprecedented reasoning capabilities of generative AI with the absolute requirement for deterministic auditability and compliance.
By maintaining a strict separation of concerns where workflow orchestration engines dictate process flow, state transitions, and compliance boundaries, enterprises can harness the cognitive flexibility of large language models without sacrificing operational transparency.
Industry analysts note that as enterprises mature their generative AI strategies, architectures that rely on unconstrained agentic loops are increasingly being supplanted by deterministic-first patterns. These hybrid models ensure that every automated action is fully traceable, reproducible, and verifiable by compliance authorities.
Future Outlook and Implementation Roadmap
Organizations intending to deploy similar production-grade architectures are advised to follow a rigorous validation methodology. Initial steps involve cloning the open-source sample repository via the AWS Cloud Development Kit (AWSCDK), seeding the environment with validated golden datasets, and systematically measuring system precision and incorrect autocode rates against historical benchmarks prior to live deployment.
Furthermore, engineering teams must carefully calibrate concurrency limits and model token quotas when scaling workflows to handle full-scale clinical studies via Step Functions Distributed Map states. By proactively monitoring resource utilization through Amazon CloudWatch and AgentCore Observability dashboards, enterprises can achieve an optimal balance between processing velocity, cost efficiency, and unyielding regulatory compliance.







