Sub topic 3
Catching Invented APIs and Outdated Library Usage in AI-Generated Code
Assume you can write basic Python, install packages with pip, run unit tests, and read library documentation. This chapter focuses on checking generated code before it reaches production.
Run the code: tests that expose wrong API usage
A generated call can look reasonable but still use a nonexistent function, an unsupported keyword, or removed behavior. Tests expose these errors when they execute the affected path.
import json
import unittest
def encode_record(record):
return json.dumps(record, indent=2)
class TestEncodeRecord(unittest.TestCase):
def test_uses_supported_json_keyword(self):
result = encode_record({"id": 1})
self.assertIn('"id": 1', result)
if __name__ == "__main__":
unittest.main()Run this with python test_encode.py. If generated code changed indent=2 to the invented keyword pretty=True, the test would fail with TypeError. Add tests for every generated integration path, not only for simple helper functions.
Verify suggested packages before installing them
Check that each suggested dependency exists in the package index, has the expected owner and documentation, and supports your Python version. Look for look-alike names and abandoned packages. Prefer a package already used by your project when it provides the needed feature.
Install a reviewed version and record it in the lockfile or requirements file. Do not accept a package merely because its name sounds familiar.
Give the model version and documentation context
Generated code is vulnerable to knowledge drift. Libraries change after the model's training data was collected. Include the runtime version, exact dependency versions, and relevant documentation links or excerpts in the prompt. Ask the model to avoid APIs absent from those versions and to identify uncertain claims.
Build a review checklist and CI guardrails
Before merging, check:
- Every imported package and symbol exists.
- Calls match the installed signatures.
- Versioned documentation confirms the behavior.
- Type checking and linting pass.
- Deprecation warnings fail CI.
- Tests execute each generated code path.
- Dependencies are reviewed and pinned.
Know what these checks will not catch
Passing tests cannot prove that every path was exercised. Static tools may miss runtime behavior, incorrect business assumptions, or an API that exists but returns an unsuitable result. Review security, data meaning, error handling, and performance separately.
Exercise
What should you provide in a prompt to reduce version-related API errors?
Show answer
Provide the runtime version, exact dependency versions, and relevant versioned documentation.