Prompt Engineering Mastery
The complete guide to writing effective prompts for LLMs — from basics to advanced agent patterns used in production AI systems.
Prompt Engineering Fundamentals
Prompt engineering is the art and science of crafting inputs that guide language models to produce desired outputs. It's the most important skill for working with AI.
What is Prompt Engineering?
Prompt engineering is the practice of designing inputs (prompts) for large language models (LLMs) to produce high-quality, relevant, and accurate outputs. Think of it as giving instructions to an incredibly capable but literal-minded assistant.
A well-crafted prompt can mean the difference between a vague, unhelpful response and a precise, actionable answer. As AI models become more powerful, the ability to communicate effectively with them becomes a critical skill.
The Anatomy of a Prompt
Every effective prompt contains some combination of these elements:
Background information the model needs. "You are a senior Python developer reviewing code for a production Django application."
The specific action you want. "Review this code and identify security vulnerabilities, performance issues, and bugs."
How you want the output structured. "Return a JSON array of findings, each with severity, title, description, and suggestion fields."
Rules and limits. "Only flag real issues, not style preferences. Be specific with line references. Keep each finding under 100 words."
Zero-Shot Prompting
The simplest form — give the model a task with no examples. Works well for straightforward tasks.
# ❌ Bad zero-shot
Summarize this article.
# ✅ Good zero-shot
Summarize this article in 3 bullet points, focusing on the key technical claims. Use plain language accessible to a non-technical audience. Each bullet should be one sentence.
Role Prompting
Assigning a role to the model activates domain-specific knowledge and adjusts the tone of responses.
# Without role
Explain how a database index works.
# With role
You are a senior database architect with 15 years of experience. Explain how database indexes work to a junior developer who understands basic SQL but not internals. Use a real-world analogy.
Core Techniques
Chain-of-Thought (CoT)
Ask the model to "think step by step" before giving an answer. This dramatically improves accuracy on complex reasoning tasks.
# Basic CoT
Analyze this code for bugs. Think step by step: 1) Identify the input/output, 2) Trace the logic flow, 3) Check edge cases, 4) Report findings.
# CoT with structured output
For each potential issue in this code, explain your reasoning chain: What you observed → What pattern it matches → Why it's problematic → What the fix should be.
Tree of Thought (ToT)
Explore multiple reasoning paths before committing to one. Great for design decisions and complex problem-solving.
Design a real-time chat system. Consider 3 different architectures: 1) WebSocket-based, 2) Server-Sent Events, 3) Long-polling. For each: list pros, cons, scalability limits, and complexity. Then recommend the best option for a 10K concurrent user app and explain why.
Self-Consistency
Generate multiple solutions and pick the most common answer. Use when accuracy matters more than speed.
Solve this problem 3 different ways, using different approaches each time. Then compare your 3 solutions, identify which is most correct/efficient, and explain why.
Output Formatting
Specifying the exact output format prevents ambiguity and makes responses programmatically usable.
# JSON output
Analyze this code. Return a JSON array where each object has: {"severity": "critical|warning|info", "title": "string", "line": number, "description": "string", "suggestion": "string"}
# Markdown table
Compare these 3 frameworks. Return a markdown table with columns: Feature, Framework A, Framework B, Framework C.
System Prompts
System prompts set the personality, knowledge boundaries, and behavioral rules for AI assistants. They're the most important part of production AI systems.
Anatomy of a Production System Prompt
A well-structured system prompt has these sections:
Identity & Role
Who the AI is, what it does, who it serves.
Knowledge Base
Facts, data, context the AI should reference.
Behavioral Rules
What to do, what not to do, tone guidelines.
Output Format
How to structure responses, length limits, formatting.
Guardrails
Safety rules, escalation paths, refusal conditions.
Real Example: Healthcare AI System Prompt
This is a production-grade system prompt used in healthcare AI systems like EvaluateMyMeds:
You are MedGuide AI, a healthcare assistant for EvaluateMyMeds. **Identity:** You help patients understand their medications, drug interactions, and health information. You are NOT a doctor and never replace professional medical advice. **Knowledge:** You have access to FDA drug databases, clinical guidelines, and peer-reviewed medical literature via RAG. **Rules:** - ALWAYS recommend consulting a healthcare provider for medical decisions - NEVER diagnose conditions or prescribe treatments - Flag dangerous drug interactions with URGENT warnings - Use plain language (8th grade reading level) - Cite sources when referencing medical studies **Output Format:** - Use markdown with clear headers - Bold critical safety information - Include a "When to See a Doctor" section - End with "This is not medical advice" disclaimer
Few-Shot Learning
Provide examples of input-output pairs to teach the model exactly what you want. This is the most reliable way to get consistent, predictable outputs.
Example: Code Review Classification
Classify code issues by severity.
**Example 1:**
Code: `eval(userInput)`
Classification: CRITICAL — Security vulnerability. Arbitrary code execution risk.
**Example 2:**
Code: `var x = 10;`
Classification: WARNING — Style issue. Use const/let instead of var.
**Example 3:**
Code: `console.log("debug")`
Classification: INFO — Best practice. Remove debug statements before deploying.
**Example 4:**
Code: `function add(a, b) { return a + b; }`
Classification: CLEAN — No issues found.
Now classify: `document.getElementById("app").innerHTML = userData;`
Few-Shot Tips
Use 3-5 examples — enough to establish the pattern without wasting tokens.
Cover edge cases — include examples that are borderline or unusual.
Match your use case — examples should closely resemble real inputs.
Consistent format — every example should follow the same structure.
Advanced Patterns
ReAct (Reason + Act)
The foundational pattern for agentic AI. The model alternates between thinking and taking actions.
You are a research agent. For each task:
1. THOUGHT: Analyze what's needed and plan your approach
2. ACTION: Choose a tool to use (search, calculate, read_file)
3. OBSERVATION: Review the result of your action
4. REPEAT until you have enough information
5. FINAL ANSWER: Provide your conclusion
Tools available:
- search(query): Search the web for information
- calculate(expression): Perform mathematical calculations
- read_file(path): Read contents of a file
Example:
THOUGHT: I need to find the latest Python version.
ACTION: search("latest Python version 2026")
OBSERVATION: Python 3.13.5 released June 2026
FINAL ANSWER: The latest Python version is 3.13.5.
Plan-and-Execute
Create a full plan first, then execute step by step. Better than ReAct for complex multi-step tasks.
You are a project planner. When given a goal: 1. ANALYZE the goal and break it into discrete steps 2. OUTPUT a numbered plan with dependencies 3. EXECUTE each step in order 4. VERIFY each step's output before proceeding 5. If a step fails, REVISE the plan and continue Output format: PLAN: 1. [Step description] (depends on: none) 2. [Step description] (depends on: step 1) ... EXECUTION: Step 1: [What you did] → [Result] ✓/✗ Step 2: [What you did] → [Result] ✓/✗ ...
Prompt Chaining
Break complex tasks into a pipeline of simpler prompts. Each step's output feeds into the next.
Extract
Pull key facts from source
Analyze
Apply reasoning to facts
Generate
Produce final output
Agent Prompt Patterns
Production-grade prompts for autonomous AI agents — the patterns behind systems like EvaluateMyMeds.
Tool-Using Agent Prompt
You are a coding assistant with access to these tools: - execute_code(code, language): Run code and return output - read_file(path): Read a file's contents - write_file(path, content): Write content to a file - search_docs(query): Search documentation When the user asks you to do something: 1. Think about which tools you need 2. Call tools one at a time, waiting for results 3. Never call a tool without a clear reason 4. If a tool call fails, try a different approach 5. Always explain what you're doing and why If you cannot complete the task with available tools, explain what's missing and suggest alternatives.
Multi-Agent Coordinator Prompt
You are the Orchestrator Agent managing a team of specialists: AVAILABLE AGENTS: - ResearchAgent: Finds information, reads documents - AnalysisAgent: Processes data, identifies patterns - CodeAgent: Writes and tests code - ReviewAgent: Validates quality, catches errors WORKFLOW: 1. Receive the user's request 2. Break it into subtasks 3. Assign each subtask to the best agent 4. Collect results from each agent 5. Synthesize a unified response 6. Run ReviewAgent to validate the final output RULES: - Never execute tasks yourself — delegate to specialists - If an agent's output is unclear, ask for clarification - Maintain a shared context document for all agents - Log all decisions for auditability
Self-Improving Agent Prompt
You are an agent that learns from its mistakes. After completing each task: 1. EVALUATE your output quality (1-10 scale) 2. IDENTIFY what could be improved 3. UPDATE your approach for similar future tasks 4. STORE lessons learned in your memory If your evaluation score is below 7: - Re-analyze what went wrong - Try a different approach - Re-attempt the task Maintain a running log of: - Tasks completed - Quality scores - Patterns in errors - Improvements made
RAG Prompts
Retrieval-Augmented Generation combines LLMs with external knowledge. The prompt must handle retrieved context effectively.
RAG System Prompt Template
You are a helpful assistant that answers questions using
the provided context documents.
INSTRUCTIONS:
1. ONLY use information from the provided context
2. If the context doesn't contain enough information,
say "I don't have enough information to answer this"
3. Always cite your sources using [Source: document_name]
4. If documents conflict, note the discrepancy
5. Never make up or assume information not in the context
CONTEXT DOCUMENTS:
{context}
USER QUESTION: {question}
ANSWER (cite sources):
RAG Best Practices
Chunk wisely — Split documents into 200-500 token chunks with overlap
Use hybrid search — Combine semantic + keyword search for better retrieval
Rerank results — Use a reranker to improve retrieval quality
Limit context — Only pass the top 5-10 most relevant chunks
Ground your answers — Always tie responses back to specific documents
Handle uncertainty — Train the model to say "I don't know" when context is insufficient
Copy-Paste Templates
Ready-to-use prompt templates for common tasks. Copy, customize, and deploy.
You are a senior code reviewer. Analyze the following {language} code:
**Review checklist:**
1. Security vulnerabilities (injection, XSS, auth bypass)
2. Bugs and logic errors
3. Performance issues (N+1 queries, memory leaks)
4. Code quality (naming, structure, DRY violations)
5. Edge cases and error handling
**Output format (JSON array):**
[{
"severity": "critical|warning|info|suggestion",
"category": "security|bug|performance|style",
"title": "Brief title",
"line": number_or_null,
"description": "What's wrong and why",
"suggestion": "How to fix it"
}]
If no issues found, return: [{"severity": "success", "title": "Clean!"}]
CODE:
```{language}
{code}
```
You are an SEO content writer for {brand_name}.
**Task:** Write a {word_count}-word blog post about "{topic}"
**SEO Requirements:**
- Primary keyword: "{primary_keyword}" (use 3-5 times)
- Secondary keywords: {secondary_keywords}
- Include H2 and H3 headings with keywords
- Meta description: 150-160 characters with primary keyword
- Include a FAQ section with schema-ready Q&A pairs
**Writing Style:**
- Tone: {tone} (professional/casual/technical)
- Audience: {audience}
- Include actionable tips and examples
- End with a clear CTA
**Output format:**
# Title (with primary keyword)
> Meta description (150-160 chars)
## H2 Heading
Content...
### H3 Heading
Content...
## FAQ
**Q: Question?**
A: Answer...
You are a data analyst. Analyze the following data and
provide insights.
**Steps:**
1. DESCRIBE: Summarize what the data contains
2. EXPLORE: Identify patterns, outliers, trends
3. ANALYZE: Calculate key metrics and statistics
4. INSIGHT: What does this data tell us?
5. RECOMMEND: What actions should we take?
**Output format:**
📊 Summary: [1-2 sentence overview]
📈 Key Metrics: [bullet points with numbers]
🔍 Patterns: [what you found]
⚡ Recommendations: [actionable next steps]
⚠️ Caveats: [limitations of the analysis]
DATA:
{data}
You are {company_name}'s AI support agent.
**Personality:** Friendly, helpful, concise. Use the customer's name.
**Rules:**
1. Greet the customer warmly
2. Understand their issue before responding
3. Provide clear, step-by-step solutions
4. If you can't help, escalate to a human agent
5. Always end with "Is there anything else I can help with?"
**Escalate to human when:**
- Customer is angry or frustrated
- Issue requires account-specific changes
- Billing dispute or refund request
- Technical issue you can't resolve in 2 attempts
**Knowledge base:** {context}
**Tone:** Professional but warm. Never robotic.
Prompt Anti-Patterns
Common mistakes that produce bad results — and how to fix them.
❌ Vague Prompts
"Write me a blog post" → The model has no direction. Instead: "Write a 1500-word technical blog post about Django performance optimization for intermediate Python developers. Include 5 actionable tips with code examples."
❌ Overloaded Prompts
"Write code, test it, deploy it, and write docs" → Too many tasks at once. Instead: chain prompts — one task per prompt, each building on the previous output.
❌ No Output Format
"Analyze this data" → You'll get unpredictable formatting. Instead: specify exactly what you want — JSON, markdown table, bullet points, etc.
❌ Ignoring Edge Cases
"Write a function to parse dates" → What about invalid dates, timezone handling, leap years? Always specify edge cases and error handling expectations.
❌ No Context Window Management
Pasting an entire codebase into a prompt wastes tokens and degrades quality. Instead: extract only the relevant sections and provide file paths as references.
Ready to Build AI Systems?
We apply these prompt engineering techniques to build production AI agents, RAG systems, and intelligent automation for businesses.
Ready to Build Something Great?
Let's discuss your project and turn your vision into reality. No commitment, just a conversation.
Get in TouchStay Updated
Get the latest tech insights, tools updates, and exclusive content delivered to your inbox.
✓ You're subscribed! Check your inbox.
Install Technlogics
Add to home screen for best experience
Technlogics AI
Online