AITraining2U

Programs

Resources

Case Studies

Quick Links

Enquire Now
AI Prompt Library

30 AI Prompts for IT & Software Engineering

Copy-ready prompts that assume you will attach the code, the error or the config — engineered to ship faster while you always test and review before merging.

30 copy-ready prompts Works with Claude, Copilot & ChatGPT
AI prompts for IT and software engineering teams — developers working across multiple code screens, Malaysia

Each prompt sets the AI an engineering persona, references what you will paste or attach, and specifies the approach and output — with a reminder to review and test. These prompts are tool-agnostic and optimised to work across all major AI assistants — Claude, Microsoft Copilot and ChatGPT (and Google Gemini). Replace the [bracketed placeholders] with your own details, and always review AI output before you act on it.

Coding

1

Function With Stated Assumptions

When to use

Writing a new function where hidden assumptions could cause bugs

Attach

no file - describe function's purpose, inputs, outputs

Steps
  1. State assumptions and edge cases before writing any code
  2. Write the function with clear naming and input validation
  3. Comment only the non-obvious parts
  4. Note accurate, specific time/space complexity in one line
Output

Assumptions list, then the code block, then a one-line Big-O note.

See example AI output
Assumptions: input is a list of hashable items; order must be preserved; None values are valid entries. Edge cases handled: empty list, all-duplicate list, single item.

```python
def dedupe_ordered(items: list) -> list:
    """Return items with duplicates removed, preserving first-seen order."""
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result
```

Complexity: O(n) time, O(n) space - one pass, one hash set.
2

Cross-Language Code Translator

When to use

Porting a function from one language to another while preserving behaviour

Attach

source code in language A + target language B

Steps
  1. Read the source code and identify its exact behaviour
  2. Rewrite in language B using idiomatic patterns, not literal transliteration
  3. Compare behaviour line by line against the original
  4. Flag anything that doesn't map cleanly (GC, typing, concurrency model)
Output

Translated code block followed by a short list of caveats or semantic gaps.

See example AI output
```go
func WithRetry(fn func() error, attempts int) error {
    var err error
    for i := 0; i < attempts; i++ {
        if err = fn(); err == nil {
            return nil
        }
        time.Sleep(time.Duration(i*i) * 100 * time.Millisecond)
    }
    return fmt.Errorf("failed after %d attempts: %w", attempts, err)
}
```

Caveats: Python's decorator wraps any callable implicitly; Go needs an explicit function parameter. Python's version used random jitter via random.uniform - omitted here; add rand.Float64() if jitter matters for your retry storms.
3

Behaviour-Preserving Refactor

When to use

Cleaning up a function for readability without changing its interface

Attach

function/file to refactor + existing tests if available

Steps
  1. Confirm current behaviour and public interface before touching code
  2. Refactor for readability and maintainability only, no new frameworks or premature abstraction
  3. Justify each change with why it's safe, not just style preference
  4. Point out seams that would make it easier to test
Output

Refactored code followed by a bullet list mapping each change to its reason.

See example AI output
```python
def process_order(order):
    validate_order(order)
    total = calculate_total(order.items, order.discounts)
    charge = charge_payment(order.customer, total)
    return build_receipt(order, charge)
```

Changes: (1) Extracted validate_order from an inline if-chain - same checks, now reusable and testable in isolation. (2) Split total calculation from payment charging - previously interleaved, which made retry-after-failure impossible; now charge_payment can be retried without recalculating. (3) Renamed proc() to process_order() for clarity. Public signature process_order(order) -> Receipt is unchanged, so callers need no updates.
4

Regex With Test Cases

When to use

Building a regex pattern you need to trust against real input variation

Attach

no file - describe pattern to match + regex flavour

Steps
  1. State the regex flavour used and write the pattern
  2. Break down each component and what it matches
  3. Provide 2-3 matching and 2-3 non-matching test strings
  4. Warn about the most common gotcha for this specific pattern, not generic advice
Output

Regex string, component breakdown, and a match/no-match test table.

See example AI output
Flavour: JavaScript.

/^(?:\+?6?01)[0-46-9]-?\d{7,8}$/

