Skip to main content

Dependencies in Code Generation Prompts

When generating code that depends on external libraries—frameworks, databases, or third-party packages—you must tell the AI model which libraries are available, their versions, and how they should be used. A 2024 Stack Overflow survey found that 58% of code generation failures were due to mismatched or outdated dependencies, highlighting how critical this is for successful code generation.

Types of Dependency Constraints

Allowed dependencies. Specify which libraries the generated code may use.

Allowed dependencies:
- numpy 1.24+ (numerical computing)
- pandas 2.0+ (data manipulation)
- sqlalchemy 2.0+ (ORM)
- requests 2.31+ (HTTP client)
- Standard library (json, csv, re, asyncio, etc.)

NOT allowed:
- scipy (too heavy for this use case)
- django (reserved for the main app)

Required dependencies. Specify libraries the code must use.

Must use:
- FastAPI 0.104+ (already in our stack)
- Pydantic 2.0+ (data validation)
- sqlalchemy (existing database layer)

Version constraints. Specify exact versions or ranges based on your project.

Library versions in use:
- Python 3.11 (not 3.10, not 3.12 yet)
- PostgreSQL 14+ (driver: psycopg2 2.9.6)
- Node.js 18 LTS (not 20, not 16)
- Rust 1.75 (async: tokio 1.35+, not 1.34)

Handling Version-Specific Behavior

Library behavior changes between versions. Specify which APIs to use:

Language: Python 3.11
SQLAlchemy version: 2.0.20 (NOT 1.4)

Behavior:
- Use SQLAlchemy 2.0 patterns: Session() context managers, not SessionLocal()
- Use from sqlalchemy import select (not session.query())
- Type hints with sqlalchemy.orm.DeclarativeBase (not declarative_base())

Similarly for JavaScript:

Language: JavaScript / Node.js 18+

Dependencies:
- React 18+ (use hooks, not class components)
- Next.js 14+ (use app router, not pages router)
- TypeScript 5.1+ (strict mode enabled)

Conflict and Compatibility Issues

If your project has conflicting requirements, mention them:

Constraint: Our project uses Django 4.2, which includes Django ORM.
For this function, you MAY NOT use SQLAlchemy (it conflicts with Django ORM).
Use Django ORM: from django.db import models.

If the function needs database access, use:
- QuerySet API (models.User.objects.filter(...))
- Not raw SQL unless unavoidable
- Not SQLAlchemy models

Or for async:

Constraint: Our async functions run on asyncio (Python standard library).
You MUST NOT use:
- threading module (blocking)
- requests library (blocking HTTP; use aiohttp instead)
- time.sleep() (blocking; use asyncio.sleep())

You MUST use:
- async def / await syntax
- asyncio.gather() for concurrency
- aiohttp for HTTP requests

Real Example: Web Framework Dependencies

Prompt to generate a user authentication handler in FastAPI:

Language: Python 3.11
Framework: FastAPI 0.104.1

Project dependencies (must use):
- FastAPI 0.104.1
- Pydantic 2.0.2 (for data validation)
- sqlalchemy 2.0.20 (for database ORM)
- python-jose 3.3.0 (for JWT tokens)
- passlib 1.7.4 (for password hashing)
- python-multipart 0.0.6 (for form parsing)

NOT allowed:
- Django (separate project)
- custom authentication libraries
- deprecated sqlalchemy 1.4 patterns

Function to generate:
def authenticate_user(email: str, password: str, db: Session) -> User | None:

Requirements:
1. Query users table for the given email (use sqlalchemy select())
2. If user not found, return None
3. If user found, verify password with passlib.context.verify()
4. If password matches, return User object; otherwise return None
5. Use existing User model (defined in app.models.User)
6. Docstring with example

Example:
- authenticate_user("[email protected]", "SecurePass123", db)
where user exists with that email and password matches
Returns: User(id=1, email="[email protected]", ...)

- authenticate_user("[email protected]", "wrong_password", db)
Returns: None

Constraints:
- Type hints: required
- Use sqlalchemy 2.0 patterns: select(), not session.query()
- Use Pydantic v2 validation if needed

This prompt is clear about which libraries are required, which are forbidden, and how to use them idiomatically.

Dependency Discovery and Documentation

