10 Battle-Tested Prompts for GPT-4: From Code Generation to Architecture Design

You are a hands-on developer who uses AI daily to speed up work. Compile a collection of prompts you actually use in your workflow. Each prompt — battle-tested, working, with a real usage example. Style — like a Telegram channel post for developers: to the point, without unnecessary explanations, focused on practical value.

Here are 10 prompts for ChatGPT and GPT-4 that I use every week for programming, debugging, and refactoring. No fluff, just copy-paste and run.


1. Generate a Function from a Description

Prompt:

Write a Python function that takes a list of strings and returns a list of unique strings sorted by frequency (most frequent first). If two strings have the same frequency, sort alphabetically. Include type hints and a docstring with example usage.

Why it works: GPT-4 understands the exact spec — no ambiguity. You get a ready-to-use function with typing and examples.

Real usage: I needed a quick dedup+sorter for log analysis. One-shot, no edits.


2. Debug with Error Trace

Prompt:

I'm getting this error in Python:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    result = process_data(data)
  File "main.py", line 8, in process_data
    return [x * 2 for x in data]
TypeError: unsupported operand type(s) for *: 'str' and 'int'

Here is the code:

def process_data(data):
    return [x * 2 for x in data]

data = [1, 2, 'three', 4]
print(process_data(data))

Explain the root cause and fix it. Also suggest how to make the function handle mixed types gracefully.

Why it works: You give the exact traceback + code. GPT-4 pinpoints the issue (line 8, string multiplication) and suggests a fix with isinstance check or try/except.

Real usage: Saved me 10 minutes of manual tracing in a 300-line script.


3. Refactor a Messy Code Block

Prompt:

Here is a JavaScript function that works but is hard to read. Refactor it to be cleaner, more modular, and add comments. Keep the same behavior.

function calc(a,b,c){
  if(a>b){return a*c}else{if(b>a){return b*c}else{return (a+b)*c}}
}

Why it works: GPT-4 rewrites it with proper formatting, descriptive variable names, and maybe even ternary operators or early returns.

Real usage: I refactored a legacy API endpoint in 5 minutes instead of 30.


4. Generate Unit Tests for a Function

Prompt:

Generate a comprehensive suite of pytest tests for the following Python function. Include edge cases, normal cases, and error cases. Use pytest fixtures where appropriate.

def divide(a: float, b: float) -> float:
    """Divide a by b. Raises ValueError if b is zero."""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

Why it works: GPT-4 outputs a test file with multiple test functions, parametrized tests, and a fixture for common setup.

Real usage: Added 20 tests in 2 minutes for a critical calculation module.


5. Convert Code Between Languages

Prompt:

Convert this Python code to TypeScript with strict typing. Keep the same logic and structure.

def fetch_user(user_id: int) -> dict | None:
    import requests
    response = requests.get(f"https://api.example.com/users/{user_id}")
    if response.status_code == 200:
        return response.json()
    return None

Why it works: GPT-4 produces TypeScript with interfaces, async/await, and error handling.

Real usage: Migrated a data pipeline from Python to Node.js in under an hour.


6. Explain a Complex Code Snippet

Prompt:

Explain the following line of code in simple terms. What does each part do?

const result = arr.reduce((acc, val) => acc + (val > 10 ? val : 0), 0);

Why it works: GPT-4 breaks down reduce, accumulator, ternary, and initial value. Great for onboarding juniors or understanding unfamiliar syntax.

Real usage: I used it to teach a colleague reduce in 30 seconds.


7. Suggest Architectural Improvements

Prompt:

I have a monolithic Express.js API with 50 routes and no separation of concerns. Suggest a refactoring plan to move to a layered architecture (controllers, services, repositories). Provide a directory structure and example code for one route. Assume I use MongoDB via Mongoose.

Why it works: GPT-4 gives a concrete plan with folder structure, dependency injection pattern, and a migration strategy.

Real usage: I planned a 2-day refactor that actually worked on the first try.


8. Generate a Regex Pattern

Prompt:

Generate a regex pattern that matches:
- Email addresses (standard format)
- But excludes emails from @example.com or @test.com
- Must be case-insensitive
- Should capture the full email in group 1

Also provide a Python example using re.findall.

Why it works: GPT-4 outputs the exact regex, explains each part, and gives a runnable example.

Real usage: Filtered out test emails from a CSV export in 1 minute.


9. Write a SQL Query with Explanation

Prompt:

Write a SQL query (PostgreSQL) that finds the top 5 customers by total order value in the last 30 days. Tables: customers(id, name), orders(id, customer_id, total, created_at). Include indexes that would speed up this query. Explain your reasoning.

Why it works: GPT-4 generates the query, suggests composite indexes on (customer_id, created_at), and explains why.

Real usage: Optimized a slow reporting query from 12 seconds to 0.3 seconds.


10. Generate API Documentation from Code

Prompt:

Generate OpenAPI 3.0 documentation for this Express.js route:

app.post('/api/users', async (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) return res.status(400).json({ error: 'Missing fields' });
  const user = await User.create({ name, email });
  res.status(201).json(user);
});

Include request body schema, response schemas for success and error, and example values.

Why it works: GPT-4 outputs a complete YAML/JSON snippet you can paste into Swagger.

Real usage: Documented 15 endpoints in 20 minutes.


Bonus: Prompt Engineering Tips

  • Be specific: "Write a Python function" vs "Write code"
  • Provide context: include error messages, existing code, or constraints
  • Use examples: "like this: ..."
  • Ask for explanations: "Explain your reasoning"

Conclusion

These 10 prompts cover 80% of my daily AI-assisted coding tasks. The key is to treat GPT-4 as a senior developer who needs clear instructions — give it the problem, constraints, and expected output. No vague requests. Try them, adapt them, and you'll cut your coding time in half.

Remember: the best prompt is the one you actually use. Start with these, then tweak to fit your stack and style.

← All posts

Comments