ToolHub
View All Posts

دليل هندسة التوجيهات للذكاء الاصطناعي: تقنيات وأفضل الممارسات

هندسة التوجيهات هي فن وعلم تصميم تعليمات فعالة لنماذج AI. خلال السنوات القليلة الماضية، تطورت من تجارب 'هندسة التوجيهات' البسيطة إلى نظام ناضج مع تقنيات مثبتة وأفضل الممارسات. سواء كنت تستخدم ChatGPT أو Claude Code أو GitHub Copilot أو أي أداة ترميز AI أخرى، فإن جودة مخرجات AI تتناسب مباشرة مع جودة توجيهاتك. يغطي هذا الدليل التقنيات الأساسية لأفضل الممارسات المتقدمة.

ما هي هندسة التوجيهات؟

هندسة التوجيهات هي عملية تصميم وتحسين المدخلات (الموجهات) لنماذج AI لتحقيق المخرجات المرغوبة. الأمر الأكثر أهمية هو التواصل: تتعلم تحديد السياق والقيود والتوقعات بوضوح لدرجة أن AI ينتج بالضبط ما تحتاجه.

تتضمن هندسة التوجيهات الفعالة عدة مكونات: السياق (المعلومات الأساسية التي يحتاجها AI للفهم)، التعليمات (المهمة المحددة التي تريد تنفيذها)، القيود (القواعد والحدود التي يجب على AI اتباعها)، تنسيق المخرجات (كيف تريد هيكلة النتيجة)، والأمثلة (عروض توضيحية للمخرجات المرغوبة).

التوجيه الصفري هو أبسط شكل من أشكال هندسة التوجيهات. تطلب من AI أداء مهمة دون تقديم أي أمثلة. هذا يعمل بشكل جيد للمهام المباشرة حيث يكون لدى AI معرفة عامة كافية. على سبيل المثال: 'صنف النص التالي إلى إيجابي أو سلبي أو محايد.'

تقنية Chain-of-Thought: إضافة 'دعنا نفكر في هذا خطوة بخطوة' إلى موجهاتك يمكن أن يحسن الدقة بنسبة 10-40% في مهام الاستدلال المعقدة. هذا هو أحد أكثر تقنيات هندسة التوجيهات فعالية.

التقنيات الأساسية

يقدم التوجيه القليل مجموعة صغيرة من الأمثلة قبل المهمة الفعلية. هذا يساعد AI على فهم النمط أو التنسيق الذي تتوقعه. أظهرت الأبحاث أن 2-5 أمثلة عادة ما تكون كافية. المزيد من الأمثلة لا يحسن النتائج دائمًا وقد يربك النموذج.

التوجيه الصفري

تشجع سلسلة التفكير AI على تقسيم المشكلات المعقدة إلى خطوات منطقية. بدلاً من طلب إجابة مباشرة، تطلب من AI 'التفكير خطوة بخطوة'. هذا يحسن الدقة بشكل كبير في مهام الاستدلال والرياضيات وحل المشكلات.

Write a Python function that validates an email address using regex.
The function should return True for valid emails and False for invalid ones.

يحدد توجيه الأدوار شخصية أو منظورًا لـ AI لتبنيه. هذا مفيد بشكل خاص لتوليد استجابات متخصصة أو الحفاظ على نغمة متسقة. على سبيل المثال: 'أنت مراجع كود أول. راجع الكود التالي لثغرات الأمان.'

التوجيه القليل

يحدد توجيه المخرجات المنظمة بالضبط كيف تريد تنسيق النتيجة. هذا أمر بالغ الأهمية عند دمج AI في سير العمل الآلي حيث تحتاج المخرجات إلى التحليل البرمجي. على سبيل المثال، طلب مخرجات JSON بالتنسيق: {"summary": "...", "score": N, "suggestions": [...]}.

Convert these database column names to camelCase JavaScript variable names:

user_first_name -> userFirstName
created_at_timestamp -> createdAtTimestamp
is_email_verified -> isEmailVerified
total_order_count ->

Now convert: product_category_id

تتضمن التقنيات المتقدمة: شجرة الفكر (استكشاف مسارات تفكير متعددة بالتوازي)، التوجيه التكراري (تحسين النتائج من خلال جولات متتالية)، الذاتي الاتساق (توليد استجابات متعددة واختيار الأكثر اتساقًا)، والتوجيه المولد للمعرفة (توليد المعرفة أولاً، ثم الإجابة على السؤال).

سلسلة التفكير

هندسة التوجيهات هي فن وعلم تصميم تعليمات فعالة لنماذج AI. تتضمن صياغة المدخلات التي تحدد بوضوح السياق والمهمة والقيود وتنسيق المخرجات المرغوب. الموجهات الجيدة تنتج مخرجات AI أفضل.

