Registering for ChatGPT and Creating Your API Key
What this lesson covers
Create an OpenAI platform account, put credits on it, mint an API key, wire it into a .env file, and run the course's first notebook — 1_foundations/1_lab1.ipynb — end to end. Budget about 30 minutes.
ChatGPT and the OpenAI API are different products. ChatGPT is the end-user chat app; the API is the developer interface at platform.openai.com. A ChatGPT Plus subscription gives you no API credit, and API credits give you no ChatGPT features. They are billed separately and, despite the lesson title, everything below is about the API.
Changed since the recording: the API documentation now lives at developers.openai.com/api/docs (platform.openai.com/docs redirects there). The console itself is still platform.openai.com. OpenAI's own quickstart now leads with the Responses API (client.responses.create); the course notebook uses Chat Completions (client.chat.completions.create), which remains fully supported — run the notebook as written.
Prefer not to use OpenAI?
The notebook works with alternatives, and the course's own guide 9 covers them. In short: OpenRouter or Google Gemini need a different key name in .env (OPENROUTER_API_KEY, or GOOGLE_API_KEY and GEMINI_API_KEY with the same value, because different libraries look for different names), plus a base_url on the client. Ollama runs locally and needs no key or .env at all. The rest of this lesson assumes OpenAI.
Before you start
- The course repo cloned, with the
.venvenvironment already built byuv(setup steps 1–3). - Cursor or VS Code with the Python (ms-python) and Jupyter (Microsoft) extensions installed.
- A card. The API needs a minimum $5 prepaid balance; this course will not come close to spending it.
Platform tour
| Page | What it is for |
|---|---|
| API keys | Create, name, scope and delete secret keys. |
| Settings → Billing | Payment details, credit balance, auto-recharge. |
| Usage | Spend and token counts by day, model and project. |
| Logs | Individual requests and their responses — first stop when a call misbehaves. |
| Settings → Projects | Projects compartmentalise work. Every org has a Default project that cannot be deleted. |
| Playground | Try prompts and models before writing code. |
Lab 1 — Create the account and organisation
- Go to platform.openai.com. You will be redirected to a login screen. Sign in with Google/Microsoft/Apple, or create an account with an email address and verify the code that arrives.
- Enter your name, then an organisation name. If this is personal learning, something like "Your Name – Education" is fine. Pick Student or Researcher for "what best describes you".
- Choose I'll invite my team later.
- The onboarding flow offers to generate a key and add credits immediately. You can do both here — but the next two labs do it through the permanent screens, which is what you will use from now on.
Done when: you land on the platform dashboard with an organisation created.
Lab 2 — Add credits
- Go to Settings → Billing and click Add payment details.
- Purchase credits. The minimum initial purchase is $5 (the field defaults to $10).
- Auto-recharge is on by default. For a learning account, turn it off, or set the trigger and target deliberately — otherwise a runaway loop quietly re-buys credits.
- Note two things: purchased credits expire after one year, and the balance is not an instant cut-off — usage in flight can push you slightly negative, which is deducted from your next purchase.
Done when: Billing shows a credit balance greater than zero.
Lab 3 — Create the API key
- Go to API keys and click Create new secret key.
- Name: anything memorable —
my test keyis the suggested default and is fine. - Project: select Default project.
- Permissions: leave on All. Restricted and read-only keys are a real feature, but choosing one here produces confusing permission errors several labs later.
- Click Create secret key, then Copy. The key begins
sk-proj-.
Copy it before you press Done. The full value is shown exactly once. If you miss it, there is nothing to recover — delete the key (red bin icon) and create another. You can hold as many keys as you like; just be sure the one in your clipboard is the one you are about to paste.
Done when: the key list shows your key, and the full sk-proj-... value is on your clipboard.
Lab 4 — Create the .env file
This is where most setup failures happen. Three details have to be exactly right.
- In Cursor's Explorer, right-click the blank space below the file tree — not on a folder — and choose New File. This puts the file in the project root (
agents), which is where it must be. - Name it exactly
.env— a dot and three letters. Not.env.txt, notenv, not.env.example. - Type the variable name in capitals with underscores, then paste your key:
It must beOPENAI_API_KEY=sk-proj-...OPENAI_API_KEY— notOPEN_AI_API_KEY, notOPENAI_KEY. No spaces around the=, no quotes, no trailing space after the key. - Save the file (Ctrl+S / Cmd+S). An editor holds unsaved changes in memory only; the white dot on the tab means not yet written to disk. Forgetting this is the single most common cause of the next lab failing.
A stop/circle-slash icon appearing next to .env is good — it means Cursor has been told never to send that file's contents to an AI.
Done when: .env sits in the project root, contains one OPENAI_API_KEY= line, and its tab shows no unsaved-changes dot.
Lab 5 — Run 1_lab1.ipynb
Open 1_foundations/1_lab1.ipynb. A Jupyter notebook mixes prose with executable cells; Shift+Enter runs the cell you are in.
- Select the kernel. Click Select Kernel at the top right → Python Environments → the entry named
.venv (Python 3.12.12)or similar. That is the environmentuvbuilt for this project; any other interpreter will not have the packages. - Run the import cell:
Anfrom dotenv import load_dotenvImportErrorhere almost always means the wrong kernel, not a missing package. - Run the loader. It must print
True:load_dotenv(override=True)Falsemeans the file was not found or not saved — go back to Lab 4. - Confirm the key is visible to Python:
You wantimport os openai_api_key = os.getenv('OPENAI_API_KEY') if openai_api_key: print(f"OpenAI API Key exists and begins {openai_api_key[:8]}") else: print("OpenAI API Key not set - please head to the troubleshooting guide in the setup folder")begins sk-proj-. Anything else means the variable name or the pasted value is wrong. - Import the client and instantiate it. Note this same import is used for Gemini, DeepSeek and OpenRouter too — only the
base_urlchanges:
The constructor readsfrom openai import OpenAI openai = OpenAI()OPENAI_API_KEYfrom the environment, which is why Lab 4 mattered. - Make the first call, using a very cheap model:
messages = [{"role": "user", "content": "Tell me a fun fact"}] response = openai.chat.completions.create(model="gpt-5.4-nano", messages=messages) print(response.choices[0].message.content)
Cell order beats cell position. A notebook executes in the order you press Shift+Enter, not top to bottom. Run out of order and you get a NameError for a variable that is sitting right there on screen. When in doubt, restart the kernel and run from the top.
Done when: the notebook prints a fun fact.
Lab 6 — Chain three calls
The rest of the notebook is the first taste of what makes an agent: feeding one model's output into the next call.
- Ask for a hard question, on the slightly stronger
gpt-5.4-mini:question = "Please propose a hard, challenging question to assess someone's IQ. Respond only with the question." messages = [{"role": "user", "content": question}] response = openai.chat.completions.create(model="gpt-5.4-mini", messages=messages) question = response.choices[0].message.content print(question) - Put that generated question into a fresh
messageslist and ask for an answer. - Render it nicely:
display(Markdown(answer))fromIPython.display. - Build an evaluation prompt containing both question and answer, and send it to the full
gpt-5.4to judge. Three models, three roles — generator, solver, evaluator.
Stretch exercise (the notebook's own): chain three calls to (1) pick a business area worth exploring for Agentic AI, (2) name a pain-point in that industry, (3) propose an agentic solution. Each call must include the previous answer in its message.
Done when: the evaluator returns a verdict, and your stretch chain produces a proposal that actually references the business area it picked.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
load_dotenv() returns False | File not saved, misnamed, or not in the project root | Save it; confirm the name is exactly .env and it sits in agents/. |
| "OpenAI API Key not set" | Variable name wrong | It must read OPENAI_API_KEY — capitals, underscores, no spaces around =. |
| Key prints but begins with something odd | Bad paste | A truncated key or a trailing space. Create a fresh key and paste again. |
ImportError on dotenv or openai | Wrong kernel | Re-select the .venv kernel, then re-run from the first cell. |
NameError | Cells run out of order | Restart the kernel and run every cell top to bottom. |
401 invalid_api_key | Key deleted, mistyped, or truncated | Create a new key and update .env — then re-run load_dotenv(override=True). |
429 insufficient_quota | No credit balance | This is billing, not rate limiting. Add credits in Lab 2. |
403 / permission errors on later labs | Restricted key | The key was scoped narrowly at creation. Make a new one with All permissions. |
Changed .env but the old key is still used | Environment cached in the running kernel | load_dotenv(override=True) re-reads it; if it still sticks, restart the kernel. |
Knowledge check
Q1. Does ChatGPT Plus include API usage?
No. Separate products, separate billing. The API needs its own prepaid credit balance.
Q2. What is the minimum first credit purchase, and do credits last forever?
$5 minimum, and purchased credits expire after one year.
Q3. Your key prints as sk-proj- but calls return 429 insufficient_quota. What is wrong?
Nothing is wrong with the key — there is no credit balance. Despite the 429 status, this is a billing problem.
Q4. load_dotenv() returned False. Name the two most likely causes.
The .env file was never saved, or it is not named exactly .env / not in the project root.
Q5. Why does OpenAI() work without passing a key?
The constructor reads OPENAI_API_KEY from the environment, which load_dotenv populated from .env.
Q6. You get a NameError for a variable you can see defined above. Why?
You ran the cells out of order. Notebooks execute in run order, not visual order. Restart the kernel and run from the top.
Q7. Why does the notebook use three different models?
Cost matching. gpt-5.4-nano for a trivial call, gpt-5.4-mini for generating and answering, full gpt-5.4 only for the harder evaluation step.
Q8. Why choose "All" permissions and the Default project when creating the key?
A restricted or narrowly-scoped key works for the first call and then fails with permission errors in later labs — a confusing failure mode that is easy to avoid up front.
FAQ
Can I use my ChatGPT login for the platform?
Yes, the same account signs in to both. What differs is billing: you still need to add API credits.
Should I use the Responses API or Chat Completions?
OpenAI's current quickstart leads with client.responses.create, and it is the better choice for new projects. The course notebook uses chat.completions.create, which is fully supported — follow the notebook, and note the difference for your own work.
How many keys should I have?
As many as you have applications. Keys are free and deleting one is instant, so never share a single key across unrelated projects.
Is the .env file safe in git?
Only because the repo's .gitignore excludes it. Verify with git status before your first commit — a key pushed to a public repo is detected and revoked within minutes, and until then anyone can spend your balance.
How do I stop a runaway bill?
Turn auto-recharge off, keep the balance small, and set a monthly spend alert on the project. Note that project spend limits raise alerts rather than hard-stopping requests.
I want to use Gemini / DeepSeek / Ollama instead. What changes?
The key name in .env and a base_url on the client — the from openai import OpenAI import stays, because those providers expose OpenAI-compatible endpoints. Ollama runs locally and needs no key at all. Guide 9 in the repo has the exact snippets.
Why two Google variables?
Some libraries look for GOOGLE_API_KEY and others for GEMINI_API_KEY. Set both to the same value and neither can bite you.
Where do I see what a call actually cost?
The Usage page for aggregates, the Logs page for individual requests.
Resources
- Lab notebook —
D:\Projects\Agentic-AI\agents\1_foundations\1_lab1.ipynb - OpenAI platform (console) — https://platform.openai.com
- API keys — https://platform.openai.com/api-keys
- Billing overview — https://platform.openai.com/settings/organization/billing/overview
- Usage — https://platform.openai.com/usage
- API documentation — https://developers.openai.com/api/docs
- Quickstart — https://developers.openai.com/api/docs/quickstart
- Prepaid billing explained — OpenAI Help: prepaid billing
- Projects in the API platform — OpenAI Help: projects
- Course repo guides —
guides/04_technical_foundations.ipynb(env vars and APIs),guides/06_python_foundations.ipynb(classes and NameErrors),guides/09_ai_apis_and_ollama.ipynb(non-OpenAI providers)
Next
Your key is set and the first chained calls work. Calling the ChatGPT API with cURL and REST Basics takes the same request apart at the HTTP level.