Lesson 1: Python Crash Course

Lesson 4 60 min

Introduction

Most “intro week” curricula leave you with a folder of disconnected scripts: one file proves you understand loops, another proves dictionaries, and a third prints a banner. That is fine for drills. It is weaker preparation for how engineers actually work—where syntax, structure, and a thin slice of system design show up in the same repository, under tests, behind an API, and sometimes in front of a user.

week_1_aiml_integrated_project is a self-contained capstone that turns Python fundamentals into something you can run, extend, and reason about as a system. The outer shell is a real application surface: a React client talking to a FastAPI backend with a Gemini-backed chat route. Core domain logic lives in an installable package (week1_python) whose objects are also exposed through FastAPI lab routes—so the same behavior can be exercised from HTTP without spinning up extra demo servers. A command-line training simulator sits alongside: stateful assistants, JSON persistence, and a menu-driven loop that feels closer to a small product than a textbook snippet.

For engineers and serious learners, the payoff is not “I finished seven files.” It is: I can trace how user intent becomes state, how state becomes I/O, and where each Python construct earns its place.


Core Components

The stack is intentionally layered. Each topic below is a distinct building block; together they form one coherent system.

Application shell and service boundary

Establishes the outer runtime: a FastAPI app (backend/app/main.py) with CORS, versioned routes under /api/v1, and a React SPA in frontend/. This is where “Python as glue for services” begins in practice—not only as a REPL language.

The UI uses a modern dashboard shell: gradient hero, card-based lab links, animated transitions, and a Gemini chat panel styled with styled-components and Lucide icons.

Variables and typed state

Centers typed state in a small agent (SimpleAIAgent): strings, numbers, booleans, lists, and dictionaries cooperating in process_input and get_agent_status. The lab router exposes metrics and demo endpoints so agent state is inspectable over HTTP.

Control flow and decision logic

Flowchart

User / client → lesson logic → branch → mutate structures → response or print Input Processing Decision State update Output

Moves decisions and iteration into first-class objects: DataValidator walks a dataset with rules and counters; SimpleSentimentAI shows branching logic standing in for a classifier. Control flow stops being abstract and becomes the gate between raw input and trustworthy downstream structures.

Lists, tuples, and batch processing

Uses AIDataProcessor to show mutable collections for growing training artifacts versus immutable tuples for configuration-shaped records, plus batch-style prediction that returns (label, confidence) pairs—mirroring how ML code often shapes results.

Dictionaries, sets, and in-memory schema

Promotes AIDataManager: nested dicts for model configuration, sets for deduplication and overlap checks, and metrics keyed by dataset name. This is the project’s “schema without a database” moment.

Composable functions and text utilities

Pulls cross-cutting utilities (clean_text, feature extractors, generate_analysis_report) into reusable functions—what later becomes “preprocess → featurize → report” in real pipelines.

Training simulator and persistence

Ties the stack together in a CLI game loop: TrainingSimulator orchestrates menus, nested interaction modes, and AIAssistant objects that classify input, learn new responses, track confidence, and serialize state to JSON under data/assistants/ (or WEEK1_ASSISTANTS_DIR).

Nothing here replaces a full ML stack; everything rehearses the shapes ML code will inherit: validated inputs, structured intermediates, deterministic side effects, and clear boundaries.


Architecture Overview

Component Architecture

Component Architecture CLI Interface Day 7 trainer React SPA Day 1 UI FastAPI Chat + /week1 lab Game Engine TrainingSimulator Logic Layer Control flow / rules Data Layer Utility Layer

At a high level, the system is a dual-surface runtime sharing one conceptual domain (“assistant / lab”):

SurfacePathRole
Product pathBrowser → React → FastAPI → Gemini clientChat plus shared configuration (backend/config/settings.py, .env)
Lab pathHTTP clients or pytest → FastAPI week1_lab router → week1_pythonDomain logic as JSON responses
Standalone pathTraining simulator CLIREPL with JSON artifacts listable via GET /api/v1/week1/day07/assistants

An optional Flask metrics dashboard under legacy/ reuses the agent-state component on port 5000 for engineers who want a second UI without duplicating core logic.

Project structure

plaintext
week_1_aiml_integrated_project/
├── backend/
│   ├── app/
│   │   ├── main.py              # FastAPI entry, CORS, router wiring
│   │   ├── routes/
│   │   │   ├── chat.py          # Gemini chat
│   │   │   └── week1_lab.py     # Lab APIs (domain modules)
│   │   └── services/
│   │       └── ai_service.py    # Gemini client wrapper
│   └── config/
│       └── settings.py          # Env-driven settings
├── frontend/
│   └── src/
│       ├── App.js
│       ├── components/
│       │   ├── DashboardShell.js   # Modern dashboard + lab links
│       │   └── ChatContainer.js    # Gemini chat UI
│       └── services/api.js
├── packages/week1_python/         # Installable domain package
│   └── src/week1_python/
│       ├── agent state module      # SimpleAIAgent, metrics
│       ├── validation module       # DataValidator, SimpleSentimentAI
│       ├── processing module       # AIDataProcessor, batch predict
│       ├── config module           # AIDataManager, dicts & sets
│       ├── utilities module        # clean_text, analysis reports
│       └── trainer module          # TrainingSimulator, AIAssistant
├── tests/
│   ├── test_week1_api.py
│   └── test_week1_package.py
├── data/assistants/             # JSON checkpoints from trainer
├── docker/
│   └── Dockerfile
├── docker-compose.yml
├── scripts/
│   ├── start.sh
│   ├── stop.sh
│   └── build.sh
├── pytest.ini
├── requirements.txt
└── .env.example

Architecture diagram

How to read it: Surfaces (CLI, browser, API) sit on top. The “engine” is the training orchestrator; the logic layer is where validators, sentiment stubs, and prediction branches live; the data layer holds the dict/list/set-heavy models; utilities (text cleaning, reporting helpers) sit slightly aside so routers and the simulator can reuse them without circular clutter.


Data and Control Flow

Two flows deserve separate mental models—HTTP lab and CLI REPL—but they rhyme.

HTTP lab: Request body → Pydantic model → instantiate a domain class or call a module-level function → return a JSON-serializable dict.

plaintext
POST /api/v1/week1/day04/predict
  → AIDataProcessor()
  → predict_batch(feature_sets)
  → {"predictions": [{"class": ..., "confidence": ...}, ...]}

CLI simulator: input() → string choice or chat line → method on TrainingSimulator or AIAssistant → prints to stdout; optional JSON write on save.

In both cases, the “model” is pedagogical: randomness and heuristics stand in for expensive inference, which keeps the focus on structure.

Control-flow diagram

Nuance: For FastAPI routes, “state update” often means constructing a fresh object per request (stateless handler), except where week1_lab intentionally keeps a module-level shared agent for agent-state demos—an honest teaching moment about global process memory in long-running servers.


State Management

State Machine

Start End Main Menu loop Exit optional save Train Chat Stats / save

The training simulator is where Python’s built-in collections become the persistence story. Each AIAssistant tracks:

  • skills as a Dict[str, List[str]] (categories to response templates),

  • scalars such as experience and confidence,

  • conversation_history as a List[Dict] with timestamps.

save_progress / load_progress serialize that graph to JSON—checkpoint semantics without a framework. TrainingSimulator adds process-level maps (self.assistants, self.current_assistant) and ensures the assistants directory exists.

The HTTP surface for listing assistants is deliberately read-only (GET /api/v1/week1/day07/assistants), which keeps file-system races out of the demo API while still connecting the browser-side story to disk artifacts.

State machine (training simulator)

Reading the loop: Nested while True blocks in chat_mode and training_mode are “micro-states” entered from the main menu; 'back' returns control without tearing down the assistant. Quit optionally flushes JSON—mirroring production habits (explicit persistence, not silent loss).


API Design

All routes live under /api/v1. The lab router uses a /week1 prefix.

MethodEndpointComponentPurpose
POST/chatChat serviceGemini chat (falls back gracefully without API key)
GET/week1/day02/metricsAgent stateStatus snapshot from SimpleAIAgent
POST/week1/day02/demoAgent stateProcess user input through the agent
POST/week1/day02/resetAgent stateReset shared lab agent
POST/week1/day03/validateValidationRun DataValidator on a dataset
POST/week1/day03/sentimentClassificationKeyword sentiment analysis
POST/week1/day04/predictBatch processingPredictions with confidence tuples
GET/week1/day05/summaryConfig & metricsIn-memory AIDataManager summary
POST/week1/day06/analyzeText utilitiesAnalysis report via composable functions
GET/week1/day07/assistantsPersistenceList saved assistant JSON files

Routers stay thin: validate body, call week1_python, return dicts. Business logic never lives in HTTP handlers.

Questions & Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *