Skip to content

Session 1: Setting Up a Python GenAI Workspace

Synopsis

Covers environment setup for GenAI development, including package management, environment variables, API key handling, notebook versus application workflows, and project structure. Learners establish good habits for secure and maintainable experimentation.

Session Content

Session 1: Setting Up a Python GenAI Workspace

Session Overview

In this session, learners will set up a clean, reproducible Python workspace for building GenAI applications. The focus is on installing the right tools, creating isolated environments, securely managing API keys, installing the OpenAI Python SDK, and running a first successful request using the OpenAI Responses API with gpt-5.4-mini.

By the end of this session, learners will be able to:

  • Create and activate a Python virtual environment
  • Install and verify the required Python packages
  • Store API credentials securely using environment variables
  • Use the OpenAI Python SDK to make a first model request
  • Organize a small GenAI project workspace with good development practices

Session Duration

~45 minutes

Suggested pacing:

  • 10 min — Why workspace setup matters
  • 10 min — Python environment setup
  • 10 min — Installing dependencies and configuring secrets
  • 10 min — First OpenAI Responses API call
  • 5 min — Wrap-up and troubleshooting

1. Why a Proper GenAI Workspace Matters

Before writing GenAI code, it is important to set up a reliable development environment.

Key reasons

  • Isolation: Avoid package conflicts between projects
  • Security: Keep API keys out of source code
  • Reproducibility: Make it easy to rerun the same project later
  • Maintainability: Use a clean folder structure and dependency list
  • Debuggability: Know exactly what tools and versions are in use
  • Use a virtual environment for every project
  • Store secrets in environment variables
  • Keep dependencies in requirements.txt
  • Separate source code from configuration
  • Add a .gitignore file early

2. Prerequisites

Learners should have:

  • Basic Python knowledge
  • Python 3.10+ installed
  • A code editor such as VS Code
  • A terminal or command prompt
  • An OpenAI API key

Check Python version

Run:

python --version

or, on some systems:

python3 --version

Example output:

Python 3.11.8

3. Creating a Project Workspace

A simple project structure helps keep GenAI experiments organized.

genai-workspace/
├── .venv/
├── src/
│   └── first_call.py
├── .env
├── .gitignore
├── requirements.txt
└── README.md

Create the folder

mkdir genai-workspace
cd genai-workspace
mkdir src

4. Creating and Activating a Virtual Environment

A virtual environment keeps project dependencies isolated from the global Python installation.

Create the virtual environment

macOS/Linux

python3 -m venv .venv

Windows

python -m venv .venv

Activate the environment

macOS/Linux

source .venv/bin/activate

Windows Command Prompt

.venv\Scripts\activate

Windows PowerShell

.venv\Scripts\Activate.ps1

Confirm activation

Your terminal prompt should show something like:

(.venv) user@machine genai-workspace %

5. Installing Required Packages

For this session, install:

  • openai — OpenAI Python SDK
  • python-dotenv — load environment variables from a .env file

Install packages

pip install openai python-dotenv

Save dependencies

pip freeze > requirements.txt

Example requirements.txt:

openai==1.108.1
python-dotenv==1.0.1

Version numbers may differ depending on installation time.


6. Managing API Keys Securely

Never hardcode API keys directly in Python source files.

Create a .env file

In the project root, create:

OPENAI_API_KEY=your_api_key_here

Create a .gitignore file

.venv/
.env
__pycache__/
*.pyc

Why this matters

  • Prevents accidental secret leaks
  • Makes local development easier
  • Keeps credentials separate from code

7. Installing and Verifying the OpenAI SDK

Create a quick verification script to ensure the package is installed correctly.

File: src/check_install.py

"""
Simple verification script to confirm that the OpenAI SDK is installed.

Run:
    python src/check_install.py
"""

from openai import OpenAI


def main() -> None:
    """Create a client instance and print a success message."""
    client = OpenAI()
    print("OpenAI SDK imported successfully.")
    print(f"Client type: {type(client).__name__}")


if __name__ == "__main__":
    main()

Run the script

python src/check_install.py

Example output

OpenAI SDK imported successfully.
Client type: OpenAI

This only verifies installation. It does not yet confirm your API key works.


8. Your First OpenAI Responses API Call

Now create a script that sends a real prompt to gpt-5.4-mini using the Responses API.

File: src/first_call.py

"""
Make a first request to the OpenAI Responses API using gpt-5.4-mini.

Requirements:
    - OPENAI_API_KEY must be set in the environment or .env file
    - openai and python-dotenv packages must be installed

Run:
    python src/first_call.py
"""

from dotenv import load_dotenv
from openai import OpenAI


def main() -> None:
    """
    Load environment variables, create an OpenAI client,
    send a prompt, and print the model's response.
    """
    # Load variables from a local .env file if present.
    load_dotenv()

    # The client automatically reads OPENAI_API_KEY from the environment.
    client = OpenAI()

    # Send a simple prompt using the Responses API.
    response = client.responses.create(
        model="gpt-5.4-mini",
        input="Write a short welcome message for students starting a Python GenAI course."
    )

    # output_text is the simplest way to access the generated text.
    print("Model response:\n")
    print(response.output_text)


if __name__ == "__main__":
    main()

Run the script

python src/first_call.py

Example output

Model response:

Welcome to your Python GenAI journey! In this course, you'll learn how to build intelligent applications that can generate text, respond to prompts, and power useful AI-driven workflows. Get ready to experiment, create, and level up your Python skills.

9. Understanding the First API Call

Let us break down the important lines from the script.

Loading environment variables

load_dotenv()

This reads values from .env and makes them available as environment variables.

Creating the client

client = OpenAI()

The SDK automatically uses OPENAI_API_KEY if available in the environment.

Sending a request

response = client.responses.create(
    model="gpt-5.4-mini",
    input="Write a short welcome message for students starting a Python GenAI course."
)

This sends a prompt to the specified model using the Responses API.

Reading the result

print(response.output_text)

This is the easiest way to access the text generated by the model.


10. Hands-On Exercise 1: Build a Workspace from Scratch

Goal

Create a fully working Python GenAI project folder on your machine.

Tasks

  1. Create a folder called genai-workspace
  2. Create a virtual environment named .venv
  3. Activate the virtual environment
  4. Install openai and python-dotenv
  5. Create:
  6. .env
  7. .gitignore
  8. src/
  9. requirements.txt
  10. Add your API key to .env
  11. Save a screenshot or note showing your environment is activated

Expected result

Your project should look similar to:

genai-workspace/
├── .venv/
├── src/
├── .env
├── .gitignore
└── requirements.txt

11. Hands-On Exercise 2: Make Your First Model Request

Goal

Run a successful request with gpt-5.4-mini using the Responses API.

Instructions

  1. Create src/first_call.py
  2. Copy the code from the earlier example
  3. Change the prompt to:
Give me 3 encouraging tips for learning Python and GenAI.
  1. Run the script
  2. Save the output

Example solution

"""
Exercise 2 solution: send a simple prompt to gpt-5.4-mini.

Run:
    python src/first_call.py
"""

from dotenv import load_dotenv
from openai import OpenAI


def main() -> None:
    """Request 3 learning tips and print the result."""
    load_dotenv()
    client = OpenAI()

    response = client.responses.create(
        model="gpt-5.4-mini",
        input="Give me 3 encouraging tips for learning Python and GenAI."
    )

    print("Tips from the model:\n")
    print(response.output_text)


if __name__ == "__main__":
    main()

Example output

Tips from the model:

1. Start small and practice consistently—short daily coding sessions build real confidence.
2. Experiment freely—GenAI is best learned by trying prompts, inspecting outputs, and improving your code step by step.
3. Be patient with yourself—both Python and AI concepts become much clearer through repetition and hands-on projects.

12. Hands-On Exercise 3: Create a Reusable Prompt Script

Goal

Make your script more reusable by letting the user define the prompt in code.

Instructions

Create a new file: src/prompt_runner.py

The script should:

  • Load the API key from .env
  • Store a prompt in a Python variable
  • Send it to gpt-5.4-mini
  • Print the prompt and response clearly

Example solution

"""
Reusable prompt runner using the OpenAI Responses API.

Run:
    python src/prompt_runner.py
"""

from dotenv import load_dotenv
from openai import OpenAI


def main() -> None:
    """Run a configurable prompt against gpt-5.4-mini."""
    load_dotenv()
    client = OpenAI()

    # Change this prompt to test different ideas.
    prompt = "Explain in 4 bullet points why virtual environments are useful in Python."

    response = client.responses.create(
        model="gpt-5.4-mini",
        input=prompt
    )

    print("Prompt:")
    print(prompt)
    print("\nResponse:")
    print(response.output_text)


if __name__ == "__main__":
    main()

Example output

Prompt:
Explain in 4 bullet points why virtual environments are useful in Python.

Response:
- They isolate dependencies for each project.
- They reduce version conflicts between libraries.
- They make projects easier to reproduce on other machines.
- They help keep your global Python installation clean.

13. Common Errors and Troubleshooting

Error: ModuleNotFoundError: No module named 'openai'

Cause: The package is not installed in the active environment.

Fix:

pip install openai

Also verify the virtual environment is activated.


Error: OPENAI_API_KEY not found

Cause: The environment variable is missing or .env was not loaded.

Fixes:

  • Check the .env file name and location
  • Ensure it contains:
OPENAI_API_KEY=your_api_key_here
  • Confirm your script calls:
load_dotenv()

Error: authentication failure

Cause: The API key is invalid, expired, or copied incorrectly.

Fixes:

  • Recopy the API key carefully
  • Ensure there are no extra spaces or quotes
  • Generate a new key if needed

Error: wrong Python interpreter in editor

Cause: Your editor may be using global Python instead of .venv.

Fix:

In VS Code:

  • Open Command Palette
  • Search: Python: Select Interpreter
  • Choose the interpreter inside .venv

14. Best Practices Introduced in This Session

By the end of this session, learners should already be using these habits:

  • One project, one virtual environment
  • Secrets stored in .env
  • Dependencies tracked in requirements.txt
  • Source files stored in src/
  • Clear, minimal scripts that can be tested quickly
  • Responses API used for all prompt examples

These habits will make future sessions easier when projects become more complex.


15. Mini Project: Workspace Readiness Checklist

Use this checklist to confirm your setup is complete.

Checklist

  • [ ] Python 3.10+ is installed
  • [ ] Project folder created
  • [ ] Virtual environment created
  • [ ] Virtual environment activated
  • [ ] openai installed
  • [ ] python-dotenv installed
  • [ ] .env file created
  • [ ] OPENAI_API_KEY stored securely
  • [ ] .gitignore includes .env and .venv/
  • [ ] src/first_call.py runs successfully
  • [ ] A response from gpt-5.4-mini is printed

16. Recap

In this session, learners set up the foundation for all future GenAI work in Python.

They learned how to:

  • Set up a dedicated project workspace
  • Use a virtual environment
  • Install the OpenAI Python SDK
  • Manage secrets safely
  • Make a first successful request with the OpenAI Responses API
  • Use gpt-5.4-mini from Python

This workspace will be reused and expanded in later sessions for prompt engineering, structured outputs, tool usage, and agentic workflows.


Useful Resources


Optional Homework

  1. Create a new script called src/three_prompts.py
  2. Send three different prompts to gpt-5.4-mini
  3. Print a separator line between outputs
  4. Try prompts for:
  5. explanation
  6. summarization
  7. brainstorming

Homework starter code

"""
Optional homework: run multiple prompts in a single script.

Run:
    python src/three_prompts.py
"""

from dotenv import load_dotenv
from openai import OpenAI


def main() -> None:
    """Send multiple prompts and print their outputs."""
    load_dotenv()
    client = OpenAI()

    prompts = [
        "Explain what a Python virtual environment is in 2 sentences.",
        "Summarize why API keys should be stored securely.",
        "Brainstorm 5 beginner project ideas using Python and GenAI."
    ]

    for index, prompt in enumerate(prompts, start=1):
        response = client.responses.create(
            model="gpt-5.4-mini",
            input=prompt
        )

        print(f"\n--- Prompt {index} ---")
        print(prompt)
        print("\nResponse:")
        print(response.output_text)


if __name__ == "__main__":
    main()

Example output

--- Prompt 1 ---
Explain what a Python virtual environment is in 2 sentences.

Response:
A Python virtual environment is an isolated environment for installing project-specific packages. It helps prevent dependency conflicts between different projects.

--- Prompt 2 ---
Summarize why API keys should be stored securely.

Response:
API keys should be stored securely to prevent unauthorized access, accidental misuse, and exposure in shared code repositories.

--- Prompt 3 ---
Brainstorm 5 beginner project ideas using Python and GenAI.

Response:
1. A study helper that explains concepts in simple language
2. A prompt-based idea generator for writing practice
3. A text summarizer for notes
4. A beginner coding assistant for Python questions
5. A small chatbot for course FAQs

Back to Chapter | Back to Master Plan | Next Session