Why does my free LLM API key work in a terminal but not in Jupyter?
If a free LLM API call works in a terminal but a notebook says the key is missing, first check which process started the notebook kernel. A Jupyter kernel is its own Python process. It receives the environment available when it starts, plus any environment configured by its kernelspec; changing a shell variable later does not update an already-running kernel. Check the exact variable name, check only whether it is present, and restart the process that owns the stale environment before making another API request.
Check the notebook without showing the key
Run this cell in the notebook that fails:
import os
import sys
key_name = "CHINAGENAI_API_KEY" # Use the exact name your client expects.
print("Python:", sys.executable)
print("Key variable present:", bool(os.getenv(key_name)))
This prints the active interpreter path and a boolean. It does not print the key. For ChinaGenAI's documented Python and Go route, the variable name is CHINAGENAI_API_KEY; another provider or SDK may expect a different name, such as OPENAI_API_KEY. Match the name in the client configuration, not just the name you remember setting in a terminal. ChinaGenAI's connection guide also uses https://chinagenai.com/v1 as the base URL and the model label free; those settings are separate from whether Python can read a key.
If the value is absent, stop before a network request. If it is present but the API returns an authentication error, then check whether it is the correct, active key for that endpoint. A presence check proves only that some non-empty value reached this process; it does not validate the credential.
Follow the process that launches the kernel
A common local launch chain looks like this:
terminal or desktop launcher
│ environment at server launch
▼
Jupyter server
│ environment at kernel launch + kernelspec settings
▼
Python kernel running the notebook cells
The browser tab is only the notebook interface in this local setup. The Python code runs in the kernel process. With a hosted notebook, a container, WSL, a remote server, or an IDE-managed server, the process chain is different: the key must reach the machine or container that actually launches the kernel.
Jupyter's kernel specification can add environment variables for a kernel before it starts. That setting is useful for a dedicated local environment, but a kernel.json file can expose secrets to anyone who can read it. Do not put a real key in a shared repository, a notebook, a screen recording, or a kernelspec committed to source control. A user-specific secret store or the notebook platform's protected secret facility is a better fit for persistent credentials.
Match the fix to the stale process
| What you changed | Why the current kernel may still miss it | Smallest safe next step |
|---|---|---|
Ran setx in Windows |
Microsoft documents setx as updating values for future command windows, not the current one. An already-open Jupyter launcher cannot pass along a value it never received. |
Open a new terminal after setting the value, launch Jupyter from that terminal, then restart the notebook kernel. |
| Exported a variable in a shell after Jupyter was already open | The server and its existing kernel keep their own process environments. A child process cannot read a later change made in a different parent shell. | Close the kernel and restart the Jupyter server from the shell that has the value; then start a fresh kernel. |
| Changed a value in the current notebook process | Python's os.environ is the current process mapping. Modifying it in this kernel affects later reads here and values inherited by new child processes, but not a separate server or an already-running sibling process. |
Use a protected secret injection path before the SDK call; avoid saving the value in a cell or notebook output. |
| Switched the notebook's kernel | The selected kernel can run another Python installation or a different kernelspec with different environment settings. | Compare sys.executable, then inspect jupyter kernelspec list and the selected kernel's kernel.json without copying secret values. |
Added a .env file |
A file is not automatically the process environment. Python code must explicitly load it or the launcher must inject its values. | Use a deliberate local loader before client creation, or use the platform's secret configuration; keep the file out of source control. |
| Key check passes, but the request fails | Environment inheritance is no longer the first suspect. Endpoint, model, key type, expiry, network policy, or service availability can still differ. | Read the sanitized status and error fields; verify the host and model against the provider's current documentation. Do not paste the key into a traceback or support post. |
Reproduce the timing issue with a fake value
This offline fixture starts a child process before setting a synthetic variable in the parent. The child reports whether it received the variable. A second child starts afterward and reports its own result. It uses no API key, network call, SDK, or provider quota.
import os
import subprocess
import sys
name = "SYNTHETIC_NOTEBOOK_KEY"
child_code = (
"import os, time; time.sleep(0.4); "
"print(bool(os.getenv('SYNTHETIC_NOTEBOOK_KEY')))"
)
command = [sys.executable, "-c", child_code]
already_started = subprocess.Popen(
command, stdout=subprocess.PIPE, text=True
)
os.environ[name] = "fixture-only"
old_child_result = already_started.communicate()[0].strip()
new_child_result = subprocess.run(
command, check=True, capture_output=True, text=True
).stdout.strip()
del os.environ[name]
print({"started_before_change": old_child_result,
"started_after_change": new_child_result})
Expected output is {'started_before_change': 'False', 'started_after_change': 'True'}. The second process sees the current parent environment because it starts later. The first child's environment was already created at launch. This demonstrates process inheritance, not a Jupyter bug and not a provider response.
Restart the right layer
Use this order to avoid debugging the wrong process:
- In the failing notebook, record
sys.executableand the key-presence boolean. Do not display the value. - Identify how the notebook server started: a terminal, Anaconda Navigator, VS Code, a hosted notebook, a container, or a remote service.
- Set the key in that launcher's protected environment, using the exact variable name the SDK or client reads.
- If the server itself started before the change, restart that server from the updated environment. Restarting only the kernel may give it the same stale server environment.
- Start a new kernel and repeat the two safe checks. If the variable is present, confirm the SDK's interpreter and installation match
sys.executable. - Only then send one small request, after checking that the endpoint, key type, and model are correct. Do not loop retries while diagnosing configuration.
For a single notebook session, a platform secret UI or a protected launcher setting avoids embedding a credential in notebook source. If a local .env loader is part of your workflow, load it explicitly before constructing the SDK client and keep the file private. Restart the kernel after changing the file or loader configuration so the notebook state is unambiguous.
Questions developers ask
Should I restart the kernel or the whole Jupyter server?
If only the kernel is stale, a kernel restart can be enough. If you changed a variable in a different terminal after the Jupyter server had already started, restart the server from that updated terminal too; a new kernel inherits from the server that launches it.
Does setx update a notebook that is already open on Windows?
No. Microsoft says setx makes the value available to future command windows. Open a new terminal, start Jupyter there, and launch a fresh kernel.
Is a key in a .env file automatically available to os.getenv?
No. os.getenv reads the Python process environment. A loader or launcher must explicitly put those values there. Do not commit the file or print its contents.
Can I print the key to see whether it is correct?
Avoid that. First check only whether the expected variable exists. If authentication still fails, verify the key through the provider's authorized key-management page and inspect a redacted error. Never put the value in notebook output, logs, screenshots, or a public issue.
Sources checked 13 November 2026
- Jupyter Client: Making kernels — kernel launch and the
envfield in a kernelspec. - Python 3.11:
os.environ— process environment mapping and when it is captured. - Microsoft Learn:
setx— values are available to future command windows, not the current one. - ChinaGenAI: API connection guide — documented
CHINAGENAI_API_KEY, base URL, and model label.
The subprocess example and decision table above are original offline diagnostic material. The fixture uses only a synthetic placeholder and makes no provider request.