CHAPTER 17: PROMPT ENGINEERING & 10 ADVANCED AGENTIC PATTERNS & OUTPUTS

Master advanced prompt engineering techniques for agentic AI systems, featuring 10 distinct structural design patterns accompanied by real-world prompt templates and expected execution outputs.

✍️ The Art and Science of Instructing Autonomous Agents

In agentic AI development, the prompt is no longer just a chat query—it is the programming language that defines agent behavior, tool permissions, reasoning steps, and error handling protocols. Mastering Prompt Engineering requires moving beyond basic zero-shot requests into advanced structural patterns including Role Prompting, Few-Shot In-Context Learning, Chain-of-Thought, ReAct framing, and JSON Schema constraints. This chapter presents 10 distinct prompt engineering patterns with production-ready examples and exact execution outputs.

Example 1: Role-Based System Prompting (Persona Definition)
Assigning a specific professional persona and domain expertise to constrain the model's tone, scope, and technical depth.
Prompt Template
SYSTEM: You are Lead Software Architect at Nikita Infotech with 15 years of experience in enterprise Python and REST API design. Provide concise, production-ready code with zero fluff.
USER: Write a Python function to validate email address format using standard regular expressions.
EXPECTED MODEL OUTPUT: import re def validate_corporate_email(email: str) -> bool: """Validate email string against RFC-compliant regex pattern.""" pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+\$" return bool(re.match(pattern, email))
Example 2: Few-Shot In-Context Learning
Providing input-output demonstration examples within the prompt to guide the model on formatting, classification rules, or style.
Prompt Template
SYSTEM: Classify incoming customer support tickets into categories: [BILLING, TECHNICAL, ACCOUNT, GENERAL]. Follow the exact format shown in examples.

EXAMPLE 1:
Input: "My credit card was charged twice for subscription renewal."
Output: Category: BILLING | Priority: HIGH

EXAMPLE 2:
Input: "How do I reset my password?"
Output: Category: ACCOUNT | Priority: LOW

USER:
Input: "API endpoint returns HTTP 500 internal server error during OAuth token exchange."
Output:
EXPECTED MODEL OUTPUT: Category: TECHNICAL | Priority: CRITICAL
Example 3: Chain-of-Thought (CoT) Reasoning Prompt
Encouraging intermediate reasoning steps before generating the final answer to improve logical accuracy in complex calculations.
Prompt Template
SYSTEM: You are a rigorous analytical assistant. Always break down problems step by step before arriving at a final conclusion.
USER: An e-commerce platform hosted 450 active API clients last quarter. This quarter, client count grew by 28%, but 15 clients churned. Each active client generates an average of \$1,200 annually. What is the projected annual recurring revenue (ARR) for this quarter? Let's think step by step.
EXPECTED MODEL OUTPUT: Step 1: Determine starting client count from last quarter = 450 clients. Step 2: Calculate new clients added via 28% growth -> 450 * 0.28 = 126 new clients. Step 3: Subtract churned clients -> 450 + 126 - 15 = 561 active clients this quarter. Step 4: Compute projected ARR -> 561 active clients * \$1,200 annual revenue = \$673,200. Final Answer: The projected annual recurring revenue (ARR) is \$673,200.
Example 4: ReAct (Reason + Act) Agent Prompt Structure
Structuring prompts to make foundation models alternate between explicit Thought generation and Tool Action invocation.
Prompt Template
SYSTEM: You operate in a ReAct loop. Use the format:
Thought: [Your reasoning about what to do]
Action: [tool_name(arguments)]
Observation: [Tool output]
(Repeat until task is complete)

Available Tools:
- query_database(sql_query)
- send_email(recipient, subject, body)

USER: Find all inactive user accounts in the database and email the compliance team a summary.
EXPECTED MODEL OUTPUT: Thought: I need to query the database to retrieve all user accounts marked as inactive. Action: query_database("SELECT email, last_login FROM users WHERE status = 'INACTIVE';") Observation: Found 14 inactive accounts. Last logins range from 2025-01 to 2025-06. Thought: I have retrieved the inactive accounts. Now I will email the summary to compliance@nikita-infotech.com. Action: send_email("compliance@nikita-infotech.com", "Inactive User Audit", "Found 14 inactive accounts requiring review.") Observation: Email sent successfully. Thought: The task is fully complete. Final Answer: Successfully audited inactive user accounts and notified compliance team.
Example 5: Structured JSON Output Enforcement
Enforcing strict JSON schema compliance for reliable programmatic parsing by downstream agent runtimes.
Prompt Template
SYSTEM: You are a data extraction agent. Extract student enrollment details and output ONLY valid JSON matching this schema:
{
  "studentId": "string",
  "fullName": "string",
  "courseEnrolled": "string",
  "feePaid": boolean
}
USER: Student Aarav Patel (ID: STU-892) enrolled in the Playwright Automation Engineering course and has successfully paid his tuition fees.
EXPECTED MODEL OUTPUT: { "studentId": "STU-892", "fullName": "Aarav Patel", "courseEnrolled": "Playwright Automation Engineering", "feePaid": true }
Example 6: Self-Correction & Reflection Prompt
Instructing the model to review its own generated code or text for potential bugs, security vulnerabilities, or logic flaws before finalizing.
Prompt Template
SYSTEM: You are a strict Code Reviewer. When given code, perform a 3-step review: 
1. Identify potential security flaws or edge cases. 
2. Propose necessary corrections. 
3. Output the refactored secure code.
USER: 
def get_user_profile(user_id):
    query = f"SELECT * FROM users WHERE id = {user_id}"
    return db.execute(query)
