Inferensys

Prompt

Dependency Bloat and Unused Package Detection Prompt

A practical prompt playbook for using Dependency Bloat and Unused Package Detection Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Identify when to run the dependency bloat detection prompt, what inputs it requires, and what it cannot safely decide on its own.

Platform engineering teams accumulate unused, duplicated, and unnecessarily pinned dependencies over time. This prompt analyzes import statements against manifest declarations to produce a removal candidate list with justification and risk notes. Use it during dependency audit sprints, before major refactors, or as a scheduled CI hygiene check. The prompt assumes you can provide the package manifest file content and a grep or static analysis output of all import statements. It does not execute code or resolve dynamic imports, so runtime-only dependencies require separate verification.

The ideal user is a platform engineer, tech lead, or DevOps practitioner who can supply two structured inputs: the full content of a package manifest (such as package.json, requirements.txt, Cargo.toml, or go.mod) and a deduplicated list of import statements extracted from the codebase via grep, rg, or a static analysis tool. The prompt works best when imports are normalized to the package names used in the manifest. If your codebase uses path aliases, monorepo internal packages, or conditional imports behind feature flags, preprocess those into canonical package names before passing them to the prompt. The output is a structured removal candidate list, not an automated deletion script—every candidate still requires human review and a passing test suite before removal.

Do not use this prompt for runtime-only dependencies that are never imported statically, such as database drivers loaded via connection strings, plugin systems that discover packages at runtime, or packages consumed only through CLI entry points. It also cannot detect packages that are imported exclusively in test files unless those imports are included in the input. For high-risk production services, pair the prompt's output with a dry-run removal and a full CI pipeline run before merging any dependency changes. The prompt is a triage accelerator, not a replacement for build verification.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before wiring it into a CI pipeline or developer workflow.

01

Good Fit: Static Manifest Audits

Use when: You have a complete package.json, requirements.txt, Cargo.toml, or similar manifest alongside the full source tree. The prompt excels at cross-referencing declared dependencies against actual import statements to find dead weight. Guardrail: Run on a clean checkout of a single project; monorepos require per-package scoping to avoid false positives from shared utilities.

02

Bad Fit: Dynamic or Runtime Imports

Avoid when: The codebase uses dynamic import(), plugin systems, or reflection-based loading (e.g., Spring auto-configuration, Python entry points). The prompt cannot trace imports that aren't statically analyzable. Guardrail: Pair with a runtime import tracer or dynamic analysis tool before feeding results to the prompt; otherwise, removal candidates will include false positives for legitimately loaded packages.

03

Required Inputs

What you must provide: A dependency manifest file, the full source tree (or a pre-computed import map), and the project's build configuration. Without all three, the prompt cannot distinguish between test-only dependencies, build-time tooling, and genuinely unused packages. Guardrail: Pre-process imports with a static analysis tool and pass the structured import list as [CONTEXT] rather than relying on the model to parse raw source files accurately.

04

Operational Risk: False Positives in Monorepos

Risk: In monorepos or multi-package projects, a dependency unused in one package may be required by another. The prompt may flag it as bloat if scoping is too narrow. Guardrail: Always scope the audit to a single deployable unit and provide a list of internal packages that should be excluded from removal consideration. Human review is mandatory before removing any package flagged as unused.

05

Operational Risk: Peer and Transitive Dependencies

Risk: A package may appear unused at the top level but is required as a peer dependency or is relied upon transitively by another package that doesn't declare it properly. Removing it breaks the build. Guardrail: Include a dependency graph or lock file in the context and instruct the prompt to check whether any flagged package is a peer dependency or a transitive requirement of another declared dependency before recommending removal.

06

Not a Replacement for Bundle Analyzers

Risk: The prompt analyzes import statements, not compiled bundle size or tree-shaking effectiveness. A package may be imported but contribute negligible code after tree-shaking. Guardrail: Use this prompt for dependency hygiene (removing unused declarations), not for bundle size optimization. Pair with a bundle analyzer for size-specific decisions and treat the prompt's output as a cleanup candidate list, not a performance optimization report.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for auditing a project's dependencies against actual import usage to identify bloat and removal candidates.

The following prompt is designed to be pasted directly into your AI harness. It instructs the model to act as a platform engineering auditor, comparing a provided package manifest against the codebase's import statements. The goal is to produce a structured, actionable list of packages that are unused, duplicated, or unnecessarily pinned, along with a risk-justified removal recommendation.

text
You are a senior platform engineer auditing a project for dependency bloat. Your task is to analyze the provided [PACKAGE_MANIFEST] and [IMPORT_DATA] to identify packages that are declared but not used, are duplicated, or are pinned to an unnecessarily strict version.

