How do you keep AI-generated Python code from drifting away from the architecture?

November 12, 2026 5 answers
Asked by if-available.try-again

AI tools were quick to get a FastAPI project started, but as the codebase grows they keep putting business logic in routes and mishandling async database sessions. Refactoring the output is starting to eat up the time saved.

How are you keeping generated code aligned with the architecture in a larger Python project?

Answers

Peppish

Write down the boundaries in a form the tool can use. For example, say that routes handle HTTP concerns, services own business logic, and explain where async sessions are created and passed. Keep separate notes for database and backend conventions if one giant instruction file gets unwieldy.

For each task, point it at a representative implementation and the relevant conventions. Then review the diff against those rules. Documentation helps, but it won't reliably enforce itself.

8fold.index.card:

Keeping a good example current matters too. If the reference implementation has drifted, the tool can reproduce that drift.

Reply to this answer
no_celery_after_midnight

Turn the rules you can define precisely into automated checks. Tests can enforce dependency boundaries or verify session handling patterns, so violations get caught before review. Run those checks on AI-generated changes just as you would on any other changes.

Not every design decision fits neatly into a test. Use the checks for clear rules and leave the subtler factoring decisions to review.

Reply to this answer
Trundly

Give it narrower jobs. Name the files and existing functions it should follow, explain the layer the change belongs in, and inspect the result before asking for the next piece. A request to build a whole feature leaves a lot of room for it to invent its own structure.

Reply to this answer
~plausible+but!wobbly

This isn't only an AI problem. People unfamiliar with a codebase also need examples and review to learn where responsibilities belong. Treat the generated diff as a contribution that needs the same scrutiny, especially around business logic and database lifetimes.

Reply to this answer
Knicksy

It may also be worth limiting where you use it. Prototypes, small scripts, and isolated tasks can be good candidates, while a cross-cutting feature in a large codebase might need enough direction and cleanup that writing it directly is quicker.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions