Skip to content
·11 min read

Advanced Prompt Patterns That Make AI Code Dramatically Better

Few-shot examples, chain-of-thought reasoning, and tree-of-thought exploration for complex coding tasks

Share

Advanced prompt patterns are the difference between AI that writes generic boilerplate and AI that solves genuinely hard problems. 92% of developers use AI tools daily, but most rely on basic "build me X" prompts. The builders getting dramatic results use structured reasoning techniques that guide AI through complex logic the way a senior engineer thinks through a problem.

This deep dive covers three advanced prompt patterns that change what AI can produce for you. Few-shot teaches AI your exact standards through examples. Chain-of-thought forces step-by-step reasoning. Tree-of-thought explores multiple solution paths before committing. Each pattern addresses a different failure mode, and combining them unlocks solutions that basic prompting cannot touch.

Few-Shot Prompting Gives AI Your Standards

Few-shot prompting means providing two or three examples of input and expected output before asking your actual question. Instead of describing what you want in abstract terms, you show the AI exactly what good looks like. The AI pattern-matches against your examples and produces output that follows the same structure, naming conventions, and logic patterns.

This matters because description is lossy. You can write three paragraphs explaining your API response format, or you can show two examples and the AI will extrapolate perfectly. Few-shot is especially powerful for repetitive tasks where consistency matters more than creativity.

Here is few-shot prompting applied to generating API endpoint handlers. You want every endpoint to follow the same pattern with validation, error handling, and response shape.

The few-shot prompt:

"I need you to generate API route handlers following this exact pattern. Here are two examples:

Example 1 - GET /api/users: Input: Fetch all users with optional role filter Output: Validate query params with Zod, query database with Prisma, return { data: users, count: number } on success, return { error: string, code: string } on failure, wrap in try-catch with 500 fallback.

Example 2 - POST /api/projects: Input: Create a new project with name and description Output: Validate request body with Zod schema, check user authentication from session, insert with Prisma, return { data: project } with 201 status, return { error: string, code: string } on validation failure with 400.

Now generate: DELETE /api/projects/[id] - Delete a project by ID, ensuring the requesting user owns the project."

The AI now generates a DELETE handler that follows your exact validation pattern, uses the same error response shape, includes ownership verification, and matches the try-catch structure from your examples. Without those examples, it would produce a working handler that does not match your conventions.

Few-shot works best when you need consistency across similar outputs. Database migrations, test files, component patterns, API handlers, and config files all benefit enormously. Two examples for simple patterns, three for complex ones. More than three rarely adds value.

Key Takeaway

Few-shot prompting eliminates the gap between what you describe and what you mean. Two concrete examples communicate your standards more precisely than any amount of written description. Use it whenever you need AI output to match existing codebase patterns exactly.

Chain-of-Thought Forces Real Reasoning

Chain-of-thought prompting adds a simple instruction that transforms how AI approaches complex problems. Instead of jumping straight to code, you ask the AI to "think step by step" or "reason through this before writing code." This forces the model to decompose the problem, consider edge cases, and build understanding before generating a solution.

Why does this matter for coding? Because most AI coding failures happen when the model jumps to implementation without understanding the full problem. It writes code that handles the happy path but misses the edge cases that cause production bugs. Chain-of-thought slows the AI down in exactly the right way.

Here is a real example. Say you need to implement a rate limiter for an API.

Without chain-of-thought: "Implement a rate limiter for my Express API that allows 100 requests per minute per user."

The AI jumps straight to code. It might use a simple in-memory counter, forget to handle distributed deployments, miss the sliding window vs fixed window distinction, or ignore what happens when the store goes down.

With chain-of-thought: "I need a rate limiter for my Express API that allows 100 requests per minute per user. Before writing any code, think step by step: What rate limiting algorithm is appropriate here? What storage backend makes sense for a multi-instance deployment? What edge cases need handling (clock skew, store failures, key expiration)? What should happen when a user hits the limit? Then implement your solution."

Now the AI reasons through the algorithm choice (sliding window log vs token bucket), considers Redis for multi-instance support, handles Redis being temporarily unavailable, adds proper 429 responses with Retry-After headers, and considers key expiration for cleanup. The code is production-ready because the AI was forced to think before it wrote.

EXPLAINER DIAGRAM: A comparison of two vertical flowcharts side by side. Left flowchart labeled BASIC PROMPT has two boxes connected by a single arrow: PROMPT at top, CODE OUTPUT at bottom. The arrow is labeled IMMEDIATE JUMP. Right flowchart labeled CHAIN-OF-THOUGHT has five boxes connected by arrows flowing downward: PROMPT, then DECOMPOSE PROBLEM, then IDENTIFY EDGE CASES, then CHOOSE APPROACH, then CODE OUTPUT. Each intermediate box has a small annotation. DECOMPOSE reads what are the subproblems. IDENTIFY reads what could go wrong. CHOOSE reads which algorithm fits best. A bracket on the right labels the three middle boxes as REASONING STEPS. Below both flowcharts a caption reads FORCING INTERMEDIATE REASONING STEPS PRODUCES MORE ROBUST CODE.
Chain-of-thought adds reasoning steps between your prompt and the code output. Each step catches problems that a direct jump would miss.

Chain-of-thought is most valuable for problems with multiple valid approaches, hidden edge cases, or architecture decisions. It is less useful for straightforward tasks like "create a button component" where there is not much to reason about.

Tree-of-Thought Explores Before It Commits

Tree-of-thought is the most powerful pattern here, and the least known. It asks the AI to consider multiple approaches, evaluate the tradeoffs of each, and then implement the best one. Where chain-of-thought is linear (think step by step), tree-of-thought is branching (consider three approaches, compare them, then choose).

This pattern shines when there is no obvious "right answer" and the best approach depends on tradeoffs specific to your situation. Architecture decisions, data modeling, performance optimization, and state management all benefit from tree-of-thought.

Here is the pattern in action. You need to implement real-time notifications in your application.

The tree-of-thought prompt: "I need to add real-time notifications to my Next.js application. Users should see new notifications without refreshing the page. Consider three different approaches for implementing this. For each approach, explain the architecture, list the pros and cons, estimate complexity, and identify what breaks at scale. After evaluating all three, recommend the best approach for a team of two shipping an MVP, then implement it."

The AI might explore: (1) Server-Sent Events with a simple event stream, (2) WebSockets via Socket.io for bidirectional communication, and (3) polling with React Query at a 5-second interval. For each, it walks through the architecture, tradeoffs, and failure modes. Then it recommends polling with React Query for the MVP because it requires no additional infrastructure, works with serverless deployment, and can be upgraded to SSE later without changing the client API.

The key difference from chain-of-thought is that tree-of-thought explicitly generates alternatives before choosing. This prevents the AI from anchoring on the first approach that comes to mind. Most AI coding failures are not logic errors but choosing the wrong approach entirely. Tree-of-thought addresses that directly.

Common Mistake

Asking the AI to "consider alternatives" without specifying how many or what to evaluate. The prompt "think about a few ways to do this" produces vague hand-waving. The prompt "consider exactly 3 approaches, evaluate complexity and scalability tradeoffs for each, then implement the best one for a two-person team" produces actionable analysis. Be specific about what you want the AI to evaluate.

When to Use Each Pattern

These three patterns are not interchangeable. Each one addresses a specific failure mode.

Use few-shot when consistency is critical. You know exactly what good output looks like and need the AI to replicate that pattern. Tests, migrations, boilerplate, and data transformations all benefit. The failure it fixes is "the AI produced something reasonable but it does not match our conventions."

Use chain-of-thought when the problem has edge cases the AI might skip. Authentication flows, payment processing, and concurrency handling all have hidden complexity that chain-of-thought surfaces. The failure it fixes is "the code works for the happy path but breaks in production."

Use tree-of-thought when there are multiple valid solutions and the right choice depends on context. Architecture decisions, technology selection, and state management all benefit from exploring alternatives. The failure it fixes is "the AI picked an approach that works but is wrong for our situation."

Combining Patterns for Maximum Impact

The real power comes from combining these patterns in a single prompt. Here is what that looks like for a complex task.

"I need to implement a file upload system for my Next.js app. Users upload images up to 10MB.

First, consider 3 approaches for handling the upload (tree-of-thought): direct to S3 with presigned URLs, through our API with streaming, or client-side compression then upload. Evaluate storage costs, complexity, and user experience for each. Choose the best for a small team deploying to Vercel.

Then think step by step through the implementation (chain-of-thought): What validation do we need? How do we handle partial uploads? What happens if the upload fails midway?

Follow this exact pattern for the API route (few-shot): Example: Our POST /api/projects handler validates with Zod, authenticates via getServerSession, returns { data } on success with 201, returns { error, code } on failure."

This prompt produces an implementation evaluated against alternatives, thought through for edge cases, and following your codebase conventions.

EXPLAINER DIAGRAM: A Venn diagram with three overlapping circles. Left circle is labeled FEW-SHOT and contains the text CONSISTENCY, with a subtitle Matches your patterns. Top right circle is labeled CHAIN-OF-THOUGHT and contains the text THOROUGHNESS, with a subtitle Catches edge cases. Bottom right circle is labeled TREE-OF-THOUGHT and contains the text ARCHITECTURE, with a subtitle Picks the right approach. Where all three circles overlap in the center is a star shape labeled PRODUCTION-QUALITY CODE. Where few-shot and chain-of-thought overlap: Consistent AND thorough. Where chain-of-thought and tree-of-thought overlap: Thorough AND well-architected. Where few-shot and tree-of-thought overlap: Consistent AND well-chosen. Below the diagram a caption reads EACH PATTERN COVERS A DIFFERENT DIMENSION OF CODE QUALITY.
Each pattern addresses a different failure mode. Combining them covers consistency, thoroughness, and architecture in a single prompt.
Ready to Try Advanced Patterns?

Start with the prompt fundamentals, then level up to these techniques.

Explore more

What This Means For You

Advanced prompt patterns are not academic concepts. They are practical tools that change the ceiling of what you can accomplish with AI coding.

  • If you are a senior developer using AI daily: These patterns match how you already think. You decompose, consider alternatives, and check edge cases naturally. Now you can encode that thinking directly into your prompts. Start with chain-of-thought on your next complex feature. The improvement will be immediate.
  • If you are building production applications: Tree-of-thought should become your default pattern for any architecture or infrastructure decision. Forcing the AI to evaluate three approaches before committing prevents the most expensive category of AI coding mistakes, choosing the wrong approach and building on it for weeks before realizing the tradeoffs.
  • If you want to move faster without sacrificing quality: Few-shot is your highest-leverage starting point. Create a small library of examples for your most common patterns (API routes, components, tests) and include two examples every time you generate something similar. Consistency compounds. Every file that matches your conventions is one less thing to review.
Build Better With AI

Advanced patterns are just the beginning. See what else top builders are doing.

Keep building
PJ
Pranay Joshi

20+ years building products at scale. VP of Product & Engineering, startup founder, and AI coach. Helping dreamers turn ideas into reality with vibe coding.

Written forDevelopers

The Tuesday Shipping Report

Every Tuesday, one focused email:

  • - The tool or technique that's actually working right now
  • - A real problem from the community (and how to solve it)
  • - What changed this week in the vibe coding landscape

Read by 1,000+ founders, developers, and creators building with AI. Free forever. No spam.