Skip to main content

STEERING the AI CODING ASSISTANT

 Of course! Here are many more examples focusing on "steering" techniques and various scenarios. Steering is about guiding the AI step-by-step, especially within your IDE where it can see your existing code.


Inline Steering with Comments


This is the most powerful technique for real-time coding assistance.


1. Step-by-Step Logic Guidance


```python

def process_orders(orders):

    # First, filter out cancelled orders (status = 'cancelled')

    active_orders = [order for order in orders if order['status'] != 'cancelled']

    

    # Then, calculate total for each order (price * quantity)

    for order in active_orders:

        order['total'] = order['price'] * order['quantity']

    

    # Now, group orders by customer_id and sum their totals

    customer_totals = {}

    for order in active_orders:

        customer_id = order['customer_id']

        # If customer doesn't exist in dict, initialize to 0, then add order total

        if customer_id not in customer_totals:

            customer_totals[customer_id] = 0

        customer_totals[customer_id] += order['total']

    

    # Finally, return the customer_totals dictionary

    return customer_totals

```


2. Filling in Complex Conditions


```javascript

function getShippingCost(order, user) {

    let baseCost = 5.99;

    

    // If order total is over $100, free shipping

    if (order.total > 100) {

        return 0;

    }

    

    // If user is premium member, apply 50% discount to base cost

    if (user.isPremium) {

        return baseCost * 0.5;

    }

    

    // If shipping is to Alaska or Hawaii, add $10 surcharge

    if (order.shippingState === 'AK' || order.shippingState === 'HI') {

        return baseCost + 10;

    }

    

    // Otherwise, return base cost

    return baseCost;

}

```


3. Data Transformation Pipeline


```python

def clean_dataset(raw_data):

    # Step 1: Remove rows with any null values

    cleaned = [row for row in raw_data if all(val is not None for val in row.values())]

    

    # Step 2: Convert all string prices from "$XX.XX" to float

    for row in cleaned:

        if isinstance(row['price'], str) and row['price'].startswith('$'):

            row['price'] = float(row['price'].replace('$', ''))

    

    # Step 3: Normalize email addresses to lowercase

    for row in cleaned:

        if 'email' in row:

            row['email'] = row['email'].lower().strip()

    

    # Step 4: Convert date strings to datetime objects (format: YYYY-MM-DD)

    for row in cleaned:

        if 'date' in row:

            row['date'] = datetime.strptime(row['date'], '%Y-%m-%d')

    

    return cleaned

```


File-Level Steering with Context


4. Creating New Files with Clear Structure


In auth_utils.py:


```python

"""

Authentication utilities for the Flask application.

Uses JWT tokens and bcrypt for password hashing.

"""


# TODO: Import necessary libraries (jwt, bcrypt, datetime)


def hash_password(password: str) -> str:

    """Hash a password using bcrypt with salt"""

    # Generate salt and hash the password

    pass


def verify_password(password: str, hashed: str) -> bool:

    """Verify a password against its hash"""

    # Use bcrypt to check if password matches hash

    pass


def generate_jwt_token(user_id: int, secret: str) -> str:

    """Generate a JWT token with user_id and expiration"""

    # Create payload with user_id and exp (24 hours from now)

    # Encode with secret and return token

    pass


def verify_jwt_token(token: str, secret: str) -> dict:

    """Verify and decode JWT token, return payload if valid"""

    # Try to decode token with secret

    # If valid, return payload; if expired or invalid, return None

    pass

```


5. React Component with Lifecycle


