Your first LLM API call in Python
Set up a virtual env, store keys safely, make the call, read the full response and handle failures.
Every serious AI product starts with an API call. We will use the OpenAI Python SDK, but the same pattern works for Gemini, Claude, Groq or a local model via an OpenAI-compatible endpoint.
An API call is an ordinary HTTPS request. Your code sends JSON (which model, which messages, a few settings) with your API key in a header. The provider runs the model on its servers and sends JSON back: the reply text plus a usage count of the tokens you will be billed for. The SDK is a thin, friendly wrapper around that one request.
Swipe to see the full diagram →
Your code talks to a hosted model over HTTPS and gets text + usage back.
Set up the project properly
A virtual environment gives this project its own Python packages, so installing something here never breaks your DSA or college project folders. Do this once per project.
mkdir study-buddy && cd study-buddy
python -m venv .venv
source .venv/bin/activate
pip install "openai>=1.0" python-dotenv
echo "OPENAI_API_KEY=paste-your-key-here" > .env
echo ".env" >> .gitignore
echo ".venv/" >> .gitignoreOn Windows, activate with .venv\Scripts\Activate.ps1 and create the .env file in VS Code instead of using echo: PowerShell can save redirected text in an encoding that python-dotenv fails to read. The .env file is one line: OPENAI_API_KEY= followed by your key, with no spaces around the equals sign.
You create the key on the provider's dashboard. It is shown only once, so copy it straight into .env. API usage is billed separately from a ChatGPT subscription. If you do not want to add a card yet, some providers have a free tier (check their current pricing page), and a local model through Ollama costs nothing per call. The code in this lesson works with all of them, as you will see near the end.
The call itself
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads .env and puts OPENAI_API_KEY into the environment
client = OpenAI() # finds the key in the environment by itself
resp = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0.3,
max_tokens=300,
messages=[
{"role": "system", "content": "You are a patient DSA tutor."},
{"role": "user", "content": "Explain binary search like I am in 2nd year."},
],
)
choice = resp.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)
print("input tokens: ", resp.usage.prompt_tokens)
print("output tokens:", resp.usage.completion_tokens)- load_dotenv() reads .env and puts OPENAI_API_KEY into the environment. OpenAI() then finds the key there by itself, so the key never appears in your code.
- model picks which model answers. Small models such as gpt-4o-mini are cheaper and faster, which is what you want while learning.
- temperature is the randomness setting from the last lesson. 0.3 keeps a tutor consistent without sounding robotic.
- max_tokens caps the length of the answer, and so caps what one call can cost. (OpenAI's newer reasoning models call this setting max_completion_tokens.)
- messages is the conversation so far: a list of role and content pairs.
The three roles
- system: standing instructions from you, the developer. Who the model is, what it must and must not do, how to format answers.
- user: what the person typed, or the data your program wants processed.
- assistant: the model's earlier replies. You add these back when you resend a conversation.
Because the model is stateless, a follow-up question only works if you send the earlier turns again. This chat loop does exactly that: it keeps one list, appends every question and every reply, and sends the full list each time. Watch the input token count climb as you chat.
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
messages = [
{"role": "system", "content": "You are a placement mentor. Keep answers under 80 words."},
]
while True:
user_text = input("you> ").strip()
if user_text.lower() in {"exit", "quit"}:
break
messages.append({"role": "user", "content": user_text})
resp = client.chat.completions.create(model="gpt-4o-mini", messages=messages)
reply = resp.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
print("bot>", reply)
print(f" (input tokens this turn: {resp.usage.prompt_tokens})")Read the whole response, not just the text
The reply text is at resp.choices[0].message.content, but two other fields save you hours of debugging.
- finish_reason: "stop" means the model finished on its own. "length" means it was cut off by max_tokens or the context limit, so the answer is incomplete.
- usage: prompt_tokens is what you sent, completion_tokens is what the model wrote, total_tokens is the sum. This is what you are billed on, so log it from day one.
Providers price input and output tokens separately, and output is usually the more expensive of the two. You do not need to memorise prices. You do need the habit of checking usage: a chat that quietly resends a long history on every turn is a classic way to burn through a small budget.
When things go wrong: timeouts, retries and streaming
Network calls fail. A key gets revoked, the hostel Wi-Fi drops, or the provider answers with a 429 error because you sent too much too fast. A real program sets a timeout, lets the SDK retry a couple of times, and prints an error a human can act on. Streaming is the other production habit: print the words as they arrive, so the user sees progress instead of a frozen screen.
import os
import sys
from dotenv import load_dotenv
from openai import APIConnectionError, APIStatusError, AuthenticationError, OpenAI, RateLimitError
load_dotenv()
if not os.getenv("OPENAI_API_KEY"):
sys.exit("OPENAI_API_KEY is not set. Create a .env file next to this script.")
client = OpenAI(timeout=30, max_retries=2) # give up after 30 s, retry twice on temporary errors
def ask(question: str) -> None:
try:
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": question}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
except AuthenticationError:
sys.exit("The API key was rejected. Check OPENAI_API_KEY in your .env file.")
except RateLimitError:
sys.exit("Rate limit or quota reached. Wait a little, or check billing on the dashboard.")
except APIConnectionError:
sys.exit("Could not reach the API. Check your internet connection.")
except APIStatusError as err:
sys.exit(f"The API returned an error (HTTP {err.status_code}).")
ask("Give me a 3-step plan to revise DBMS before a placement test.")Same code, different provider
Many providers and local servers accept the same request format as OpenAI. That means you can keep the SDK and change only three things: the base URL, the key and the model name. This version reads all three from the environment and defaults to a model running on your own laptop through Ollama (install Ollama, then run ollama pull llama3.1 once).
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
# Same SDK, different server. Only the base URL, the key and the model name change.
client = OpenAI(
base_url=os.getenv("LLM_BASE_URL", "http://localhost:11434/v1"), # default: Ollama on your laptop
api_key=os.getenv("LLM_API_KEY", "ollama"), # Ollama ignores the key, but the SDK needs a value
)
model = os.getenv("LLM_MODEL", "llama3.1")
resp = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "In one line, what is a virtual environment?"}],
)
print(resp.choices[0].message.content)To point it at a hosted provider instead, set LLM_BASE_URL, LLM_API_KEY and LLM_MODEL in your .env. For example, Groq's OpenAI-compatible endpoint is https://api.groq.com/openai/v1. Check each provider's docs for its URL and model names.
Keys are passwords
- Add .env to .gitignore before your first commit, not after.
- Never put a key in frontend JavaScript, a mobile app or a public notebook. Anyone can read it there. Call the model from your backend.
- If a key leaks, revoke it on the provider dashboard and create a new one. Deleting the commit is not enough: the key is still in the git history and may already have been copied.
- When you deploy, set the key as an environment variable in the hosting platform's settings. Do not upload .env.
- Set a monthly spending limit on the provider dashboard if it offers one.
Never commit your .env. Bots scan public GitHub repos for keys all day, and a leaked key can be abused within minutes.
Common mistakes
- Naming your script openai.py. Python then imports your file instead of the library and the import fails. Call it hello_llm.py.
- Forgetting to activate the virtual environment, then seeing ModuleNotFoundError: No module named 'openai'.
- Copying an old tutorial that uses openai.ChatCompletion.create. That style was removed in version 1.0 of the SDK. Use client.chat.completions.create.
- Running the script where load_dotenv() cannot find .env. Keep .env in the project folder, next to your script.
- Assuming a ChatGPT subscription includes API usage. They are billed separately.
- Ignoring finish_reason and shipping answers that stop mid-sentence.
- Putting an API call inside a loop with no max_tokens and no usage logging.
How this shows up in interviews
- Q: Walk me through what happens when your code calls an LLM API. A: The SDK sends an HTTPS POST with the model name, the messages and settings, and my key in the Authorization header. The provider tokenises the input, runs the model and returns JSON with the choices and a usage block. I read choices[0].message.content, check finish_reason and log usage.
- Q: How do you handle API keys in a project? A: Environment variables. A .env file that is in .gitignore for local work, the platform's secret settings in deployment, and never in client-side code. If a key leaks I revoke and rotate it, and I keep a spending limit on the account.
- Q: What is the difference between the system, user and assistant roles? A: System holds the developer's standing instructions, user holds the person's input, assistant holds the model's previous replies. Since the model is stateless, I resend all of them to continue a conversation.
- Q: The API is slow or failing in production. What do you do? A: Set timeouts, retry rate-limit and server errors with backoff, show the user a clear message, and stream the response so the first words appear quickly. I also log tokens and latency per call to see where the time goes.
Keep the model name and base URL in configuration, not scattered through your code. Swapping providers then becomes a one-line change, and being able to say you designed for that is a strong point in an interview.
Build the module project as study_buddy.py: running python study_buddy.py "binary search" prints a beginner, an intermediate and an expert explanation of the topic, followed by the total tokens used. It must read the key from .env, exit with a clear message if the key is missing, and set max_tokens. Push it to GitHub with .env in .gitignore and a README that shows one sample run.
Stuck? That's normal. Ask in the community Discord or email hello@beyondplaced.com. No question is too basic.