Breakdown: \+?6?01 - optional country code +60, then mobile prefix 01; [0-46-9] - second digit excludes 5 (not a valid MY mobile prefix); -?\d{7,8} - optional hyphen then 7-8 digits.

Should match: 0123456789, +60123456789, 019-8765432.
Should not match: 0153456789 (invalid prefix), 012345 (too short).

Edge case: this rejects landlines (03-xxxx) entirely - if you need both, add a separate landline pattern.
5

Pre-Code Implementation Approach

When to use

Deciding how to build a feature before writing any code

Attach

no file - describe requirement + known constraints (scale, team, deadline)

Steps
  1. Restate the requirement to confirm understanding
  2. Sketch the data model and main components
  3. Present two viable options, preferring boring proven tech over novel ones
  4. Recommend one option with trade-off reasoning - no code yet
Output

Requirement restatement, data model, two options with trade-offs, and a clear recommendation.

See example AI output
Requirement: employees submit leave requests, managers approve/reject, HR sees a dashboard.

Data model: LeaveRequest(id, employee_id, dates, status, approver_id), Employee, Manager.

Option A: synchronous REST API with a Postgres status enum and email notification on change - simple, easy to debug, fine under 500 employees.
Option B: event-driven with a queue (SQS) triggering notification workers - scales better but adds infra to operate.

Recommendation: Option A. At your headcount, the queue adds operational cost with no real benefit; revisit only if notification volume becomes a bottleneck.

Debugging

6

Root-Cause Error Diagnosis

When to use

Diagnosing a crash or exception from a stack trace

Attach

full error/stack trace + relevant surrounding code

Steps
  1. Identify the most likely root cause from the actual stack trace, not guesswork
  2. Propose the fix and distinguish symptom from root cause
  3. Explain why the bug happened so it's avoided next time
  4. List a short, actionable fallback checklist if the fix doesn't resolve it
Output

Diagnosis, the fix (code if applicable), and a short fallback checklist.

See example AI output
Diagnosis: TypeError: Cannot read properties of undefined (reading 'email') at sendInvoice.js:42 - customer is undefined because getCustomer(id) returns null for soft-deleted customers, but the code assumes it always returns an object.

Fix: const customer = await getCustomer(id); if (!customer) throw new NotFoundError('Customer not found or deleted'); before accessing .email.

Why: soft-delete was added last sprint without updating this call site.

If it still fails: check whether getCustomer is also being called with a stale cached id from the queue message.
7

Expected vs Actual Behaviour Trace

When to use

Tracking down where code diverges from its intended behaviour

Attach

code + description of expected vs actual behaviour

Steps
  1. Trace the execution path step by step
  2. Identify exactly where behaviour diverges and the faulty assumption behind it
  3. Give the corrected code, changing no more than necessary
  4. Point to the specific line that was wrong
Output

Bug location and faulty assumption, corrected code, and a short reasoning note.

See example AI output
Bug: line 17, for i in range(0, total, page_size + 1) - the +1 causes the loop to skip one record per page.

Faulty assumption: the author assumed range needed an offset to avoid duplicate boundary records, but range's stop value is already exclusive, so no adjustment is needed.

Fix: for i in range(0, total, page_size):

Trace: with total=25, page_size=10, the original visits offsets 0, 11, 22 - dropping records 10 and 21. The corrected version visits 0, 10, 20, covering all 25 records across 3 pages.
8

Unfamiliar Code Walkthrough

When to use

Onboarding onto code you didn't write and don't yet trust

Attach

unfamiliar code block, ideally with surrounding file context

Steps
  1. Explain the code line by line in plain language
  2. Summarise what it does overall
  3. Flag any side effect explicitly (mutation, I/O, global state)
  4. Note anything surprising or non-obvious
Output

Annotated line-by-line walkthrough followed by a short overall summary.

See example AI output
Line 1-2: @lru_cache(maxsize=128) wraps the function so results are cached in memory keyed by arguments. Line 3: function signature takes user_id. Line 4: makes a DB call - this only runs on a cache miss.

Summary: this memoises get_user_profile so repeated calls with the same user_id skip the database after the first hit.

Risk: lru_cache is process-local and never invalidated on user updates - if a profile changes, callers may see stale data for up to 128 cached users. Surprising: this silently breaks in multi-process deployments since each process has its own cache.
9

Intermittent Issue Diagnosis Plan

When to use

Chasing a bug that only shows up sometimes, with no clear repro

Attach

no file - describe the intermittent issue, symptoms, frequency

Steps
  1. Identify exactly what to log at each suspect point, kept minimal and low-noise
  2. Specify which metrics to watch and their thresholds
  3. Describe how to reproduce the issue reliably or narrow its trigger
  4. Turn this into a concrete, actionable step-by-step diagnosis plan
Output

A diagnosis plan listing specific log points, metrics, and a reproduction approach.

See example AI output
Log points: request start/end timestamps at the load balancer, plus connection-pool checkout time (pool.checkout_ms).

Metrics: DB pool saturation (active/max), p99 latency per endpoint, upstream timeout count.

Reproduction: load test at 150 req/s for 5 min - 502s reportedly start above 120 req/s, matching a pool max of 20 connections at ~6ms avg query time.

Plan: 1) add pool metrics, 2) run the load test, 3) correlate 502s against pool-exhaustion events, 4) confirm by raising pool size to 40.
10

Breaking-Input Edge Case Review

When to use

Stress-testing a function against nulls, boundaries and bad input before shipping

Attach

function to review + expected input types

Steps
  1. Review against nulls, empty collections and boundary values
  2. Consider concurrency/race conditions and unusually large inputs
  3. Rank findings by likelihood and impact, skipping near-zero-likelihood theoretical cases
  4. Give a concrete test for each finding
Output

A ranked list of edge cases, each with a one-line test.

See example AI output
1. (High) Empty list -> calculate_total([]) should return 0, currently throws ZeroDivisionError. Test: assert calculate_total([]) == 0.
2. (High) Negative discount -> currently increases the total instead of erroring. Test: calculate_total(items, discount=-10) should raise ValueError.
3. (Medium) Concurrent calls mutating the shared items list - no lock present. Test: two threads appending/calculating simultaneously, assert no IndexError.
4. (Low) 100,000-item list - O(n^2) discount-matching loop is slow. Test: benchmark at 100k items, assert under 500ms.

Code review

11

Prioritised Pull Request Review

When to use

Reviewing a PR before merge and needing findings ranked by severity

Attach

PR diff or full changed files

Steps
  1. Review for correctness bugs first, then security, then readability
  2. Prioritise every finding by severity
  3. Separate must-fix from nice-to-have clearly
  4. Suggest the concrete fix for each finding
Output

Findings list grouped by severity (must-fix / nice-to-have) with a suggested fix for each.

See example AI output
Must-fix: (1) amount comes straight from the request body and hits the payment gateway unvalidated - a negative value could trigger a refund-as-charge; add if amount <= 0: raise ValidationError. (2) Idempotency key is generated server-side per request, so a network retry double-charges the customer - accept a client-supplied key instead.

Nice-to-have: processPayment() is 80 lines, extract the retry logic; rename p to payment on line 34.

Overall: solid structure, but the two must-fix items are real money-risk bugs - fix before merge.
12

Vulnerability Findings With Exploits

When to use

Security-auditing endpoint handlers, DB queries or auth logic

Attach

code to audit (endpoints, DB queries, auth logic)

Steps
  1. Check for injection, auth, secrets, unsafe deserialisation and SSRF issues
  2. For each finding, explain the concrete exploit path, not a theoretical risk
  3. Cite the exact line for every finding, no false alarms
  4. Explain the remediation for each
Output

Findings ranked by severity, each with exploit, line reference and remediation.

See example AI output
Critical (line 22): db.execute(f"SELECT * FROM users WHERE name = '{q}'") - classic SQL injection; q="' OR '1'='1" returns all users, q="'; DROP TABLE users;--" is destructive. Remediation: parameterised queries - db.execute("SELECT * FROM users WHERE name = %s", (q,)).

High (line 41): API key hardcoded as SECRET = "sk_live_49fA..." - anyone with repo read access has production access. Remediation: move to env var/secrets manager, rotate the key immediately.
13

Hotspot Performance Analysis

When to use

Investigating why a function or module is slow at scale

Attach

function/module to analyse + typical input sizes