```jsx

// UserProfile.jsx - A component that fetches user data on mount

import { useState, useEffect } from 'react';


const UserProfile = ({ userId }) => {

    // State for user data, loading status, and error

    const [user, setUser] = useState(null);

    const [loading, setLoading] = useState(true);

    const [error, setError] = useState(null);

    

    // useEffect to fetch user data when component mounts or userId changes

    useEffect(() => {

        const fetchUser = async () => {

            try {

                setLoading(true);

                // Make API call to /api/users/{userId}

                const response = await fetch(`/api/users/${userId}`);

                if (!response.ok) throw new Error('Failed to fetch user');

                const userData = await response.json();

                setUser(userData);

            } catch (err) {

                setError(err.message);

            } finally {

                setLoading(false);

            }

        };

        

        fetchUser();

    }, [userId]);

    

    // If loading, show spinner

    if (loading) return <div className="spinner">Loading...</div>;

    

    // If error, show error message

    if (error) return <div className="error">Error: {error}</div>;

    

    // If user data loaded, render profile

    return (

        <div className="user-profile">

            <h2>{user.name}</h2>

            <p>Email: {user.email}</p>

            <img src={user.avatar} alt={`${user.name}'s avatar`} />

        </div>

    );

};


export default UserProfile;

```


API Development Steering


6. Express.js Route with Validation


```javascript

// routes/users.js - Express route with comprehensive validation

const express = require('express');

const router = express.Router();


// POST /api/users - Create a new user

router.post('/users', async (req, res) => {

    try {

        // Validate request body has required fields: name, email, password

        const { name, email, password } = req.body;

        if (!name || !email || !password) {

            return res.status(400).json({ 

                error: 'Missing required fields: name, email, password' 

            });

        }

        

        // Validate email format using regex

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailRegex.test(email)) {

            return res.status(400).json({ error: 'Invalid email format' });

        }

        

        // Validate password length (at least 6 characters)

        if (password.length < 6) {

            return res.status(400).json({ 

                error: 'Password must be at least 6 characters long' 

            });

        }

        

        // Check if user with email already exists in database

        const existingUser = await User.findOne({ email });

        if (existingUser) {

            return res.status(409).json({ error: 'User already exists' });

        }

        

        // Hash the password using bcrypt (10 salt rounds)

        const hashedPassword = await bcrypt.hash(password, 10);

        

        // Create new user in database

        const newUser = new User({

            name,

            email,

            password: hashedPassword,

            createdAt: new Date()

        });

        

        await newUser.save();

        

        // Generate JWT token for the new user

        const token = jwt.sign(

            { userId: newUser._id }, 

            process.env.JWT_SECRET, 

            { expiresIn: '7d' }

        );

        

        // Return success response with user data (excluding password) and token

        res.status(201).json({

            message: 'User created successfully',

            user: {

                id: newUser._id,

                name: newUser.name,

                email: newUser.email

            },

            token

        });

        

    } catch (error) {

        console.error('Error creating user:', error);

        res.status(500).json({ error: 'Internal server error' });

    }

});

```


Database Query Steering


7. Complex SQL Query Building


```sql

-- Get monthly sales report with customer insights

SELECT 

    -- Extract year and month from order date

    EXTRACT(YEAR FROM o.order_date) as order_year,

    EXTRACT(MONTH FROM o.order_date) as order_month,

    

    -- Count total orders and unique customers

    COUNT(DISTINCT o.order_id) as total_orders,

    COUNT(DISTINCT o.customer_id) as unique_customers,

    

    -- Calculate total revenue and average order value

    SUM(oi.quantity * oi.unit_price) as total_revenue,

    AVG(oi.quantity * oi.unit_price) as avg_order_value,

    

    -- Identify returning customers (those with >1 order in the month)

    COUNT(DISTINCT CASE WHEN customer_order_count > 1 THEN o.customer_id END) as returning_customers

    

FROM orders o

-- Join with order_items to get product details

INNER JOIN order_items oi ON o.order_id = oi.order_id

-- Subquery to count orders per customer per month for returning customer calculation

INNER JOIN (

    SELECT 

        customer_id,

        EXTRACT(YEAR FROM order_date) as year,

        EXTRACT(MONTH FROM order_date) as month,

        COUNT(*) as customer_order_count

    FROM orders

    GROUP BY customer_id, EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date)

) customer_stats ON o.customer_id = customer_stats.customer_id 

                 AND EXTRACT(YEAR FROM o.order_date) = customer_stats.year 

                 AND EXTRACT(MONTH FROM o.order_date) = customer_stats.month


