Overview
AI-Powered Code Generation
AI code assistants leverage large language models trained on billions of lines of code to accelerate software development. These systems understand syntax, semantics, design patterns, and best practices across multiple programming languages.
Core capabilities:
- Intelligent code completion with multi-line suggestions
- Full function/class generation from natural language descriptions
- Code translation between programming languages
- Automated refactoring and optimization
- Bug detection and fix suggestions
- Test case generation (unit, integration, E2E)
- Documentation generation from code analysis
- Code review with security and performance insights
Training Methodology
Code models are trained using specialized approaches:
Pre-training
Trained on public repositories (GitHub, GitLab, Stack Overflow). Datasets: 1-5TB of filtered code across 80+ languages.
Fill-in-the-Middle (FIM)
Training objective that predicts code between prefix and suffix contexts. Essential for IDE completions.
Repository-Level Context
Models trained to understand cross-file dependencies, imports, and project structure.
Instruction Tuning
Fine-tuned on programming tasks with natural language instructions for better prompt adherence.
Industry Impact Metrics
Production studies on AI coding assistants show measurable productivity gains:
| Metric | Improvement | Source |
|---|---|---|
| Code completion acceptance rate | 25-35% | GitHub Copilot internal metrics |
| Development speed increase | 40-55% | GitHub study (2022) |
| Time to complete tasks | -55% reduction | Accenture internal study |
| Bug reduction (with AI review) | 15-30% | DeepCode analysis |
| Test coverage increase | 20-40% | Meta AI research |
Code Models
Specialized Code LLMs
Code-specific models outperform general-purpose LLMs on programming tasks through specialized training objectives and data curation.
| Model | Parameters | Context | Languages | Best For |
|---|---|---|---|---|
| GPT-5.6 | ~1.7T (MoE) | 128K | All major | Complex reasoning, full apps |
| Claude Sonnet 5 | ~200B | 1M | All major | Large codebase analysis |
| DeepSeek Coder V2 | 236B (MoE) | 128K | 338 languages | Cost-efficient, high quality |
| CodeLlama 70B | 70B | 100K | 20+ languages | Self-hosted, infilling |
| StarCoder2 | 15B | 16K | 600+ languages | Open-source, fine-tuning |
| Codestral (Mistral) | 22B | 32K | 80+ languages | Fast inference, FIM |
Benchmark Performance
HumanEval and MBPP are standard benchmarks for code generation (pass@1 accuracy):
| Model | HumanEval | MBPP | MultiPL-E |
|---|---|---|---|
| GPT-5.6 | 88.4% | 84.1% | 81.7% |
| Claude Sonnet 5 | 92.0% | 87.3% | 84.2% |
| DeepSeek Coder V2 | 90.2% | 85.7% | 82.9% |
| CodeLlama 70B | 67.8% | 71.4% | 62.3% |
| StarCoder2 15B | 46.3% | 52.1% | 44.8% |
IDE Integration Options
GitHub Copilot
Model: GPT-5.6 + Codex
IDEs: VS Code, JetBrains, Neovim
Price: $10/mo individual, $19/mo business
Features: Multi-line completion, chat, CLI
Cursor
Model: GPT-5.6, Claude Sonnet 5
IDEs: Standalone (VS Code fork)
Price: $20/mo Pro
Features: Codebase chat, multi-file edits
Codeium
Model: Proprietary + GPT-5.6
IDEs: 40+ IDEs
Price: Free individual, $12/mo Pro
Features: Unlimited completions, chat
Windsurf (Codeium)
Model: Cascade (proprietary)
IDEs: Standalone
Price: Free
Features: Flow State, agentic coding
Tabnine
Model: Custom + GPT-5.6
IDEs: All major IDEs
Price: $12/mo Pro
Features: On-prem deployment, privacy
Amazon CodeWhisperer
Model: AWS proprietary
IDEs: VS Code, JetBrains
Price: Free
Features: AWS integration, security scans
Code Completion
Intelligent Code Completion Systems
Modern code completion uses Fill-in-the-Middle (FIM) training to predict code based on both prefix (code before cursor) and suffix (code after cursor) context.
Traditional LSP Completion:
Prefix: "const user = {|"
→ Suggests: "name, email, id" (based on local types)
AI-Powered FIM Completion:
Prefix: "const user = {"
Suffix: "}; await db.users.insert(user);"
→ Suggests complete object based on DB schema:
{
name: string,
email: string,
created_at: Date,
role: 'user' | 'admin'
}
Context Sources for Completion
AI completions leverage multiple context sources for accuracy:
- Current file: Full buffer content (up to 128K tokens)
- Open tabs: Recently edited files in IDE
- Imports: Referenced modules and dependencies
- Type definitions: TypeScript/JSDoc types, interfaces
- Repository snippets: Relevant code from project (RAG-based)
- Comments: Natural language intent from docstrings
- Recent edits: User's coding patterns and style
Maximizing Completion Quality
Poor context (generic completion):
function process(data) {
// Process data
|
Rich context (specific completion):
/**
* Validates user registration data and creates new user account
* @param {Object} data - User registration form data
* @returns {Promise} Created user object
*/
async function processUserRegistration(data) {
// Validate required fields
|
// Model suggests:
if (!data.email || !data.password) {
throw new Error('Email and password are required');
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
throw new Error('Invalid email format');
}
if (data.password.length < 8) {
throw new Error('Password must be at least 8 characters');
}
// Hash password and create user
const hashedPassword = await bcrypt.hash(data.password, 10);
return await db.users.create({
email: data.email,
password: hashedPassword,
created_at: new Date()
});
}
Multi-Line vs Single-Line Completion
| Type | Trigger | Use Case | Latency |
|---|---|---|---|
| Single-line | Every keystroke | Variable names, method calls, parameters | <50ms |
| Multi-line | Pause (300-500ms) | Complete functions, loops, conditionals | 100-300ms |
| Whole function | Comment + newline | Generate entire function from description | 500-2000ms |
Acceptance Rate Optimization
Techniques to improve completion acceptance:
1. Write Clear Comments
Detailed docstrings and inline comments significantly improve suggestion relevance (30-40% higher acceptance).
2. Consistent Naming
Use descriptive, conventional names. Models trained on idiomatic code perform better with standard patterns.
3. Type Annotations
TypeScript types or Python type hints provide crucial context for accurate completions.
4. Small Functions
Break code into single-purpose functions. Completions are more accurate for focused tasks.
Code Generation
Natural Language to Code
Generate complete, production-ready code from high-level descriptions using systematic prompt engineering.
Effective Code Generation Prompts
Vague prompt:
"Create a user authentication system"
Detailed prompt with specifications:
"""
Create a JWT-based authentication system for a Node.js/Express API with:
Requirements:
- User registration with email/password
- Email validation (regex)
- Password hashing (bcrypt, 10 rounds)
- JWT token generation (7-day expiry)
- Token refresh endpoint
- Protected route middleware
- MongoDB integration (Mongoose)
- Error handling with appropriate HTTP status codes
Input validation:
- Email: valid format, unique
- Password: min 8 chars, 1 uppercase, 1 number, 1 special char
Security:
- Rate limiting on auth endpoints (5 req/min)
- HTTPS only
- HTTP-only cookies for tokens
Response format:
- Success: { success: true, token, user }
- Error: { success: false, error: "message" }
Tech stack: Express 4.18, Mongoose 7.x, bcryptjs, jsonwebtoken
"""
Iterative Refinement Strategy
Generate code in stages for better quality and control:
Stage 1: Architecture
"Design the folder structure and file organization for this authentication system"
Stage 2: Interfaces
"Define TypeScript interfaces and types for User, AuthRequest, AuthResponse"
Stage 3: Core Logic
"Implement the user registration controller with validation"
Stage 4: Integration
"Add route handlers and middleware, integrate with MongoDB"
Complex Generation Example
Prompt: "Create a React hook for infinite scroll pagination with the following..."
GPT-5.6 Output:
import { useState, useEffect, useCallback, useRef } from 'react';
interface UseInfiniteScrollOptions {
fetchFn: (page: number, limit: number) => Promise;
initialPage?: number;
pageSize?: number;
threshold?: number;
}
interface UseInfiniteScrollReturn {
data: T[];
loading: boolean;
error: Error | null;
hasMore: boolean;
loadMore: () => void;
reset: () => void;
}
export function useInfiniteScroll({
fetchFn,
initialPage = 1,
pageSize = 20,
threshold = 0.8
}: UseInfiniteScrollOptions): UseInfiniteScrollReturn {
const [data, setData] = useState([]);
const [page, setPage] = useState(initialPage);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [hasMore, setHasMore] = useState(true);
const observer = useRef(null);
const loadMore = useCallback(async () => {
if (loading || !hasMore) return;
setLoading(true);
setError(null);
try {
const newData = await fetchFn(page, pageSize);
if (newData.length < pageSize) {
setHasMore(false);
}
setData(prev => [...prev, ...newData]);
setPage(prev => prev + 1);
} catch (err) {
setError(err instanceof Error ? err : new Error('Unknown error'));
} finally {
setLoading(false);
}
}, [page, pageSize, loading, hasMore, fetchFn]);
const reset = useCallback(() => {
setData([]);
setPage(initialPage);
setHasMore(true);
setError(null);
}, [initialPage]);
const lastElementRef = useCallback((node: Element | null) => {
if (loading) return;
if (observer.current) observer.current.disconnect();
observer.current = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && hasMore) {
loadMore();
}
}, { threshold });
if (node) observer.current.observe(node);
}, [loading, hasMore, loadMore, threshold]);
useEffect(() => {
loadMore();
}, []);
return {
data,
loading,
error,
hasMore,
loadMore,
reset,
lastElementRef
};
}
Code Translation Between Languages
Prompt: "Convert this Python function to TypeScript with equivalent type safety"
Python input:
def calculate_stats(numbers: List[float]) -> Dict[str, float]:
return {
'mean': statistics.mean(numbers),
'median': statistics.median(numbers),
'std_dev': statistics.stdev(numbers),
'min': min(numbers),
'max': max(numbers)
}
TypeScript output:
interface Statistics {
mean: number;
median: number;
stdDev: number;
min: number;
max: number;
}
function calculateStats(numbers: number[]): Statistics {
if (numbers.length === 0) {
throw new Error('Array cannot be empty');
}
const sorted = [...numbers].sort((a, b) => a - b);
const mean = numbers.reduce((a, b) => a + b) / numbers.length;
const median = numbers.length % 2 === 0
? (sorted[numbers.length / 2 - 1] + sorted[numbers.length / 2]) / 2
: sorted[Math.floor(numbers.length / 2)];
const variance = numbers.reduce((sum, num) =>
sum + Math.pow(num - mean, 2), 0) / numbers.length;
const stdDev = Math.sqrt(variance);
return {
mean,
median,
stdDev,
min: sorted[0],
max: sorted[sorted.length - 1]
};
}
Code Review
AI-Powered Code Review
Automated code review using LLMs to identify bugs, security vulnerabilities, performance issues, and style violations.
Comprehensive Review Prompt Template
Review the following code for:
1. **Bugs & Logic Errors**
- Off-by-one errors, null pointer exceptions
- Race conditions, deadlocks
- Incorrect algorithm implementation
2. **Security Vulnerabilities**
- SQL injection, XSS, CSRF
- Authentication/authorization flaws
- Sensitive data exposure
- Insecure dependencies
3. **Performance Issues**
- O(n²) algorithms where O(n) exists
- Unnecessary database queries (N+1 problem)
- Memory leaks
- Blocking operations in async code
4. **Code Quality**
- Code duplication (DRY violations)
- Overly complex functions (cyclomatic complexity > 10)
- Poor naming conventions
- Missing error handling
5. **Best Practices**
- SOLID principles violations
- Improper use of design patterns
- Missing input validation
- Inadequate logging
For each issue found, provide:
- Severity: Critical / High / Medium / Low
- Location: File:line
- Description: What's wrong
- Recommendation: How to fix
Code to review:
```python
[paste code here]
```
Example Review Output
Input code:
def get_user_orders(user_id):
orders = []
for order in db.query("SELECT * FROM orders"):
if order['user_id'] == user_id:
orders.append(order)
return orders
AI Review:
🔴 CRITICAL - SQL Injection Vulnerability
Location: Line 3
Issue: Raw SQL query without parameter binding
Recommendation:
orders = db.query(
"SELECT * FROM orders WHERE user_id = ?",
(user_id,)
)
🔴 HIGH - Performance Issue (N+1 Query + Inefficient Filtering)
Location: Lines 3-5
Issue: Fetching all orders then filtering in Python. O(n) database scan.
Recommendation: Use WHERE clause to filter at database level:
return db.query(
"SELECT * FROM orders WHERE user_id = ?",
(user_id,)
).fetchall()
🟡 MEDIUM - Missing Error Handling
Location: Function level
Issue: No handling for database connection failures or invalid user_id
Recommendation:
def get_user_orders(user_id: int) -> List[Dict]:
if not isinstance(user_id, int) or user_id <= 0:
raise ValueError("Invalid user_id")
try:
return db.query(...).fetchall()
except DatabaseError as e:
logger.error(f"DB error fetching orders: {e}")
raise
🟢 LOW - Missing Type Hints
Location: Function signature
Issue: No type annotations for better code documentation
Recommendation: Add typing:
from typing import List, Dict
def get_user_orders(user_id: int) -> List[Dict[str, Any]]:
Automated Review Integration
# GitHub Actions workflow for AI code review
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Get changed files
id: files
run: |
git diff --name-only origin/${{ github.base_ref }}...HEAD > changed_files.txt
- name: AI Review
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
python scripts/ai_review.py \
--files changed_files.txt \
--model gpt-4-turbo \
--output review_results.json
- name: Post Review Comments
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const results = JSON.parse(fs.readFileSync('review_results.json'));
for (const issue of results.issues) {
if (issue.severity === 'CRITICAL' || issue.severity === 'HIGH') {
await github.rest.pulls.createReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: `**${issue.severity}**: ${issue.description}\n\n${issue.recommendation}`,
path: issue.file,
line: issue.line
});
}
}
Test Generation
AI-Generated Test Suites
Automatically generate comprehensive test cases covering edge cases, error conditions, and integration scenarios.
Unit Test Generation Prompt
Generate comprehensive unit tests for this function:
Requirements:
- Testing framework: [Jest/Pytest/JUnit]
- Cover all edge cases and error conditions
- Test boundary values
- Mock external dependencies
- Achieve >90% code coverage
- Include descriptive test names following AAA pattern (Arrange, Act, Assert)
Function to test:
```typescript
function calculateDiscount(
price: number,
discountPercent: number,
membershipLevel: 'bronze' | 'silver' | 'gold'
): number {
if (price < 0 || discountPercent < 0 || discountPercent > 100) {
throw new Error('Invalid input');
}
let finalDiscount = discountPercent;
if (membershipLevel === 'silver') {
finalDiscount += 5;
} else if (membershipLevel === 'gold') {
finalDiscount += 10;
}
const discountAmount = (price * finalDiscount) / 100;
return Math.max(0, price - discountAmount);
}
```
Generated Test Suite Example
describe('calculateDiscount', () => {
describe('valid inputs', () => {
it('should apply basic discount for bronze member', () => {
const result = calculateDiscount(100, 10, 'bronze');
expect(result).toBe(90);
});
it('should apply additional 5% for silver member', () => {
const result = calculateDiscount(100, 10, 'silver');
expect(result).toBe(85);
});
it('should apply additional 10% for gold member', () => {
const result = calculateDiscount(100, 10, 'gold');
expect(result).toBe(80);
});
it('should handle zero discount', () => {
const result = calculateDiscount(100, 0, 'bronze');
expect(result).toBe(100);
});
it('should handle 100% discount for gold member', () => {
const result = calculateDiscount(100, 90, 'gold');
expect(result).toBe(0);
});
it('should not go below zero price', () => {
const result = calculateDiscount(100, 100, 'gold');
expect(result).toBe(0);
});
});
describe('edge cases', () => {
it('should handle small prices correctly', () => {
const result = calculateDiscount(0.01, 10, 'bronze');
expect(result).toBeCloseTo(0.009, 3);
});
it('should handle large prices', () => {
const result = calculateDiscount(1000000, 10, 'silver');
expect(result).toBe(850000);
});
it('should handle floating point discounts', () => {
const result = calculateDiscount(99.99, 15, 'bronze');
expect(result).toBeCloseTo(84.99, 2);
});
});
describe('error cases', () => {
it('should throw error for negative price', () => {
expect(() => calculateDiscount(-100, 10, 'bronze'))
.toThrow('Invalid input');
});
it('should throw error for negative discount', () => {
expect(() => calculateDiscount(100, -10, 'bronze'))
.toThrow('Invalid input');
});
it('should throw error for discount over 100%', () => {
expect(() => calculateDiscount(100, 101, 'bronze'))
.toThrow('Invalid input');
});
});
describe('membership level variations', () => {
it.each([
['bronze', 10, 90],
['silver', 10, 85],
['gold', 10, 80],
])('should apply correct discount for %s member',
(level, discount, expected) => {
const result = calculateDiscount(100, discount, level as any);
expect(result).toBe(expected);
}
);
});
});
Integration Test Generation
Generate integration tests for API endpoint:
POST /api/users
Body: { email, password, name }
Expected: 201 Created, returns { id, email, name, token }
Test scenarios:
- Successful user creation
- Duplicate email rejection
- Invalid email format
- Weak password rejection
- Missing required fields
- Database connection failure
- Email service failure
Generated tests:
describe('POST /api/users', () => {
let app, db;
beforeAll(async () => {
app = await createTestApp();
db = await setupTestDatabase();
});
afterAll(async () => {
await db.close();
await app.close();
});
beforeEach(async () => {
await db.users.deleteMany({});
});
it('should create user successfully with valid data', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: 'test@example.com',
password: 'SecurePass123!',
name: 'Test User'
});
expect(response.status).toBe(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: 'test@example.com',
name: 'Test User',
token: expect.any(String)
});
expect(response.body.password).toBeUndefined();
// Verify user in database
const user = await db.users.findOne({ email: 'test@example.com' });
expect(user).toBeTruthy();
expect(user.password).not.toBe('SecurePass123!'); // Should be hashed
});
it('should reject duplicate email', async () => {
await db.users.create({
email: 'existing@example.com',
password: 'hashed',
name: 'Existing'
});
const response = await request(app)
.post('/api/users')
.send({
email: 'existing@example.com',
password: 'SecurePass123!',
name: 'Duplicate'
});
expect(response.status).toBe(409);
expect(response.body.error).toMatch(/email already exists/i);
});
it('should reject invalid email format', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: 'invalid-email',
password: 'SecurePass123!',
name: 'Test'
});
expect(response.status).toBe(400);
expect(response.body.error).toMatch(/invalid email/i);
});
});
AI-Assisted Debugging
Error Diagnosis with AI
Leverage LLMs to analyze stack traces, identify root causes, and suggest fixes.
Debugging Prompt Template
I'm encountering this error:
**Error message:**
```
[paste full error message and stack trace]
```
**Code context:**
```python
[paste relevant code snippet]
```
**Environment:**
- Language/Framework: Python 3.11 / FastAPI
- Dependencies: [list key packages and versions]
- OS: Ubuntu 22.04
**What I've tried:**
1. [attempted fix 1]
2. [attempted fix 2]
Please:
1. Explain the root cause of this error
2. Provide a step-by-step fix
3. Explain why the fix works
4. Suggest how to prevent similar errors
Example Debugging Session
Error:
TypeError: Cannot read property 'map' of undefined
at ProductList.render (ProductList.tsx:15:23)
Code:
function ProductList({ category }) {
const [products, setProducts] = useState();
useEffect(() => {
fetchProducts(category).then(setProducts);
}, [category]);
return (
{products.map(product => (
))}
);
}
AI Diagnosis:
**Root Cause:**
The error occurs because `products` is initially `undefined` (line 2). When the component first renders, `products.map()` is called before the API fetch completes, attempting to call `.map()` on `undefined`.
**Fix (3 approaches):**
1. **Initialize with empty array (simplest):**
```typescript
const [products, setProducts] = useState([]);
```
2. **Conditional rendering:**
```typescript
return (
{products?.map(product => (
))}
);
```
3. **Loading state (best UX):**
```typescript
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetchProducts(category)
.then(setProducts)
.finally(() => setLoading(false));
}, [category]);
if (loading) return ;
return (
{products.map(product => (
))}
);
```
**Why this happens:**
React renders components immediately, but async data fetches take time. Without proper initialization, attempting to use array methods on undefined/null values throws TypeErrors.
**Prevention:**
- Always initialize state with appropriate empty values ([], {}, null)
- Add TypeScript types to catch these at compile time
- Implement loading states for async data
- Use optional chaining (?.) for defensive programming
Performance Debugging
Prompt: "This React component is re-rendering excessively. Identify the cause and optimize."
Code:
function UserDashboard() {
const [users, setUsers] = useState([]);
const filteredUsers = users.filter(u => u.active);
const sortedUsers = filteredUsers.sort((a, b) =>
a.name.localeCompare(b.name)
);
return (
{sortedUsers.map(user => (
setUsers([...users])}
/>
))}
);
}
AI Analysis:
**Performance Issues Identified:**
1. **Expensive operations on every render**
- `filter()` and `sort()` run on every render, even when `users` hasn't changed
- O(n log n) complexity on each render
2. **Prop instability**
- New `onUpdate` function created every render
- Causes all UserCard children to re-render unnecessarily
3. **Array mutation in setState**
- `setUsers([...users])` creates new array but doesn't trigger effect
**Optimized version:**
import { useMemo, useCallback } from 'react';
function UserDashboard() {
const [users, setUsers] = useState([]);
// Memoize expensive computation
const sortedUsers = useMemo(() => {
return users
.filter(u => u.active)
.sort((a, b) => a.name.localeCompare(b.name));
}, [users]);
// Stable callback reference
const handleUpdate = useCallback((userId, updates) => {
setUsers(prev => prev.map(u =>
u.id === userId ? { ...u, ...updates } : u
));
}, []);
return (
{sortedUsers.map(user => (
))}
);
}
// Optimize child component
const UserCard = React.memo(({ user, onUpdate }) => {
// ... component logic
});
**Performance gains:**
- Filter/sort only runs when users array changes
- UserCard components don't re-render unless their user data changes
- 10-100× fewer re-renders depending on data size
Production Deployment
AI-Generated CI/CD Pipelines
Automate deployment with AI-generated GitHub Actions, GitLab CI, and Docker configurations.
GitHub Actions Workflow Generation
Prompt: "Generate GitHub Actions workflow for Node.js app with:"
- Run tests on PR
- Build Docker image on main branch
- Deploy to AWS ECS
- Slack notifications
- Environment: staging and production
Generated .github/workflows/deploy.yml:
name: CI/CD Pipeline
on:
pull_request:
branches: [main, develop]
push:
branches: [main]
env:
NODE_VERSION: '20.x'
AWS_REGION: us-east-1
ECR_REPOSITORY: my-app
ECS_CLUSTER: production-cluster
ECS_SERVICE: my-app-service
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test -- --coverage
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
build-and-deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build and push Docker image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: ${{ github.sha }}
run: |
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG \
$ECR_REGISTRY/$ECR_REPOSITORY:latest
docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest
- name: Deploy to ECS
run: |
aws ecs update-service \
--cluster ${{ env.ECS_CLUSTER }} \
--service ${{ env.ECS_SERVICE }} \
--force-new-deployment
- name: Notify Slack on success
if: success()
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": " Deployment successful: ${{ github.repository }}",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Deployment Status:* Success\n*Repository:* ${{ github.repository }}\n*Commit:* ${{ github.sha }}\n*Author:* ${{ github.actor }}"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
- name: Notify Slack on failure
if: failure()
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": " Deployment failed: ${{ github.repository }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
Docker Configuration Generation
Prompt: "Create production-ready Dockerfile for Next.js 14 app with multi-stage build"
Generated Dockerfile:
# Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
# Install dependencies based on package manager
COPY package.json package-lock.json* ./
RUN npm ci --only=production && \
npm cache clean --force
# Stage 2: Builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
# Build Next.js app
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Stage 3: Runner
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs
# Copy necessary files
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
# Set correct permissions
RUN chown -R nextjs:nodejs /app
USER nextjs
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
CMD ["node", "server.js"]
# Metadata
LABEL maintainer="devops@company.com"
LABEL version="1.0"
LABEL description="Production Next.js application"
Kubernetes Deployment Manifests
Prompt: "Generate Kubernetes manifests for Node.js API with:"
- Deployment with 3 replicas
- HorizontalPodAutoscaler (CPU-based)
- Service (LoadBalancer)
- ConfigMap and Secrets
- Health checks
Generated k8s/deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-deployment
labels:
app: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: myregistry/api:latest
ports:
- containerPort: 3000
env:
- name: NODE_ENV
value: "production"
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: api-secrets
key: database-url
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: api-config
key: redis-host
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 10
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: api-service
spec:
type: LoadBalancer
selector:
app: api
ports:
- protocol: TCP
port: 80
targetPort: 3000
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api-deployment
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80