Analyze this React component for performance issues. Think step by step:

1. First, identify all state variables and their update patterns
2. Then, check for unnecessary re-renders
3. Next, look for missing memoization opportunities
4. Finally, suggest specific optimizations with code examples

Here's the component:
[component code]

التوجيه الصفري يطلب من AI أداء مهمة دون أمثلة. التوجيه القليل يقدم 2-5 أمثلة قبل المهمة. التوجيه القليل أفضل للمهام المعقدة أو المخرجات المنسقة، بينما التوجيه الصفري يكفي للمهام البسيطة والمباشرة.

توجيه الأدوار

كن محددًا وواضحًا. حدد السياق والمهمة والقيود وتنسيق المخرجات. استخدم الأمثلة عندما يكون ذلك مناسبًا. قسم المهام المعقدة إلى خطوات. راجع وصقل موجهاتك بناءً على النتائج.

Act as a senior security engineer with 15 years of experience in web application security. Review this authentication implementation and identify any vulnerabilities, ranking them by severity. For each vulnerability, explain the attack vector and provide a secure code fix.

3-5 أمثلة عادة ما تكون مثالية للتوجيه القليل. الكثير من الأمثلة يمكن أن تربك النموذج أو تؤدي إلى الإفراط في التخصيص. القليل جدًا من الأمثلة قد لا يوضح النمط بشكل كافٍ. جرب أعدادًا مختلفة للعثور على ما يناسب مهمتك.

توجيه المخرجات المنظمة

بالتأكيد. الموجهات الغامضة أو غير المحددة أو غير الواضحة تؤدي إلى مخرجات AI سيئة. AI ينتج بالضبط ما تطلبه، وليس بالضرورة ما تريده. الموجهات الواضحة والمحددة مع السياق والقيود هي المفتاح للحصول على نتائج جيدة.

CLAUDE.md file functions as a persistent system prompt. In ChatGPT, you can set custom instructions that act as system prompts for all conversations.

# System prompt example
You are a TypeScript expert working on a Next.js 14 project using:
- App Router (not Pages Router)
- Server Components by default
- Prisma for database access
- Tailwind CSS for styling
- Zod for validation

Always use strict TypeScript. Prefer server actions over API routes.
Never use 'any' type. Use 'unknown' and narrow with type guards.

# User prompt example
Add a user profile page that shows the current user's name, email,
avatar, and last 10 activity records. Include loading states and
error handling.

التقنيات المتقدمة

Certain command patterns have proven remarkably effective across all major AI coding tools. These are not literal commands but rather directive phrases that consistently trigger high-quality responses. Think of them as power words that activate specific capabilities in AI models.

الأمرالغرضأفضل سيناريو
"Act as..." / "You are a..."تعيين الدورالحصول على استجابات بمستوى خبير المجال
"Step by step"تسلسل الأفكارالاستدلال المعقد والتصحيح
"Think aloud"شفافية الاستدلالفهم عملية اتخاذ القرار لدى الذكاء الاصطناعي
"Explain like I'm 5"تبسيط الشرحتعلم سريع للمفاهيم الجديدة
"Review and critique"مراجعة الكودالحصول على ملاحظات بناءة على الكود
"Write tests for"توليد الاختباراتتغطية اختبارية شاملة
"Refactor using..."إعادة الهيكلة المبنية على الأنماطتطبيق أنماط التصميم
"Find bugs in"تصحيح الأخطاءتحديد المشكلات الخفية
"Convert from X to Y"ترجمة الكودالترحيل بين اللغات أو الأطر
"Document this"توليد التوثيقإنشاء توثيق مضمن وملف README
"Optimize for performance"تحسينتعزيز السرعة والكفاءة
"Add error handling"تعزيز المتانةجعل الكود جاهزًا للإنتاج

توجيه الشجرة الفكرية

Role assignment is one of the most powerful commands in prompt engineering. By specifying a role, you activate domain-specific knowledge and set expectations for the depth and style of the response. The more specific the role, the better the output.

You are a senior backend engineer at a fintech company who specializes
in building secure, high-throughput payment processing systems.
You have deep expertise in PostgreSQL, Redis, and distributed systems.
You always consider edge cases, race conditions, and failure modes.

Design a payment processing API that handles:
- Credit card payments via Stripe
- Bank transfers via Plaid
- Retry logic with exponential backoff
- Idempotency keys to prevent duplicate charges

التوجيه التكراري

Adding "step by step" or "let's think step by step" to your prompt triggers the AI to break down its reasoning process. This is particularly effective for debugging, algorithm design, and architecture decisions. The step-by-step approach not only produces better results but also makes the AI's reasoning transparent, allowing you to catch errors in logic.

