Setting up OpenAI, Gemini and Claude accounts
Create OpenAI, Gemini and Claude API accounts, store the keys safely in a .env file, and run one Python script that gets an answer from all three.
Words in this lessonAPI · API key · SDK · Environment variable · Rate limit
- API
- A published doorway that lets one program ask another program to do something, in an agreed format. Like a bakery counter: you do not walk into the kitchen; you order in a set way and get your order back.
- API key
- A long secret string that identifies your account when your code calls an API. Like the key to the shop's back door: anyone holding it gets in, and whatever they take goes on your tab.
- SDK
- A ready-made library that lets you call an API in a few lines of your own programming language. Like a waiter who already speaks the kitchen's language, so you do not have to shout into the kitchen yourself.
- Environment variable
- A named value, like ANTHROPIC_API_KEY, that programs started from your shell can read. Like notes pinned on the kitchen noticeboard that every cook on the shift can read.
- Rate limit
- A cap on how many requests or tokens an API will accept from you in a period of time. Like a supplier who takes only so many orders per hour and asks callers to ring back later.
On this page
- What you are setting up, and why each piece exists
- Step 1: Create the project
- Step 2: Get a Gemini key (free tier)
- Step 3: Get an OpenAI key, and Arjun's first surprise
- Step 4: Get a Claude key
- Step 5: Put the keys in a .env file
- Step 6: Say hello to all three
- Step 7: Put a fence around your spending
- Step 8: Check you did not commit a secret
- Recap
- Go deeper
Priya sticks a yellow note on Arjun’s monitor. It has three words on it: OpenAI. Gemini. Claude.
“By lunch, I want one Python script that asks the same question to all three and prints the answers. Not one provider. All three.”
“Why three?” asks Arjun. “The Claude one worked fine in the chat window.”
“Because prices change every few months, models get better and worse at different things, and providers have outages. In March, one provider’s cheap model might be best for sorting emails, and another’s for writing Marathi replies. If our code can only talk to one, we are stuck with whatever they decide. If it can talk to all three, we decide.”
Arjun estimates twenty minutes. It takes him most of the morning, and he nearly leaks a key to the whole internet along the way. This lab follows his morning, so you can skip his mistakes.
Important
The idea in one sentence: to call an LLM from code you need an account with each provider, an API key that proves who you are, the provider’s SDK installed in your project, and a safe home for the key, which is a .env file that never goes into Git.
What you are setting up, and why each piece exists
Three words first, because you will see them constantly.
An API (application programming interface) is a door that lets your program send a request to someone else’s software and receive a response. OpenAI, Google and Anthropic run their models on their own servers, behind APIs. Your code never downloads the model; it sends text through the door and gets text back.
An API key is a long secret string that your code sends with every request. It tells the provider who you are and whom to bill. It works like a password and a credit card at the same time: anyone who has your key can make requests that you pay for. Treat it like Crumb’s bank PIN.
An SDK (software development kit) is a library each provider publishes, so you can call its API with a few lines of Python instead of hand-building web requests. You will install three: openai, google-genai and anthropic.
flowchart LR
A[".env file with three keys"] --> B["load_dotenv() copies them into the environment"]
B --> C["Your Python script"]
C --> D["openai SDK"] --> G["OpenAI API"]
C --> E["google-genai SDK"] --> H["Gemini API"]
C --> F["anthropic SDK"] --> I["Claude API"]
Under the hood, each SDK does the same three things: it reads its key from an environment variable, it turns your Python call into an HTTPS request with the key in a header, and it turns the JSON response back into Python objects. Knowing this makes almost every error in this lab easy to diagnose.
Time: about 45 minutes, most of it sign-up and email verification. Cost: Gemini has a free tier. OpenAI and Anthropic need a small prepaid amount; five US dollars (about ₹450) each is plenty for this entire module. A single test question costs a fraction of a rupee.
Step 1: Create the project
Arjun’s first instinct is to put a new script in the same folder as Crumb’s order system. Priya stops him. “New folder. Its own environment. If you break something while learning, you break only that.”
Open a terminal and create a project with uv, the Python project manager from the Python refresher:
uv init crumb-ai
cd crumb-ai
uv add openai google-genai anthropic python-dotenv
uv init creates the project. uv add installs the four libraries into a private environment for this project and records them in pyproject.toml, so a teammate can recreate the same setup with one command. (Without uv, run pip install openai google-genai anthropic python-dotenv inside a virtual environment.)
python-dotenv is the fourth library: it reads a .env file and loads its values into your program’s environment variables (named settings a program can read from its surroundings, outside the code itself).
Now open .gitignore (create it if uv did not) and make sure it contains this line:
.env
This tells Git never to track a file called .env. Do this before the file exists, so there is no moment when Git could pick it up.
You should now see a crumb-ai folder containing pyproject.toml, a .gitignore that lists .env, and a .venv folder holding the installed libraries. Running uv run python -c "import openai, anthropic; from google import genai; print('ok')" should print ok.
Step 2: Get a Gemini key (free tier)
Arjun starts with Gemini because it is free.
- Open the Gemini API docs (linked at the bottom) and follow the “Get an API key” link to Google AI Studio.
- Sign in with a Google account.
- Find the API keys page and create a key. Copy it.
The free tier has rate limits (caps on how many requests you may send per minute and per day). They are generous enough for learning, and you will hit them only if you run a tight loop.
One serious caution before you use it. On free tiers, Google may use what you send to improve its products. Read the current terms, and never send real customer data through a free tier: no real names, phone numbers, addresses or order histories. While learning, use made-up test data like “Rohan, order CR-20931”. When Crumb goes live with real customers, it will use a paid tier with data terms the business has actually read.
You should now see a key beginning with AIza in your clipboard.
Step 3: Get an OpenAI key, and Arjun’s first surprise
- Go to the OpenAI developer platform at https://platform.openai.com and sign in.
- Open the Billing settings and add a small amount of prepaid credit.
- Open the API keys page, create a new secret key, and name it
crumb-ai-arjun-laptop. - Copy it immediately. Most providers show the full key only once. If you lose it, delete it and make another.
Arjun skipped step 2. He already pays for ChatGPT Plus, so he assumed his account had credit. His first request failed with an error code 429 and the message “insufficient quota”.
“ChatGPT and the API are different products with different billing,” says Priya. “Your ChatGPT subscription pays for the chat app. API usage is metered separately, per token, against the platform account’s credit.”
Why name the key after the laptop? Because a few months from now you will have keys in a laptop, a test server and a production server. If one leaks, the name tells you which to revoke without breaking the others.
You should now see a key beginning with sk- in your clipboard, and a credit balance on the billing page.
Step 4: Get a Claude key
- Open the Claude docs at https://docs.anthropic.com and follow the link to the Claude Console. Create an account.
- Add a small amount of prepaid credit in the billing settings.
- Open API keys, create a key named
crumb-ai-arjun-laptop, and copy it immediately.
You should now see a key beginning with sk-ant- in your clipboard.
Note
Pause and think. Arjun now has three keys on a sticky note next to his keyboard, “just for today”. Name two ways that could cost Crumb money, and what the safer habit is.
Show the answer
Anyone who sees the note (a visitor, a photo of the desk posted online, a screen-share) can copy a key and run requests billed to Crumb, possibly thousands of rupees of them before anyone notices. And keys copied around by hand end up pasted into chats, emails and code. The safer habit: paste each key straight from the provider’s page into the .env file, and nowhere else. If a key has been anywhere you do not control, revoke it and create a new one. It takes thirty seconds.
Step 5: Put the keys in a .env file
Create a file called .env in the crumb-ai folder:
# .env (never commit this file)
OPENAI_API_KEY=sk-...your key...
GEMINI_API_KEY=AIza...your key...
ANTHROPIC_API_KEY=sk-ant-...your key...
# Model names change often, so they live here too, not in the code.
OPENAI_MODEL=gpt-5-mini
GEMINI_MODEL=gemini-2.5-flash
No quotes, no spaces around =. The variable names matter, because each SDK looks for its own by default: OpenAI() reads OPENAI_API_KEY, genai.Client() reads GEMINI_API_KEY, and anthropic.Anthropic() reads ANTHROPIC_API_KEY. Spell one wrong and that SDK cannot find its key.
Why put model names in .env? Providers release new models and retire old ones every few months. When this course says gpt-5-mini or gemini-2.5-flash, check each provider’s models page for current names. Updating one line in .env is easier than hunting through code. (In this course, Claude examples use the model claude-opus-5-5 directly.)
Also create a file called .env.example, which is committed. It has the same variable names with empty values, so a teammate cloning the repo knows exactly which keys to get:
# .env.example (safe to commit: no real values)
OPENAI_API_KEY=
GEMINI_API_KEY=
ANTHROPIC_API_KEY=
OPENAI_MODEL=gpt-5-mini
GEMINI_MODEL=gemini-2.5-flash
Now run git init (if the folder is not a repository yet) and git status.
You should now see .env.example listed as a new file, and .env not listed at all. If .env appears, your .gitignore is wrong. Fix it before anything else.
Step 6: Say hello to all three
Create hello.py. Read it once before you run it; every part is explained below.
# hello.py: one question, three providers
import os
from dotenv import load_dotenv
load_dotenv() # copy the values from .env into environment variables
QUESTION = "In one short sentence, what is a croissant?"
def ask_openai() -> str:
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY
resp = client.chat.completions.create(
model=os.getenv("OPENAI_MODEL", "gpt-5-mini"),
messages=[{"role": "user", "content": QUESTION}],
)
return resp.choices[0].message.content
def ask_gemini() -> str:
from google import genai
client = genai.Client() # reads GEMINI_API_KEY
resp = client.models.generate_content(
model=os.getenv("GEMINI_MODEL", "gemini-2.5-flash"),
contents=QUESTION,
)
return resp.text
def ask_claude() -> str:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=2000,
messages=[{"role": "user", "content": QUESTION}],
)
return next(b.text for b in response.content if b.type == "text")
for name, fn in [("OpenAI", ask_openai), ("Gemini", ask_gemini), ("Claude", ask_claude)]:
try:
print(f"{name}: {fn()}")
except Exception as err: # keep going, so one broken key does not hide the others
print(f"{name} FAILED: {type(err).__name__}: {err}")
What each part does:
load_dotenv()must run before any client is created, or the clients will look for keys that are not loaded yet.- Each
ask_function creates a client, sends one message with the roleuser(meaning “this is the person talking”), and pulls the text out of the response. The three responses have different shapes, which you will take apart in the next lesson. - The
try/exceptaround each call means one failing provider prints its error instead of crashing the whole script. When you are debugging three providers, you want to see all three results at once.
Run it:
uv run hello.py
Arjun’s first run printed this:
OpenAI FAILED: RateLimitError: Error code: 429 - ... insufficient_quota ...
Gemini: A croissant is a buttery, flaky, crescent-shaped French pastry made from layered yeast dough.
Claude FAILED: AuthenticationError: Error code: 401 - ... invalid x-api-key ...
The OpenAI error was the missing credit from Step 3. The Claude one took longer. Priya asked him to print the key’s length:
print(len(os.getenv("ANTHROPIC_API_KEY", "")))
It was two characters longer than the key on screen. He had pasted it into .env wrapped in quote marks and with a trailing space. Removing both fixed it.
After adding credit and cleaning the key, you should now see three one-sentence definitions of a croissant, one per provider, each worded a little differently. Each call costs a tiny fraction of a rupee.
Stuck? Common errors and what they mean
AuthenticationErroror401: the key is wrong or not loaded. Check for quotes, spaces or a missing character in.env, and thatload_dotenv()runs before the client is created. Printlen(os.getenv("..."))to compare lengths without printing the secret itself.RateLimitErroror429: either no credit (OpenAI, Anthropic) or the free tier’s per-minute limit (Gemini). Add credit, or wait a minute and try again.NotFoundErroror404, “model not found”: the model name is wrong, retired, or not available to your account. Check the provider’s models page and update.env. Do not copy dated model names from old blog posts.- A warning that both
GOOGLE_API_KEYandGEMINI_API_KEYare set: the Gemini SDK will useGOOGLE_API_KEY. Remove whichever one you do not want. ModuleNotFoundError: No module named 'openai': you ranpython hello.pyoutside the project’s environment. Useuv run hello.py.- Nothing happens for a long time: usually a network or proxy problem on office Wi-Fi. Try a phone hotspot to confirm.
Note
Pause and think. Arjun wonders why hello.py gave three different croissant sentences, and why running it again gives slightly different wording from the same provider. Using what you learned earlier in this module, explain both.
Show the answer
Different providers mean different models, trained on different text with different extra tuning, so their most likely continuations differ. And the same model varies between runs because of sampling: at each token it picks from a probability list rather than always taking the top choice. None of the three is “the right one”. They are three plausible answers from three different writers.
Step 7: Put a fence around your spending
Before you write any loop that could call an API ten thousand times by accident, protect yourself. Priya tells Arjun about a colleague at her old company whose script retried a failing request in an infinite loop overnight, at roughly two requests per second, for nine hours. Each call was cheap. Sixty-five thousand of them were not.
- In each provider’s console, find the limits, budget or usage settings, and set a monthly spending cap or email alert. A few dollars is right for learning.
- Keep prepaid credit small. Auto-recharge is convenient in production but dangerous while learning.
- Look at each provider’s usage page now, after your hello script. You should see a tiny charge, or a few requests on the free tier. Get used to checking it; it is the ground truth for what your code costs.
Warning
If a key is ever pushed to GitHub, even to a private repository, even for a minute, treat it as stolen. Bots scan public code for keys within minutes. Revoke the key in the provider’s console, create a new one, and update .env. Deleting the commit is not enough, because the key remains in Git history.
You should now see a spending limit or alert configured on every account that holds credit, and your first requests visible on each usage page.
Step 8: Check you did not commit a secret
This is the step Arjun almost skipped. Before lunch he ran git add . and was about to commit. Because his .gitignore had a typo (.evn), git status listed .env as a new file. Priya happened to be walking past.
Run this every time before your first commit in a new project:
git status
git check-ignore -v .env
git check-ignore -v .env prints the .gitignore rule that ignores .env. If it prints nothing, the file is not ignored, and you must fix .gitignore before committing.
You should now see output like .gitignore:1:.env .env, confirming the rule is in place.
Recap
- Each provider gives you an account, an API key and a Python SDK; API billing is separate from consumer chat subscriptions.
- Keys live in
.env, loaded withpython-dotenvbefore the clients are created, and.envis listed in.gitignore. - Each SDK reads its own variable:
OPENAI_API_KEY,GEMINI_API_KEY,ANTHROPIC_API_KEY. - Model names change, so keep them in
.envand check the providers’ models pages. 401usually means a bad key,429means no credit or too many requests,404means a wrong model name.- Set spending limits before writing loops, and revoke any key that leaks.
Just before lunch, Arjun’s script prints three croissant definitions and he posts a screenshot in the team chat. Priya replies with a single question: “Great. Now tell me how many tokens each one used, and why each one stopped talking.”
Arjun scrolls back through his output. Neither number is there. “Where would I even find those?”
Go deeper
- OpenAI platform docs, quickstart and API keys: https://platform.openai.com/docs
- Gemini API docs, quickstart and API keys: https://ai.google.dev/gemini-api/docs
- Claude docs, getting started: https://docs.anthropic.com
- uv docs, managing project dependencies: https://docs.astral.sh/uv/