Spaces:
Running
Running
| <html lang="en"> | |
| <head> | |
| <!-- | |
| ______ __ | |
| / ____/___ ____ ___ ____ __ __/ /____ _____ | |
| / / / __ \/ __ `__ \/ __ \/ / / / __/ _ \/ ___/ | |
| / /___/ /_/ / / / / / / /_/ / /_/ / /_/ __/ / | |
| \____/\____/_/ /_/ /_/ .___/\__,_/\__/\___/_/ | |
| /_/ | |
| Created with Perplexity Computer | |
| https://www.perplexity.ai/computer | |
| --> | |
| <meta name="generator" content="Perplexity Computer"> | |
| <meta name="author" content="Perplexity Computer"> | |
| <meta property="og:see_also" content="https://www.perplexity.ai/computer"> | |
| <link rel="author" href="https://www.perplexity.ai/computer"> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Ch 6: Precognition (Thinking Step by Step) — Claude Prompt Engineering</title> | |
| <meta name="description" content="Master Chain-of-Thought prompting: zero-shot CoT, explicit reasoning, the thinking tag pattern, self-consistency, and extended thinking mode in Claude 3.7+."> | |
| <link href="https://api.fontshare.com/v2/css?f[]=cabinet-grotesk@400,500,600,700,800&f[]=satoshi@300,400,500,700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="../css/style.css"> | |
| <script src="../js/main.js" defer></script> | |
| </head> | |
| <body> | |
| <nav class="navbar"> | |
| <div class="navbar__inner"> | |
| <a href="../index.html" class="navbar__logo"> | |
| <svg width="28" height="28" viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="currentColor" opacity="0.1"/><path d="M8 24 L16 8 L24 24" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M10.5 19 L21.5 19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="8" r="2" fill="var(--color-primary)"/></svg> | |
| <span class="navbar__logo-text">Claude <span>PE</span></span> | |
| </a> | |
| <div class="navbar__nav"> | |
| <a href="../index.html" class="navbar__link">Home</a> | |
| <a href="../index.html#curriculum" class="navbar__link active">Lessons</a> | |
| <a href="../playground.html" class="navbar__link">Playground</a> | |
| </div> | |
| <div class="navbar__actions"> | |
| <button class="theme-toggle" data-theme-toggle aria-label="Toggle theme"> | |
| <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg> | |
| </button> | |
| <button class="hamburger" aria-label="Open menu"><span></span><span></span><span></span></button> | |
| </div> | |
| </div> | |
| <div class="mobile-menu"> | |
| <a href="../index.html">Home</a> | |
| <a href="../index.html#curriculum">All Lessons</a> | |
| <a href="../playground.html">Playground</a> | |
| </div> | |
| </nav> | |
| <div class="lesson-layout" style="padding-block: var(--space-8);"> | |
| <!-- SIDEBAR --> | |
| <aside class="lesson-sidebar"> | |
| <div class="sidebar__title">Course Contents</div> | |
| <ul class="sidebar__list" role="list"> | |
| <li class="sidebar__item"><a href="ch01-basic-structure.html"><span class="num">01</span> Basic Prompt Structure</a></li> | |
| <li class="sidebar__item"><a href="ch02-clear-direct.html"><span class="num">02</span> Clear and Direct</a></li> | |
| <li class="sidebar__item"><a href="ch03-assigning-roles.html"><span class="num">03</span> Assigning Roles</a></li> | |
| <li class="sidebar__item"><a href="ch04-separating-data.html"><span class="num">04</span> Separating Data</a></li> | |
| <li class="sidebar__item"><a href="ch05-formatting-output.html"><span class="num">05</span> Formatting Output</a></li> | |
| <li class="sidebar__item active"><a href="ch06-precognition.html"><span class="num">06</span> Precognition / CoT</a></li> | |
| <li class="sidebar__item"><a href="ch07-using-examples.html"><span class="num">07</span> Using Examples</a></li> | |
| <li class="sidebar__item"><a href="ch08-avoiding-hallucinations.html"><span class="num">08</span> Avoiding Hallucinations</a></li> | |
| <li class="sidebar__item"><a href="ch09-complex-prompts.html"><span class="num">09</span> Complex Prompts</a></li> | |
| <li class="sidebar__item"><a href="app01-chaining-prompts.html"><span class="num">A</span> Chaining Prompts</a></li> | |
| <li class="sidebar__item"><a href="app02-tool-use.html"><span class="num">B</span> Tool Use</a></li> | |
| </ul> | |
| </aside> | |
| <!-- MAIN CONTENT --> | |
| <article class="lesson-content"> | |
| <div class="progress-bar"><div class="progress-bar__fill" style="width: 54%"></div></div> | |
| <header class="lesson-header"> | |
| <nav class="lesson-breadcrumb" aria-label="Breadcrumb"> | |
| <a href="../index.html">Home</a> <span>/</span> | |
| <a href="../index.html#curriculum">Lessons</a> <span>/</span> | |
| <span>Chapter 6</span> | |
| </nav> | |
| <div class="lesson-header__badge"> | |
| <span class="lesson-card__badge badge--intermediate">Intermediate</span> | |
| </div> | |
| <h1 class="lesson-title">Precognition: Thinking Step by Step</h1> | |
| <p class="lesson-subtitle">Asking Claude to reason before answering is one of the most reliable ways to improve accuracy on complex tasks. Learn Chain-of-Thought prompting, the <thinking> tag pattern, and extended thinking mode.</p> | |
| <div class="lesson-meta"> | |
| <span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> 16 min read</span> | |
| <span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/></svg> 8 examples</span> | |
| <span>Chapter 6 of 11</span> | |
| </div> | |
| </header> | |
| <div class="lesson-body"> | |
| <h2>What Chain-of-Thought Prompting Is</h2> | |
| <p>Chain-of-Thought (CoT) prompting is the practice of instructing Claude to work through its reasoning explicitly before delivering a final answer. Instead of jumping to a conclusion, Claude narrates its thought process — each step informing the next — like showing its work on a math exam.</p> | |
| <p>The term "precognition" captures the intuition: <em>think before you speak</em>. By generating intermediate reasoning steps, Claude dramatically reduces errors on tasks that require multi-step logic, mathematical calculation, nuanced analysis, or careful inference.</p> | |
| <div class="callout callout--note"> | |
| <div class="callout__icon">💡</div> | |
| <div> | |
| <div class="callout__title">Why It Works</div> | |
| <div class="callout__body">Language models generate text sequentially, token by token. Without CoT, Claude must "jump" to a conclusion in one pass. With CoT, each intermediate reasoning step becomes context for the next step — allowing Claude to build up to complex answers incrementally rather than guessing them directly.</div> | |
| </div> | |
| </div> | |
| <h2>Zero-Shot CoT: The Simplest Trigger</h2> | |
| <p>The most basic CoT technique requires no examples — just a simple instruction appended to your prompt:</p> | |
| <div class="technique-grid"> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">🧠</div> | |
| <div class="technique-card__title">"Think step by step"</div> | |
| <div class="technique-card__desc">The classic zero-shot CoT trigger. Reliable for math, logic, and analysis tasks. Append to any prompt that requires multi-step reasoning.</div> | |
| </div> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">🔍</div> | |
| <div class="technique-card__title">"Before answering, reason through..."</div> | |
| <div class="technique-card__desc">More directive — specifies when to reason and implies what to reason about. Better for tasks where you want to constrain the reasoning to specific considerations.</div> | |
| </div> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">📝</div> | |
| <div class="technique-card__title">"Work through this carefully"</div> | |
| <div class="technique-card__desc">A softer trigger that still activates deliberate processing. Useful for judgment calls and analysis where "step by step" sounds too mechanical.</div> | |
| </div> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">✅</div> | |
| <div class="technique-card__title">"Show your reasoning, then answer"</div> | |
| <div class="technique-card__desc">Explicitly separates the reasoning process from the final answer, making it easy to validate the reasoning chain independently.</div> | |
| </div> | |
| </div> | |
| <h2>The <thinking> Tag Pattern</h2> | |
| <p>For applications where you want Claude's reasoning to be <em>separable</em> from its answer — so you can display or hide it, log it, or evaluate it independently — use the <code><thinking></code> tag pattern:</p> | |
| <div class="code-block"> | |
| <div class="code-block__header"> | |
| <span class="code-block__label">Thinking Tag Pattern</span> | |
| <button class="code-block__copy">Copy</button> | |
| </div> | |
| <pre><code>Analyze the following business scenario and recommend a course of action. | |
| First, use <thinking> tags to work through the problem: | |
| - What are the key factors at play? | |
| - What are the trade-offs of each option? | |
| - What assumptions am I making? | |
| After your thinking, provide your recommendation in plain prose. | |
| <scenario> | |
| A Series B SaaS startup (ARR: $8M, burn rate: $600K/month, runway: 14 months) | |
| has two offers: (1) strategic acquisition at 4x ARR from a larger competitor, | |
| or (2) a new funding round at a 20% down round valuation. The founding team | |
| wants to remain independent. Three key engineers have competing offers. | |
| </scenario></code></pre> | |
| </div> | |
| <p>Claude responds with explicit <code><thinking></code> XML wrapped around its reasoning, followed by the clean recommendation. Your code can then parse and separate the two sections.</p> | |
| <div class="code-block"> | |
| <div class="code-block__header"> | |
| <span class="code-block__label">Parsing Thinking Tags (Python)</span> | |
| <button class="code-block__copy">Copy</button> | |
| </div> | |
| <pre><code>import re | |
| def parse_cot_response(response_text: str) -> dict: | |
| """Separate thinking from final answer.""" | |
| thinking_match = re.search( | |
| r'<thinking>(.*?)</thinking>', | |
| response_text, | |
| re.DOTALL | |
| ) | |
| thinking = thinking_match.group(1).strip() if thinking_match else "" | |
| answer = re.sub(r'<thinking>.*?</thinking>', '', response_text, flags=re.DOTALL).strip() | |
| return {"reasoning": thinking, "answer": answer}</code></pre> | |
| </div> | |
| <h2>Before / After: Direct vs. CoT — Math Word Problem</h2> | |
| <div class="prompt-example"> | |
| <div class="prompt-example__tabs"> | |
| <button class="prompt-example__tab active" data-panel="ex6a-weak">❌ Direct Answer</button> | |
| <button class="prompt-example__tab" data-panel="ex6a-strong">✅ With CoT</button> | |
| <button class="prompt-example__tab" data-panel="ex6a-output">📄 Output</button> | |
| </div> | |
| <div class="prompt-panel active" id="ex6a-weak"><span class="tag-content">A train leaves Chicago at 2:30 PM traveling at 65 mph toward New York. A second train leaves New York at 4:00 PM traveling at 80 mph toward Chicago. The distance between cities is 790 miles. At what time do the trains meet?</span></div> | |
| <div class="prompt-panel" id="ex6a-strong"><span class="tag-content">Solve this problem step by step. Show each calculation clearly. At the end, state the answer as a specific time. | |
| A train leaves Chicago at 2:30 PM traveling at 65 mph toward New York. A second train leaves New York at 4:00 PM traveling at 80 mph toward Chicago. The distance between cities is 790 miles. At what time do the trains meet?</span></div> | |
| <div class="prompt-panel" id="ex6a-output"><span class="tag-content">Step 1 — Head start distance. | |
| Train A departs 1.5 hours before Train B. | |
| Distance covered by Train A before Train B departs = 65 × 1.5 = 97.5 miles. | |
| Step 2 — Remaining distance when Train B departs. | |
| 790 - 97.5 = 692.5 miles remaining between the two trains at 4:00 PM. | |
| Step 3 — Combined closing speed. | |
| 65 mph + 80 mph = 145 mph (trains are moving toward each other). | |
| Step 4 — Time to close the gap. | |
| 692.5 ÷ 145 = 4.776... hours ≈ 4 hours 46.6 minutes | |
| Step 5 — Meeting time. | |
| 4:00 PM + 4h 47m = 8:47 PM | |
| The trains meet at approximately 8:47 PM.</span></div> | |
| </div> | |
| <h2>CoT for Financial Analysis</h2> | |
| <div class="code-block"> | |
| <div class="code-block__header"> | |
| <span class="code-block__label">Financial Analysis with Structured Reasoning</span> | |
| <button class="code-block__copy">Copy</button> | |
| </div> | |
| <pre><code>You are a financial analyst. Evaluate whether this company is worth | |
| acquiring at the proposed valuation. | |
| Before reaching your conclusion: | |
| 1. Calculate the key valuation multiples (EV/Revenue, EV/EBITDA) | |
| 2. Compare them to industry benchmarks (note your benchmarks) | |
| 3. Assess the qualitative risks | |
| 4. Weigh the strategic value | |
| Then provide a final recommendation: Proceed / Negotiate / Pass. | |
| <company_data> | |
| Revenue: $12M ARR (35% YoY growth) | |
| EBITDA: -$2M (investing in growth) | |
| Proposed acquisition price: $60M | |
| Industry: B2B HR tech SaaS | |
| Comparable transactions: typically 5-8x ARR for this growth rate | |
| Strategic fit: fills gap in enterprise product suite | |
| Key risk: 2 of 4 engineers are contractors | |
| </company_data></code></pre> | |
| </div> | |
| <h2>Self-Consistency: Asking Claude to Verify Its Own Answer</h2> | |
| <p>Self-consistency is a technique where you ask Claude to check its own work — either by re-solving the problem from scratch, or by explicitly asking it to verify each step of its reasoning:</p> | |
| <div class="code-block"> | |
| <div class="code-block__header"> | |
| <span class="code-block__label">Self-Consistency Verification Pattern</span> | |
| <button class="code-block__copy">Copy</button> | |
| </div> | |
| <pre><code># Pattern 1: Solve then verify | |
| Solve this logic puzzle step by step. | |
| After reaching your answer, verify it by checking if it satisfies | |
| all the stated constraints. If it doesn't, revise your solution. | |
| # Pattern 2: Independent re-solve | |
| First, solve this problem using approach A. | |
| Then, solve the same problem using a completely different approach. | |
| If both approaches agree, report that answer. If they disagree, | |
| identify which approach has an error and correct it. | |
| # Pattern 3: Confidence-gated verification | |
| Solve this problem step by step. | |
| Rate your confidence in the answer from 1-10. | |
| If confidence is below 8, re-examine your reasoning and identify | |
| the weakest step.</code></pre> | |
| </div> | |
| <h2>Extended Thinking Mode (Claude 3.7+)</h2> | |
| <p>Claude 3.7 Sonnet and later models support <strong>extended thinking</strong> — a native API-level feature where Claude generates an internal reasoning trace before producing its response. This is more powerful than prompt-level CoT because the thinking happens in a dedicated scratchpad that isn't constrained by the response format.</p> | |
| <div class="code-block"> | |
| <div class="code-block__header"> | |
| <span class="code-block__label">Extended Thinking API (Python)</span> | |
| <button class="code-block__copy">Copy</button> | |
| </div> | |
| <pre><code">import anthropic | |
| client = anthropic.Anthropic() | |
| response = client.messages.create( | |
| model="claude-3-7-sonnet-20250219", | |
| max_tokens=16000, | |
| thinking={ | |
| "type": "enabled", | |
| "budget_tokens": 10000 # tokens allocated for internal reasoning | |
| }, | |
| messages=[{ | |
| "role": "user", | |
| "content": "Design the optimal database schema for a multi-tenant SaaS application that needs row-level security, audit logging, and soft deletes. Consider performance implications." | |
| }] | |
| ) | |
| # Response contains two content blocks: | |
| for block in response.content: | |
| if block.type == "thinking": | |
| print("Internal reasoning:", block.thinking) | |
| elif block.type == "text": | |
| print("Final answer:", block.text)</code></pre> | |
| </div> | |
| <h2>When NOT to Use CoT</h2> | |
| <p>CoT increases token usage and latency. It's valuable for complex reasoning but wasteful for:</p> | |
| <div class="technique-grid"> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">❌</div> | |
| <div class="technique-card__title">Skip CoT for:</div> | |
| <div class="technique-card__desc">Simple factual lookups ("What is the capital of France?"), direct translations, basic text transformations, classification with obvious categories, and creative tasks where reasoning scaffolding constrains rather than helps.</div> | |
| </div> | |
| <div class="technique-card"> | |
| <div class="technique-card__icon">✅</div> | |
| <div class="technique-card__title">Use CoT for:</div> | |
| <div class="technique-card__desc">Math problems, logic puzzles, multi-step analysis, legal or medical reasoning, debugging (reason through the failure mode), financial modeling, decision-making with multiple trade-offs, and any task where the answer could be "gotcha'd" by a subtlety.</div> | |
| </div> | |
| </div> | |
| <div class="callout callout--tip"> | |
| <div class="callout__icon">✅</div> | |
| <div> | |
| <div class="callout__title">Chapter 6 Takeaway</div> | |
| <div class="callout__body">Asking Claude to reason before answering is one of the highest-ROI prompt techniques for accuracy on complex tasks. Use zero-shot "think step by step" for quick wins, the <thinking> tag pattern for separable reasoning in applications, and extended thinking API mode for maximum reasoning depth on hard problems. Reserve CoT for tasks where the reasoning path matters — it's overkill for simple lookups.</div> | |
| </div> | |
| </div> | |
| </div><!-- /lesson-body --> | |
| <!-- LESSON NAV --> | |
| <nav class="lesson-nav" aria-label="Lesson navigation"> | |
| <a href="ch05-formatting-output.html" class="lesson-nav__btn"> | |
| <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg> | |
| <div> | |
| <div class="lesson-nav__label">Previous lesson</div> | |
| <div class="lesson-nav__title">Formatting Output & Speaking for Claude</div> | |
| </div> | |
| </a> | |
| <a href="ch07-using-examples.html" class="lesson-nav__btn" style="text-align:right;"> | |
| <div> | |
| <div class="lesson-nav__label">Next lesson</div> | |
| <div class="lesson-nav__title">Using Examples (Few-Shot)</div> | |
| </div> | |
| <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg> | |
| </a> | |
| </nav> | |
| </article> | |
| </div> | |
| <footer class="footer"> | |
| <div class="container"> | |
| <div class="footer__inner"> | |
| <div class="footer__brand"> | |
| <svg width="20" height="20" viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="currentColor" opacity="0.1"/><path d="M8 24 L16 8 L24 24" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M10.5 19 L21.5 19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg> | |
| Claude Prompt Engineering Course | |
| </div> | |
| <div class="footer__links"> | |
| <a href="../index.html">Home</a> | |
| <a href="../playground.html">Playground</a> | |
| <a href="https://docs.anthropic.com" target="_blank" rel="noopener">Anthropic Docs</a> | |
| </div> | |
| </div> | |
| <div class="footer__credit"><a href="https://www.perplexity.ai/computer" target="_blank" rel="noopener noreferrer">Created with Perplexity Computer</a></div> | |
| </div> | |
| </footer> | |
| <script data-pplx-inline-edit> | |
| (function(){ | |
| if(window===window.top)return; | |
| function inlineAll(orig,clone){ | |
| if(orig.nodeType!==1)return; | |
| try{ | |
| var cs=getComputedStyle(orig); | |
| var t=''; | |
| for(var i=0;i<cs.length;i++){t+=cs[i]+':'+cs.getPropertyValue(cs[i])+';';} | |
| clone.style.cssText=t; | |
| }catch(e){} | |
| var oc=orig.children,cc=clone.children; | |
| for(var j=0;j<oc.length&&j<cc.length;j++){inlineAll(oc[j],cc[j]);} | |
| } | |
| function stripExternal(clone){ | |
| var imgs=clone.querySelectorAll('img'); | |
| for(var i=0;i<imgs.length;i++){ | |
| var s=imgs[i].getAttribute('src'); | |
| if(s&&!s.startsWith('data:'))imgs[i].removeAttribute('src'); | |
| } | |
| var all=clone.querySelectorAll('*'); | |
| for(var i=0;i<all.length;i++){ | |
| var st=all[i].style.cssText; | |
| if(st&&st.indexOf('url(')>=0){ | |
| all[i].style.cssText=st.replace(/url\(["']?(?!data:)[^)"']*["']?\)/gi,'none'); | |
| } | |
| } | |
| } | |
| window.addEventListener('message',function(e){ | |
| if(!e.data||e.data.type!=='INLINE_EDIT_CAPTURE_REQUEST')return; | |
| var scrollX=window.scrollX||window.pageXOffset||0; | |
| var scrollY=window.scrollY||window.pageYOffset||0; | |
| var w=window.innerWidth,h=window.innerHeight; | |
| try{ | |
| var clone=document.documentElement.cloneNode(true); | |
| var rm=clone.querySelectorAll('script,link[rel="stylesheet"],style'); | |
| for(var i=0;i<rm.length;i++){rm[i].remove();} | |
| inlineAll(document.documentElement,clone); | |
| stripExternal(clone); | |
| var html=new XMLSerializer().serializeToString(clone); | |
| var svg='<svg xmlns="http://www.w3.org/2000/svg" width="'+w+'" height="'+h+'">' | |
| +'<foreignObject width="100%" height="100%">' | |
| +'<div xmlns="http://www.w3.org/1999/xhtml" style="width:'+w+'px;height:'+h+'px;overflow:hidden">' | |
| +'<div style="transform:translate(-'+scrollX+'px,-'+scrollY+'px);transform-origin:top left">' | |
| +html+'</div></div></foreignObject></svg>'; | |
| var svgUrl='data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg); | |
| var img=new Image(); | |
| img.onload=function(){ | |
| var c=document.createElement('canvas');c.width=w;c.height=h; | |
| c.getContext('2d').drawImage(img,0,0); | |
| window.parent.postMessage({type:'INLINE_EDIT_SCREENSHOT_RESULT',dataUrl:c.toDataURL('image/png'),scrollX:scrollX,scrollY:scrollY},'*'); | |
| }; | |
| img.onerror=function(){ | |
| window.parent.postMessage({type:'INLINE_EDIT_SCREENSHOT_RESULT',dataUrl:null,scrollX:scrollX,scrollY:scrollY},'*'); | |
| }; | |
| img.src=svgUrl; | |
| }catch(err){ | |
| window.parent.postMessage({type:'INLINE_EDIT_SCREENSHOT_RESULT',dataUrl:null,scrollX:scrollX,scrollY:scrollY},'*'); | |
| } | |
| }); | |
| })(); | |
| </script></body> | |
| </html> | |