Sub topic 7
Checking that packages and APIs are real
This chapter assumes you can read a diff, install packages with a package manager such as pip or npm, and run short Python scripts. It covers one review step: confirming that every package, function, and parameter in an AI-written change exists, is the right one, and works the way the code assumes.
Why existence is not a given
A language model predicts text that looks right. It does not look names up in a registry or in the library's source. When it writes import fastjson_utils or client.fetch_all(retry=True), the name is plausible because similar names appear in its training data. The package or method may not exist.
There are three kinds of failure:
- Invented packages. The import names a package that is not published.
- Invented members. The package is real, but the function, class, or parameter is not.
- Wrong version. The API existed in another release. It may have been removed, renamed, or changed since, or it may not exist yet in the version you pin.
An invented package name is also a supply-chain risk. Attackers can register names that assistants tend to invent, then publish malicious code under them. This is sometimes called slopsquatting, a relative of typosquatting. If you run pip install on an unverified name from AI output, you may execute an attacker's install script.
Step 1: Find every new dependency in the diff
Start by listing what the change adds. Dependencies appear in two places: manifest files, and import statements in the code.
git diff -U0 -- requirements.txt pyproject.toml package.json
git diff -U0 | grep -E '^\+\s*(import|from)\s'The first command shows changed manifest lines. The second shows added Python imports. Compare the two lists. Look for these cases:
- An import with no matching manifest entry. The code would fail on a clean machine, or it relies on a transitive dependency (a package pulled in by another package) that may disappear.
- A manifest entry that nothing imports. This is clutter and extra attack surface.
- A new name that is one character away from a popular package, for example
reqeustsorpython-dateutils.
Step 2: Confirm the package exists and is the right one
For each new name, ask the official registry, not the assistant.
pip index versions requests
npm view express name version time.createdBoth commands return an error for unpublished names. pip index is marked experimental, so its output format can change. The script below does the same check through the PyPI JSON API and also reports when the package first appeared and how many releases it has.
import json
import sys
import urllib.error
import urllib.request
def pypi_summary(name: str):
"""Return basic facts about a PyPI project, or None if it is not published."""
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
uploads = [
f["upload_time_iso_8601"]
for files in data["releases"].values()
for f in files
]
return {
"latest": data["info"]["version"],
"summary": data["info"]["summary"],
"releases": len(data["releases"]),
"first_upload": min(uploads) if uploads else None,
}
if __name__ == "__main__":
for pkg in sys.argv[1:]:
info = pypi_summary(pkg)
print(f"{pkg}: {'NOT FOUND' if info is None else info}")Run it as python check_pkg.py requests some-made-up-name. A 404 means the name is not on PyPI. Do not "fix" it by guessing a similar name. Go back to the requirement and decide what the code needs.
A name that exists is still not proof that it is the right package. Check these signals:
| Signal | Why it matters | Warning sign |
|---|---|---|
| First upload date | Squatted names are often new | Created days or weeks ago, with a name an assistant might invent |
| Release count and history | Established projects have steady releases | One release, or many releases in one day |
| Project links | Lets you find the source repository | No repository, or a repository that does not match the package |
| Maintenance | Unmaintained code gets no security fixes | No release in years, with open security issues |
| License | It must be compatible with your project | Missing or unexpected license |
| Existing use | Your team may already have a standard library for this task | A second package that duplicates one you already depend on |
The last row matters in practice. If the project already uses httpx, a change that adds requests for one call is a design problem even though both packages are real.
Step 3: Confirm the API exists
A real package can still be used wrongly. Check each function, class, and parameter the change calls. Two checks are cheap: look in the documentation for the version you pin, or ask the interpreter.
import importlib
import inspect
def api_exists(module_name: str, dotted_path: str) -> bool:
"""Return True if module_name exposes the attribute at dotted_path."""
obj = importlib.import_module(module_name)
for part in dotted_path.split("."):
if not hasattr(obj, part):
return False
obj = getattr(obj, part)
return True
print(api_exists("json", "loads"))
print(api_exists("json", "parse_string"))
print(inspect.signature(__import__("json").dumps))This prints True, then False, then the real signature of json.dumps. The signature shows which parameters exist. Run the check in the project's own environment, because the installed version decides the result.
For compiled libraries, inspect.signature may fail. Use help() or the documentation instead. In JavaScript or TypeScript, a type checker does this work for you, provided the package ships type definitions. Chapter material on type checkers covers that in more depth.
Step 4: Check the version
Most API errors in otherwise well-formed code are version mismatches. Check three things:
- The version your project pins or has installed. In Python,
importlib.metadata.version("package")returns it. - The version the code seems to be written for. Old patterns, such as deprecated methods, hint at older training data.
- Whether the manifest entry is pinned or bounded. An unbounded
packageline lets a later release change behavior silently.
If the AI used an API from a newer release, you have two options. Upgrade deliberately, with the changelog read and the test suite run, or rewrite the call for the pinned version. Do not let a change quietly bump a major version.
Putting the checks in order
The last step matters. An API can exist and still behave differently from what the generated code assumes: a different return type, a different default, or a different exception. A test that calls the real library is the final evidence.
Common mistakes
- Trusting the assistant's own confirmation. Asking the same assistant "does this package exist?" produces another prediction. Use the registry.
- Checking only the package name. A real package with a made-up method passes Step 2 and fails in production.
- Checking only the happy path. Some invented calls sit in error handling code that tests never reach. Read those branches, or write a test that reaches them.
- Installing first and reviewing later. Install scripts run during installation. Verify before you install.
- Skipping the lockfile. Commit the updated lockfile, and check that it lists only the packages you expect.
Exercise
An AI-written change adds import datafusion_tools and the line datafusion_tools.load(path, strict=True). You run pip index versions datafusion-tools and it returns a version list, with the first release two weeks ago and no source repository link. What do you do, and in what order?
Show answer
Do not install it yet. A name that exists is not enough, and the package is new and has no repository, which matches the squatting pattern. First check the original requirement and whether a library the project already uses covers the need. If the package is still wanted, read its published source and metadata in the registry. Then confirm that load exists and accepts strict in the version you would pin, checking the documentation or the source. If you cannot verify the package, reject the dependency and ask for a revision that uses a trusted library. If you keep it, pin the version, update the lockfile, and add a test that calls load with real input.