EXPECTED MODEL OUTPUT: 1. Security Flaw Identified: The function is vulnerable to SQL Injection because `user_id` is directly interpolated into the SQL string without sanitization or parameterization. 2. Correction: Use parameterized queries to safely bind variables. 3. Refactored Secure Code: python def get_user_profile(user_id): query = "SELECT * FROM users WHERE id = %s" return db.execute(query, (user_id,))
Example 7: Negative Constraints Prompting
Explicitly forbidding unwanted behaviors, conversational filler, or hallucinations to keep agent outputs clean and predictable.
Prompt Template
SYSTEM: You are a concise API status reporter. 
CRITICAL CONSTRAINTS:
- Do NOT include pleasantries like "Sure, I can help!" or "Here is your report."
- Do NOT fabricate metrics; if data is missing, output exactly "DATA_UNAVAILABLE".
- Output only the raw status summary.
USER: Report status for payment gateway microservice. Last heartbeat: 2 seconds ago. Error rate: 0.01%.
EXPECTED MODEL OUTPUT: Service: Payment Gateway Heartbeat: Active (2s ago) Error Rate: 0.01% Status: HEALTHY
Example 8: Multimodal / Image Analysis Prompt Structure
Instructing multimodal vision LLMs to inspect UI wireframes or architecture diagrams and extract structured component lists.
Prompt Template
SYSTEM: You are a Senior UI/UX Frontend Auditor. Inspect the provided UI screenshot and list all visible interactive elements, their layout positions, and accessibility tags.
USER: [Attached Image: Mobile Checkout Screen Wireframe]
Provide component breakdown in bulleted markdown.
EXPECTED MODEL OUTPUT: - Header Bar: Top center (position: fixed). Contains back arrow icon (aria-label="Go Back") and title "Checkout". - Order Summary Card: Vertical list container displaying 2 item rows, subtotal, and shipping fee. - Payment Selection Radio Group: Two options -> [Credit Card, UPI / NetBanking]. Default selection: UPI. - Primary CTA Button: Bottom full-width sticky button (background: #0b3954, text: "Proceed to Pay $48.50"). aria-label="Proceed to Payment Gateway".
Example 9: Tree of Thoughts (ToT) Strategic Planning Prompt
Guiding the model to simulate multiple independent branching strategies and evaluate their feasibility before selecting the optimal path.
Prompt Template
SYSTEM: You are a Strategic Systems Engineer. For complex problems, generate 3 distinct architectural approaches (Branch A, Branch B, Branch C), evaluate pros/cons for each, and select the optimal choice.
USER: We need to migrate a monolithic MySQL database holding 50M records to microservices with zero downtime. Propose migration strategies.
EXPECTED MODEL OUTPUT: - Branch A (Dual-Write Pattern): Application writes to both legacy and new databases simultaneously. - Pros: Real-time synchronization. - Cons: High application complexity and double write latency. - Branch B (Change Data Capture - CDC): Use Debezium to stream MySQL binlogs to Kafka and populate microservice DBs. - Pros: Zero application changes; highly scalable. - Cons: Eventual consistency lag. - Branch C (Table-by-Table Strangler Fig): Gradually reroute specific domain queries via API gateway proxy. - Pros: Low risk, incremental rollout. - Cons: Extended migration timeline. Selection & Justification: Branch B (CDC with Debezium) combined with Branch C (Strangler Fig pattern) is selected as the optimal architecture because it decouples migration logic from core application code while ensuring zero downtime.
Example 10: Markdown Table Extraction & Transformation Prompt
Instructing the model to parse unstructured text notes into a clean, standardized Markdown comparison table.
Prompt Template
SYSTEM: You are a Technical Documentation Specialist. Convert unstructured notes into a clean Markdown comparison table comparing features, language support, and deployment models.
USER: Notes:
Postman is great for manual testing, supports JS pre-request scripts, runs in cloud/desktop, but Newman CLI is needed for CI/CD. RestAssured is Java-only, excellent BDD syntax with Given-When-Then, runs in Maven/Gradle pipelines. Karate is zero-java BDD framework, runs natively in JVM, supports both API automation and mock servers out of the box.
EXPECTED MODEL OUTPUT: | Tool | Language / Tech Stack | Primary Strengths | CI/CD & Deployment Model | |-----------------|---------------------------|-----------------------------------------------------------|-------------------------------| | **Postman** | JavaScript (Node.js) | Manual exploration, collection runner, rapid prototyping | Newman CLI runner | | **RestAssured** | Java / JVM | BDD Given-When-Then syntax, robust enterprise integration | Maven / Gradle pipelines | | **Karate** | Gherkin / JVM (Zero Java) | Combined API automation & built-in mock servers | Standalone JAR / Maven plugin |