Environment Setup
A good setup saves hours of frustration later. In this session we refresh the Python you need, set up virtual environments, Jupyter and Colab, learn the everyday Git workflow, keep API keys safe, and meet the two UI tools we use all through the course: Streamlit and Gradio.
In this session
- Python refresher: functions, type hints and classes
- Virtual environments and pip
- Jupyter Notebook and Google Colab with a free GPU
- Git and GitHub: the daily workflow
- API keys, .env files and secrets hygiene
- Streamlit vs Gradio
01Python refresher for AI
You do not need advanced Python for this course, but you must be comfortable with functions, lists and dictionaries, and simple classes. LLM APIs send and receive lists of dictionaries all the time, so this example uses a chat history:
# Functions: reusable blocks with inputs and a return value
def count_tokens(text: str, chars_per_token: float = 4.0) -> int:
"""Rough token estimate for English text."""
return max(1, round(len(text) / chars_per_token))
# A small class: data (attributes) + behaviour (methods) together
class ChatHistory:
def __init__(self, system_prompt: str):
self.messages = [{"role": "system", "content": system_prompt}]
def add(self, role: str, content: str) -> None:
self.messages.append({"role": role, "content": content})
def total_tokens(self) -> int:
return sum(count_tokens(m["content"]) for m in self.messages)
def __len__(self):
return len(self.messages)
chat = ChatHistory("You are a helpful banking assistant.")
chat.add("user", "How do I reset my UPI PIN?")
chat.add("assistant", "Open your UPI app, choose the bank account and tap 'Reset UPI PIN'.")
print(len(chat), "messages")
print("approx tokens:", chat.total_tokens())
print([m["role"] for m in chat.messages])| Concept | In the code | Why it matters for AI |
|---|---|---|
| Function with type hints | count_tokens(text: str) -> int | Clear inputs and outputs; LLM tool schemas use the same idea |
| Default argument | chars_per_token=4.0 | Sensible defaults like temperature=0.7 |
| Class | ChatHistory | Bundle data (messages) with behaviour (add, count) |
__init__ | runs when the object is created | Set up starting state, e.g. the system prompt |
| List of dicts | [{"role": ..., "content": ...}] | The exact format chat APIs expect |
02Virtual environments and pip
Different projects need different library versions. A virtual environment is a private folder of packages for one project, so projects do not break each other.
python -m venv .venv # create source .venv/bin/activate # activate (macOS/Linux) .venv\Scripts\activate # activate (Windows) pip install openai streamlit python-dotenv pip freeze > requirements.txt # save exact versions pip install -r requirements.txt # recreate on another machine deactivate
Like a separate tiffin box for each meal. Keep each project’s packages in its own box, so the dal from one does not spill into the rice of another.
.venv/ to .gitignore. Share requirements.txt, not the environment folder.03Jupyter Notebook and Google Colab
To get a GPU in Colab: Runtime → Change runtime type → T4 GPU → Save. Check it worked:
!nvidia-smi # shows the GPU name and memory import torch print(torch.cuda.is_available()) # True means PyTorch can use the GPU
- The
!runs a shell command inside a notebook cell. - Colab already has PyTorch installed. Install extras with
!pip install transformers. - Colab storage is temporary: save work to Google Drive or GitHub.
04Git and GitHub workflow
Git tracks every change to your code; GitHub stores it online and lets you collaborate. This is the daily workflow for the course repository:
05API keys, .env files and secrets hygiene
An API key is like your ATM PIN for an AI service: whoever has it can spend your money. Never put keys in your code. Put them in a .env file and load them at runtime:
OPENAI_API_KEY=sk-demo-1234567890abcdef APP_ENV=dev
# pip install python-dotenv
import os
from dotenv import load_dotenv
load_dotenv() # reads .env from the current folder
key = os.getenv("OPENAI_API_KEY")
if not key:
raise SystemExit("OPENAI_API_KEY is missing. Add it to your .env file.")
print("Environment:", os.getenv("APP_ENV", "prod"))
print("Key loaded:", key[:6] + "..." + key[-4:]) # never print the full key.env .venv/ __pycache__/ .ipynb_checkpoints/
| Do ✅ | Don’t ❌ |
|---|---|
| Keep keys in .env or a secrets manager | Paste keys into notebooks you share |
| Add .env to .gitignore before the first commit | Commit keys to GitHub, even to a private repo |
| Use separate keys for dev and production | Share one key across the whole team |
| Set spending limits; rotate keys regularly | Print the full key in logs |
06Streamlit and Gradio
We will put a simple web page in front of most projects. Two tools make this a few lines of Python:
| Streamlit | Gradio | |
|---|---|---|
| Style | Script that reruns top to bottom | Wrap a function |
| Best for | Dashboards, multi-page apps, data apps | Quick model demos, chat UIs |
| Chat UI | st.chat_input, st.chat_message | gr.ChatInterface |
| Free hosting | Streamlit Community Cloud | Hugging Face Spaces |
With the input “How do I reset my UPI PIN?”, both apps show about 6 tokens (26 characters ÷ 4). Module 2 explains real tokenization.
07Summary
- Know functions, lists of dicts and simple classes: LLM APIs use them everywhere.
- One virtual environment per project; share
requirements.txt. - Use Colab for a free GPU; save work to Drive or GitHub.
- Git workflow: branch → add → commit → push → pull request.
- Keys live in .env (ignored by Git) or a secrets manager, never in code.
- Streamlit for apps and dashboards, Gradio for quick model demos.
08Quick quiz
1. Why use a virtual environment?
2. How do you get a GPU in Google Colab?
3. Which file should be in .gitignore?
4. What does git commit do?
5. Gradio’s main idea is…