Bootstrap a Reproducible Python Environment for an LLM Project
System DesignModel answerLast updated
Walk through pinning a Python interpreter, isolating dependencies with a lockfile, securing API credentials, and verifying the setup with a live smoke test.
Setting Up a Reproducible Python Dev Environment for an LLM Project
You are starting a new project that calls a hosted LLM API (in this case, Mistral). Before writing any application logic, you need a local environment that another developer — or a CI machine — can recreate exactly from the repository.
Your task: describe and demonstrate how you would set up this environment from scratch. Specifically, cover each of the following layers:
- Interpreter management — pin a specific Python version so the project does not silently float to whatever Python happens to be installed on the machine.
- Virtual environment — isolate the project's packages from the system Python and from other projects.
- Dependency management with a lockfile — separate the declaration of what you need from the compiled, hashed record of exactly what gets installed.
- Secrets handling — store API keys in environment variables, never in source control. Provide a way for new contributors to know which variables are required.
- Project layout — organise files so the project is easy to run and test locally.
- End-to-end verification — write a short smoke-test script that makes a real API call, prints the model name the API reports back, and exits non-zero on failure.
What to show:
- The shell commands a new contributor would run after cloning the repo.
- The key configuration files (with relevant content).
- The smoke-test script and at least two unit tests that run without any network access.
- Where your approach could break and how you would handle it.
You may mention modern tooling (e.g. uv) but ground your answer in the underlying concepts — the goal is to show you understand why each step exists, not just that you know a command.
Hints
Hint 1
Think in four independent layers — interpreter, isolation, packages, configuration — and explain what goes wrong if any one of them is missing.
Hint 2
A lockfile is not the same as pinned versions in requirements.txt. What extra guarantee do hashes give you, and which tool produces them?
Hint 3
Your smoke test should exit with a non-zero code on failure, and your unit tests should never touch the network. How do you enforce that split?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is an environment that any machine can reproduce byte-for-byte from the repo. That means controlling four independent layers: the interpreter version, the package isolation boundary, the exact installed packages, and how secrets enter the process. A smoke test then exercises all four in one shot.
Layer 1 — Pin the Interpreter with pyenv
pyenv install 3.12.4
cd my-llm-project
pyenv local 3.12.4 # writes .python-version — commit this file
python --version # confirms: Python 3.12.4
.python-version is a one-line file. pyenv reads it on cd and silently switches the active interpreter. Without it, the project floats to whatever Python the next developer has, which is a common source of subtle incompatibilities.
Layer 2 — Isolate with a Virtual Environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip pip-tools
Create the venv after pyenv local is set, otherwise it captures the wrong interpreter. Add .venv/ to .gitignore.
Layer 3 — Declare Intent in pyproject.toml, Compile a Lockfile
pyproject.toml records what the project needs:
[project]
name = "my-llm-project"
version = "0.1.0"
requires-python = ">=3.12,<3.13"
dependencies = ["mistralai>=1.0", "python-dotenv>=1.0"]
[project.optional-dependencies]
dev = ["pytest>=8", "ruff>=0.5"]
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[tool.pytest.ini_options]
addopts = "-m 'not live'"
markers = ["live: hits the real API"]
pip-compile resolves the full dependency tree and records each package's hash:
pip-compile --extra dev --generate-hashes -o requirements.lock pyproject.toml
pip-sync requirements.lock # installs exactly the lock, removes anything extra
pip install -e . --no-deps # make src/ importable in editable mode
Commit requirements.lock. The hashes defend against a tampered package silently replacing a legitimate one on PyPI — plain pinned versions in a requirements.txt do not give you that. To upgrade, run pip-compile --upgrade and review the diff in a PR.
uv is a faster modern alternative (uv lock, uv sync) but the concepts are identical.
Layer 4 — Secrets via Environment Variables
# .env.example ← committed; documents required variables, contains no real values
MISTRAL_API_KEY=
MISTRAL_MODEL=mistral-small-latest
cp .env.example .env # fill in your real key here; .env is git-ignored
.gitignore must include .env. As an extra guard, add gitleaks or detect-secrets as a pre-commit hook to catch accidental key commits before they reach the remote.
Project Layout
my-llm-project/
├── .python-version
├── .env.example
├── .gitignore
├── pyproject.toml
├── requirements.lock
├── Makefile
├── src/agent/
│ ├── __init__.py
│ ├── config.py
│ └── client.py
├── scripts/smoke_test.py
└── tests/test_config.py
A Makefile keeps onboarding to one command:
setup:
python -m venv .venv && .venv/bin/pip install pip-tools \
&& .venv/bin/pip-sync requirements.lock \
&& .venv/bin/pip install -e . --no-deps
smoke:
.venv/bin/python scripts/smoke_test.py
test:
.venv/bin/pytest
Code
# src/agent/config.py
import os
from dataclasses import dataclass
from dotenv import load_dotenv
@dataclass(frozen=True)
class Settings:
api_key: str
model: str
def __repr__(self) -> str:
# keep the key out of tracebacks and log lines
return f"Settings(api_key='***', model={self.model!r})"
def load_settings() -> Settings:
load_dotenv() # no-op when real env vars are already set (e.g. in CI)
key = os.getenv("MISTRAL_API_KEY", "").strip()
if not key:
raise RuntimeError(
"MISTRAL_API_KEY is not set — copy .env.example to .env and fill it in"
)
return Settings(api_key=key, model=os.getenv("MISTRAL_MODEL", "mistral-small-latest"))
# src/agent/client.py
from mistralai import Mistral
from agent.config import Settings
def make_client(settings: Settings) -> Mistral:
return Mistral(api_key=settings.api_key)
def ping(client: Mistral, model: str) -> str:
"""One minimal chat request; returns the model name the API reports."""
resp = client.chat.complete(
model=model,
messages=[{"role": "user", "content": "Reply with the single word: ok"}],
max_tokens=5,
)
return resp.model
# scripts/smoke_test.py
import sys
from agent.config import load_settings
from agent.client import make_client, ping
def main() -> int:
try:
settings = load_settings()
model = ping(make_client(settings), settings.model)
except Exception as exc:
print(f"FAILED — {type(exc).__name__}: {exc}", file=sys.stderr)
return 1
print(f"Model: {model}")
return 0
if __name__ == "__main__":
sys.exit(main())
# tests/test_config.py
import pytest
from agent.config import load_settings
def test_missing_key_raises(monkeypatch):
monkeypatch.setenv("MISTRAL_API_KEY", "")
with pytest.raises(RuntimeError, match="MISTRAL_API_KEY"):
load_settings()
def test_repr_hides_key(monkeypatch):
monkeypatch.setenv("MISTRAL_API_KEY", "sk-supersecret")
assert "sk-supersecret" not in repr(load_settings())
Unit tests use monkeypatch and make zero network calls. Live tests go in a separate file, marked @pytest.mark.live, and are excluded by default via addopts.
Common Mistakes
- Creating the venv before
pyenv local: the venv embeds the wrong interpreter path. Delete and recreate it. - Committing
.env: happens more often than people expect. A pre-commit hook catches it before it becomes a production incident. - Checking in
requirements.lockwithout hashes: you get reproducible versions but lose supply-chain integrity. Always use--generate-hashes. load_dotenv()overwriting CI secrets:load_dotenv()skips variables that are already set, so real environment variables in CI always take precedence over the file — this is the correct default behaviour.- pyenv install failures: almost always missing system libraries (
libssl-dev,zlib1g-dev,libffi-devon Debian/Ubuntu). Install them first, then retry.
Why This Holds Up
The lockfile plus hashes makes the install deterministic and tamper-evident. The .python-version file eliminates interpreter drift. The load_settings fail-fast check means a missing secret surfaces as a clear error on startup, not a cryptic 401 deep in a call stack. And the smoke test exits non-zero on any failure, so it works as a CI gate without extra logic.