Steps
  1. Identify the performance hotspots and their time/space complexity
  2. Suggest optimisations, noting the trade-off each introduces (readability, memory)
  3. State explicitly when an optimisation isn't worth the added complexity
Output

Hotspot analysis plus a prioritised list of suggestions with trade-offs.

See example AI output
Hotspot: line 30, nested loop comparing every order against every customer - O(n x m); at 10k x 5k that's 50M comparisons, matching the reported 8-second runtime.

Fix 1: build a customer_id -> customer dict first, cutting lookup to O(1), bringing this to O(n). Trade-off: +5k dict entries in memory, negligible.

Fix 2: cache the report if inputs haven't changed in the last hour. Trade-off: adds staleness risk - worth it only since logs show 40 requests/hour.
14

Idiomatic Code Convention Check

When to use

Checking whether code follows language idioms before merge

Attach

code to review

Steps
  1. Check whether the code follows idiomatic practice for the language
  2. Point out anti-patterns and naming issues, citing the specific convention referenced
  3. Suggest structural improvements
  4. Explain the why behind each suggestion, not just the rule
Output

A review listing each issue with the convention cited and the reasoning.

See example AI output
1. Line 12: bare except: catches everything including KeyboardInterrupt. Convention: catch specific exceptions (except ValueError:) - silent catch-alls hide real bugs.
2. Line 8: variable named l (lowercase L) - PEP 8 discourages this as visually ambiguous with 1 and I; rename to line_count.
3. Class userManager uses camelCase - Python convention is PascalCase (UserManager), so other developers can navigate the codebase by convention alone.
15

Teaching-Focused Review Comments

When to use

Reviewing a junior developer's PR to build their skills, not just fix code

Attach

diff + junior developer's context (seniority, what they're learning)

Steps
  1. Write review comments a junior developer will learn from, encouraging tone throughout
  2. For each comment, explain the underlying principle, not just the fix
  3. Prioritise the comments that teach the most transferable lessons
Output

A list of review comments, each pairing the fix with the principle behind it.

See example AI output
Nice work getting the integration working end-to-end! A few things to level up:

1. Line 15 - requests.get() has no timeout. Principle: any network call can hang forever if the server doesn't respond; always set timeout=5 so your app fails fast instead of freezing - applies to every external call you'll write.
2. Line 28 - retrying immediately in a loop with no delay can hammer a struggling service. Try exponential backoff (time.sleep(2 ** attempt)) - the industry-standard retry pattern.

Documentation

16

Docstrings With Runnable Example

When to use

Documenting a function so its contract and usage are self-evident

Attach

function to document, including its signature

Steps
  1. Write the docstring covering parameters, return value and exceptions
  2. Match the language's standard docstring convention (Google/NumPy/JSDoc/etc.)
  3. Add a runnable usage example that actually executes as shown
  4. Keep it concise, not padded
Output

The function with its complete docstring inserted, including the example.

See example AI output
```python
def fetch_with_retry(url: str, attempts: int = 3) -> dict:
    """Fetch JSON from a URL, retrying on failure.

    Args:
        url: The endpoint to fetch.
        attempts: Max retry attempts before giving up. Defaults to 3.

    Returns:
        Parsed JSON response as a dict.

    Raises:
        ConnectionError: If all attempts fail.

    Example:
        >>> fetch_with_retry("https://api.example.com/status")
        {'status': 'ok'}
    """
```
The docstring follows Google style, covers all three required sections, and the example is copy-pasteable to verify behaviour directly in a REPL.
17

New-Developer README Draft

When to use

Onboarding a new developer who needs to get the project running unaided

Attach

project details - what it does, tech stack, install/run steps

Steps
  1. Describe what the project does and who it's for
  2. List prerequisites and installation/setup steps, assuming nothing is 'obvious'
  3. Explain usage and configuration
  4. Add a troubleshooting section for common setup failures
Output

A complete README in markdown: Overview, Prerequisites, Install, Usage, Config, Troubleshooting.

See example AI output
# Invoice Reconciler

Matches bank statement CSVs against outstanding invoices and flags mismatches.

## Prerequisites
- Python 3.11+
- PostgreSQL 14

