How to Write Effective AI Prompts

Complete guide to getting the best results from artificial intelligence

What is a Prompt?

A prompt is the instruction you give to an AI to perform a task. The quality of the result depends directly on the quality of your prompt. A good prompt is like a good recipe: it needs precise ingredients and clear steps.

The 4 Elements of a Perfect Prompt

1. Context

Provide information about your situation, experience level, and end goal.

Bad: "Write code"
Good: "I'm a junior developer working on an e-commerce app with React and I need..."

2. Specific Task

Be as specific as possible about what you want the AI to do.

Bad: "Make a function"
Good: "Create a TypeScript function that filters an array of products by minimum and maximum price, category, and stock availability"

3. Output Format

Specify how you want to receive the response.

Example: "Give me the code with explanatory comments, include unit tests, and explain the time complexity"

4. Constraints

Set clear boundaries.

Example: "Don't use external libraries, code must be compatible with Node.js 18+, maximum 50 lines"

Ready-to-Use Prompt Templates

For generating code

"As an expert in [language], create a function that [detailed description]. Requirements: - Input: [describe input format] - Output: [describe output format] - Constraints: [limits and conditions] - Include: [tests, comments, error handling] Briefly explain how it works and the O(n) complexity."

For debugging code

"Find the bug in this [language] code: [code] Error I'm getting: [full error message] Expected behavior: [what should happen] Actual behavior: [what is happening] Explain the root cause and provide the fix."

For learning a concept

"Explain [concept] to me as if I were [level] years old. Include: 1. Simple definition 2. Real-world analogy 3. Practical code example 4. When to use it and when not to 5. Common mistakes"

Advanced Techniques

Chain of Thought

Ask the AI to think step by step:

Prompt: "Solve this problem step by step, explaining your reasoning at each stage..."

Few-Shot Learning

Provide examples before asking for the task:

"Convert these sentences to formal style: 'Hey, what's up?' → 'Hello, how are you doing?' 'I need that now' → 'I kindly request that you send me...' Now convert: 'Send me the file when you can'"

Role Playing

Assign an expert role to the AI:

Prompt: "Act as a senior developer with 15 years of experience in software architecture. Review this code and suggest improvements..."

Common Mistakes When Writing Prompts

Perfect Prompt Checklist

Prompt Examples by Language

Each programming language has its own conventions, patterns, and best practices. Below are specific prompts tailored to the most popular languages, so you can get much more precise and useful results.

Python

Python is characterized by its readability and scientific ecosystem. Effective Python prompts should mention PEP 8, type hints, and the specific libraries you use in your project.

"As a Python 3.12 expert, create a class that manages an asynchronous task queue using asyncio. Requirements: - Follow PEP 8 and include complete type hints - Use dataclasses for data models - Implement methods: enqueue, dequeue, peek, is_empty - Handle exceptions with custom classes - Include Google-style docstrings - Add a usage example with asyncio.run() - Compatible with Python 3.10+ The queue should support priorities and configurable timeouts."

JavaScript / TypeScript

For JavaScript and TypeScript, it's essential to specify the runtime environment (browser or Node.js), the module system, and whether you prefer a functional or object-oriented style.

"As a senior frontend developer, create a React custom hook called useDebounce in TypeScript. Requirements: - Strict TypeScript with generic types - Compatible with React 18+ - Use useEffect and useState from React - Include cleanup to prevent memory leaks - Accepts value and delay as parameters - Returns the debounced value - Include a usage example with a search input - Export necessary types Don't use external libraries, only React."

SQL

SQL prompts should include the specific database engine (PostgreSQL, MySQL, SQL Server), the schema of the tables involved, and the expected result with sample data.

"As an expert PostgreSQL 16 DBA, write an optimized query to get the top 10 customers who have purchased the most in the last 90 days. Table schemas: - customers (id, name, email, created_at) - orders (id, customer_id, total, status, created_at) - order_items (id, order_id, product_id, quantity, price) Requirements: - Use CTEs for better readability - Include recommended indexes - Explain the expected execution plan - Only orders with status = 'completed' - Show: name, email, total spent, number of orders - Optimize for a table with 1M+ records"

