Sub topic 10
Give the Model Version and Documentation Context
This chapter assumes you can read Python, install packages with pip, run a test suite, and look up a function in library documentation. It also assumes you have read the earlier chapters on why generated code drifts from the installed library (knowledge drift) and on pinning down the versions you run. Here we use those versions as input. The goal is to reduce errors before they happen by telling the model what it is writing for.
Why context changes the output
A model writes code from patterns learned during training. It does not look at your machine. If you ask for "a function that fetches JSON with requests", it returns the most probable code given its training data. That code may match an older release, a newer one, or a blend of several.
Adding facts to the prompt narrows the set of plausible answers. Three kinds of facts matter most:
- The language and library versions you run.
- The real signatures and documentation text of the functions involved.
- The rules of your project, such as "no new dependencies" or "no deprecated calls".
This is prevention, not verification. A model can still ignore the context or invent a call anyway. Every check from the other chapters still applies. Context lowers the rate of errors those checks have to catch.
What to put in the prompt
Not every fact is worth the space. Prompt length is limited, and long prompts can bury the important lines. Include the facts that change which API is correct.
| Context item | How to get it | Error it prevents |
|---|---|---|
| Python version | `sys.version` or `platform.python_version()` | Syntax or standard-library calls that do not exist in your release |
| Library versions | `importlib.metadata.version` | Calls from a newer or older major version |
| Real signatures | `inspect.signature` | Wrong or invented keyword arguments |
| Docstring or changelog excerpt | Docs for your version | Outdated behavior, removed methods |
| Project constraints | Your own conventions | Unwanted dependencies, deprecated patterns |
| Failing error message | Test output or traceback | Repeating the same mistake on a retry |
Collect versions with a script
Do not type versions from memory. Generate them. The script below prints a block you can paste at the top of a prompt.
import platform
import sys
from importlib.metadata import PackageNotFoundError, version
def environment_report(distributions):
"""Return a short text block describing the runtime and chosen packages."""
lines = [
f"Python {platform.python_version()} ({platform.python_implementation()})",
f"Platform: {sys.platform}",
]
for name in distributions:
try:
lines.append(f"{name}=={version(name)}")
except PackageNotFoundError:
lines.append(f"{name}: not installed")
return "\n".join(lines)
if __name__ == "__main__":
print(environment_report(["requests", "pandas", "pydantic"]))The "not installed" line is useful. If the model sees that a package is missing, it should not use it without telling you. Without that line, the model may assume the package is present.
If your project has a lock file, you can paste the relevant lines instead. To list everything installed in the active environment, run:
python -m pip freezePasting the whole list is usually too much. Pick the libraries the task touches, plus the framework they run inside.
Name the version in plain words
Put the version next to the instruction, not only in a block at the top. Compare these two prompts:
Write a function that appends rows to a DataFrame.Environment: Python 3.12, pandas 2.2.
Write a function that builds a DataFrame from a list of dict rows.
DataFrame.append was removed in pandas 2.0, so do not use it.The second prompt does two things. It states the version, and it names a specific trap. Naming known traps is cheap when you already know them. Your team can keep a short list of removed or deprecated calls for the libraries it uses and paste the relevant lines.
Supply real signatures and documentation
Versions tell the model which release you use, but the model may not remember that release's API well, especially for smaller or newer libraries. You can close that gap by pasting the actual signature and docstring of the functions you want it to call.
The script below resolves a dotted name, then prints its signature and the first lines of its docstring.
import importlib
import inspect
def load(dotted_name):
"""Import the longest module prefix, then walk the remaining attributes."""
parts = dotted_name.split(".")
for i in range(len(parts), 0, -1):
try:
obj = importlib.import_module(".".join(parts[:i]))
except ModuleNotFoundError:
continue
for attr in parts[i:]:
obj = getattr(obj, attr) # AttributeError if the name is invented
return obj
raise ModuleNotFoundError(dotted_name)
def api_excerpt(dotted_name, max_doc_lines=15):
"""Return the signature and start of the docstring for a named object."""
obj = load(dotted_name)
try:
signature = str(inspect.signature(obj))
except (TypeError, ValueError):
signature = "(signature unavailable)"
doc = inspect.getdoc(obj) or "(no docstring)"
doc_lines = doc.splitlines()[:max_doc_lines]
return f"{dotted_name}{signature}\n" + "\n".join(doc_lines)
if __name__ == "__main__":
print(api_excerpt("json.dumps"))Running it on json.dumps prints the real parameter list, including indent. A model that sees this has no reason to suggest a pretty argument.
There are two limits to know about:
- Some objects have no inspectable signature. Built-in functions implemented in C sometimes raise
ValueErrorfrominspect.signature, which is why the script catches it. In that case, paste the documentation text instead. - A docstring describes the installed version, which is what you want. A web page found by a search may describe a different one. Prefer the local source of truth, and check the version selector when you copy from online docs.
Paste changelog text for migrations
When you upgrade a library, the old patterns in the model's memory are the main risk. Copy the relevant section of the release notes or migration guide into the prompt. For example:
Environment: Python 3.12, pandas 2.2.
Migration note from the pandas 2.0 release notes:
- DataFrame.append was removed. Use pandas.concat or build the frame from a list of rows.
Task: update the function below so it works on this version. Keep behavior the same.Quote only the relevant lines. A whole changelog dilutes the one fact that matters.
Write instructions that make errors visible
The way you phrase the request affects whether a mistake can be spotted. Useful instructions include:
- "Use only functions that appear in the excerpts below. If you need another function, say so instead of guessing."
- "List every third-party function you call, with the module it comes from."
- "If you are unsure whether an argument exists in this version, mark the line with a comment
# VERIFY." - "Do not add new dependencies. If one is required, name it and explain why."
These instructions do not make the model more correct. They make its uncertainty and its assumptions easier to find. A list of called functions turns review into a short checklist: run each name through your load helper, and any invented name fails immediately.
names = ["requests.get", "requests.get_json", "json.dumps"]
for name in names:
try:
load(name)
print(f"ok {name}")
except (AttributeError, ModuleNotFoundError):
print(f"MISSING {name}")This snippet reuses load from the previous script, so run it in the same file or import the helper. With the requests library installed, requests.get_json is reported as missing, and the other two are reported as present.
Common errors with context
Giving context introduces its own mistakes. These come up often.
The context is wrong
You paste versions from one environment, but the code runs in another, such as a container, CI runner, or production host. The model writes correctly for the wrong release. Generate the report in the same environment where the code runs, or pin the same versions in all of them.
The context is stale
Docs and excerpts copied last month may describe a version you have since upgraded. Regenerate excerpts when dependencies change. Storing the generated report beside the lock file makes it easy to see when it is out of date.
The context is too long
A prompt packed with entire modules and changelogs makes it more likely that the model overlooks a key line. Keep each excerpt to what the task touches. If a task needs many functions, split it into smaller tasks, each with its own excerpts.
The model prefers its memory
Even with the correct signature in the prompt, a model may produce a call that matches an older pattern. This happens more often when the prompt is long or the instruction is buried. Repeat the critical rule close to the task statement, and always run the output through the checks from the earlier chapters.
Secrets and private code leak into the prompt
Environment reports and error messages can include paths, hostnames, tokens, or internal package names. Review what you paste before sending it to any external service. The report script above only prints versions and the platform name, which keeps this risk low. Pasted tracebacks and pip freeze output deserve a closer look. A pip freeze may include internal package names or private index URLs.
A reusable prompt template
Combine the pieces into a template you fill in per task.
Environment:
<output of environment_report>
Constraints:
- Use only the functions shown in the excerpts, or standard-library functions.
- Do not add dependencies.
- Do not use deprecated APIs. Known removed calls: <list>.
Reference excerpts:
<output of api_excerpt for each function the task needs>
Task:
<what you want, in one or two sentences>
Output:
- The code.
- A list of every third-party function called, with its module.
- A comment "# VERIFY" on any line where you are not sure the API exists in this version.After you receive the code, run the checks from the earlier chapters. If one fails, add the error message and the correct signature to the prompt and ask for a fix. That is the loop in the diagram: each failure becomes new, accurate context for the next attempt.
Summary
- Context reduces errors but does not verify anything. Keep the checks.
- Generate versions and signatures from the running environment instead of typing them from memory.
- Paste only the excerpts the task needs, and use the version-matched docstring or changelog text.
- Ask the model to list the third-party functions it calls, so you can check each one.
- Regenerate the context when dependencies change, and keep secrets out of it.
Exercise
You paste a report that says pandas==2.2.0, but the model still writes code that calls DataFrame.append. Name two changes to the prompt or process that would reduce the chance of this happening again, and say which check would catch the problem if it happens anyway.
Show answer
Put the specific trap in the prompt, for example "DataFrame.append was removed in pandas 2.0, so use pandas.concat or build the frame from a list of rows", and place that rule next to the task statement instead of only in the header. Also paste the relevant release-note lines and ask the model to list the pandas functions it calls. If the call still appears, a test run on the installed version fails with an AttributeError, and the existence check with the load helper reports that the name is missing. Promoting DeprecationWarning to an error would also catch calls that are deprecated but not yet removed.
Exercise
Why is it better to produce the version report with a script than to write "I use the latest requests" in the prompt?
Show answer
"Latest" is relative to when the model's training data ended and to when you read the sentence, not to the environment that runs the code. A script reads the version actually installed, in the same environment where the code runs, so the model sees an exact number. The script also reports packages that are not installed, which tells the model it must not rely on them.