## Install
```
git clone ...
pip install -r requirements.txt
cp .env.example .env  # fill in DB_URL
```

## Usage
```
python reconcile.py --statement jan.csv --month 2026-01
```

## Configuration
Set MATCH_TOLERANCE in .env (default RM 0.50) for acceptable rounding differences.

## Troubleshooting
- psycopg2.OperationalError: check DB_URL and that Postgres is running on port 5432.
- No matches found: confirm CSV date format is DD/MM/YYYY.
18

Plain-English Business Rules Doc

When to use

Explaining business logic in code to non-technical stakeholders

Attach

code implementing the business logic to translate

Steps
  1. Explain what the code does in plain English, no jargon
  2. Describe inputs and outputs without technical jargon
  3. Extract and state the business rules it enforces
  4. Verify accuracy against the actual code - don't oversimplify to the point of being wrong
Output

A plain-English explanation covering what it does, inputs/outputs, and the business rules.

See example AI output
What it does: decides whether a customer qualifies for the loyalty discount at checkout.

Inputs: the customer's total spend this year, and how many orders they've placed.

Output: either 'no discount', '5% off', or '10% off'.

Business rules: customers get 5% off once they've spent RM 2,000 this year OR placed 10+ orders. They get 10% off once they've spent RM 5,000 this year. New customers (fewer than 3 orders) never qualify for 10%, even if a single large order pushes them over RM 5,000 - this is intentional, to stop one-off bulk buyers gaming the loyalty tier.
19

Copy-Paste API Reference Entry

When to use

Documenting an endpoint so another developer can try it immediately

Attach

endpoint implementation or route definition

Steps
  1. Document method, path and parameters, with type and required/optional for each
  2. Provide an example request and response
  3. List error codes and what triggers each
  4. State the authentication requirement
Output

A structured API reference entry: Method/Path, Auth, Parameters, Example Request/Response, Error Codes.

See example AI output
### POST /api/v1/invoices

Auth: Bearer token required.

Parameters:
- customer_id (string, required)
- amount (number, required, in cents)
- due_date (ISO 8601 date, required)

Example request:
{"customer_id": "cus_88f2", "amount": 150000, "due_date": "2026-05-17"}

Example response (201):
{"id": "inv_a91c", "status": "pending"}

Errors:
- 400 - missing or invalid amount
- 401 - missing/expired token
- 404 - customer_id not found
20

Frequency-Ordered Troubleshooting Guide

When to use

Writing a support doc from recurring tickets, ordered by what users hit most

Attach

no file - describe the system and common issues reported

Steps
  1. List common issues and order them by frequency reported, most common first
  2. Give the likely cause for each
  3. Give the tested, practical fix for each, not speculative steps
Output

A troubleshooting guide table: Symptom, Likely Cause, Fix - ordered by frequency.

See example AI output
1. 'Connection timed out' (60%) - corporate firewall blocking UDP 1194; switch to TCP 443.
2. 'Authentication failed' (25%) - expired SSO token cached locally; log out fully, clear the token cache, log back in.
3. Connects but no internal sites load (10%) - split-tunnel DNS not applied; restart the client after connecting.
4. Random disconnects every ~30 min (5%) - laptop sleep/wake killing the tunnel; enable 'Prevent sleep on VPN'.

Testing

21

Unit Tests With Coverage Notes

When to use

Writing tests for a function and flagging what's still untested

Attach

function to test + testing framework in use

Steps
  1. Write tests for the happy path, edge cases and error conditions
  2. Cover boundary values explicitly, keep tests independent of each other
  3. Avoid over-mocking - test real behaviour where practical
  4. Note any coverage gaps that remain
Output

A test file in the given framework, plus a short note on coverage gaps.

See example AI output
```js
describe('calculateDiscount', () => {
  test('applies 10% for orders over RM500', () => {
    expect(calculateDiscount(600)).toBe(60);
  });
  test('applies no discount at exactly RM500 boundary', () => {
    expect(calculateDiscount(500)).toBe(0);
  });
  test('throws on negative amount', () => {
    expect(() => calculateDiscount(-10)).toThrow('Invalid amount');
  });
  test('returns 0 discount for amount of 0', () => {
    expect(calculateDiscount(0)).toBe(0);
  });
});
```
Coverage gap: no test for non-numeric input (e.g. calculateDiscount('abc')) - add one if the function is reachable from user-facing forms.
22