## Inputs
- **Package Manifest:** [PACKAGE_MANIFEST]
- **Import Data:** [IMPORT_DATA]
- **Project Context:** [PROJECT_CONTEXT]

## Instructions
1.  **Cross-reference:** Compare every dependency declared in the manifest against the import statements found in the import data.
2.  **Categorize:** Classify each finding into one of the following categories:
    - `UNUSED`: Declared in the manifest but never imported.
    - `DUPLICATE`: The same package is declared multiple times or a sub-package is declared alongside its parent.
    - `OVERLY_PINNED`: The version is pinned to an exact patch when a looser range would be safe based on the project's usage.
    - `DEV_IN_PROD`: A package typically used for development (testing, linting, building) is declared as a production dependency.
3.  **Justify:** For each finding, provide a concise justification. For `UNUSED` packages, note if the package could be a peer dependency or is used in a build script not captured by the import scan.
4.  **Assess Risk:** Assign a removal risk level (`LOW`, `MEDIUM`, `HIGH`) based on the potential for breaking the build, runtime, or development workflow.

## Output Schema
Return a single JSON object with the following structure:
{
  "analysis_summary": {
    "total_dependencies": <number>,
    "unused_count": <number>,
    "duplicate_count": <number>,
    "overly_pinned_count": <number>,
    "dev_in_prod_count": <number>
  },
  "findings": [
    {
      "package_name": "<string>",
      "category": "UNUSED | DUPLICATE | OVERLY_PINNED | DEV_IN_PROD",
      "current_version": "<string>",
      "recommended_action": "<string>",
      "risk_level": "LOW | MEDIUM | HIGH",
      "justification": "<string>"
    }
  ]
}

## Constraints
- Do not flag packages that are used via dynamic imports or reflection unless you have clear evidence from the project context.
- If a package is a well-known peer dependency of another used package, note this in the justification and lower the risk level.
- If the import data is incomplete or ambiguous, state your assumptions clearly in the justification.
- Only return the JSON object. Do not include any other text.

To adapt this template, replace the placeholders with your actual data. [PACKAGE_MANIFEST] should contain the full content of your package.json, requirements.txt, Cargo.toml, or equivalent. [IMPORT_DATA] should be a pre-processed list of all import statements, which you can generate with a tool like grep or a static analysis script. [PROJECT_CONTEXT] is optional but highly recommended; it can include details like the build system used, known dynamic imports, or a list of scripts in package.json that might use otherwise unimported packages. For high-risk production systems, always have a senior engineer review the output before removing any packages.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate these before each run to prevent false positives on unused packages and false negatives on dynamically loaded modules.

PlaceholderPurposeExampleValidation Notes

[MANIFEST_PATH]

Path to the package manifest file to analyze

package.json, requirements.txt, go.mod, Cargo.toml

Must resolve to a readable file. Validate file exists and is not empty before prompt assembly.

[MANIFEST_CONTENT]

Raw content of the dependency manifest

Full text of package.json with dependencies and devDependencies

Parse as valid JSON, TOML, or plain text per ecosystem. Reject if unparseable or missing required dependency sections.

[IMPORT_MAP]

List of all import statements extracted from the codebase

import lodash from 'lodash'; require('express')

Must be generated by a static analysis tool, not manual entry. Validate non-empty array. Each entry must include source file path for traceability.

[ECOSYSTEM]

Target package ecosystem for resolution rules

npm, pypi, maven, cargo, go

Must match one of the supported enum values. Controls how peer dependencies, dev dependencies, and transitive packages are classified.

[ENTRY_POINTS]

Application entry point files to start the import graph traversal

src/index.ts, main.go, app/init.py

Validate each path exists in the repository. Missing entry points cause false unused-package classifications for root-level imports.

[DYNAMIC_IMPORT_PATTERNS]

Regex or glob patterns for dynamic imports and require calls

require(variable), import(variable), import(name)

Optional but strongly recommended. Absence increases false-positive rate for packages loaded via reflection, plugin systems, or dynamic configuration.

[EXCLUSION_LIST]

Packages to exclude from unused detection

eslint, prettier, jest, typescript

Validate each entry exists in the manifest. Use for build tools, test runners, and CLI-only packages that have no import footprint. Document reason for each exclusion.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the dependency bloat detection prompt into a CI pipeline, code review bot, or scheduled audit job with validation, retries, and human review gates.

This prompt is designed to run inside an automated workflow, not as a one-off chat interaction. The most common integration points are a CI pipeline triggered on manifest file changes (e.g., package.json, requirements.txt, Cargo.toml), a scheduled weekly audit job that scans the full repository, or a pull request bot that comments with removal candidates when a dependency is added. The harness must supply the prompt with a structured input containing the dependency manifest content, a list of all import statements extracted from the codebase, and any project-level constraints such as pinned packages that should be excluded from analysis. Without accurate import extraction, the prompt will produce false positives—flagging packages that are actually used but were missed by a naive grep.

