Sub topic 1
What goes wrong: invented, mis-signed, and outdated API calls
AI coding assistants write code that reads well and often runs. Sometimes it calls a function that does not exist, passes arguments the function never accepted, or uses behavior that a newer library version removed. This chapter defines those failure modes, shows an example of each, and explains why each one is hard to spot in review. Later chapters cover the checks that catch them.
Prerequisites
This chapter assumes you have:
- Working knowledge of Python or a similar language.
- Basic use of a package manager such as pip.
- Familiarity with running unit tests.
- Some experience reading library documentation.
The examples use Python. The same failure modes appear in every language with third-party libraries.
Why this problem deserves its own name
A syntax error stops you at once. A call to a wrong API often passes a quick read, because the name looks right and the surrounding code is clean. The model produces text that is statistically plausible. It does not look up your installed library before it writes.
An API (application programming interface) is the set of functions, classes, and arguments a library offers to your code. In this chapter, "API call" means any use of that surface: a function call, a method call, a keyword argument, or an attribute access.
There are four failure modes:
| Failure mode | What the code does | When it fails |
|---|---|---|
| Invented API | Calls a name that no version of the library ever had | At runtime, on the line that executes the call |
| Wrong signature | Calls a real function with arguments it does not accept | At runtime, or silently if the argument is swallowed |
| Outdated usage | Calls something that existed in an older version | On newer versions, or only as a warning |
| Nonexistent package | Imports or installs a package name that does not exist or is not the intended one | At install or import time, or never, if an attacker registered the name |
The sections below take them in turn.
Invented APIs
An invented API is a function, class, method, or module that the library does not have and never had. The model combines patterns it has seen. A library has requests.get and Response.json, so the model proposes a tidy shortcut that merges the two.
import requests
# Invented API: the requests module has no get_json function.
# data = requests.get_json("https://example.com/api")
# Real API: call get, then decode the body with Response.json().
response = requests.get("https://example.com/api", timeout=10)
data = response.json()The commented-out line looks plausible. If you ran it, Python would raise AttributeError: module 'requests' has no attribute 'get_json'.
Invented names tend to follow a few patterns:
- A shortcut that merges two real calls, as with
get_json. - A name borrowed from a similar library. Another HTTP library may have a helper that
requestslacks. - A method that would be convenient, so the model assumes it exists, such as
df.to_markdown_file(). - A real name placed on the wrong object, such as a method that lives on
Responsebut is called on therequestsmodule.
Invented APIs usually fail loudly, but only when the line runs. If the call sits in an error handler, a rarely used branch, or a cleanup path, it can ship and fail in production on the first uncommon event. This is why tests that reach every generated branch matter, and a later chapter covers them.
Wrong signatures
A signature is the list of parameters a function accepts: their names, order, types, and defaults. A wrong signature is a call to a real function that does not match it.
The function exists, so a search for the name finds it. The error is in the arguments.
import inspect
import json
sig = inspect.signature(json.dumps)
print(sig)
print("indent" in sig.parameters) # True
print("pretty" in sig.parameters) # Falsejson.dumps accepts indent, but not pretty. An assistant that writes json.dumps(data, pretty=True) has borrowed the idea from a tool in another language or from a different library. Because json.dumps also takes **kw (extra keyword arguments passed to the encoder class), the failure is TypeError at call time, from the encoder constructor. The error message points into the standard library rather than at the line you need to fix, which makes the cause easy to miss.
Common signature errors:
- A misspelled or invented keyword.
pretty=Trueinstead ofindent=2. - Swapped positional arguments. A function that takes
(source, destination)is called with(destination, source). Both are strings, so nothing complains until files go to the wrong place. - An argument from a different version. A parameter added in a later release, or renamed in one.
- A wrong return type assumption. Code treats a result as a list when the function returns an iterator, or as a string when it returns bytes.
- Silently ignored arguments. Some functions accept
**kwargsand discard what they do not recognize. The call succeeds and the option has no effect.
The last item is the dangerous one. A wrong signature that raises TypeError is caught the first time the code runs. A wrong signature that is silently accepted produces code that works and does the wrong thing, for example a timeout that never applies or a verification flag that is never read.
Outdated usage
Outdated usage means calling something that was valid in an earlier version of the library and has since been deprecated or removed. A deprecated feature still works but is scheduled for removal, and usually emits a warning. A removed feature raises an error.
The standard example is DataFrame.append in pandas. It was deprecated in pandas 1.4 and removed in pandas 2.0.
import pandas as pd
rows = [{"id": 1}, {"id": 2}]
# Outdated: DataFrame.append was removed in pandas 2.0.
# df = pd.DataFrame()
# for row in rows:
# df = df.append(row, ignore_index=True)
# Current: build the frame in one step, or use pd.concat.
df = pd.DataFrame(rows)The old code was correct for years, and many tutorials and repositories still contain it. A model trained on that material reproduces it with confidence. On pandas 1.x it works. On pandas 2.x it raises AttributeError. Same code, different environment, different result.
A second example is subtler, because the old call still runs:
from datetime import datetime, timezone
# Deprecated since Python 3.12: naive UTC timestamp.
# now = datetime.utcnow()
# Preferred: timezone-aware timestamp.
now = datetime.now(timezone.utc)datetime.utcnow() returns a naive datetime, one with no timezone attached. Comparing it with an aware datetime raises TypeError, and converting it to local time can give wrong answers. On Python 3.12 and later the call emits a DeprecationWarning. The code keeps working, so nothing forces you to fix it until the function is removed.
Outdated usage splits into three cases:
- Removed. The code fails with
AttributeErrororImportErroron current versions. - Deprecated. The code works and prints a warning that is hidden by default in many contexts.
- Behavior changed. The name and signature are the same, but the result differs. A changed default value is a typical cause.
The third case is the hardest to catch, because no error or warning appears. Only the documentation and changelog for the version you run will show it.
A look at how the failures relate
The four failure modes differ in where the mismatch lies: with the library's history, with its current surface, or with the package index.
The order matters for diagnosis. Check the package first, then the name, then the arguments, then the version. A failure at an earlier step makes later steps meaningless.
Why these errors survive review
Several properties of generated code let these errors through.
- Fluent surface. The code is well formatted, uses consistent naming, and carries sensible comments. Reviewers read fluent code as correct code.
- Plausible names. An invented name follows the library's naming conventions, so it does not stand out.
- Lazy failure. Python resolves attribute names when a line executes, not when the file loads. A bad call in an unexecuted branch is invisible until that branch runs.
- Silent acceptance. Functions with
**kwargsswallow bad arguments. - Hidden warnings. Python ignores
DeprecationWarningby default unless it is triggered directly by code in__main__. Deprecated calls inside your own modules typically pass unnoticed. - Version blindness. The reviewer reads the code without knowing which library version it was written for, and so does the model.
Nonexistent and look-alike packages
The fourth failure mode moves from code to dependencies. An assistant may suggest pip install for a package that does not exist, or import a module name that differs from the package name.
This matters for two reasons. First, the install fails and you lose a few minutes. Second, and more seriously, an attacker can register a name that models tend to invent. If you install it without checking, you run the attacker's code. This is a supply-chain risk, and it is the reason later chapters treat package verification as a security check, not a convenience.
Related errors are less dramatic but common:
- Import name differs from package name. You install
pillowbut importPIL. You installbeautifulsoup4but importbs4. An assistant can mix these up. - Look-alike names. A package named almost like a popular one (
requestversusrequests) may be unrelated or malicious. - Abandoned or renamed packages. The name exists but points to a project that is no longer maintained, or that moved elsewhere.
A package that exists on the index is not necessarily the one you intended. Existence is a weaker check than identity.
A short worked comparison
Suppose an assistant produces this helper:
import json
from datetime import datetime
import pandas as pd
import requests
def fetch_report(url):
data = requests.get_json(url)
df = pd.DataFrame()
for row in data["rows"]:
df = df.append(row, ignore_index=True)
df["fetched_at"] = datetime.utcnow()
return json.dumps(df.to_dict("records"), pretty=True, default=str)Each line shows a different failure mode:
| Line | Problem | Category |
|---|---|---|
| `requests.get_json(url)` | No such function | Invented API |
| `df.append(row, ...)` | Removed in pandas 2.0 | Outdated usage |
| `datetime.utcnow()` | Deprecated in Python 3.12, returns a naive value | Outdated usage |
| `json.dumps(..., pretty=True)` | `pretty` is not a parameter | Wrong signature |
Four problems sit in six lines of tidy code. Execution reaches the first one on line one of the function, so a single test would expose it. But after you fix that line, the next error appears, and fixing one at a time without understanding the pattern is slow. A systematic routine is faster, and the rest of this tutorial builds one.
What to take forward
Each failure mode has a different detector:
- Invented names are caught by checking that the symbol exists.
- Wrong signatures are caught by comparing arguments to the signature.
- Outdated usage is caught by knowing your installed version and by surfacing deprecation warnings.
- Nonexistent packages are caught by verifying them before installation.
All four share a root cause: the model wrote from memory of a library, not from your installed copy of it. The next chapters explain how that gap arises and how to close it.
Exercise
An assistant writes response = requests.get(url, timeout=10, retries=3). The call raises no error and the requests are never retried. Which failure mode is this, and why did it go unnoticed? What would you check first?
Show answer
This is a wrong signature. requests.get has no retries parameter, but it forwards extra keyword arguments in **kwargs to lower-level request code, and the unrecognized option has no effect (depending on version, it may raise TypeError; either way the retry behavior you wanted does not exist). Retries in requests are configured by mounting an HTTPAdapter with a Retry object on a session. First check the signature of requests.get and the documentation for the installed version, and confirm in a test that a failing request is actually retried.
Exercise
A generated snippet uses df.append(row, ignore_index=True). It works on a colleague's machine and fails on yours with AttributeError. Name the failure mode and give two ways to find the cause.
Show answer
This is outdated usage. DataFrame.append was removed in pandas 2.0, and your colleague likely has pandas 1.x installed. To confirm, print the installed version with importlib.metadata.version("pandas") (or pip show pandas) on both machines, and check the pandas 2.0 release notes for the removal. The fix is to build the frame with pd.DataFrame(rows) or to use pd.concat.
Exercise
Why can a deprecated call such as datetime.utcnow() remain in a codebase for months even though tests pass?
Show answer
A deprecated call still works, so tests pass. Python also hides DeprecationWarning by default unless the warning is triggered directly by code in __main__, so the warning does not appear in normal output. Nothing signals the problem until the function is removed. Turning warnings into errors during tests surfaces it earlier.