Risk-Ranked Test Case Design

When to use

Designing test scenarios for a feature before it ships

Attach

no file - describe the feature and its expected behaviour

Steps
  1. Design functional, boundary/negative and integration test scenarios
  2. Include the edge cases people typically forget
  3. Prioritise by risk, highest first - each case independently verifiable
Output

A test-case table: Scenario, Steps, Expected Result - ordered by risk.

See example AI output
| Scenario | Steps | Expected |
|---|---|---|
| Upload valid PDF under 10MB | Select file, click upload | File appears in list, status 'processed' |
| Upload 0-byte file | Select empty file, upload | Error: 'File is empty' |
| Upload file exactly at 10MB limit | Select 10MB file | Uploads successfully (boundary, not rejected) |
| Upload 10.1MB file | Select oversized file | Error: 'File exceeds 10MB limit' |
| Two users upload same filename simultaneously | Concurrent upload | Both succeed, stored with distinct IDs, no overwrite |
| Upload during network drop | Start upload, disconnect wifi | Upload resumes or fails clearly, no corrupt partial file |
23

Failing Test Root-Cause Fix

When to use

A test is failing and it's unclear whether the test or the code is wrong

Attach

failing test code + exact error/assertion output

Steps
  1. Reason about what the assertion is actually checking, from the real output
  2. Determine whether the test or the code under test is wrong
  3. Give the fix for whichever is wrong - don't weaken a correct assertion
  4. Explain the reasoning
Output

A diagnosis of test vs. code fault, followed by the corrected code or test.

See example AI output
Assertion: expect(formatDate('2026-01-05')).toBe('05/01/2026') fails - actual output is '01/05/2026'.

Diagnosis: the code is correct - US-format (MM/DD/YYYY) per the function's JSDoc - but the test assumes DD/MM/YYYY. This is a test bug, not a code bug, since the function was never spec'd as locale-aware.

Fix: expect(formatDate('2026-01-05')).toBe('01/05/2026'). If DD/MM/YYYY is actually wanted, that's a product decision - file it as a feature change, not a test fix.
24

Risk-Based Test Plan

When to use

Scoping test coverage for a feature before a release

Attach

no file - describe the feature, scope, and known risk areas

Steps
  1. Define scope: what is and isn't covered
  2. Specify test levels needed (unit, integration, end-to-end)
  3. Identify key risks to prioritise coverage around, not exhaustive-by-default
  4. Define data needs and measurable exit criteria
Output

A test plan: Scope, Test Levels, Key Risks, Data Needs, Exit Criteria.

See example AI output
Scope: covers salary calculation and payslip generation; excludes tax-authority API integration (tested separately).

Test levels: unit tests for calculation logic (target 90% coverage), integration tests for DB writes, end-to-end test for one full payroll run.

Key risks: rounding errors in EPF/SOCSO deductions (financial + compliance risk), and duplicate payslip generation on retry (financial risk).

Data needs: 20 synthetic employee records covering full-time, part-time and mid-month joiners.

Exit criteria: zero critical/high bugs open, unit coverage >=90%, one successful full payroll dry-run reconciled manually against a spreadsheet.
25

Realistic Test Dataset With Edge Cases

When to use

Generating sample data to exercise validation logic before launch

Attach

no file - describe the scenario/schema the data needs to represent

Steps
  1. Generate valid representative records matching real-world patterns
  2. Generate boundary-value records
  3. Generate deliberately malformed records covering scenario-specific edge cases
  4. Note what each group is designed to test
Output

A dataset in the requested format, grouped by category, with a note on what each group tests.

See example AI output
```json
[
  {"name": "Aisyah Rahman", "email": "aisyah@example.com", "age": 34},
  {"name": "Wei Ming Tan", "email": "wei.ming@example.com", "age": 18},
  {"name": "A", "email": "a@b.co", "age": 120},
  {"name": "", "email": "not-an-email", "age": -5}
]
```
Group 1 (records 1-2): valid, representative signups. Group 2 (record 3): boundary - minimum name length, maximum plausible age. Group 3 (record 4): malformed - empty name, invalid email, negative age, should all be rejected by validation.