If you're not sure what the generated code should import, include examples from your codebase:

Project context: Our app uses FastAPI with SQLAlchemy.

Existing pattern (from auth/login.py):
```python
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from app.models import User
from app.schemas import UserCreate

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

async def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)

async def get_current_user(token: str, db: Session = Depends(get_db)) -> User:
# implementation
pass

New function should follow the same patterns and use the same imports where applicable.


By showing your existing patterns, the AI model can generate code that integrates smoothly with your codebase.

## Handling Missing or Optional Dependencies

Some functions are useful with or without certain libraries. Specify the fallback:

Preference order:

  1. Use the requests library if available (HTTP requests)
  2. Fallback to urllib.request (standard library) if requests not installed
  3. In the docstring, note: "Requires: requests library (optional)"

Requirements:

  • If requests is available, use it (better API)
  • If requests is not available, use urllib.request (stdlib fallback)
  • Never raise ImportError; gracefully degrade

Or specify a minimum-viable approach:

Constraint: No external dependencies allowed. Use only Python standard library.

For HTTP requests: use urllib.request (not requests) For JSON processing: use json module (not ijson) For date handling: use datetime (not dateutil) For parsing: use re (not regex)


## Table: Dependency Specification Examples

| Constraint Type | Example | Why It Matters |
|---|---|---|
| Version pinning | pandas 2.0.2 (exact) | Behavior changed in 2.0; 1.x is incompatible |
| Version range | sqlalchemy 2.0+ (>=2.0, <3.0) | New major version may break API |
| Forbidden libraries | No scipy | Performance, bloat, or conflict reasons |
| Conditional use | Use requests OR urllib | Graceful degradation |
| Async requirement | Must use asyncio, not threading | Project architecture constraint |

## Checking Dependency Compatibility

Before finalizing your prompt, verify:

1. **Library versions are installed** and compatible with your language version.
- Example: Python 3.11 + django 4.2 compatible? Check the Django docs.

2. **Dependencies don't conflict** (no two libraries that can't coexist).
- Example: Can't use both requests and httpx for HTTP in the same code (pick one).

3. **Versions match your actual project** (don't assume; check requirements.txt or package.json).

4. **APIs match the specified version.**
- Example: Pydantic v1 uses `Field()` syntax; v2 uses slightly different patterns.

## Key Takeaways

- Specify allowed and required dependencies; list forbidden ones.
- Always include library versions; behavior changes between versions.
- Show existing patterns from your codebase so generated code matches your style.
- Call out version-specific API changes (SQLAlchemy 1.4 vs 2.0, React class vs hooks).
- For optional dependencies, specify fallback behavior (graceful degradation).

## Frequently Asked Questions

### Should I always pin exact versions in my prompt?

Yes, for critical libraries (database drivers, async runtimes, async frameworks). For helper libraries, a range like `requests 2.28+` is fine. But always pin your main framework (FastAPI, Django, Spring, etc.) to the version you're actually using.

### What if the AI generates code using a deprecated API from an older library version?

Include a note in your prompt: "Deprecated patterns to avoid: SessionLocal() (use Session() context manager instead)." Or show the correct pattern in your existing-code examples.

### Can I use code generation to upgrade dependencies?

Partially. You can prompt: "Rewrite this function to use SQLAlchemy 2.0 patterns instead of 1.4." But for major version upgrades, it's safer to do a few functions at a time and test thoroughly.

### What if a library I want isn't available in the target environment?

Specify this constraint: "Use only libraries in requirements.txt: [list them]. If you need functionality not in that list, implement it from scratch." The AI model will work within your constraints.

### How do I handle transitive dependencies (dependencies of dependencies)?

Usually, you don't need to. If you specify the top-level dependency (e.g., FastAPI), the transitive dependencies (Starlette, Pydantic) come along automatically. Only mention transitive dependencies if you need to control their versions specifically.

## Further Reading

- [Semantic Versioning: 2.0.0](https://semver.org/)
- [Python Package Authority: Dependency Specifications](https://packaging.python.org/en/latest/specifications/)
- [npm: Dependency Management](https://docs.npmjs.com/cli/v10/configuring-npm/package-json)
- [Rust: Cargo Version Specification](https://doc.rust-lang.org/cargo/manifest.html)