Praneel Panchigar 863c9db9a1 Merged in feature/code_optimization (pull request #903)
Feature/code optimization

* Ran Black

* made a small change in code_last_check, fixed so it returns string and not single char

* Made changes to make sure that default_ind postprocess only happens to the cc output and not dashboard

* Merge bugfix/default_ind_postprocess into feature/code_optimization

- Parent-child: child_rank column init and cols_to_keep filter
- Postprocess: default_ind only on cc output
- code_last_check: parser str/list return handling + exception logging
- Prompt: FIELD ASSIGNMENT for code extraction (no CRITICAL prefix)

* More prompt changes and debugging print statements

* Added system to group same service term + bill type cd + claim type cd and then parallelize the code extraction (will improve consistency)

* Revert one-time PROV_INFO_JSON ad hoc logic; retain json_utils and output format

- Remove temporary postprocess step that filled empty TIN in PROV_INFO_JSON from
  FILENAME_TIN (fill_prov_info_tin_from_filename_tin call in postprocess.py).
  This behavior is intended to move upstream per JIRA (tin_npi_funcs / extraction).

- Revert postprocess_existing_output.py to generic config: empty INPUT_DIR,
  INPUT_FILENAME, OUTPUT_CSV. Remove one-time hyphen-strip for TIN/NPI in
  PROV_INFO_JSON and remove _strip_hyphens_from_prov_info_json_cell.

- Keep json_utils PROV_INFO_JSON helpers (parse_prov_info_json_cell,
  serialize_prov_info_json, format_prov_info_json) and (str,str) serialization
  in contract_config_postprocess. Keep fill_prov_info_tin_from_filename_tin and
  related helpers in postprocessing_funcs for potential upstream reuse.

- Tests in test_json_parsers.py updated for (str,str) PROV_INFO_JSON output.

* Add arbitration-based implicit code flow and prefer Level 2 RAG (Fix 5d, 4c+7)

Implicit flow no longer uses first-match-wins. We build a case from all
applicable strategies and run a single arbitration step to choose the
best candidate.

- build_implicit_candidates: Run Category (when explicit had Category),
  Special, and RAG; return list of {source, code_answer_dict}. RAG
  result uses preferred level when both return (Fix 5d).

- code_implicit_rag (Fix 5d): Run both Level 1 and Level 2, collect
  results; when both return non-empty, prefer Level 2 over Level 1.

- code_implicit_arbitration: 0 candidates -> None; 1 candidate -> return
  it with CODE_METHODOLOGY = 'Implicit - Arbitration (Source)' (no LLM);
  2+ candidates -> one CODE_IMPLICIT_ARBITRATION LLM call (chosen_index or
  no_match). If no candidates or no_match, code_last_check runs as before.

- prompt_templates: Add CODE_IMPLICIT_ARBITRATION and
  CODE_IMPLICIT_ARBITRATION_INSTRUCTION (cached). Use
  _create_json_dict_parser(field_names=['chose…
* fix: test_code_breakout avoid LLM call and flaky order on CI

- Add BILL_TYPE_CD_DESC to test data so pre-pass skips fill_bill_type (no Bedrock on CI)
- Use side_effect function keyed by SERVICE_TERM for deterministic result under ThreadPoolExecutor

* ran black

* feat: hybrid code validation with unmatched tagging and code quality fixes

Validation and unmatched tagging:
- Add format-only filtering for explicit codes (drop wrong-format, preserve valid)
- Add unified _has_unmatched_codes() used by both explicit and implicit paths
- Tag CODE_METHODOLOGY with "- Unmatched" when codes are format-valid but
  not explicit keys in our mappings (codes and range keys count as mapped)
- Remove retry logic and "Explicit - Validation Failed" in favor of single
  LLM call with Unmatched tagging
- Include all revenue level mappings in valid revenue set

Code quality and bug fixes:
- Fix fill_bill_type += string bug (was splitting "11X" into chars)
- Fix bare except clauses in code_explicit, code_category,
  code_implicit_special, fill_bill_type (now except Exception as e)
- Replace eval() with json.loads() in fill_grouper_cd_desc
- Implement INVALID_SERVICE short-circuit in RAG (Fix 5a)
- Cache valid procedure/revenue code sets per Constants instance
- Store mappings in level_dicts…
* chore: remove debug print statements from code extraction pipeline

Remove all [DEBUG_CODE_EXTRACTION] print statements added during
development of the hybrid validation and implicit arbitration flow.

* refactor: robust PROV_INFO_JSON sanitization with multi-format parsing

Replace the simple format_prov_info_json with a layered
sanitize_prov_info_json that handles all known malformed variants:
single-quoted dicts, empty-value-after-colon patterns, list-typed
field values, and hyphenated TINs. Extract _normalize_prov_entries
and _prov_value_to_str helpers for uniform str-valued output.
format_prov_info_json now delegates to sanitize_prov_info_json.

* merge: sync feature/code_optimization with DEV

Resolve conflict in prompt_templates.py: keep detailed CRITICAL field
assignment instructions from feature branch; accept new
AARETE_DERIVED_PROVIDER_NAME prompt function from DEV.

* Minor change to explict prompt

* fix: resolve mypy errors and remove stale pipe-delim splits in RAG

- Narrow grouper_cd type to str|None with explicit None check to
  satisfy mypy in fill_grouper_cd_desc.
- Remove dead pipe-delim split logic from CPT and HCPCS matching
  blocks (no pipes in those mappings).
- Retain pipe split for revenue block only (rev_level1.csv keys are
  pipe-delimited, e.g. "0810|0811|0812").

* Code extraction: format-only explicit, keep unmapped tag, RAG Level 1/2 as separate candidates

- Explicit: accept all format-valid codes (single + range); do not drop for mapping.
  Validity check only appends "- Unmatched" to methodology when code not in mappings.
- Add _procedure_code_or_range_format_valid; use in validate_explicit_codes and _has_unmatched_codes.
- RAG: return list of Level 1 and Level 2 candidates (distinct source keys); remove Level 2 preference.
- build_implicit_candidates: consume RAG list and append each as separate candidate.
- CODE_EXPLICIT: clarify range extraction when service term describes a range.
- CODE_IMPLICIT_ARBITRATION: choose most appropriate candidate(s), avoid overly broad.
- Tests updated for new RAG return shape and validate_explicit_codes behavior.

* Resolved Merge Conflicts

* Fixed failing tests

* Remove unused functions

* Remove unused functions

* Revert "Remove unused functions"

This reverts commit 39954db6a421e55501282d4e6a270c88624049fe.

* remove unused

* Merged DEV into feature/code_optimization

* Merged DEV into feature/code_optimization


Approved-by: Katon Minhas
2026-03-11 17:39:31 +00:00
2026-02-06 14:25:04 -05:00

Field Extraction Pipeline

Contract field extraction using LLMs.

Setup

Install uv (if not already installed)

# Ubuntu/WSL (recommended)
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc  # or restart terminal

# macOS
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows (PowerShell - native, not WSL)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Verify installation: uv --version

Install dependencies

uv sync

Running the Code

Use uv run with Python's module flag from the project root:

# Run the default SaaS pipeline
uv run python -m src.pipelines.saas.main

# Run with unified runner (supports client selection)
uv run python -m src.pipelines.runner --client saas --input-dir /path/to/input

# Run with specific client
uv run python -m src.pipelines.runner --client clover --input-dir /path/to/input

Note: Always use uv run to ensure correct virtual environment. Always use -m flag for proper imports.

Development

Before pushing, always run these checks to avoid breaking the CI pipeline:

# Format code
uv run black src/

# Type checking
uv run mypy src/

# Run tests
uv run pytest

All checks must pass before merging to main.

Project Structure

├── src/
│   ├── pipelines/              # Pipeline implementations
│   │   ├── runner.py           # Unified CLI entry point with client routing
│   │   ├── saas/               # Default SaaS pipeline
│   │   │   └── main.py         # Main entry point for SaaS
│   │   ├── shared/             # Shared pipeline components
│   │   │   ├── preprocessing/  # Document preprocessing
│   │   │   ├── extraction/     # Field extraction logic
│   │   │   └── postprocessing/ # Result postprocessing
│   │   └── clients/            # Client-specific overrides
│   │       └── clover/         # Clover client customizations
│   ├── core/                   # Core utilities (registry, fieldset)
│   ├── constants/              # Constants, mappings, and field definitions
│   │   ├── mappings/           # Crosswalk JSON files
│   │   └── lists/              # Lookup lists
│   ├── prompts/                # LLM prompt templates
│   ├── utils/                  # Shared utilities (IO, string, logging, etc.)
│   ├── codes/                  # Medical code extraction utilities
│   ├── crosswalk/              # Crosswalk mapping logic
│   ├── embeddings/             # Pre-computed embeddings for code matching
│   ├── qc_qa/                  # QC/QA validation pipeline
│   ├── parent_child/           # Parent-child relationship mapping
│   ├── document_classification/ # Document type classification (DTC)
│   └── tests/                  # Unit tests
├── documentation/              # Project documentation
├── outputs/                    # Pipeline output files (gitignored)
├── logs/                       # Log files (gitignored)
└── pyproject.toml              # Project dependencies (uv/pip)

Branching

Naming Conventions

Type Pattern Use Case Example
Feature feature/<ticket>-<description> New functionality feature/PROJ-123-add-export-csv
Bugfix bugfix/<ticket>-<description> Bug fixes bugfix/PROJ-456-fix-null-handling
Hotfix hotfix/<ticket>-<description> Urgent production fixes hotfix/PROJ-789-critical-parse-error
Test test/<description> Testing/experimentation test/lesser-table-caching-refactor
Release release/<version> Release preparation release/v1.2.0

Branch Guidelines

  • Use lowercase with hyphens (kebab-case) for descriptions
  • Include ticket number when applicable (e.g., JIRA, GitHub issue)
  • Keep branch names concise but descriptive
  • Delete branches after merging

Workflow

  1. Create branch from main
  2. Make changes and commit with clear messages
  3. Run checks before pushing: uv run black src/ && uv run mypy src/ && uv run pytest
  4. Create PR to main
  5. Ensure all CI checks pass
  6. Get code review approval
  7. Squash and merge
S
Description
AARETE DoczyAI pipelines mirror.
Readme 642 MiB
Languages
Python 80.5%
Jupyter Notebook 13%
HCL 3.1%
HTML 1.6%
PLpgSQL 1.5%
Other 0.2%