DevOps and architecture

26

Config Walkthrough With Fixes

When to use

Auditing a Dockerfile or CI config for security and reliability risk

Attach

config or script (Dockerfile, CI YAML, etc.)

Steps
  1. Explain the config line by line, stating the risk of each current line
  2. Identify security, caching and reliability risks in the current version
  3. Prioritise fixes by impact, not by ease
  4. Suggest the concrete improvement for each
Output

A line-by-line walkthrough followed by a prioritised improvement list.

See example AI output
Line 1: FROM node:latest - unpinned, builds aren't reproducible and can break on image updates.
Line 5: COPY . . before npm install - invalidates Docker's layer cache on every source change, forcing full reinstalls.
Line 8: runs as root (no USER directive) - container escape risk if compromised.

Priority fixes: 1) Pin to node:20.11-alpine. 2) Copy package.json + install first, then source (cache). 3) Add USER node before the entrypoint (security).
27

Secure CI/CD Workflow

When to use

Writing a new pipeline that needs to handle secrets and permissions safely

Attach

no file - describe pipeline steps (lint, test, deploy) + CI tool

Steps
  1. Write the workflow with each step explained
  2. Handle secrets via the platform's secret store, never plaintext
  3. Apply least-privilege permissions to the workflow
  4. Cache dependencies and fail fast on first failure
Output

The complete workflow file with inline comments explaining each step.

See example AI output
```yaml
name: CI
on: [pull_request]
permissions:
  contents: read  # least privilege
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }  # caches node_modules
      - run: npm ci
      - run: npm run lint
      - run: npm test -- --ci
```
Secrets: none needed for this lint+test job - the deploy step (separate workflow, main branch only) reads DEPLOY_TOKEN from GitHub encrypted secrets, never logged or echoed.
28

Two-Option Architecture Recommendation

When to use

Choosing an architecture for a new system before building it

Attach

no file - describe requirement, expected scale, constraints (budget, team)

Steps
  1. Propose two viable options, preferring managed/simple over self-hosted/complex
  2. Describe each in a simple diagram-in-words
  3. Compare trade-offs: cost, complexity, scale, latency
  4. Recommend one option with reasoning, justifying any added complexity
Output

Two options with trade-offs, followed by a clear recommendation.

See example AI output
Option A: Postgres full-text search (tsvector) on the existing DB - App -> Postgres, one system. Trade-off: near-zero added cost/complexity, but relevance ranking is basic and may slow past 1M documents.

Option B: dedicated search engine (e.g. Meilisearch) alongside Postgres, synced via a job. Trade-off: much better relevance and speed at scale, but adds a service and sync pipeline to maintain.

Recommendation: Option A - at ~50k documents it's more than adequate; revisit Option B only past ~500k documents or if users complain about relevance.
29

Blameless Post-Mortem Writer

When to use

Writing up an incident after the fact for the team

Attach

incident timeline notes, chat logs or monitoring data

Steps
  1. Reconstruct the timeline of the incident and its impact (users, duration, revenue)
  2. Identify the root cause, focusing on system and process, not individuals
  3. Capture what went well and what didn't
  4. List action items, each with an owner and realistically achievable
Output

A post-mortem: Timeline, Impact, Root Cause, What Went Well/Didn't, Action Items.

See example AI output
Timeline: 14:02 v2.4.1 deployed; 14:05 checkout error rate hit 40%; 14:11 alert fired; 14:19 rollback completed; 14:22 error rate normalised.

Impact: ~380 failed checkouts over 17 minutes, ~RM 12,000 in lost transactions.

Root cause: v2.4.1 removed a default on shipping_method, which the payment step required but never validated.

Went well: rollback took under 8 minutes. Didn't: alert fired 6 minutes late - threshold too high.

Action items: lower error-rate alert threshold to 5% (Owner: Priya); add schema validation to CI (Owner: Faiz).
30

Under-Pressure Operational Runbook

When to use

Documenting a risky ops procedure (e.g. DB failover) for on-call use

Attach

no file - describe the operational task + current environment

