GenAI Course · Module 1 · Session 3

Environment Setup

⏱ 14 min read🎯 Beginner friendly🖼 2 diagrams🧪 2 live demos🐍 Python code

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:

refresher.py
# 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])
3 messages approx tokens: 32 ['system', 'user', 'assistant']
ConceptIn the codeWhy it matters for AI
Function with type hintscount_tokens(text: str) -> intClear inputs and outputs; LLM tool schemas use the same idea
Default argumentchars_per_token=4.0Sensible defaults like temperature=0.7
ClassChatHistoryBundle data (messages) with behaviour (add, count)
__init__runs when the object is createdSet 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.

terminal
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.

Tip: add .venv/ to .gitignore. Share requirements.txt, not the environment folder.

03Jupyter Notebook and Google Colab

Jupyter (local)• runs on your laptop• your files, no upload• limited by your hardware• pip install notebookGoogle Colab (cloud)• runs in the browser• free GPU (T4) runtime• sessions time out• nothing to install
Both run notebooks: code cells and notes in one document.

To get a GPU in Colab: Runtime → Change runtime type → T4 GPU → Save. Check it worked:

colab_cell.py
!nvidia-smi                      # shows the GPU name and memory
import torch
print(torch.cuda.is_available())  # True means PyTorch can use the GPU

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:

Demo · The Git workflow
Working folderedit filesgit addstage changesgit commitsave a snapshotgit pushupload to GitHub
Every change goes: edit → add → commit → push.

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:

.env
OPENAI_API_KEY=sk-demo-1234567890abcdef
APP_ENV=dev
load_env.py
# 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
Environment: dev Key loaded: sk-dem...cdef
.gitignore
.env
.venv/
__pycache__/
.ipynb_checkpoints/
Do ✅Don’t ❌
Keep keys in .env or a secrets managerPaste keys into notebooks you share
Add .env to .gitignore before the first commitCommit keys to GitHub, even to a private repo
Use separate keys for dev and productionShare one key across the whole team
Set spending limits; rotate keys regularlyPrint the full key in logs
Leaked a key? Revoke it in the provider dashboard immediately and create a new one. Deleting the commit is not enough: bots scan GitHub for keys within minutes.

06Streamlit and Gradio

We will put a simple web page in front of most projects. Two tools make this a few lines of Python:

Demo · Same app, two tools
StreamlitGradio
StyleScript that reruns top to bottomWrap a function
Best forDashboards, multi-page apps, data appsQuick model demos, chat UIs
Chat UIst.chat_input, st.chat_messagegr.ChatInterface
Free hostingStreamlit Community CloudHugging 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

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…

09References

Created by Ajeetkumar