01. Prompt Foundations, Anatomy & Components

Sections 1-13: What is Prompt Engineering, Mental Model, 9 Prompt Anatomy Components, Roles, Tasks, Context, Delimiters, Constraints, Formats, Quality Criteria & Zero/Few-Shot.

1. What is Prompt Engineering?

🇬🇧 English Definition
Prompt engineering is the systematic practice of designing instructions, context, constraints, and formatting rules to guide an AI language model toward useful, relevant, accurate, and reproducible outputs.
🇮🇳 Hinglish Definition
AI ko exactly kya karna hai, kis context mein karna hai, kis format mein response chahiye aur kya avoid karna hai — ye clearly specify karne ki technique ko Prompt Engineering kehte hain.
// Basic vs Engineered Prompt Comparison // Vague Baseline: "Write something about Python." // Engineered Prompt: ROLE: Senior Technical Author TASK: Write a 3-paragraph introduction to Python for web developers. CONTEXT: Target audience is Java developers migrating to FastAPI. CONSTRAINTS: Focus on async/await performance, zero jargon, max 300 words. OUTPUT: Markdown with headers and bullet points.
🔍 Line-by-Line Prompt / Code Breakdown
  • ROLE: Defines expert perspective (Senior Technical Author).
  • TASK: Explicit action verb (Write 3-paragraph intro).
  • CONTEXT: Specific audience background (Java devs moving to FastAPI).
  • CONSTRAINTS: Measurable boundaries (word count, zero jargon, async focus).
🎯 Interview Focus & Questions

Q: Why is Prompt Engineering considered an essential software engineering discipline?
A: Because AI models are non-deterministic probabilistic interfaces. Prompt engineering provides the deterministic contracts, schemas, and guardrails needed for reliable software integration.

2. Why Prompt Engineering Matters

🇬🇧 English Definition
Engineering clear prompts reduces model ambiguity, minimizes hallucinations, lowers API token costs, improves response consistency, and enables automated output validation in software applications.
🇮🇳 Hinglish Definition
Accurate prompts AI ambiguity ko kam karte hain, retries & API costs save karte hain, and software pipelines ke liye predictable JSON/Markdown output deliver karte hain.
// Impact of Prompt Optimization on Token Usage & Accuracy def calculate_prompt_efficiency(vague_prompt_tokens, optimized_prompt_tokens): saving = vague_prompt_tokens - optimized_prompt_tokens return f"Saved {saving} tokens per call by removing fluff and specifying exact constraints." print(calculate_prompt_efficiency(1200, 350))
🔍 Line-by-Line Prompt / Code Breakdown
  • Token Efficiency: Short, highly specific prompts reduce prompt token overhead while ensuring complete task adherence.
🎯 Interview Focus & Questions

Q: Can a good prompt guarantee 100% factual accuracy from an LLM?
A: No. Prompts optimize model conditioning, but factual claims still require retrieval grounding (RAG), external tool verification, or human oversight.

3. AI Model Mental Model

🇬🇧 English Definition
An AI model operates as a probabilistic next-token predictor conditioned on input context. Missing requirements force the model to invent assumptions based on pretraining weights.
🇮🇳 Hinglish Definition
LLM ko probability engine samjho. Jab aap instructions mein gaps chhodte ho, to model un gaps ko apke bina bataye guess karta hai. Prompting ka goal implicit assumptions ko explicit requirements banana hai.
// Mental Model: Conditioned Token Probability P(Next Token | Prompt Context) import numpy as np def model_next_token_prediction(context_length, constraint_clarity_score): // Higher clarity reduces entropy/uncertainty in token sampling uncertainty = 1.0 - (constraint_clarity_score / 10.0) return f"Model Prediction Uncertainty: {uncertainty:.2f}" print(model_next_token_prediction(context_length=500, constraint_clarity_score=9))
🔍 Line-by-Line Prompt / Code Breakdown
  • constraint_clarity_score=9: High constraint specificity lowers generation entropy, forcing deterministic outputs.
🎯 Interview Focus & Questions

Q: What happens when prompt instructions contradict each other?
A: The model enters an ambiguous state where decoding weights split between contradictory goals, often resulting in erratic or partial compliance.

4. Prompt Anatomy

🇬🇧 English Definition
A complete prompt architecture contains up to 9 functional blocks: Role/Persona, Task Objective, Context, Delimited Inputs, Constraints, Output Format, Quality Criteria, Examples (Few-Shot), and Verification Instructions.
🇮🇳 Hinglish Definition
Production prompt ke 9 main components hote hain: Role, Task, Context, Inputs, Constraints, Output Format, Quality Criteria, Examples, aur Verification rules. Mandatory nahi ki har prompt mein saare 9 hon.
// 9-Part Complete Prompt Anatomy Structure PROMPT_ANATOMY = { "1. Role": "Senior Cloud Security Specialist", "2. Task": "Audit the provided AWS IAM Policy JSON", "3. Context": "Enterprise fintech backend with PCI-DSS compliance", "4. Input": "{POLICY_DATA}", "5. Constraints": "List only Critical and High severity risks", "6. Output Format": "JSON array with keys: risk_id, severity, remediation", "7. Quality Criteria": "Must follow principle of least privilege", "8. Examples": "[Few-shot JSON examples]", "9. Verification": "Double check all policy wildcards (*)" } print("Anatomy Components:", len(PROMPT_ANATOMY))
🔍 Line-by-Line Prompt / Code Breakdown
  • PROMPT_ANATOMY: Standard enterprise checklist for designing high-reliability production prompts.
🎯 Interview Focus & Questions

Q: Which two components of prompt anatomy are most critical for API integrations?
A: Delimited Inputs (to prevent prompt injection) and explicit Output Format (to guarantee schema parsing).

5. Role / Persona

🇬🇧 English Definition
Assigning a Role or Persona conditions the model's latent feature space toward specific domain vocabulary, technical depth, perspective, and communication style.
🇮🇳 Hinglish Definition
Role dene se model us specific field ke domain language, technical terminology, and problem-solving perspective ko activate kar leta hai (e.g. 'Act as a Senior Database Administrator').
// Role Activation Prompt Examples role_prompt_1 = "Act as a Lead Python Developer reviewing code for memory leaks." role_prompt_2 = "Act as a Patient High School Math Tutor explaining calculus." print("Role 1:", role_prompt_1) print("Role 2:", role_prompt_2)
🔍 Line-by-Line Prompt / Code Breakdown
  • Act as...: Activates specialized domain style, tone, and technical rigor in the model's response.
🎯 Interview Focus & Questions

Q: Does assigning a Role make the model immune to factual errors?
A: No. A role changes perspective and style, but it does not magically turn the model into a real-time factual authority without retrieval context.

6. Task Definition

🇬🇧 English Definition
Task definition states the target action using precise imperative action verbs (analyze, classify, extract, debug, summarize, synthesize, critique) while eliminating vague language.
🇮🇳 Hinglish Definition
Task clear action verb se start hona chahiye (e.g. 'Extract all dates', 'Debug memory leak'). Vague words jaise 'make it better' avoid karo.
// Vague vs Precise Task Verbs vague_task = "Look at this article and do something good." precise_task = "Summarize the key 3 arguments of the article into a bulleted list of under 150 words." print("Precise Task Action:", precise_task)
🔍 Line-by-Line Prompt / Code Breakdown
  • precise_task: Combines strong verb ('Summarize') with quantitative scope ('3 arguments', 'under 150 words').
🎯 Interview Focus & Questions

Q: Why should you avoid open-ended requests like 'improve this code' in production?
A: Because 'improve' is subjective. The model might refactor working code, change formatting, or introduce unwanted dependencies without clear success criteria.

7. Context

🇬🇧 English Definition
Context provides essential background information (target audience, environment constraints, business goals, assumptions) that directly alters how the model should fulfill the task.
🇮🇳 Hinglish Definition
Context wo necessary background knowledge hai jo answer ka style ya direction badal sakti hai (e.g. target audience, OS version, business constraints).
// Context Inclusion Pattern context_block = """Target Audience: Executive Leadership Team (C-Suite). Business Goal: Decide whether to migrate from monolith to microservices. Tech Environment: Legacy Django 3.2 monolith handling 50k RPM. Key Constraint: Zero downtime migration required.""" print("Context Block Loaded.")
🔍 Line-by-Line Prompt / Code Breakdown
  • context_block: Supplies business goals and environment state to steer executive recommendations.
🎯 Interview Focus & Questions

Q: How much context is too much context?
A: Irrelevant context dilutes model attention (Lost in the Middle phenomenon) and increases token costs. Provide only context that actively changes the final output.

8. Input Delimiters