Debug this SQL query that's causing a timeout. Think step by step:

1. First, analyze the query structure and joins
2. Identify potential performance bottlenecks
3. Check for missing indexes
4. Suggest an optimized version with EXPLAIN analysis

SELECT u.name, COUNT(o.id), SUM(o.amount)
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
LEFT JOIN order_items oi ON o.id = oi.order_id
WHERE o.created_at > '2026-01-01'
GROUP BY u.name
HAVING COUNT(o.id) > 10
ORDER BY SUM(o.amount) DESC;

التوجيه الذاتي الاتساق

"Think aloud" is similar to "step by step" but focuses more on the AI's decision-making process. It asks the AI to narrate its reasoning, including what alternatives it considered and why it chose a particular approach. This is invaluable when you need to understand the trade-offs in a design decision or when you want to evaluate whether the AI's reasoning is sound.

I need to choose between WebSocket and Server-Sent Events for a
real-time notification system. Think aloud about the trade-offs,
considering: browser support, bidirectional communication needs,
server resource usage, and scalability. Then recommend one with
justification.

التوجيه المولد للمعرفة

When learning a new concept or trying to understand complex code, "explain like I'm 5" (ELI5) strips away jargon and provides intuitive, analogy-based explanations. This is especially useful for onboarding onto new projects, understanding unfamiliar codebases, or explaining technical concepts to non-technical stakeholders.

Explain like I'm 5: What is a monad in functional programming,
and why do Haskell developers keep talking about them?
Use a real-world analogy, not code.

ما هي هندسة التوجيهات للذكاء الاصطناعي؟

Using "review and critique" signals the AI to adopt a critical perspective rather than simply accepting the code as-is. This produces more thorough analysis, including potential bugs, security issues, performance problems, and style violations. It is like getting a senior engineer's code review on demand.

Review and critique this Express.js middleware. Focus on:
- Security vulnerabilities
- Error handling gaps
- Performance concerns
- Best practice violations
- Suggest improvements with code examples

[paste your middleware code]

ما هو التوجيه الصفري مقابل التوجيه القليل؟

Test generation is one of the highest-value uses of AI coding tools. By specifying "write tests for" along with your testing framework and coverage expectations, you can quickly generate comprehensive test suites. The key is to specify edge cases and testing priorities.

Write tests for the UserService.register method using Jest.
Cover these scenarios:
- Happy path with valid input
- Duplicate email registration
- Invalid email format
- Password too short
- Missing required fields
- Database connection failure
- Concurrent registration attempts

Use describe/it blocks. Include setup and teardown.
Mock the database layer.

ما هي أفضل طريقة لكتابة موجهات AI؟

Specifying a design pattern or principle in your refactoring prompt gives the AI a clear target architecture. Instead of vague "refactor this" requests, naming the pattern produces focused, consistent refactoring that follows established software engineering principles.

Refactor this notification system using the Strategy pattern.
Currently, all notification types (email, SMS, push) are handled
in a single class with if-else chains. Create separate strategy
classes for each notification type, a context class that delegates
to the active strategy, and a factory for creating strategies.

[paste your current code]

كم عدد الأمثلة التي يجب تضمينها في التوجيه القليل؟

The "find bugs in" command activates the AI's analytical mode, prompting it to look for issues rather than just generating code. This works best when you provide the code, describe the expected behavior, and mention any symptoms you have observed.

Find bugs in this async Node.js function. It's supposed to process
a batch of orders and update their status, but sometimes orders
get processed twice and the status updates are inconsistent under
high load.

[paste your function code]

هل يمكن للموجهات السيئة أن تولد مخرجات سيئة من AI؟

Many AI-generated code snippets work for the happy path but lack proper error handling. The "add error handling" command specifically targets this gap, asking the AI to consider failure modes, edge cases, and recovery strategies.

Add error handling to this file upload function. Consider:
- File size limits
- Invalid file types
- Network interruptions during upload
- Disk space errors
- Concurrent upload conflicts
- Partial upload cleanup

Use try-catch with specific error types. Add retry logic for
transient failures. Return meaningful error messages to the client.

التفاعل متعدد الأدوار

Beyond individual commands, certain prompt patterns have proven especially effective for specific types of code generation tasks. These patterns combine techniques like role assignment, context provision, and output specification into structured prompts that consistently produce high-quality results.

Feature Implementation Prompts

When implementing a new feature, the most effective prompts follow a specification-like structure: describe the feature, specify the tech stack, define the acceptance criteria, and mention any constraints. This gives the AI a complete picture of what needs to be built.

Implement a user avatar upload feature for a Next.js 14 application.

Tech stack: Next.js App Router, TypeScript, Prisma, PostgreSQL, AWS S3

