Module 00 · Lesson 2

Setting up your environment and API key

Set up a Python project with uv, get a DeepSeek API key and store it in environment variables, and confirm everything works with one script. Also covers switching to Qwen, Kimi or a local Ollama.

  • About 30 min
  • Level: Beginner
  • Tested: 2026-09-14 deepseek-flash, uv 0.12

Code and program output are shown exactly as they ran, so comments and printed output are in Chinese.

By the end of this lesson you'll have a Python environment that can call a large language model, and a script that confirms it works. The whole thing takes about half an hour, most of it spent signing up for an account.

Install Python and uv

This course manages Python environments with uv. It's a Python package manager that is much faster than the traditional pip plus venv combination, and it installs a suitable Python version for you along the way, so you don't need to install Python separately first.

On macOS and Linux, run this in a terminal:

curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, run this in PowerShell:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

With Homebrew, brew install uv works too. Once it's installed, open a new terminal window and run uv --version; if you see a version number, you're set.

If you're used to pip and venv, or to conda, feel free to keep using them. The course's code depends on only a few common packages, and any tool can install them. I'll give the pip version of the commands below as well.

Create a project

Find a place for your code and create a project directory:

uv init --no-package ai-course
cd ai-course
uv add openai

--no-package means "this is just a project for scripts, not something to package and publish". Without it, recent versions of uv generate a packaging layout (a src/ directory and build configuration), which this course doesn't need.

uv init created these files:

ai-course/
  .git/             uv 顺手帮你初始化了 git 仓库
  .gitignore        已经写好了该忽略的文件,包括 .venv
  .python-version   这个项目用哪个版本的 Python
  main.py           一个打印 Hello 的示例脚本
  pyproject.toml    项目信息和依赖列表
  README.md

uv add openai added two more things: the .venv directory is this project's virtual environment, and openai is installed inside it; uv.lock records the exact version of every package, so anyone who gets your project can run uv sync and end up with an identical environment. openai was also written into the dependencies of pyproject.toml.

Check that it runs:

uv run main.py

If you see Hello from ai-course!, it works.

From now on, run scripts in this project with uv run:

uv run python 你的脚本.py

uv run uses the project's virtual environment automatically, so you don't have to activate it by hand.

With pip it looks like this, and does the same thing:

mkdir ai-course && cd ai-course
python3 -m venv .venv
source .venv/bin/activate      # Windows 用 .venv\Scripts\activate
pip install openai

With this approach, you have to run source .venv/bin/activate again every time you open a new terminal, and then run scripts directly with python your_script.py.

Why a virtual environment

Each project gets its own set of packages, and they don't interfere with each other. If you install the latest openai for this course today and an old project needs an older version tomorrow, both keep working. Put every package into the system Python and sooner or later versions clash, in a way that's hard to clean up.

Editor

Use whatever editor you're comfortable with. If you have no preference, I recommend VS Code with Microsoft's official Python extension. After opening the ai-course directory in VS Code, press Ctrl+Shift+P (Cmd+Shift+P on macOS), type "Python: Select Interpreter", and choose the Python inside .venv. Only then does the editor recognize the packages you installed, instead of covering the screen in red squiggles.

Get a DeepSeek API key

  1. Open the DeepSeek platform, sign up with a phone number and log in.
  2. In the left menu, go to "Top up" and add a little money. The whole first part usually costs less than US$1, so the minimum amount is plenty.
  3. Go to the API keys page, click "Create API key", and give it a name such as "ai-course".
  4. Copy the key it generates. It starts with sk- and is shown only this once; close the page and you can never see it again. If you didn't copy it, just delete it and create another.

Store the key in environment variables

A key is as good as the money in your account. Anyone who gets it can spend your balance calling models. So there's one rule: never write a key into a code file.

What's wrong with putting it in code? Code gets committed to git, pushed to GitHub, shared with colleagues and pasted online when you ask for help. Any of those steps can carry the key out with it. People continuously scan public GitHub repositories for keys, and a leaked key gets abused quickly.

The right way is to keep the key in an environment variable and have the code read it at run time. This course uses three environment variables throughout:

Variable Meaning Value for DeepSeek
LLM_API_KEY The key The sk-... you just copied
LLM_BASE_URL Service address https://api.deepseek.com
LLM_MODEL Model name deepseek-flash

The reason for not using the DEEPSEEK_API_KEY name from DeepSeek's own docs is that the course's code has to switch between providers. If you want to move to another provider later, you change the values of these three variables and not a single line of code.

macOS and Linux: open ~/.zshrc (zsh is the default shell on macOS) or ~/.bashrc (most Linux distributions) and add at the end:

export LLM_API_KEY="sk-你的密钥"
export LLM_BASE_URL="https://api.deepseek.com"
export LLM_MODEL="deepseek-flash"

Save, then close and reopen the terminal, or run source ~/.zshrc.

Windows: run the three lines below in PowerShell. They save the variables permanently to your user account:

setx LLM_API_KEY "sk-你的密钥"
setx LLM_BASE_URL "https://api.deepseek.com"
setx LLM_MODEL "deepseek-flash"

Variables set with setx don't take effect in the current window; close PowerShell and open it again. This is the most common trap on Windows: you set the variable, and the program still says it can't find it.

Another way: a .env file

Some people prefer to put the key in a .env file in the project directory and read it in at startup with the python-dotenv package. That works too, but add .env to .gitignore first:

echo ".env" >> .gitignore