Steps
  1. List pre-checks to confirm before starting
  2. Write steps in exact, unambiguous order, followable under on-call pressure
  3. Define how to verify each step succeeded, especially after risky actions
  4. Define a safe, tested rollback procedure if something goes wrong
Output

A runbook: Pre-checks, Steps, Verification, Rollback.

See example AI output
Pre-checks: confirm replica lag under 5s and no active migration running.

Steps: 1) Enable MAINTENANCE_MODE=true (read-only). 2) Promote replica: pg_ctl promote -D /data/replica. 3) Update DATABASE_URL to the new primary. 4) Redeploy app pods.

Verification: SELECT pg_is_in_recovery(); must return false; confirm health check returns 200.

Rollback: if promotion fails, revert DATABASE_URL to the original primary and unset MAINTENANCE_MODE - it was never demoted, so this is safe within 10 minutes of starting.

Frequently Asked Questions

Treat it as a draft from a fast but fallible colleague — always read, test and review it before merging. AI can introduce subtle bugs and security issues and does not know your full codebase. Never paste secrets or proprietary code into public consumer tools; use approved enterprise or local tooling. These prompts build in review and testing steps.

Yes — the prompts assume you will paste code, stack traces, configs and diffs. For proprietary code, use your organisation's approved enterprise or self-hosted AI so nothing leaves your control.

For in-editor coding, agentic tools like Claude Code and GitHub Copilot lead; for reasoning, review and design, Claude and ChatGPT are excellent. These prompts work across all of them.

No — it changes the job. Engineers move up toward design, review, orchestration and judgement while AI handles more of the typing. The engineers who thrive are AI-fluent, which is what our AI Engineering course teaches.

Yes. AITraining2U's AI Engineering course is HRD Corp SBL-KHAS claimable for eligible Malaysian employers.

No - treat AI review as a fast first pass, not a replacement. AI catches common bugs, style issues and known vulnerability patterns quickly and consistently, freeing senior engineers to focus on architecture, business-logic correctness and judgement calls AI cannot make. For Malaysian SMEs with lean dev teams, running AI review before a human review shortens review cycles significantly, but a human should still approve before merging to production, especially for anything touching payments, PDPA-covered data or core business logic.

Be cautious. Public consumer tools (free ChatGPT, free Claude.ai) may use conversations to improve their models unless you've opted out, and pasted code could theoretically surface elsewhere. For proprietary or client code, use business/enterprise tiers with data-retention opt-outs, self-hosted models, or tools like GitHub Copilot Enterprise under your organisation's data agreement. Malaysian SMEs handling client IP or PDPA-covered systems should set a written policy on what can and cannot be pasted into AI tools before developers start using them daily.

Yes, and this is one of AI's strongest SME use cases. Paste in legacy code (COBOL, old PHP, VB6, whatever it is) and ask the AI to explain it line by line, generate a plain-English business-rules summary, or draft a README from scratch. It won't know the tribal knowledge behind why a workaround exists, so pair AI-generated docs with a short review from whoever last touched the system. This turns a task engineers avoid for months into a few hours of AI-assisted drafting plus review.

They suit different moments. GitHub Copilot excels at in-editor autocomplete and small in-context suggestions as you type. Claude Code and similar agentic CLI tools are stronger for larger, multi-file tasks - refactors, migrations, writing whole features from a spec, or working autonomously through a backlog. ChatGPT and Claude's chat interfaces are best for reasoning, design discussions and code review outside the editor. Many Malaysian dev teams run Copilot for daily coding plus a chat tool for architecture and review - the tools are complementary, not exclusive.

Yes, if you keep it in a supporting role. AI can quickly summarise error logs, suggest likely root causes from a stack trace, draft the customer-facing status update, and write the post-mortem afterwards - all real time savers during a stressful outage. It should not be given authority to run remediation commands unsupervised or make the final call on rollback vs fix-forward - those decisions need an accountable human, especially for SMEs without a dedicated SRE team to catch a wrong call.

Go beyond prompts — train your team

Prompts are the start. AITraining2U runs hands-on, HRD Corp SBL-KHAS claimable AI training for Malaysian teams — from everyday AI productivity to building agents that run it & software engineering workflows end-to-end.