CSS / Tailwind

CSS prompts should describe the desired visual design, responsive behavior, and accessibility constraints you need to meet.

"As a modern CSS expert, create a responsive dashboard layout with CSS Grid. Requirements: - Fixed 250px sidebar that collapses on mobile (hamburger menu) - Sticky 64px header - Main content area with auto-fill card grid - Footer that always stays at the bottom (sticky footer) - Use CSS custom properties for theming (light/dark) - Smooth transition animations - Compatible with the last 2 browser versions - Include media queries for mobile (320px), tablet (768px), desktop (1200px) - No frameworks, pure CSS"

How to Iterate and Refine Prompts

You rarely get the perfect result on the first try. The key is to treat prompt writing as an iterative process where each version improves upon the previous one. Below we show you how to transform mediocre prompts into precise instructions.

Iteration 1: From vague to structured prompt

The first attempt is usually too generic. The AI needs context and specificity to produce professional-quality code.

Vague prompt (attempt 1): "Make me a function to validate emails" Result: The AI generates a basic regex that doesn't cover real-world cases. Improved prompt (attempt 2): "Create a TypeScript function that validates emails according to RFC 5322. - Input: string - Output: { valid: boolean, reason?: string } - Should reject: emails without @, domains without TLD, emails with spaces - Should accept: emails with +, subdomains, international domains - Include unit tests with Jest - Maximum 30 lines"

Iteration 2: Refining the result

Once you have a working first version, you can request specific improvements to the generated code.

Refinement prompt (attempt 3): "The function you generated works well, but I need you to: 1. Extract the regex to a constant with a descriptive name 2. Add an optional 'options' parameter with: - allowPlusAddressing: boolean (default true) - maxLength: number (default 254) - allowedDomains: string[] (optional, whitelist) 3. Throw typed errors (EmailValidationError) instead of returning an object 4. Add complete JSDoc with @example 5. Optimize the regex to prevent ReDoS"

Iteration 3: Adapting to your codebase

The final step is adapting the generated code to the conventions and patterns of your existing project.

Adaptation prompt (attempt 4): "Adapt this function to my project's conventions: - We use Zod for schema validation - Errors extend from AppError (I'll share the class) - The style is functional, not object-oriented - We export as named export - Tests use vitest instead of jest - The file goes in src/utils/validators/ Here's my AppError: [code] Here's an example of how we write validations: [code]"

Tips for iterating effectively

Follow these principles to get the most out of each iteration with the AI. It's not about rewriting the entire prompt, but adding layers of precision progressively.

Frequently Asked Questions

How long should an ideal prompt be?

There's no fixed length, but the most effective prompts typically have between 100 and 300 words. What matters isn't the quantity but the density of useful information. A very specific 50-word prompt can outperform a 500-word prompt full of irrelevant information. The general rule is: include everything necessary and nothing more. If your prompt exceeds 500 words, you're probably trying to cover too many tasks in a single request and should break it into steps.

Do prompts work the same across all AIs?

The fundamental principles are the same (context, task, format, constraints), but each model has its particularities. ChatGPT responds well to detailed and conversational instructions, Claude excels with long prompts and extensive documents, and Gemini works well with prompts that include structured data. The recommendation is to learn each model's strengths and adapt your prompting style accordingly. A well-written prompt will work reasonably well on any model, but optimal results require specific adjustments.

Should I write prompts in English or another language?

Most AI models have been trained predominantly in English, so prompts in this language tend to produce slightly better results, especially for code and technical documentation. However, current models handle other languages quite well. A good strategy is to use technical terms in English (for example, "implement a middleware with error handling"). For code, variable and function names should always be in English.

How do I prevent the AI from hallucinating or inventing libraries?

To minimize hallucinations, always include the explicit constraint "use only libraries that exist and are actively maintained" and provide your project's dependency list (your package.json, requirements.txt, etc.). You can also ask the AI to verify its answer: "Before giving me the code, confirm that all libraries you use exist on npm/PyPI and are in their latest version." Another effective technique is to ask it to cite the official documentation of the APIs it uses.