Input assembly is the critical pre-processing step. Use a deterministic script to extract imports before calling the model: grep -rE '^(import|from|require|use) ' --include='*.py' --include='*.js' --include='*.ts' --include='*.rs' src/ or a language-specific AST parser for higher accuracy. Combine this with the raw manifest file content and any lock file data. The prompt's [MANIFEST_CONTENT] placeholder expects the full manifest text, [IMPORT_LIST] expects a deduplicated list of imported packages, and [PROJECT_CONSTRAINTS] can include known false positives to suppress (e.g., type stubs, test-only dependencies, build tools that are imported indirectly). Package the assembled input as a JSON object matching the prompt's expected schema before sending it to the model.

Model choice and validation matter for reliability. Use a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent) and request JSON output with a defined schema. Validate the response before acting on it: check that every removal candidate includes a non-empty package_name, justification, and risk_level field. Reject responses where the removal_candidates array is empty but the manifest contains packages not in the import list—this indicates the model missed something. Implement a retry loop with exponential backoff (max 3 attempts) for malformed JSON or schema validation failures. Log every response and validation result for auditability.

Human review gates are essential because removing a dependency can break runtime behavior that static import analysis misses—dynamic imports, plugin systems, configuration-driven loading, or packages required by transitive dependencies that your code doesn't import directly. Configure the harness to open a ticket or PR comment with the removal candidate list rather than automatically deleting packages. Require approval from a platform engineer or tech lead before any package is removed. For high-risk packages (those flagged with risk_level: high), add an additional review step that requires a second approver. The harness should also check whether any removal candidate is a direct dependency of another listed package by consulting the lock file—if so, suppress it from the removal list and log the reason.

Scheduled audit mode requires additional state tracking. Store the previous run's removal candidates and compare them to the current run. Packages that appear as removal candidates across multiple consecutive runs but remain in the manifest may indicate that the team has consciously chosen to keep them—suppress these from future reports or add them to a persistent allowlist. Packages that newly appear as removal candidates should be highlighted as high-priority findings. Integrate the output with your team's notification system (Slack, email, ticketing system) with a summary message: 'Found 3 unused packages (2 low risk, 1 medium risk). Review required.' Avoid alert fatigue by batching low-risk findings into a weekly digest rather than triggering per-run notifications.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact JSON structure, types, and validation rules for the dependency bloat detection prompt output. Use this contract to parse, validate, and integrate the model response into your CI pipeline or dependency audit tool.

Field or ElementType or FormatRequiredValidation Rule

analysis_summary.total_dependencies

integer

Must equal the count of entries in the dependencies array. Parse check: count array length.

analysis_summary.unused_count

integer

Must be >= 0 and <= total_dependencies. Parse check: count entries where removal_candidate is true.

analysis_summary.duplicated_count

integer

Must be >= 0 and <= total_dependencies. Parse check: count entries where is_duplicate is true.

dependencies[].package_name

string

Must match a package name from the provided [MANIFEST_FILE]. Schema check: non-empty string.

dependencies[].version_specified

string

Must match the version string exactly as it appears in [MANIFEST_FILE]. Schema check: non-empty string.

dependencies[].import_count

integer

Must be >= 0. A value of 0 indicates a candidate for removal. Parse check: integer validation.

dependencies[].removal_candidate

boolean

Must be true if import_count is 0, otherwise false. Consistency check: cross-field validation required.

dependencies[].removal_risk

string

Must be one of: 'low', 'medium', 'high'. Enum check: validate against allowed values. Set to 'high' if the package is a known build-time or CLI dependency not captured by import scanning.

dependencies[].risk_justification

string

Required if removal_candidate is true. Must provide a concrete reason referencing the package's role. Null allowed if removal_candidate is false. Null check: conditional requirement.

dependencies[].is_duplicate

boolean

Must be true if the same package name appears with different version constraints elsewhere in the manifest. Schema check: boolean type.

dependencies[].duplicate_of

string or null

Required if is_duplicate is true. Must contain the package_name of the primary or preferred version. Null allowed if is_duplicate is false. Null check: conditional requirement.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using LLMs to detect dependency bloat and how to guard against it.

01

Static Analysis Blindness

What to watch: The model cannot execute a build or resolve dynamic imports, so it misses packages loaded via require() variables, import() expressions, or plugin systems. Guardrail: Pre-process the codebase with a bundler or static analysis tool to generate a complete dependency graph, then provide that graph as [CONTEXT] to the prompt instead of raw files.