-- Filter for completed orders only

WHERE o.status = 'completed'


-- Group by year and month for monthly reporting

GROUP BY 

    EXTRACT(YEAR FROM o.order_date),

    EXTRACT(MONTH FROM o.order_date)

    

-- Order by most recent months first

ORDER BY 

    order_year DESC,

    order_month DESC;

```


Error Handling Steering


8. Comprehensive Error Handling Patterns


```python

def robust_api_call(url, retries=3, timeout=10):

    """

    Make an API call with retry logic and comprehensive error handling

    """

    for attempt in range(retries + 1):

        try:

            # Make the HTTP request with timeout

            response = requests.get(url, timeout=timeout)

            

            # Check for HTTP errors (4xx, 5xx status codes)

            response.raise_for_status()

            

            # Try to parse JSON response

            try:

                return response.json()

            except json.JSONDecodeError as e:

                raise ValueError(f"Invalid JSON response: {e}")

                

        except requests.exceptions.Timeout:

            print(f"Attempt {attempt + 1}: Request timeout")

            if attempt == retries:

                raise Exception("All retries failed due to timeout")

                

        except requests.exceptions.ConnectionError as e:

            print(f"Attempt {attempt + 1}: Connection error - {e}")

            if attempt == retries:

                raise Exception("All retries failed due to connection issues")

                

        except requests.exceptions.HTTPError as e:

            # Don't retry on client errors (4xx)

            if 400 <= response.status_code < 500:

                raise Exception(f"Client error {response.status_code}: {e}")

            else:

                print(f"Attempt {attempt + 1}: Server error {response.status_code}")

                if attempt == retries:

                    raise Exception(f"Server error after {retries} retries")

                    

        except ValueError as e:

            # Don't retry on JSON parsing errors

            raise e

            

        except Exception as e:

            print(f"Attempt {attempt + 1}: Unexpected error - {e}")

            if attempt == retries:

                raise Exception(f"Unexpected error after {retries} retries")

        

        # Wait before retry (exponential backoff)

        if attempt < retries:

            sleep_time = (2 ** attempt) + random.uniform(0, 1)

            time.sleep(sleep_time)

    

    # This should never be reached, but just in case

    raise Exception("Unexpected end of function")

```


Testing Guidance Steering


9. Test File with Comprehensive Scenarios


```python

# test_user_service.py - Comprehensive test suite for UserService

import pytest

from unittest.mock import Mock, patch

from myapp.services.user_service import UserService

from myapp.exceptions import UserNotFoundError, InvalidEmailError


class TestUserService:

    

    def setup_method(self):

        """Set up fresh mocks for each test"""

        self.mock_user_repo = Mock()

        self.user_service = UserService(user_repository=self.mock_user_repo)

    

    def test_get_user_by_id_success(self):

        """Test successfully retrieving a user by ID"""

        # Setup: Mock repository to return a user

        expected_user = {'id': 1, 'name': 'John Doe', 'email': 'john@example.com'}

        self.mock_user_repo.find_by_id.return_value = expected_user

        

        # Execute: Call the service method

        result = self.user_service.get_user_by_id(1)

        

        # Assert: Verify the result and that repository was called correctly

        assert result == expected_user

        self.mock_user_repo.find_by_id.assert_called_once_with(1)

    

    def test_get_user_by_id_not_found(self):

        """Test behavior when user is not found"""

        # Setup: Mock repository to return None

        self.mock_user_repo.find_by_id.return_value = None

        

        # Execute & Assert: Verify the correct exception is raised

        with pytest.raises(UserNotFoundError):

            self.user_service.get_user_by_id(999)

    

    def test_create_user_with_invalid_email(self):

        """Test creating user with invalid email format"""

        # Setup: Invalid email data

        user_data = {'name': 'John', 'email': 'invalid-email'}

        

        # Execute & Assert: Verify validation error

        with pytest.raises(InvalidEmailError):

            self.user_service.create_user(user_data)

        

        # Assert: Repository should not be called

        self.mock_user_repo.create.assert_not_called()

    

    @patch('myapp.services.user_service.send_welcome_email')

    def test_create_user_success_with_email(self, mock_send_email):

        """Test successful user creation with welcome email"""

        # Setup: Valid user data and mock repository response

        user_data = {'name': 'Jane Doe', 'email': 'jane@example.com'}

        created_user = {**user_data, 'id': 2}

        self.mock_user_repo.create.return_value = created_user

        

        # Execute: Create the user

        result = self.user_service.create_user(user_data)

        

        # Assert: Verify user creation and email sending

        assert result == created_user

        self.mock_user_repo.create.assert_called_once_with(user_data)

        mock_send_email.assert_called_once_with('jane@example.com')

