Skip to main content

Explain and Document Code with AI

Level: Intermediate · Time: 30–40 min · Category: Command line

Tags: Python · OpenAI SDK · Developer tools

Build a CLI that reads a Python file and asks the Research Computing OpenAI-compatible API to explain it in plain English, then to suggest docstrings. It is a useful tool for understanding inherited research code.

Prerequisites

Confirm Python 3 and pip are available before you start:

New to this? What are Python and pip?

Python is the programming language these tutorials use. You run a Python program by typing python (or python3) followed by the file name.

pip is Python's package installer. It downloads add-on libraries your program needs (like the OpenAI SDK) from the internet. It comes with modern Python installs, so you do not install it separately.

Install Python 3.9 or newer. Pick your operating system:

macOS: download the latest installer from python.org/downloads, open the .pkg, and click through it. If you use Homebrew, you can instead run brew install python.

Linux: most distributions already include Python 3. If not, install it with your package manager, for example sudo apt install python3 python3-pip (Debian/Ubuntu).

On the supercomputer

Do not install your own Python. Load a provided module instead — for example module load python — then run the checks below.

Now confirm Python and pip work. Each should print a version number:

python3 --version      # expect 3.9 or newer
python3 -m pip --version
If a command is "not found"

This almost always means your terminal was open before you installed Python, or the "Add to PATH" box was left unchecked on Windows. Fully quit and reopen the terminal and try again; if it still fails, reinstall using the steps above.

What you will do

  • Create a Python CLI workspace with the OpenAI SDK.
  • Read a source file and send it to the API.
  • Ask for a plain-English, function-by-function explanation.
  • Add a docstring-suggestion mode you review before applying.

Build it step by step

1. Create the CLI workspace

mkdir code-explainer
cd code-explainer
python3 -m venv .venv
source .venv/bin/activate
pip install openai python-dotenv rich
Keep this out of Git

If you track this project with Git, do not commit your virtual environment or any secrets. Create a .gitignore file in the project folder with at least these lines:

.gitignore
.venv/
.env
__pycache__/

.venv/ is large and specific to your machine, and .env holds your API key — neither belongs in a shared repository. New to Git? See Track a New Project with Git.

2. Add API connection values

Your program needs three values to reach the API: your API key, the gateway URL, and a model ID. You keep them in a small text file named .env so they stay out of your code — and out of Git.

What is a .env file, and where does it go?

A .env ("dot-env") file is a plain text file that stores settings as NAME=value lines, one per line. Programs read it at startup so you never have to paste secrets like API keys directly into your code.

  • The filename is literally .env — a leading dot with nothing before it (not config.env or .env.txt).
  • It goes in your project folder: the same directory you just created, where the .venv lives and where you run your commands.
  • The python-dotenv package loads it with load_dotenv(), which looks for .env in the folder you run the program from.
  • Because it holds a secret, never commit it to Git (see the note below).

Create a new file named .env in your project folder — in VS Code use File → New File, or run code .env in the terminal — then paste these three lines and replace the placeholders:

.env
OPENAI_API_KEY="paste-your-key-here"
OPENAI_BASE_URL="https://openai.rc.asu.edu/v1"
RC_LLM_MODEL="paste-model-id-here"
Where do the values come from?

Get your API key and a valid model ID from the LLM API guide. The OPENAI_BASE_URL above is already correct for the Research Computing gateway.

  • Use the /v1 base URL, not the full /chat/completions URL, for the Python SDK.
  • Use a model ID that appears in the voyager model list for your account.
  • Keep .env out of Git: add a line containing .env to your .gitignore (see Track a New Project with Git).

3. Pick a file to explain

Use a small Python file you already have, or create a short sample so you can see the tool work.

cat > sample.py <<'PY'
def load_values(path):
with open(path) as f:
return [float(line) for line in f if line.strip()]

def mean(values):
return sum(values) / len(values)

if __name__ == "__main__":
import sys
print(mean(load_values(sys.argv[1])))
PY

4. Ask for the first explainer

You are helping me build a beginner Python CLI that explains a Python file using an OpenAI-compatible API.

Project goal:
- Command: python explain.py sample.py
- Read the source file as text.
- Send it to the chat completions API through the OpenAI Python SDK.
- Print a plain-English explanation of what the file does, function by function.
- Read OPENAI_API_KEY, OPENAI_BASE_URL, and RC_LLM_MODEL from a .env file.

Constraints:
- Keep the first version in one file named explain.py.
- Add friendly errors for a missing file, missing API key, or API failure.

Please:
1. Create explain.py.
2. Explain how the source is sent to the model.
3. Show the command to run it on sample.py.

5. Add a docstring mode

Please add a --docstrings mode to explain.py:

Behavior:
- With --docstrings, ask the model to suggest a Google-style docstring for each function.
- Print the suggestions to the terminal only. Do not modify the source file.

Constraints:
- Keep the plain-English explanation as the default mode.
- Explain how to run the new mode.

6. Add one feature of your own

Please add one focused feature to explain.py:

Feature:
- Accept a folder path and explain each .py file in it, one at a time.

Constraints:
- Keep single-file mode working.
- Keep the code beginner-readable.
- Explain how to test the folder mode.

More prompts to try

  • Add a --summary mode that prints a one-paragraph overview of the whole file.
  • Ask the model to flag risky patterns such as bare except or hard-coded paths.
  • Add a --write option that inserts reviewed docstrings, and remind me to commit first.

Troubleshooting

  • For large files, ask the assistant to split the file by function with the ast module before sending it.
  • Always read AI-suggested docstrings. They can describe intent incorrectly.
  • If you add a --write option, commit your file to Git first so you can undo unwanted edits.
  • If you get a model error, use a model ID from the voyager model list for your account.

Next steps