Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
LLM Engineering LLM Engineering: From Zero to Production Module 2 - Working with LLM APIs

Setting Up Your Environment: Python, API Keys, and First Call

Reviewed & accurate
AI Summary

What You Will Learn

BEGINNER
  • Install Python, pip, and the OpenAI SDK in 5 minutes
  • Secure API key management (so you never leak a key)
  • Your first working "hello LLM" script — and what's actually happening

Step 1: Install Python & pip

If you don't have Python yet, install Python 3.11 or newer from python.org. On macOS, use brew install python. On Linux, your distro package manager (apt install python3). Verify it works:

Terminal
$ python --version
Python 3.11.9
$ pip --version
pip 24.0 from /usr/lib/python3.11/site-packages/pip (python 3.11)

Step 2: Get an OpenAI API Key

Go to platform.openai.com/api-keys, sign in, click "Create new secret key", copy it. Treat this key like a credit card — anyone with it can spend your money. The key looks like sk-proj-abc123... (about 100 characters).

CRITICAL: Never Hardcode Keys
Never paste your API key directly into code you share or push to GitHub. Leaked keys are scraped by bots in minutes and burned through $1,000s of credits before you notice. Always load from environment variables or a secrets manager.

Step 3: Secure API Key Management

The right way: store your key in an environment variable. Create a file called .env in your project folder:

.envbash
# .env file (NEVER commit this to git!)
OPENAI_API_KEY=sk-proj-your-actual-key-habcdefg1234567890

# Add .env to your .gitignore:
echo ".env" >> .gitignore

Then in Python, use the python-dotenv library to load it:

load_key.pypython
# Install: pip install openai python-dotenv
from dotenv import load_dotenv
import os

load_dotenv()  # loads variables from .env file
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise SystemExit("Set OPENAI_API_KEY in your .env file!")

Step 4: Your First LLM Call

Now the magic moment. With your key loaded, here's a complete working script:

hello_llm.pypython
from dotenv import load_dotenv
from openai import OpenAI
import os

load_dotenv()
client = OpenAI()  # auto-reads OPENAI_API_KEY from env

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful teacher."},
        {"role": "user", "content": "Explain what an API is, in one sentence."},
    ],
)

print(response.choices[0].message.content)
Terminal
$ python hello_llm.py
An API is a set of rules that lets different software programs talk to each other and share data.
What Happens When You Call the API Your Pythonsend messages HTTPS POST OpenAI APIroutes to GPT-4o-mini JSON response Your Pythonprint response
Your script sends an HTTPS POST with messages. OpenAI runs the model and returns a JSON response. Total round-trip: 500-2000ms.

What's Actually in the Response?

The response is a Python object with several useful fields. Let's print them all:

inspect_response.pypython
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Say hi"}],
)

# The main text
print("Answer:", response.choices[0].message.content)
# The reason the model stopped (usually "stop")
print("Finish reason:", response.choices[0].finish_reason)
# Token usage (for cost tracking)
print("Tokens used:", response.usage)
# Which model was actually used
print("Model:", response.model)
Terminal
$ python inspect_response.py
Answer: Hi there! How can I help you today?
Finish reason: stop
Tokens used: CompletionUsage(completion_tokens=10, prompt_tokens=12, total_tokens=22)
Model: gpt-4o-mini-2024-07-18
🌍 REAL WORLD: Cost Tracking in Production
In production apps, always log response.usage.total_tokens per request. Multiply by the model's per-token price to compute cost. Tools like Helicone and LangSmith (Lesson 71) do this automatically — but for a quick script, logging usage yourself takes 2 lines of code and saves surprises on your bill.

Step 5: Set Up a Project Folder

Best practice for any LLM project: one folder per project, with a clean structure:

project_structurebash
my-llm-app/
├── .env                  # API keys (gitignored)
├── .gitignore            # tells git to ignore .env
├── requirements.txt      # pip dependencies
├── main.py               # entry point
├── prompts/              # your prompt templates
│   └── system.txt
└── tests/                # unit tests
    └── test_api.py

Create requirements.txt with your pinned dependencies:

requirements.txttext
# requirements.txt
openai>=1.50.0
python-dotenv>=1.0.1
tiktoken>=0.7.0
pydantic>=2.0

Then anyone can reproduce your environment with pip install -r requirements.txt.

Install Python 3.11+ and verify with python --version
Sign up at platform.openai.com, add $5 of credit, generate an API key
Create your project folder, add .env with your key, add .env to .gitignore
Install dependencies: pip install openai python-dotenv
Run the hello_llm.py script above — you should get an answer back in 1-2 seconds
Print response.usage to see how many tokens your call used (multiply by $0.15 / 1M to see cost)

🎯 Key Takeaways

  • Install Python 3.11+, the openai SDK, and python-dotenv — that's all you need to start.
  • NEVER hardcode API keys. Always load from .env via os.getenv().
  • Your first call is just: client.chat.completions.create(model, messages).
  • Always log response.usage.total_tokens to track costs.
  • Use a clean project structure: .env, requirements.txt, main.py, prompts/.

🧠 Quick Check

Q1. Why must you never hardcode API keys in Python source?
→ Keys pushed to GitHub are scraped by bots in minutes. Stolen keys are used to run up charges against your account before you notice.
Q2. What does response.usage.total_tokens tell you?
→ Total tokens used (input + output). Multiply by the model's price per token to compute the cost of that API call.
Q3. What's the minimum viable call to the OpenAI Chat Completions API?
→ client.chat.completions.create(model='gpt-4o-mini', messages=[{'role':'user','content':'hi'}]) — model + messages is enough.
Previously: Previously: Lesson 08 surveyed the 2026 LLM landscape.
Today: Today: you set up Python, secured your API key, made your first LLM call, and inspected the response.
Next: Next: Lesson 10 deep-dives every parameter of the Chat Completions API — temperature, top_p, max_tokens, response_format, and more.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments