If you’re working with Python and APIs like OpenAI, using a virtual environment (venv) is no longer optional—it’s a best practice. In this guide, you’ll learn how to:
-
Create and activate a Python virtual environment
-
Install dependencies safely (without touching global Python)
-
Load an OpenAI API key using
.env -
Build a simple OpenAI client
-
Upgrade the script to accept user input instead of a hardcoded prompt
This tutorial is beginner-friendly and works on Windows, macOS, and Linux.
Why You Should Always Use a Python Virtual Environment
A virtual environment allows you to:
-
Isolate project dependencies
-
Avoid version conflicts
-
Reproduce your setup later
-
Match professional and enterprise workflows
Each project gets its own Python and packages, separate from the system installation.
Step 1: Create a Project Folder
Open a terminal or PowerShell and navigate to your project directory:
Example (Windows):
Step 2: Create a Virtual Environment
Run the following command inside your project folder.
Windows
macOS / Linux
This creates a venv folder containing an isolated Python runtime.
Step 3: Activate the Virtual Environment
Windows (PowerShell)
If PowerShell blocks the script:
macOS / Linux
When activated, your terminal prompt will show:
This means all installs are now local to this project.
Step 4: Install Required Packages (Inside venv Only)
With the virtual environment active:
Using python -m pip guarantees the packages install into the active venv.
Step 5: Create a .env File for Your API Key
In the project root (same level as your Python file), create a file named .env:
Important notes:
-
No quotes
-
No spaces
-
Never commit this file to Git
Step 6: Python Script with OpenAI Client (User Input Enabled)
Below is a clean, production-safe script that:
-
Loads the API key from
.env -
Uses object-oriented design
-
Prompts the user for input instead of a hardcoded string
<?php
# ===== START CODE BLOCK =====
from openai import OpenAI
from dotenv import load_dotenv
import os
load_dotenv()
def get_api_key() -> str:
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable not set")
return api_key
class LLMClient:
def __init__(self, api_key: str, model: str = "gpt-4.1-mini"):
self.client = OpenAI(api_key=api_key)
self.model = model
def chat(self, prompt: str) -> str:
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
if __name__ == "__main__":
api_key = get_api_key()
llm_client = LLMClient(api_key)
user_prompt = input("Enter your question: ")
response = llm_client.chat(user_prompt)
print("LLM Response:", response)
# ===== END CODE BLOCK =====