Requirements:
- Accept JPEG, PNG, WebP (max 5MB)
- Resize to 200x200 and 400x400 thumbnails using Sharp
- Upload originals to S3 with unique keys
- Store S3 URLs in the User model
- Delete old avatar when uploading a new one
- Return presigned URLs for frontend display

Acceptance criteria:
- Invalid file types return 400 with error message
- Files over 5MB return 413
- Successful upload returns 200 with avatar URLs
- Old avatars are cleaned up from S3

Create: API route, service layer, Prisma schema update, and types.

API Design Prompts

API design prompts benefit from specifying the architectural style, authentication method, versioning strategy, and response format upfront. This ensures the generated API is consistent and follows your project's conventions.

Design a RESTful API for a project management application.

Architecture: Express.js with TypeScript, following clean architecture
Auth: JWT with refresh token rotation
Versioning: URL-based (/api/v1/)
Response format: { success: boolean, data?: T, error?: { code, message } }

Endpoints needed:
- Projects CRUD with team membership
- Tasks CRUD with assignee, priority, status
- Comments on tasks with mentions
- Activity feed (recent actions across projects)

Include:
- Request/response TypeScript interfaces
- Zod validation schemas
- Error handling middleware
- Pagination for list endpoints (cursor-based)

Database Schema Prompts

Database schema prompts should specify the ORM, naming conventions, indexing strategy, and relationships. The AI can generate complete schemas with proper constraints, indexes, and migration files.

Design a Prisma schema for an e-commerce platform with these entities:

- Users (authentication, profile, addresses)
- Products (variants, categories, inventory)
- Orders (line items, status history, payments)
- Reviews (ratings, images, helpful votes)
- Cart (items, applied coupons)

Requirements:
- Use PostgreSQL with UUID primary keys
- Soft deletes with deletedAt timestamps
- Proper indexes for common query patterns
- Enums for order status, payment status
- Decimal fields for prices (not float)
- Full-text search on product name and description
- Include a migration file

UI Component Prompts

For UI components, specifying the framework, styling approach, accessibility requirements, and interactive states produces much better results than generic "create a component" prompts.

Create a reusable DataTable component in React with TypeScript.

Styling: Tailwind CSS + shadcn/ui conventions
Features:
- Column definitions with sort, filter, and custom renderers
- Server-side pagination with page size selector
- Row selection (single and multi) with checkboxes
- Loading skeleton state
- Empty state with custom message
- Responsive: card layout on mobile, table on desktop

Accessibility:
- Keyboard navigation (arrow keys, Enter, Escape)
- Screen reader announcements for sort and filter changes
- ARIA labels on all interactive elements

Props interface:
- data, columns, isLoading, pagination, onSort, onFilter, onSelect

Include a usage example with a user list table.

Configuration and DevOps Prompts

DevOps and configuration prompts should specify the target environment, security requirements, and any organizational standards. This prevents the AI from generating generic configurations that don't match your infrastructure.

Create a Docker Compose setup for a development environment with:
- Next.js app (hot reload enabled)
- PostgreSQL 16 with persistent volume
- Redis for session storage
- MinIO (S3-compatible) for local file storage

Requirements:
- All services on a shared network
- Environment variables from .env file
- Health checks for all services
- Volumes for node_modules (avoid bind mount issues)
- PostgreSQL initialized with seed data
- Non-root containers where possible

Also create:
- Dockerfile for the Next.js app (multi-stage build)
- .env.example with all required variables
- Makefile with common commands (up, down, logs, reset-db)

تحسين المخرجات

Once you have mastered the fundamental techniques and commands, these advanced strategies will help you tackle complex, multi-step development tasks that go beyond what a single prompt can accomplish.

Prompt Chaining

Prompt chaining breaks a complex task into a sequence of smaller, focused prompts where each prompt builds on the output of the previous one. This strategy produces better results than trying to accomplish everything in a single massive prompt because each step gets the AI's full attention and context.

# Step 1: Design the architecture
"Design the architecture for a real-time chat application.
List the components, their responsibilities, and how they
communicate. Use a diagram-like text format."

# Step 2: Define the data model
"Based on the architecture above, design the database schema
for the chat application. Include users, conversations,
messages, and read receipts. Use Prisma schema format."

# Step 3: Implement the API
"Implement the REST API for the chat application based on
the architecture and schema we designed. Start with the
message endpoints: send, list, delete."

# Step 4: Add WebSocket support
"Now add WebSocket support for real-time message delivery.
Use Socket.io. Integrate with the existing message API."

# Step 5: Write tests
"Write integration tests for the chat API and WebSocket
events using Jest and Supertest."