```


Configuration and Setup Steering


10. Dockerfile with Multi-Stage Build


```dockerfile

# Multi-stage Dockerfile for Python Flask application


# Stage 1: Build stage

FROM python:3.11-slim as builder


# Set working directory and environment variables

WORKDIR /app


# Copy requirements first for better caching

COPY requirements.txt .


# Install build dependencies and Python packages

RUN apt-get update && \

    apt-get install -y --no-install-recommends gcc python3-dev && \

    pip install --user --no-cache-dir -r requirements.txt && \

    apt-get remove -y gcc python3-dev && \

    apt-get autoremove -y


# Stage 2: Production stage

FROM python:3.11-slim


# Set environment variables for production

ENV PYTHONUNBUFFERED=1 \

    PYTHONDONTWRITEBYTECODE=1 \

    FLASK_ENV=production


# Create non-root user for security

RUN groupadd -r appuser && useradd -r -g appuser appuser


# Install runtime dependencies only

RUN apt-get update && \

    apt-get install -y --no-install-recommends libpq5 && \

    rm -rf /var/lib/apt/lists/*


# Copy installed packages from builder stage

COPY --from=builder /root/.local /home/appuser/.local

ENV PATH=/home/appuser/.local/bin:$PATH


# Switch to non-root user

USER appuser


# Copy application code

COPY --chown=appuser:appuser . .


# Expose port and define healthcheck

EXPOSE 5000

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \

    CMD curl -f http://localhost:5000/health || exit 1


# Set the entrypoint command

CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]

```


Pro Steering Techniques


11. The "Fill-in-the-Blanks" Pattern


```python

class DataProcessor:

    def __init__(self, config):

        self.config = config

        # TODO: Initialize logger based on config

        self.logger = self._setup_logger()

        

        # TODO: Initialize database connection pool

        self.db_pool = self._setup_database()

        

        # TODO: Initialize cache client (Redis)

        self.cache = self._setup_cache()

    

    def _setup_logger(self):

        # Implement logger setup with rotating file handler and console handler

        # Use log level from config, format: "[%(asctime)s] %(levelname)s: %(message)s"

        pass

    

    def _setup_database(self):

        # Create connection pool with settings from config

        # Max connections: 20, timeout: 30 seconds

        pass

    

    def _setup_cache(self):

        # Initialize Redis client with connection details from config

        # Set decode_responses=True for string values

        pass

    

    def process_batch(self, batch_data):

        # Step 1: Validate batch_data structure

        if not self._validate_batch(batch_data):

            # Log error and raise ValidationError

            pass

        

        # Step 2: Check cache for processed results

        cache_key = self._generate_cache_key(batch_data)

        cached_result = self.cache.get(cache_key)

        if cached_result:

            return json.loads(cached_result)

        

        # Step 3: Process data in database transaction

        with self.db_pool.get_connection() as conn:

            try:

                # Start transaction

                # Insert raw data into staging table

                # Transform data according to business rules

                # Commit transaction

                pass

            except Exception as e:

                # Rollback transaction

                # Log detailed error

                raise ProcessingError(f"Batch processing failed: {e}")

        

        # Step 4: Cache the result for 1 hour

        # Serialize result to JSON and store in cache with expiration

        pass

```


12. The "Fix This Code" Pattern


```javascript

// BUG: This function has memory leaks and doesn't handle errors properly

// FIX: Implement proper error handling, resource cleanup, and use async/await correctly

async function fetchUserData(userId) {

    // Problem: No try/catch, fetch response not checked, no timeout

    const response = fetch(`/api/users/${userId}`);

    const data = await response.json();

    return data;

}


// FIXED VERSION WITH STEERING COMMENTS:

async function fetchUserData(userId) {

    // Create AbortController for timeout functionality

    const controller = new AbortController();

    const timeoutId = setTimeout(() => controller.abort(), 5000);

    

    try {

        // Make fetch request with signal for abort capability

        const response = await fetch(`/api/users/${userId}`, {

            signal: controller.signal

        });

        

        // Check if response is OK (status 200-299)

        if (!response.ok) {

            throw new Error(`HTTP error! status: ${response.status}`);

        }

        

        // Parse JSON response

        const data = await response.json();

        return data;

        

    } catch (error) {

        // Handle different error types appropriately

        if (error.name === 'AbortError') {

            console.error('Request timeout for user ID:', userId);

            throw new Error('Request timeout - please try again');

        } else if (error.name === 'TypeError') {

            console.error('Network error for user ID:', userId);

            throw new Error('Network error - check your connection');

        } else {

            console.error('Unexpected error for user ID:', userId, error);

            throw error; // Re-throw unexpected errors

        }

    } finally {

        // Always clear the timeout to prevent memory l

Comments

Popular posts from this blog

PART 0.1.0 RAD PROTOTYPE Web-App: Post-Video & Comments [program]

Video List — JP Kanji Ultra Translation CONTROL SECTION — Login (Admin) Username: Password: Login CONTROL SECTION — Admin Panel Enable Comments Disable Comments Logout Activity Log Show Video COMMENTS DISABLED BY ADMIN Leave a Comment: Additional Comment Show Video COMMENTS DISABLED BY ADMIN Leave a Comment: Additional Comment Show Video COMMENTS DISABLED BY ADMIN Leave a Comment: Additional Comment Show Video COMMENTS DISABLED BY ADMIN Leave a Comment: Additional Comment

My Pending and Delayed POSTs SUMMARY [APPs]
MADE by ChatGPT

🔗 My Pending and Delayed POSTs SUMMARY Sort by Date Sort by Auto Title Sort by My Title Ascending Descending (Newest First) Insert URL: Your Own Title (Optional): Status: Pending Done ➕ ADD ENTRY 💾 SAVE EDIT (MAIN FORM) DATE / TIME AUTO TITLE MY TITLE STATUS URL ACTIONS 📝 TO DO LIST SUMMARY Sort by Date Sort by Header Sort by Detail ...

Tablet Holder di Mobil dan Konsep DOUBLE Tablet Holder aka +secondary supporting holder

Gw udah pasang Holder khusus Tablet yg menurut gw sudah pilihan terbaik! Karena memiliki Arm KERAS/RIGID yg dibutuhkan utk menggenggam ERAT Dalam hal menopang Tablet yg lebih berat dr HP biasa Cekidot Lapak (click here!!) Namun .. Setelah gw pasang Bukan tidak bagus Tapi kalau melewati jalan jelek GOYANG (sikit) juga Gan! Akan tetapi .... Gw rasa bisa makin dimaksimalkan KERIGIDAN dengan menambah PENOPANG KEDUA Check it out: Dari searching2 di MarketPlace Gw ketemu yg mirip holder lampu belajar zaman doeloe Dan .. namun .. tiba2 gw menemukan Ide (lanjutan) Mekanisme yg bisa diReApplied kalau suatu saat diperlukan di Kreasi Agan2 lain  Gunakan Kombo 2 Perangkat berikut apabila membutuhkan holdingan tablet tambahan yg memiliki  "hold area"  yg lebih sempit karena holder kedua "takutnya/dirasa" tidak akan muat utk menggenggam Tablet sebagai penopang kedua, sebagai akibat holder pertama/utama sudah "cukup banyak" memakan tempat Perangkat Pertama (kon...