Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
What you will learn
- Install uv and let it bring Python 3.12, then pin every package with pyproject.toml and uv.lock
- Use a check script to spot the works-on-my-machine problem, and fix it with uv sync
- Point VS Code at .venv and keep the API key in .env, out of git
- Make a first model call that also runs without a key, using a stand-in test model, and run the tests with pytest
Before you start
- Basic Python
- Python Virtual Environments
Think of a recipe that says "add some flour". My cake turns out fine, yours doesn't, and we both followed the recipe. Code works the same way. On my machine I have pytest 9.2.0, on yours you have 8.3.4, and the same project breaks for you.
The fix is a recipe with exact amounts. In Python that's a lock file: every package, at one exact version. In this article we build one environment that every AI project can run in: uv brings Python 3.12 and the pinned packages, VS Code points at it, the API key sits in a .env file, and a stand-in test model means you can run everything even before you have a key.
If you're new to virtual environments, read Python Virtual Environments first. Here we let uv do that work for us.
Install uv, then let it bring Python
uv is one small program that replaces a whole pile of tools: it installs Python, makes the virtual environment and installs the packages. Both install commands come from the uv website.
# Windows PowerShell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
Then check the version and ask uv for Python 3.12:
uv --version
uv python install 3.12
uv 0.12.13 (0ebbd9274 2026-09-10 x86_64-pc-windows-msvc)
Python 3.12 is already installed
On this machine Python 3.12 was already there. If it isn't on yours, uv downloads it. You don't need a separate Python installer.
A first project in four commands
Before the real project, here's a tiny one so you can see what uv does on its own:
uv init ticket-helper --app --no-package --vcs none --author-from none --python 3.12
cd ticket-helper
uv add python-dotenv==1.2.4
uv run main.py
Initialized project `ticket-helper`
Using CPython 3.12.14
Creating virtual environment at: .venv
Resolved 2 packages in 4ms
Installed 1 package in 9ms
+ python-dotenv==1.2.4
Hello from ticket-helper!
uv initmakes the project:.python-version,README.md,main.pyandpyproject.toml.--appmeans a small application, not a library you publish. The other flags skip git and author details for now.uv addwrites the pin intopyproject.toml. There's no environment yet, so uv creates.venvwith Python 3.12 and installs the package.uv runruns the script inside that environment. Notice there's no activate step. uv run takes care of it.
pyproject.toml holds the pins
Now the real project. Everything important is in pyproject.toml:
[project]
name = "ai-engineer-setup"
version = "0.1.0"
description = "Become an AI Engineer - the course environment (S01L04)"
requires-python = ">=3.12"
dependencies = [
"anthropic==2.8.0",
"httpx2==2.16.0",
"python-dotenv==1.2.4",
"pytest==9.2.0",
]
[tool.uv]
package = false
[tool.pytest.ini_options]
testpaths = ["tests"]
requires-pythonsays 3.12 or newer. The.python-versionfile next to it says exactly3.12.- Four packages, each pinned with
==to one exact version. - Here's the subtle part: these four pull in other packages, and the
uv.lockfile pins those too. package = falsetells uv this is a project you run, not something you publish.
The failure first: plain python, four FAILs
The project ships a small script, check_setup.py. Two of its checks do most of the work (an excerpt; the file starts with import os, import sys and from importlib import metadata):
def check_venv() -> tuple[bool, str]:
inside = sys.prefix != sys.base_prefix or bool(os.getenv("VIRTUAL_ENV")) or os.path.exists("/.dockerenv")
return inside, "virtual environment active" if inside else "not in a virtual environment -> use: uv run check_setup.py"
def check_package(name: str, wanted: str) -> tuple[bool, str]:
try:
found = metadata.version(name)
except metadata.PackageNotFoundError:
return False, f"{name} missing -> run: uv sync"
if found != wanted:
return False, f"{name} {found} (course pins {wanted}) -> run: uv sync"
return True, f"{name} {found}"
Inside a virtual environment, sys.prefix is different from sys.base_prefix. The second check asks Python which version of each package is installed (metadata is importlib.metadata). A missing package or a different version is a FAIL, and the line tells you the fix.
Now run it the way most people would, with plain python:
python check_setup.py
[ok] Python 3.13.7
[FAIL] not in a virtual environment -> use: uv run check_setup.py
[FAIL] anthropic missing -> run: uv sync
[ok] httpx2 2.16.0
[FAIL] python-dotenv 1.0.1 (course pins 1.2.4) -> run: uv sync
[FAIL] pytest 8.3.4 (course pins 9.2.0) -> run: uv sync
Fix the FAIL lines, then run this again.
Four FAIL lines and exit code 1. Not in a virtual environment, anthropic missing, and python-dotenv and pytest present but at other versions. This is exactly the works-on-my-machine problem.
The fix: uv sync, then uv run
uv sync
Using CPython 3.12.14
Creating virtual environment at: .venv
Resolved 25 packages in 0.92ms
Installed 23 packages in 535ms
+ annotated-types==0.8.0
+ anthropic==2.8.0
+ anyio==4.16.0
+ colorama==0.4.6
+ docstring-parser==0.18.0
+ h11==0.16.0
+ httpcore2==2.16.0
+ httpx2==2.16.0
+ idna==3.20
+ iniconfig==2.3.1
+ jiter==0.19.0
+ opentelemetry-api==1.45.2
+ packaging==26.3
+ pluggy==1.7.0
+ pydantic==2.14.3
+ pydantic-core==2.50.4
+ pygments==2.21.0
+ pytest==9.2.0
+ python-dotenv==1.2.4
+ sniffio==1.3.1
+ truststore==0.10.5
+ typing-extensions==4.16.0
+ typing-inspection==0.4.5
uv sync creates .venv with Python 3.12, reads the lock file and installs everything, in well under a second here. The four pins plus what they need come to 23 packages, and they're the same on every machine.
uv run check_setup.py
[ok] Python 3.12.14
[ok] virtual environment active
[ok] anthropic 2.8.0
[ok] httpx2 2.16.0
[ok] python-dotenv 1.2.4
[ok] pytest 9.2.0
[ok] ANTHROPIC_API_KEY not set -> the stand-in test model will answer (fine for the course)
Ready for the course.
Every line says ok. No key is set yet, so the stand-in test model will answer. We'll get to that.
Point VS Code at .venv
The project ships a small .vscode/settings.json:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": ["tests"],
"python.envFile": "${workspaceFolder}/.env"
}
defaultInterpreterPathpoints VS Code at the Python inside.venv, so the editor sees the same packages as uv. (.venv/Scripts/python.exeis the Windows path. On macOS and Linux it lives in.venv/bin/python.)pytestEnabledlets you run the tests from the editor.envFilemakes the editor read the.envfile too.
If VS Code doesn't pick the environment by itself, press Ctrl+Shift+P, type Python: Select Interpreter and choose the one in .venv. When you open the folder, VS Code also suggests three extensions from .vscode/extensions.json: Python, Pylance and Ruff. Accept them.
The key lives in .env, never in git
You create the key in your provider's console: open API keys, choose create key, give it a name and copy it. It's shown once, so paste it straight into your file. While you're there, set a monthly spend limit, and check the provider's pricing page for current prices.
Three small files keep it safe:
| File | In git? | Contents |
|---|---|---|
.env.example | Yes | ANTHROPIC_API_KEY= (empty) |
.env | No | ANTHROPIC_API_KEY=your-key-here |
.gitignore | Yes | First line: .env |
Copy .env.example to .env (copy on Windows, cp on macOS and Linux) and put your key after the equals sign. Because .env is the first line of .gitignore, the key never ends up in git. (New to git? See Git and GitHub Fundamentals.)
Run the check again and the last line changes:
[ok] ANTHROPIC_API_KEY set (value hidden) -> the real model will answer
Ready for the course.
The script only says whether the key is there. It never prints the key itself, and neither should your code.
Real model or stand-in, same code
How can one piece of code work with and without a key? It's all in llm_client.py:
import json
import os
import httpx2 # the HTTP library the Anthropic SDK 2.x is built on
from anthropic import Anthropic
from dotenv import load_dotenv
MODEL = "claude-sonnet-5-5"
STAND_IN_REPLY = (
"Hello from the stand-in test model. Your Python, uv and VS Code setup works. "
"Put ANTHROPIC_API_KEY in .env and this same code talks to Claude."
)
load_dotenv() # reads .env next to this file, if there is one
def has_key() -> bool:
return bool(os.getenv("ANTHROPIC_API_KEY", "").strip())
def _stand_in(request: httpx2.Request) -> httpx2.Response:
"""Answers POST /v1/messages with a provider-shaped message, like the real API would."""
body = json.loads(request.content)
reply = {
"id": "msg_stand_in_001",
"type": "message",
"role": "assistant",
"model": body["model"],
"content": [{"type": "text", "text": STAND_IN_REPLY}],
"stop_reason": "end_turn",
"stop_sequence": None,
"usage": {"input_tokens": 0, "output_tokens": 0},
}
return httpx2.Response(200, json=reply)
def make_client() -> Anthropic:
if has_key():
return Anthropic() # reads ANTHROPIC_API_KEY from the environment
return Anthropic(api_key="stand-in", http_client=httpx2.Client(transport=httpx2.MockTransport(_stand_in)))
def source() -> str:
return "real model" if has_key() else "stand-in test model"
make_client(), so nothing else changes when you add your key.load_dotenv()reads the.envfile into the environment.has_key()just checks: is there a key at all?- If there is,
make_client()returns the real Anthropic client. - If not, it returns the same client, wired to a stand-in through a mock transport. The stand-in sends back a message shaped like the real API's, so the rest of your code can't tell the difference.
One question in, one answer out
Here's the first call, hello_claude.py:
import sys
from llm_client import MODEL, make_client, source
def ask(question: str) -> str:
client = make_client()
response = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[{"role": "user", "content": question}],
)
if response.stop_reason == "refusal":
return "(the model declined this request)"
return "".join(block.text for block in response.content if block.type == "text")
if __name__ == "__main__":
question = " ".join(sys.argv[1:]) or "In one sentence, what does an AI engineer do?"
print(f"model : {MODEL} [{source()}]")
print(f"you : {question}")
print(f"reply : {ask(question)}")
messages.create sends one message: the model id, a token limit and the question. Before we use the text, we check stop_reason in case the model declined. Then we join the text blocks, and that's the reply.
uv run hello_claude.py
model : claude-sonnet-5-5 [stand-in test model]
you : In one sentence, what does an AI engineer do?
reply : Hello from the stand-in test model. Your Python, uv and VS Code setup works. Put ANTHROPIC_API_KEY in .env and this same code talks to Claude.
No key, and it still runs end to end. With a key in .env, the label says [real model] and the reply comes from Claude. For every field of this call, see The Claude Messages API: Your First Call.
Five offline tests
The project has five tests in tests/test_setup.py. Before the imports, the file blanks the key, so the tests always use the stand-in and never need a key or the network. Here are that line and two of the five tests (an excerpt, not the whole file):
os.environ["ANTHROPIC_API_KEY"] = "" # always test against the stand-in
def test_missing_package_says_how_to_fix():
ok, line = check_setup.check_package("a-package-that-is-not-there", "1.0")
assert not ok and "uv sync" in line
def test_first_call_returns_the_stand_in_reply():
assert hello_claude.ask("Hello?") == llm_client.STAND_IN_REPLY
uv run pytest -q
..... [100%]
5 passed in 1.76s
Five tests, all offline, five passed. You can also run them from the Testing panel in VS Code, thanks to the settings file. More on pytest in Testing FastAPI with pytest.
Common mistakes
- Running
python script.pyinstead ofuv run script.py. Plain python uses whatever Python and packages the laptop has. That's where the four FAILs came from. - Pinning only your direct packages. The packages they pull in change too. Commit
uv.lockso those are pinned as well. - Committing
.env. Keep it as the first line of.gitignore, and commit only.env.examplewith an empty value. - Printing the key to check it. Print whether it's set, never its value.
- VS Code using the wrong Python. If the editor doesn't pick
.venvby itself, run Python: Select Interpreter and choose it.
Quick recap
| Step | Command or file | What you saw |
|---|---|---|
| Install uv and Python | uv python install 3.12 | uv 0.12.13, Python 3.12 |
| Pin packages | pyproject.toml + uv.lock | 4 pins, 23 packages installed |
| The problem | python check_setup.py | Four FAIL lines |
| The fix | uv sync, uv run check_setup.py | Every line ok, Ready for the course. |
| Editor | .vscode/settings.json | VS Code uses .venv |
| API key | .env, listed in .gitignore | "set (value hidden)" |
| First call | uv run hello_claude.py | Stand-in reply without a key |
| Tests | uv run pytest -q | 5 passed |
Try it yourself
Run uv sync, then uv run check_setup.py until every line says ok. Then ask your own question with uv run hello_claude.py "What is RAG?". When you have a key, copy .env.example to .env, add it, and run the check again.
The project files for this setup are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)