The key to effective prompt chaining is ensuring each step produces a complete, usable output before moving to the next step. Review each output, make corrections if needed, and then feed the refined result into the next prompt.

Context Stuffing

Context stuffing involves providing the AI with all relevant code, documentation, and context before asking your question. While it might seem obvious, many developers skip this step and then wonder why the AI makes incorrect assumptions. The more relevant context you provide, the more accurate and specific the AI's response will be.

 {
    await this.db.query('UPDATE users SET email = $1 WHERE id = $2', [email, id]);
    await this.cache.del(`user:${id}`);
  }
}
```

Here is the User type:
```typescript
interface User {
  id: string;
  email: string;
  name: string;
  role: 'admin' | 'user';
  createdAt: Date;
}
```

Now, add an updateProfile method that allows updating name and email,
with validation that the email is not already taken by another user.

Notice how providing the existing code and types allows the AI to generate a method that is perfectly consistent with the existing patterns, uses the same caching strategy, and respects the existing type definitions.

Constraint Specification

Setting explicit constraints prevents the AI from making unwanted assumptions. Constraints define what the AI should NOT do, which is often as important as what it should do. Common constraints include technology versions, performance requirements, security rules, and coding standards.

Build a URL shortener API with these constraints:

MUST:
- Use Node.js 20+ with native fetch (no axios)
- Use PostgreSQL via pg driver (no ORM)
- Generate short codes of exactly 7 characters
- Support custom aliases (max 20 chars)
- Return 301 for existing short URLs
- Rate limit to 100 creates per hour per IP

MUST NOT:
- Use any ORM or query builder
- Store full URLs without normalization
- Allow short codes that conflict with existing routes
- Return database errors to the client

PERFORMANCE:
- Handle 10,000 requests per second
- Cache hot URLs in Redis with 5-minute TTL
- P99 latency under 50ms for redirects

Output Format Control

Specifying the desired output format ensures the AI's response is immediately usable without reformatting. This is especially important when the output needs to be parsed by other tools, inserted into documentation, or used as configuration files.

Analyze this codebase and provide the output in this exact format:

## Architecture Overview
[2-3 paragraph summary]

## Component Diagram
```mermaid
graph TD
    [components and relationships]
