Start learning free

LESSON 13 OF 129 · AI ENGINEERING: CALLING A MODEL

Keys Live in the Environment

Practice

A model's API is paid, so every request carries an API key: a secret string that says whose account to bill. You never gave one to Anthropic(). It finds the key by itself in the environment: named values that live outside your program, set on the computer that runs it. The key's name there is ANTHROPIC_API_KEY.

That is where a key belongs. Written in the code, it would travel with every copy of the file, and whoever reads it could spend your money.

Reading the environment: os.environ works like a dictionary, so .get gives the value, or None when the name is missing. Here it is on another name:

import os

city = os.environ.get("SHOP_CITY")
print(city)   # None when SHOP_CITY is not set

A careful program checks the key first. When it is missing or empty, it stops at once with a clear message: sys.exit("...") prints the message as an error and ends the program. When the key is there, it shows it masked, only its first characters, because what a program prints ends up in logs.

The check also runs your function without the key and with an empty one. The full output must be:

Using key: sk-ant-****
Welcome to the Corner Shop! Come in and take a look around.
Without the key: ANTHROPIC_API_KEY is not set. Add it to the environment, never to the code.
With an empty key: ANTHROPIC_API_KEY is not set. Add it to the environment, never to the code.

Your task: write check_key(). It reads ANTHROPIC_API_KEY from the environment, stops with the message when the key is missing or empty, and prints Using key: with the key's first 7 characters and ****. Call it before the client is made.


Assignment
Follow the Coding Tutorial to check the API key before the first model call.


Hint
if not key: is true for None and for an empty string. Anthropic() keeps its empty parentheses: the key never appears in your code.


STEP 1 OF 6
    Ctrl + Enter to check