02

Monorepo Scope Creep

What to watch: The model conflates imports across multiple packages in a monorepo, flagging a package as unused globally when it is only used by a sibling workspace. Guardrail: Partition the analysis by workspace. Provide a package.json per workspace and restrict the import scan to that workspace's source tree. Use a separate prompt run per package.

03

Type-Only Import Hallucination

What to watch: The model misidentifies type-only imports (which are erased at runtime) as runtime dependencies, or conversely, ignores a package that is required for build tooling or code generation. Guardrail: Explicitly instruct the model to classify each dependency as runtime, dev, build, or type-only in the output schema. Cross-reference with devDependencies vs dependencies in the manifest.

04

Peer Dependency Misattribution

What to watch: The model flags a package as unused because it is not directly imported, but it is a peer dependency required by another library at runtime. Guardrail: Provide the peerDependencies map from the manifest as explicit [CONSTRAINTS]. Instruct the model to never flag a peer dependency for removal without a human approval flag.

05

Overly Aggressive Removal Recommendations

What to watch: The model confidently recommends removing a package that is used in a script tag, a configuration file, or a CI pipeline that was not included in the source scan. Guardrail: Require the output to include a confidence score and a removal_risk field. Any package with a risk above low must route to a human review queue before a removal PR is created.

06

Lockfile Drift Mismatch

What to watch: The model analyzes the package.json but ignores the lockfile, missing that a package is a transitive dependency pinned for a security or compatibility reason. Guardrail: Always provide both the manifest and the lockfile. Instruct the model to cross-reference removal candidates against the lockfile's dependency graph and flag any package that appears as a transitive dependency of a kept package.

IMPLEMENTATION TABLE

Evaluation Rubric

How to test output quality before shipping. Run these checks against a known test repository with seeded unused, duplicated, and pinned dependencies.

CriterionPass StandardFailure SignalTest Method

Unused Dependency Recall

All seeded unused packages appear in the removal candidate list

Any seeded unused package is missing from the output

Parse the output JSON against the ground-truth list of seeded unused packages. Check for exact package name match.

False Positive Rate on Active Dependencies

Zero active dependencies are flagged as unused

Any package imported in the test repo's source code appears in the removal list

Cross-reference the removal candidate list against a pre-computed set of actively imported packages. Flag any intersection.

Duplication Detection Accuracy

All seeded duplicated packages are identified with correct version resolution

A duplicated package is missed or the recommended version is not the highest declared version

Compare the output's deduplication list against the seeded duplicates manifest. Validate the 'recommended_version' field matches the expected resolution.

Pinned Dependency Justification

Every removal candidate for a pinned dependency includes a non-empty justification string

A pinned dependency appears in the removal list with a null or empty justification field

Schema validation on the output JSON. Assert that for each item in 'pinned_removal_candidates', the 'justification' field is a non-empty string.

Output Schema Compliance

The output is valid JSON matching the [OUTPUT_SCHEMA] exactly

JSON parsing fails or required fields like 'package_name' or 'removal_risk' are missing

Validate the raw model output against the provided JSON Schema. Check for missing required fields and incorrect enum values for 'removal_risk'.

Risk Classification Consistency

All removal candidates have a 'removal_risk' value of 'low', 'medium', or 'high'

A removal candidate has an unexpected risk value or the risk is 'high' for a devDependency with no imports

Assert that the 'removal_risk' field is one of the allowed enum values. Spot-check that a known test devDependency is not classified as 'high' risk.

Import Statement Parsing Robustness

Handles dynamic imports, require statements, and aliased paths without false positives

A package used via a non-standard import pattern is incorrectly flagged as unused

Include test files with dynamic imports and path aliases in the test repository. Verify the package does not appear in the removal list.

Handling of Empty or Missing Lock File

Returns an empty removal list and a specific warning message when no lock file is provided

The prompt hallucinates dependencies or throws an unhandled error

Run the prompt with [LOCKFILE_CONTENT] set to an empty string. Assert the output contains an empty list and a warning message indicating no lock file data was available.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single project manifest and a small set of source files. Accept a simple markdown table output without strict schema enforcement. Run interactively in a chat interface to explore findings before hardening.

Prompt modification

  • Remove strict [OUTPUT_SCHEMA] constraints; replace with: "Output a markdown table with columns: Package, Status, Justification."
  • Add: "If you are uncertain about a package, mark it as Review Needed rather than guessing."
  • Limit [CONTEXT] to one package.json or requirements.txt and one directory of imports.

Watch for

  • False positives on packages used via dynamic imports, reflection, or config files
  • Missing detection of test-only or build-only dependencies that are actually needed
  • Overly broad removal recommendations that break CI pipelines
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.