Add .gitignore first, then create .env. Do it the other way round and some day a git add . may commit it. Once it's been committed, it stays in git's history even if you delete it later. If that happens, don't try to rewrite history; go to the platform, delete that key and create a new one.

Check it

Save the script below as check_env.py:

"""检查三个环境变量有没有设置好,并用一次最便宜的请求确认密钥可用。"""
import os
import sys

from openai import APIConnectionError, AuthenticationError, OpenAI

key = os.environ.get("LLM_API_KEY")
base_url = os.environ.get("LLM_BASE_URL", "https://api.deepseek.com")
model = os.environ.get("LLM_MODEL", "deepseek-flash")

if not key:
    sys.exit("没有找到 LLM_API_KEY。设置完环境变量后,要重新打开一个终端窗口才会生效。")

# 只显示密钥的开头和结尾,避免截图时泄露
print(f"密钥:{key[:5]}...{key[-4:]}")
print(f"地址:{base_url}")
print(f"模型:{model}")

client = OpenAI(api_key=key, base_url=base_url)
try:
    available = [m.id for m in client.models.list().data]
except AuthenticationError:
    sys.exit("密钥不对(401)。检查有没有复制完整、有没有多出空格。")
except APIConnectionError:
    sys.exit("连不上服务器。检查地址有没有写错,或者网络是否需要代理。")

print(f"这个密钥能用的模型:{', '.join(available)}")
if model not in available:
    print(f"注意:{model} 不在列表里,调用时可能会报错或被映射到别的模型。")
else:
    print("一切正常,可以开始上课了。")

Run it:

uv run python check_env.py

This is what I got (the middle of the key is hidden):

密钥:sk-7f...805f
地址:https://api.deepseek.com
模型:deepseek-flash
这个密钥能用的模型:deepseek-flash, deepseek-v4-pro
一切正常,可以开始上课了。

When the last line says "一切正常" (all good), your environment is ready. The line before it lists the models your key can call; as of September 2026, DeepSeek offers deepseek-flash and deepseek-v4-pro. The course uses deepseek-flash by default: it's cheap and fast, and it handles every task in the course well.

The script calls the "list models" endpoint, which generates no text, so it costs nothing.

Switching to another provider

The course's code depends only on OpenAI's Python SDK, so any service with an OpenAI-compatible API works. The providers below all have Chinese documentation; check each one's official docs for the current address and model names (as of September 2026):

Provider LLM_BASE_URL Example LLM_MODEL Where to get a key
DeepSeek https://api.deepseek.com deepseek-flash platform.deepseek.com
Alibaba Cloud Model Studio (Qwen) https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1, with the part in braces replaced by your workspace ID; the console lets you copy the full address See the model list in the console Model Studio console
Kimi (Moonshot AI) https://api.moonshot.cn/v1 kimi-k3 platform.kimi.com
Ollama (runs locally) http://localhost:11434/v1/ The name of a model you downloaded with ollama pull Not needed; set LLM_API_KEY to any non-empty value

Two things to keep in mind.

First, "OpenAI-compatible" doesn't mean exactly the same everywhere. The most basic chat call works with all of them, but features such as tool calling, JSON output and streaming aren't supported by every model, and details differ. When later lessons use these features, I'll say which parts are specific to DeepSeek.

Second, a local Ollama is completely free and needs no internet connection, but the models an ordinary laptop can run are small, and they're clearly weaker than large cloud models; some exercises may be out of their reach. I suggest finishing the first part with a cloud model; module 10 covers local deployment properly.

Common problems

The script says ModuleNotFoundError: No module named 'openai': the package is installed in the project's virtual environment, but you're running the system Python. Run it with uv run python ..., or activate the virtual environment first.

It says "没有找到 LLM_API_KEY" (LLM_API_KEY not found), but I set it: you need to reopen the terminal after setting an environment variable. If you're running from VS Code, close the whole of VS Code and reopen it; closing just its terminal panel isn't enough.

A 401 error: the key wasn't copied completely, or it picked up extra spaces or quotes. The key may also have been deleted on the platform.

A 402 error or an "insufficient balance" message: top up on the platform.

Exercises

  1. In a terminal, run echo $LLM_MODEL (echo $env:LLM_MODEL in Windows PowerShell) and check that it prints the model name.
  2. Deliberately change one letter of LLM_API_KEY and run check_env.py again to see what the error looks like. Remember to change it back. To change a variable temporarily in a terminal, write LLM_API_KEY=sk-wrong uv run python check_env.py; it only applies to that one command.
  3. If you have a Qwen or Kimi account, set the three variables to that provider's values using the table above, and run check_env.py again.

Self-check

1. Why can't you write an API key directly into your code?

Code gets committed to git, pushed to GitHub and sent to other people. Every one of those steps can leak the key, and whoever has the key can spend the money in your account directly. With the key in an environment variable, the code files contain no secrets and can be shared safely.

2. On Windows you set LLM_API_KEY with setx and immediately run the script, but it says it can't find it. Why?

setx wrote the variable into your user settings, but windows that are already open don't reread those settings. Close PowerShell (or the whole of VS Code) and open it again.

3. Why does this course use the three variables LLM_API_KEY, LLM_BASE_URL and LLM_MODEL instead of DEEPSEEK_API_KEY?

So that switching providers doesn't require changing code. Every OpenAI-compatible service needs just these three things: a key, an address and a model name. To switch providers you only change the values of these three variables.