```

## API Endpoints
| Method | Path | Description | Auth |
|--------|------|-------------|------|

## Database Tables
| Table | Columns | Indexes | Relations |
|-------|---------|---------|-----------|

## Recommendations
1. [Priority] [Description] - [Estimated effort]
2. ...

## Technical Debt
- [ ] [Description] - [Impact: High/Medium/Low]

Iterative Refinement

Iterative refinement is the practice of progressively improving AI output through follow-up prompts. The first response is rarely perfect, but it provides a starting point that you can refine. Each iteration narrows in on the desired result more efficiently than trying to get everything right in a single prompt.

# Iteration 1: Get a starting point
"Write a rate limiter middleware for Express.js"

# Iteration 2: Add specificity
"Good start. Now modify it to use Redis for distributed
rate limiting across multiple server instances. Use sliding
window instead of fixed window."

# Iteration 3: Add edge cases
"Add handling for: Redis connection failures (fall back to
in-memory), custom rate limits per route, burst allowance
for legitimate traffic spikes, and proper headers
(X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)."

# Iteration 4: Add tests
"Write comprehensive tests for all the scenarios we've
covered, including Redis failures and burst handling."

This iterative approach is more effective than writing a single massive prompt because each iteration allows you to course-correct and add detail based on the AI's previous output. It mirrors how you would work with a human developer: start with a rough implementation, then refine.

أفضل الممارسات

While the techniques above work across all AI tools, each platform has unique strengths and quirks. Adapting your prompting style to each tool's characteristics can significantly improve your results.

ChatGPT / GPT-4

ChatGPT and GPT-4 excel at conversational interactions and benefit from structured, well-organized prompts. They handle long context well and are particularly good at explaining concepts and generating documentation.

# Effective GPT-4 prompt structure
**Role:** Senior TypeScript developer
**Task:** Implement a JWT authentication middleware
**Context:** Express.js API, PostgreSQL, existing User model
**Constraints:** No external auth libraries, use crypto module
**Output:** Complete, production-ready code with types
**Format:** Single file with inline comments for complex logic

Claude / Claude Code

Claude and Claude Code are particularly strong at understanding large codebases, following complex instructions, and producing well-structured output. Claude Code's agentic capabilities make it ideal for multi-step tasks.

# Effective Claude Code prompt
Read the following files to understand the current architecture:
- src/routes/userRoutes.ts
- src/middleware/authMiddleware.ts
- src/models/User.ts

Then refactor the authentication flow to support:
1. JWT access tokens (15 min expiry) + refresh tokens (7 day expiry)
2. Token rotation on refresh (invalidate old refresh token)
3. Rate limiting on the refresh endpoint (5 per minute per user)

Update all related files and run the test suite when done.

GitHub Copilot

GitHub Copilot operates differently from chat-based tools — it provides inline suggestions as you type. Effective Copilot usage relies on writing code that clearly signals your intent through comments, type signatures, and surrounding context.

> {
  // Copilot will generate the implementation based on these types

Cursor

Cursor combines IDE integration with AI chat capabilities, offering both inline completions and a chat interface that understands your codebase. Its strength lies in deep project awareness and the ability to reference specific files and symbols.

# Effective Cursor prompt
@src/services/paymentService.ts @src/types/payment.ts

Refactor the processPayment function to use the Strategy pattern.
Create separate strategy classes for each payment provider
(Stripe, PayPal, BankTransfer). The function should accept a
payment method and delegate to the appropriate strategy.

Keep the same public API so existing callers don't break.

Codex CLI

Codex CLI is OpenAI's terminal-based coding agent, similar in concept to Claude Code. It excels at executing multi-step development tasks from the command line.

الأخطاء الشائعة

Even experienced developers make these common prompting mistakes. Recognizing and avoiding them will immediately improve your AI interactions.

Vague Instructions

The most common mistake is providing vague, underspecified instructions. Prompts like "fix this," "make it better," or "add a feature" give the AI almost nothing to work with. The AI will make assumptions, and those assumptions often won't match your intent.

# Bad
"Fix the login bug"

# Good
"Fix the bug where users with uppercase emails cannot log in.
The issue is in src/auth/login.ts - the email comparison is
case-sensitive but emails are stored in lowercase in the database.
The fix should normalize the email to lowercase before comparison."

Missing Context

AI models don't know your project unless you tell them. Failing to provide relevant context — your tech stack, framework version, existing code patterns, or project structure — forces the AI to guess, often incorrectly. Always include the context that a new team member would need to understand your request.

# Bad
"Write a function to send emails"

# Good
"Write an email sending function for our NestJS application.
We use:
- @nestjs/mailer with Handlebars templates
- SMTP via AWS SES
- Templates stored in src/templates/emails/
- Existing MailService class in src/mail/mail.service.ts

The function should accept a template name, recipient, and
template variables. Include error handling for SES throttling
and bounce notifications."

Overloading Prompts

Trying to accomplish too many unrelated tasks in a single prompt leads to mediocre results across the board. The AI's attention is divided, and it may skip important details for some tasks while over-indexing on others. Break complex requests into focused, sequential prompts.

# Bad - Too many tasks in one prompt
"Build a complete user management system with authentication,
profile management, email verification, password reset,
role-based access control, and an admin dashboard"

# Good - Break it into focused prompts
Prompt 1: "Design the database schema for a user management system..."
Prompt 2: "Implement the authentication endpoints..."
Prompt 3: "Add email verification flow..."
Prompt 4: "Implement role-based access control middleware..."

Ignoring Output Format

When you need output in a specific format — JSON, markdown, a particular file structure — failing to specify this leads to unpredictable formatting. The AI might return prose when you need JSON, or a single file when you need multiple files. Always specify the desired output format explicitly.

# Bad
"List all the API endpoints"

# Good
"List all API endpoints in a markdown table with these columns:
| Method | Path | Description | Auth Required | Request Body | Response |"

Not Iterating

Accepting the AI's first response without refinement is a missed opportunity. The first response provides a foundation that you can improve through follow-up prompts. Iteration is where the real power of AI-assisted development emerges — each cycle produces better, more refined output.

# Instead of accepting the first response, iterate:
"Good start. Now add input validation using Zod schemas."
"Now add proper error handling with custom error classes."
"Now add logging for all operations."
"Now write tests for all the edge cases we've discussed."
Pro Tip: The best prompt engineers treat AI interactions as a conversation, not a search query. Start with a clear initial prompt, review the output, and then refine through follow-up messages. This iterative approach consistently produces better results than trying to craft the "perfect" single prompt.

الأسئلة الشائعة

Here are ready-to-use prompt templates for common developer tasks. Copy these templates, fill in the placeholders, and adapt them to your specific needs. Each template combines multiple prompting techniques for maximum effectiveness.

Template 1: Feature Implementation

You are a senior {language} developer specializing in {framework}.

Implement {feature_description} for our {project_type} application.

Tech stack:
- {language} {version} with {framework} {version}
- {database} for data storage
- {orm} for database access
- {testing_framework} for tests

Requirements:
- {requirement_1}
- {requirement_2}
- {requirement_3}

Constraints:
- Must follow existing patterns in the codebase
- Must include input validation
- Must handle errors gracefully
- Must be backward compatible

Output:
1. Implementation code with inline comments for complex logic
2. Unit tests covering happy path and edge cases
3. Brief explanation of design decisions

Template 2: Bug Investigation

You are a debugging specialist with expertise in {language}/{framework}.

Investigate and fix this bug:

**Symptom:** {describe_the_observed_behavior}
**Expected:** {describe_the_expected_behavior}
**Frequency:** {always/sometimes/under_specific_conditions}
**Environment:** {production/staging/development}

Relevant code:
```
{paste_relevant_code}
```

Error output / stack trace:
```
{paste_error_output}
```

Think step by step:
1. Identify the root cause
2. Explain why this bug occurs
3. Provide the fix with code
4. Suggest how to prevent similar bugs
5. Write a regression test

Template 3: Code Review

You are a senior code reviewer at a {company_type} company.

Review this {language} code for:

1. **Correctness:** Logic errors, off-by-one errors, null handling
2. **Security:** Injection, XSS, auth bypasses, data exposure
3. **Performance:** N+1 queries, unnecessary allocations, missing caches
4. **Maintainability:** Code smells, naming, complexity
5. **Testing:** Missing test cases, brittle tests

Code to review:
```
{paste_code}
```

For each issue found, provide:
- Severity: 🔴 Critical / 🟡 Warning / 🔵 Info
- Category: Which of the 5 areas above
- Description: What's wrong and why
- Suggestion: How to fix it, with code example

End with an overall assessment and top 3 priorities.

Template 4: API Endpoint Design

Design a {http_method} {endpoint_path} endpoint for {resource_description}.

Framework: {framework}
Auth: {auth_method}
Database: {database}

The endpoint should:
- {functionality_1}
- {functionality_2}
- {functionality_3}

Provide:
1. Route definition with middleware chain
2. Request validation schema ({validation_library})
3. Controller/handler function
4. Service layer function
5. Database query/function
6. Response types (success and error)
7. Example curl request and response

Template 5: Database Migration

Create a database migration for {change_description}.

Current schema:
```
{current_schema}
```

Desired changes:
- {change_1}
- {change_2}

ORM: {orm_name}
Database: {database_type}

Requirements:
- Migration must be reversible (include down migration)
- Preserve existing data (write data migration SQL if needed)
- Add appropriate indexes for new columns
- Consider performance impact on large tables
- Include rollback safety checks

Template 6: Test Suite Generation

Write a comprehensive test suite for {function_or_class_name}.

Testing framework: {framework}
Mocking library: {library}

Code under test:
```
{paste_code}
```

Test categories to cover:
- ✅ Happy path: All valid inputs produce correct outputs
- 🔄 Edge cases: Empty inputs, boundary values, null/undefined
- ❌ Error cases: Invalid inputs, permission denied, network failures
- 🏎️ Performance: Response time expectations for critical paths
- 🔒 Security: Auth checks, input sanitization

For each test:
- Use descriptive test names that read like documentation
- Follow Arrange-Act-Assert pattern
- Include setup/teardown for shared state
- Mock external dependencies

Template 7: Refactoring Plan

You are a software architect specializing in {language} refactoring.

Current code:
```
{paste_current_code}
```

Problems with current code:
- {problem_1}
- {problem_2}

Refactor using {pattern_or_principle}.

Provide:
1. **Analysis:** What's wrong and why the current approach doesn't scale
2. **Target Architecture:** How the refactored code should be structured
3. **Step-by-step Plan:** Ordered refactoring steps (safe, incremental)
4. **Refactored Code:** Complete implementation
5. **Migration Guide:** How to transition from old to new without breaking changes
6. **Risk Assessment:** What could go wrong and how to mitigate

Template 8: Documentation Generation

Generate documentation for this {language} code:

```
{paste_code}
```

Documentation type: {JSDoc/TSDoc/Python docstrings/README section}

Requirements:
- Document all public functions/classes/methods
- Include parameter descriptions with types
- Include return type descriptions
- Add usage examples for non-obvious APIs
- Note any side effects or important caveats
- Use {style_guide} conventions

For README documentation, include:
- Overview (1-2 paragraphs)
- Installation instructions
- Quick start example
- API reference table
- Configuration options

Template 9: Performance Optimization

You are a performance engineering specialist.

Analyze and optimize this code for performance:

```
{paste_code}
```

Current performance:
- {metric}: {current_value}
- Target: {target_value}
- Bottleneck suspected at: {location}

Optimization constraints:
- Must not change the public API
- Must maintain all existing test passes
- Must not sacrifice readability for micro-optimizations
- {additional_constraint}

Provide:
1. **Profiling Analysis:** Where time/memory is being spent
2. **Optimization Strategies:** Ranked by expected impact
3. **Optimized Code:** With comments explaining each change
4. **Benchmark Comparison:** Before vs after expected metrics
5. **Trade-offs:** Any readability or complexity costs

Template 10: Security Audit

You are a security engineer specializing in {language}/{framework} security.

Perform a security audit on this code:

```
{paste_code}
```

Check for:
- Injection attacks (SQL, NoSQL, command, LDAP)
- Authentication and authorization bypasses
- Cross-site scripting (XSS) vulnerabilities
- Cross-site request forgery (CSRF) exposure
- Insecure direct object references (IDOR)
- Sensitive data exposure (logging, error messages)
- Insecure cryptography or key management
- Race conditions in concurrent operations
- Denial of service vulnerabilities

For each finding:
- Severity: Critical / High / Medium / Low
- OWASP Category: Which Top 10 category
- Description: Clear explanation of the vulnerability
- Attack Scenario: How an attacker would exploit it
- Remediation: Specific code fix
- Verification: How to confirm the fix works

Ready to supercharge your development workflow with AI? Explore ToolHub's curated collection of AI coding assistants, prompt optimization tools, and developer productivity utilities — all free and ready to use.

اقرأ المزيد

Frequently Asked Questions

What is prompt engineering and why is it important for developers?

Prompt engineering is the practice of crafting effective instructions for AI language models to produce desired outputs. For developers, it matters because the quality of AI-generated code, debugging assistance, and documentation directly depends on how well you communicate your intent. Small changes in prompt wording, structure, and context can dramatically improve output quality, turning vague or incorrect responses into precise, useful code and explanations. As AI tools become central to development workflows, prompt engineering is becoming as fundamental as knowing how to write a good bug report or code review comment.

What are the most important prompting techniques for developers?

The most important prompting techniques include: zero-shot prompting (direct instructions without examples), few-shot prompting (providing examples to guide output format), chain-of-thought prompting (asking the AI to reason step by step), role-playing prompts (assigning a persona like "act as a senior engineer"), and system prompts (setting persistent instructions). Combining these techniques with specific commands like "step by step," "think aloud," and "review and critique" produces the best results for coding tasks. The key is to match the technique to the task — use chain-of-thought for debugging, role-playing for expert-level advice, and few-shot for consistent formatting.

How do I write better prompts for AI coding assistants?

To write better prompts: be specific about your tech stack and requirements, provide relevant code context, specify the desired output format, break complex tasks into smaller steps, use role assignment to set expertise level, include constraints and edge cases, and iterate on your prompts when the first result isn't perfect. Avoid vague instructions, missing context, and overloading a single prompt with too many tasks. The most impactful improvement most developers can make is simply providing more context — share the relevant code, types, and project structure before asking your question.

Which AI coding tool is best for prompt engineering?

The best tool depends on your use case. ChatGPT and GPT-4 excel at conversational debugging and explanation. Claude and Claude Code are ideal for large-context tasks and agentic workflows where the AI needs to understand an entire codebase. GitHub Copilot provides the best inline code completion in IDEs. Cursor offers deep IDE integration with multi-file awareness and file references. Codex CLI is great for terminal-based code generation. Most developers benefit from using multiple tools together, each for its strengths — Copilot for inline completion, Claude Code for multi-file tasks, and ChatGPT for learning and explanation.

What are common mistakes to avoid when prompting AI for code?

Common mistakes include: using vague instructions like "fix this" without context, failing to specify your tech stack or framework version, overloading a single prompt with too many unrelated tasks, not specifying the desired output format (JSON, markdown, etc.), accepting the first response without iterating, and not providing enough code context for the AI to understand your project structure. The single biggest mistake is insufficient context — always share relevant code, types, and project details before asking your question. Always iterate and refine your prompts for better results.

Can prompt engineering replace traditional coding skills?

No, prompt engineering complements traditional coding skills but cannot replace them. You need to understand programming concepts, architecture patterns, and system design to write effective prompts and evaluate AI output. Prompt engineering helps you leverage AI tools more effectively, but you still need the expertise to recognize when AI output is incorrect, insecure, or suboptimal. Think of it as a multiplier on your existing skills — a senior engineer with good prompting skills will always outperform a junior developer with the same prompting skills because they can provide better context and evaluate output quality.

How do I handle AI hallucinations in code generation?

AI hallucinations — when the model generates plausible but incorrect code — are a real concern. To mitigate them: always review generated code before using it, run tests to verify correctness, ask the AI to explain its reasoning (chain-of-thought prompting), provide specific library versions and documentation references, and cross-check API usage against official documentation. When the AI references a function or method you're not familiar with, verify it exists before using it. For critical code (security, financial, medical), always have a human expert review the output thoroughly.