🇬🇧 English Definition
Input delimiters (XML tags like ``, triple backticks ```` `, markdown headers) cleanly isolate instructions from external, untrusted user data.
🇮🇳 Hinglish Definition
Delimiters (XML tags ya triple backticks) instruction ko user data se alag rakhte hain. Isse model confusion aur prompt injection attacks prevent hote hain.
// Delimited Prompt Construction def build_delimited_prompt(system_rule, user_text): prompt = f"""{system_rule} Process ONLY the text inside the tags: {user_text} """ return prompt print(build_delimited_prompt("Summarize document", "User document contents..."))
🔍 Line-by-Line Prompt / Code Breakdown
  • : XML tags explicitly bounding untrusted user data to prevent instruction blending.
🎯 Interview Focus & Questions

Q: Why are XML tags preferred over quotes or backticks for complex data delimiters?
A: XML tags can be nested cleanly (`

...
`) and are explicitly recognized by modern models like Anthropic Claude and OpenAI GPT-4.

9. Constraints

🇬🇧 English Definition
Constraints set negative boundaries, length limits, forbidden terms, required sources, and strict operational rules to prevent unwanted outputs.
🇮🇳 Hinglish Definition
Constraints wo rules hote hain jo model ko restrictive boundary mein rakhte hain (e.g. 'Do not mention competitors', 'Max 200 words', 'Use only provided facts').
// Explicit Constraints Array constraints = [ "1. Do not use external knowledge outside provided context.", "2. If context is missing information, output 'INSUFFICIENT_DATA'.", "3. Do not include markdown code block backticks in response.", "4. Maximum output length is 3 sentences." ] print("Constraints Applied:\n" + "\n".join(constraints))
🔍 Line-by-Line Prompt / Code Breakdown
  • Constraints: Explicit negative rules ('Do not', 'Must not') preventing assumption making and controlling response formatting.
🎯 Interview Focus & Questions

Q: How do you enforce negative constraints effectively?
A: State negative constraints clearly ('Do not use X'), explain the positive fallback behavior ('If X occurs, output Y'), and include a few-shot example demonstrating constraint compliance.

10. Output Format

🇬🇧 English Definition
Output Format explicitly defines the structural layout of the response, such as bullet lists, Markdown tables, raw JSON schemas, SQL queries, or HTML widgets.
🇮🇳 Hinglish Definition
Output Format specify karta hai ki answer kis layout mein chahiye: JSON, Markdown table, Bullet points, ya Raw SQL. Isse backend code easily response parse kar pata hai.
// Output Format Specification Template output_format_spec = """Respond ONLY with a valid JSON object following this exact schema: { "summary": "string", "risk_level": "LOW | MEDIUM | HIGH", "action_items": ["string"] } Do not include any conversational intro or outro text.""" print(output_format_spec)
🔍 Line-by-Line Prompt / Code Breakdown
  • output_format_spec: Defines explicit JSON key names, allowed enum values, and bans extra conversational text.
🎯 Interview Focus & Questions

Q: What is the risk of not specifying output formatting rules in API-driven applications?
A: The model may include conversational preambles (e.g. 'Here is your JSON:') that break automated string/JSON deserialization pipelines.

11. Quality Criteria

🇬🇧 English Definition
Quality criteria tell the model what defines a successful output: accuracy, conciseness, production readiness, edge-case handling, or educational clarity.
🇮🇳 Hinglish Definition
Quality Criteria model ko batati hain ki 'Achha answer' kis chiz ko samjha jayega: production-ready code, edge-case handled, beginner-friendly, or evidence-backed.
// Quality Criteria Specification quality_criteria = """QUALITY STANDARDS: - Code must be production-safe with explicit exception handling. - All SQL queries must be optimized for PostgreSQL 15 indexes. - Explanations must be clear to a junior developer.""" print(quality_criteria)
🔍 Line-by-Line Prompt / Code Breakdown
  • QUALITY STANDARDS: Outlines qualitative evaluation benchmarks the model must satisfy before completing response.
🎯 Interview Focus & Questions

Q: How do Quality Criteria improve code generation?
A: Prompts requesting 'production-safe code with exception handling and edge-case checks' trigger models to output robust boilerplate that simple prompts omit.

12. Examples / Few-Shot Prompting

🇬🇧 English Definition
Few-Shot prompting supplies 1 to 5 representative input-output pairs inside the prompt, teaching the model complex formatting rules, tone, or classification logic by example.
🇮🇳 Hinglish Definition
Few-Shot Prompting mein 2-3 input-output examples include kiye jaate hain. Jab rules words mein samjhana mushkil ho, to examples se model pattern turant pick kar leta hai.
// Few-Shot Prompt Example few_shot_prompt = """Classify log messages into severity levels. Input: "Database connection timed out after 3000ms" Output: CRITICAL Input: "User logged out successfully" Output: INFO Input: "Cache hit ratio dropped below 75%" Output: WARNING Input: "Disk storage space at 98%" Output:""" print(few_shot_prompt)
🔍 Line-by-Line Prompt / Code Breakdown
  • few_shot_prompt: Uses 3 clear input-output pairs to anchor severity classification for unseen log lines.
🎯 Interview Focus & Questions

Q: How many examples should be included in a few-shot prompt?
A: Typically 2 to 5 representative examples. Adding too many examples consumes context window space and can introduce unwanted pattern biases.

13. Zero-Shot Prompting

🇬🇧 English Definition
Zero-shot prompting asks the model to perform a task directly without providing prior training examples, relying entirely on the model's pre-trained knowledge and clear instructions.
🇮🇳 Hinglish Definition
Zero-Shot Prompting mein bina kisi example ke direct task Poocha jata hai. Standard tasks (summarization, translation, direct coding) ke liye ye zero extra token waste kiye best work karta hai.
// Zero-Shot Prompt Example zero_shot_prompt = "Translate the following English technical paragraph to Hindi: 'Cloud computing provides on-demand data storage and processing power.'" print(zero_shot_prompt)
🔍 Line-by-Line Prompt / Code Breakdown
  • zero_shot_prompt: Direct instruction and input without example pairs.
🎯 Interview Focus & Questions

Q: When should you upgrade from Zero-Shot to Few-Shot prompting?
A: Upgrade when Zero-Shot fails to consistently produce the exact desired formatting, classification boundaries, or specialized domain tone.