Introduction
In modern software development, it's not enough to just write code that works on your machine. We need to ensure it runs reliably everywhere. This is where containerization comes in. Using tools like Docker, we can package our application with all its dependencies into a single, isolated "container".
In this task, you will develop a simple calculator that uses a Large Language Model (LLM) to perform calculations. You will then create a Dockerfile to package this Python application, build a Docker image, and run it as a container. This process is a fundamental skill in Rapid Application Development (RAD) for creating portable and scalable applications.
Part A: Analysis and Project Setup (LO1)
Learning Outcome 1: Analyse an engineering application to facilitate the development of a software solution using rapid application development (RAD) techniques.
In this section, you will analyse the requirements for our application. This involves identifying necessary tools, external services (the LLM API), and dependencies. Your analysis will result in a structured project setup and a plan for managing dependencies, which are the first steps in building a robust software solution.
Step 1: Project Structure
First, create a dedicated folder for this task and set up the necessary empty files. This keeps our project organized.
mkdir ai_calculator
cd ai_calculator
touch main.py Dockerfile requirements.txt
Your folder should now contain:
main.py: This will hold our Python calculator code.requirements.txt: This file will list the Python libraries our project needs.Dockerfile: This is the blueprint for building our Docker image.
Step 2: Obtain a Free LLM API Key
Our calculator will use the Groq™ API, which provides very fast LLM inference. Their free tier is generous and does not require a credit card.
- Navigate to https://console.groq.com/keys.
- Sign up for a free account (e.g., with your Google or GitHub account).
- Once logged in, click "Create API Key".
- Give your key a name (e.g., "DE6412-Lab") and click "Create".
- Copy the key and save it somewhere safe, like a text file on your computer. You will not be able to see it again!
Security Warning: An API key is like a password. Never share it or commit it to a public repository like GitHub. We will learn how to use it securely in the next steps.
Step 3: Define Application Dependencies
Our Python script needs two external libraries:
groq: The official Python client to interact with the Groq™ API.python-dotenv: A helper library to manage environment variables (like our API key), though we will primarily use Docker's environment variable handling.
Open your requirements.txt file and add the following lines:
# requirements.txt
groq
python-dotenv
Part B: Application Development (LO2)
Learning Outcome 2: Develop a software solution for an engineering application using RAD techniques.
Here, you will develop the two main components of the software solution. First, the Python script that implements the calculator's logic. Second, the Dockerfile, a key RAD tool that defines how to build a portable container for our application.
Step 4: Develop the Python Calculator Script
Open main.py and add the following code. The code prompts the user for a mathematical expression and uses the Groq API to get the answer.
# main.py
import os
from groq import Groq
# It's best practice to get the API key from an environment variable
# for security reasons.
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
raise ValueError("GROQ_API_KEY environment variable not set!")
client = Groq(api_key=api_key)
def calculate(expression: str) -> str:
"""Uses an LLM to evaluate a mathematical expression."""
try:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are a calculator. Your only purpose is to evaluate mathematical expressions. "
"Return ONLY the final numerical answer, with no extra text, explanations, or symbols. "
"For example, if the user asks for '2+2', you return '4'."
},
{
"role": "user",
"content": f"Please calculate the following: {expression}",
},
],
model="llama3-8b-8192", # A small, fast model suitable for this task
temperature=0.0, # We want deterministic, precise answers
)
return chat_completion.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
if __name__ == "__main__":
print("Welcome to the AI Calculator!")
print("Enter a mathematical expression (or type 'exit' to quit).")
while True:
user_input = input("Calculate: ")
if user_input.lower() == 'exit':
print("Goodbye!")
break
result = calculate(user_input)
print(f"Result: {result}")
Step 5: Create the Dockerfile
Now, let's write the instructions to containerize our application. The Dockerfile specifies the base environment, copies our code, installs dependencies, and defines the startup command.
Open your Dockerfile and add the following content:
# Dockerfile
# 1. Use an official Python runtime as a parent image.
# Using 'slim' makes the image smaller.
FROM python:3.9-slim
# 2. Set the working directory inside the container.
WORKDIR /app
# 3. Copy the dependencies file and install them.
# This step is done separately to leverage Docker's layer caching.
# If requirements.txt doesn't change, this layer won't be rebuilt.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 4. Copy the rest of the application source code into the container.
COPY . .
# 5. Command to run the application when the container starts.
# The API key will be passed in as an environment variable at runtime.
CMD ["python", "main.py"]
Part C: Containerization and Evaluation (LO3)
Learning Outcome 3: Evaluate the performance of a RAD software solution to an engineering application.
In this final part, you will build and run your containerized application. By interacting with it, you will test its functionality and evaluate its performance, identifying potential deficiencies and areas for improvement as a software engineer.
Step 6: Build and Run the Docker Container
Make sure you have Docker Desktop installed and running on your machine. Open a terminal or command prompt in your ai_calculator directory.
-
Build the Docker Image: This command reads the
Dockerfileand builds an image namedai-calculator. The.at the end tells Docker to use the current directory as the build context.docker build -t ai-calculator . -
Run the Docker Container: This command runs the image we just built.
-itruns the container in interactive mode so we can type into our application.--rmautomatically removes the container when it exits, keeping things clean.-e GROQ_API_KEY="..."securely passes your API key as an environment variable to the container.
Replace `your_api_key_here` with the actual key you saved earlier.
docker run -it --rm -e GROQ_API_KEY="your_api_key_here" ai-calculator
If successful, you should see the "Welcome to the AI Calculator!" message. Test it with a few expressions like 2 + 2, (100 / 5) * 3, and sqrt(16).
Submission
To complete this lab task, please bundle the following files into a single ZIP archive named DE6412_Lab1_Task3_YourName.zip and submit it:
- Your Python script:
main.py - Your dependencies list:
requirements.txt - Your Docker blueprint:
Dockerfile - A screenshot of your terminal showing you running the Docker container and successfully calculating an expression (e.g., `(50-10)/2`).