Sub topic 1
Catching Invented APIs and Outdated Library Usage in AI-Generated Code
Prerequisites
Assume you know basic Python, package managers such as pip, unit tests, and how to read library documentation. This chapter focuses on checking generated code before you trust it.
What Goes Wrong
AI-generated code can fail in several ways:
- An invented API calls a function or attribute that the library never provided. For example,
requests.get_json()looks plausible, butrequestsprovidesget(); JSON decoding happens on the returned response. - A mis-signed call uses a real function with unsupported arguments, such as
json.dumps(data, pretty=True). - Outdated usage calls an API that existed in an earlier release. For example,
DataFrame.append()was removed in pandas 2.0.
These errors often look reasonable during review because names and arguments follow familiar patterns.
Why Generated Code Drifts
A model learns from examples collected at earlier times. Its training data may describe several library versions, outdated blog posts, or code written for a different framework. The model usually does not know which version your environment has installed unless you provide that context.
The result is version drift: generated code matches a plausible version, but not the version that runs your application.
Pin Down Your Versions
Record the versions used by the project before reviewing a suggestion:
python -m pip show requests
python --versionFor reproducible builds, pin dependencies in a lock file or requirements file. When asking for generated code, state the language version and relevant package versions. “Use pandas 2.2” gives a model a narrower target than “use pandas.”
Check the Symbol and Signature
Use introspection, which means examining objects while the program runs:
import inspect
import json
print(hasattr(json, "dumps")) # True
print(hasattr(json, "get_json")) # False
signature = inspect.signature(json.dumps)
print("indent" in signature.parameters) # True
print("pretty" in signature.parameters) # FalseThen compare the result with documentation for the installed version. A symbol can exist while its parameters or behavior differ. Test the important path as well, because introspection cannot prove that your arguments produce the intended result.
Exercise
What kind of error is json.dumps(data, pretty=True) if json.dumps exists but does not accept pretty?
Show answer
It is a mis-signed call. Python raises a TypeError for the unexpected keyword argument.