
Chain Of Thought
- 45 installs
- Updated November 18, 2025
- wesley1600/claudecodeframework
Helps with ai & agent building tasks.
About
chain-of-thought is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- chain-of-thought
- AI & Agent Building
- AI-coding skill
Chain Of Thought by the numbers
- 45 all-time installs (skills.sh)
- +2 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #7,749 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/wesley1600/claudecodeframework --skill chain-of-thoughtAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 45 |
|---|---|
| Last updated | November 18, 2025 |
| Repository | wesley1600/claudecodeframework ↗ |
What it does
Helps with ai & agent building tasks.
Files
Chain of Thought Reasoning
Purpose
This skill enables structured, transparent reasoning by injecting chain of thought (CoT) blocks into prompts. It encourages the model to think step-by-step, explicitly show reasoning processes, and separate thinking from final outputs.
Chain of thought reasoning improves:
- Problem-solving accuracy - Breaking down complex problems into manageable steps
- Transparency - Making reasoning visible and auditable
- Self-correction - Allowing the model to catch and fix errors during reasoning
- Planning - Enabling reflection and iterative plan refinement
- Debugging - Understanding how conclusions were reached
When to Use
Activate this skill for tasks that benefit from explicit reasoning:
- Complex problem-solving - Multi-step mathematical, logical, or analytical problems
- Code analysis - Understanding unfamiliar codebases, debugging, or architecture decisions
- Planning and design - Breaking down features, designing systems, or creating implementation plans
- Research tasks - Synthesizing information from multiple sources
- Decision-making - Evaluating trade-offs between multiple approaches
- Error diagnosis - Investigating bugs or unexpected behavior
- Refactoring - Reasoning about code improvements and their implications
- Any task where "showing your work" leads to better outcomes
How It Works
Chain of thought uses XML tags to demarcate reasoning and output sections:
Primary Structure
<thinking>
Step 1: [Analyze the problem]
- What are we trying to accomplish?
- What information do we have?
- What's missing?
Step 2: [Break down the approach]
- What are the main steps?
- What are potential challenges?
Step 3: [Evaluate options]
- Option A: pros and cons
- Option B: pros and cons
- Decision: [chosen approach and why]
Step 4: [Verify reasoning]
- Does this make sense?
- Are there edge cases?
- What could go wrong?
</thinking>
<answer>
[Clear, concise final output based on the reasoning above]
</answer>Advanced Structure for Multi-Agent Systems
Inspired by the Manus AI multi-agent system, use nested thinking for complex workflows:
<thinking>
## Initial Analysis
[First pass understanding]
## Plan Formation
Current plan:
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Reflection
Is this plan optimal?
- Consideration 1: [reflection]
- Consideration 2: [reflection]
## Plan Update
Revised plan:
1. [Updated step 1]
2. [Updated step 2]
3. [New step 3]
Rationale for changes: [explanation]
## Execution Strategy
How to implement step 1:
- [Details]
- [Considerations]
</thinking>
<answer>
[Final output incorporating refined thinking]
</answer>Prompt Injection Patterns
Pattern 1: Problem-Solving Template
<thinking>
1. Problem understanding:
- Given: [what we know]
- Goal: [what we need to find/do]
- Constraints: [limitations]
2. Approach:
- Strategy: [chosen method]
- Why: [rationale]
3. Step-by-step execution:
- [Step 1 with reasoning]
- [Step 2 with reasoning]
- [Step 3 with reasoning]
4. Verification:
- Does the solution meet requirements?
- Are there edge cases?
</thinking>
<answer>
[Solution]
</answer>Pattern 2: Code Analysis Template
<thinking>
1. Code structure overview:
- Main components: [list]
- Data flow: [description]
2. Key observations:
- Pattern 1: [what and why]
- Pattern 2: [what and why]
3. Analysis:
- [Detailed reasoning about the code]
4. Conclusion:
- [Synthesis of findings]
</thinking>
<answer>
[Clear explanation or recommendation]
</answer>Pattern 3: Planning Template
<thinking>
1. Requirements analysis:
- Must have: [core requirements]
- Nice to have: [optional features]
2. Initial plan:
[List of steps]
3. Risk assessment:
- Risk 1: [description and mitigation]
- Risk 2: [description and mitigation]
4. Plan refinement:
[Updated plan based on risks]
5. Validation:
- Does this plan address all requirements?
- Is it feasible?
- What assumptions are we making?
</thinking>
<answer>
[Final plan with clear action items]
</answer>Guidelines
1. Structure Your Thinking
- Start with understanding - State what you know and what you need to find out
- Break down complex tasks - Divide into smaller, manageable pieces
- Show your work - Write out intermediate steps, not just conclusions
- Be explicit - State assumptions, trade-offs, and reasoning clearly
2. Use Reflection
- Question your approach - "Is this the best way?"
- Check your logic - "Does this reasoning hold up?"
- Consider alternatives - "What other approaches exist?"
- Update your plan - Don't be afraid to revise based on new insights
3. Separate Thinking from Output
- Thinking block - For exploration, reasoning, and working through problems
- Answer block - For the polished, final response
- Keep thinking raw - Don't over-polish; show genuine reasoning
- Keep answers concise - User sees the answer; thinking is internal
4. When to Use Each Block
Use `<thinking>` for:
- Analyzing requirements
- Breaking down problems
- Evaluating options
- Working through logic
- Planning implementation
- Reflecting on decisions
- Catching errors
- Exploring trade-offs
Use `<answer>` for:
- Final recommendations
- Implemented solutions
- Clear explanations
- Action items
- Conclusions
5. Best Practices
- Be honest in thinking - If uncertain, say so
- Show error correction - If you notice a mistake, correct it in the thinking block
- Use markdown - Format thinking blocks for readability
- Number your steps - Makes reasoning easier to follow
- Summarize in answer - Don't make users read all thinking to get the point
Examples
Example 1: Debugging a Problem
Prompt: "This function is returning incorrect results for negative numbers. Can you fix it?"
<thinking>
1. Understanding the problem:
- Function works for positive numbers
- Fails for negative numbers
- Need to identify why negatives cause issues
2. Code analysis:
- [Read through the function]
- Line 15: Uses Math.abs() - converts negative to positive
- Line 20: Returns result without sign restoration
- Aha! The absolute value removes the sign, but we never restore it
3. Solution approach:
- Option A: Track sign separately and reapply
- Option B: Handle negative numbers differently
- Choosing A: cleaner and preserves existing logic
4. Implementation plan:
- Store original sign
- Apply absolute value for calculation
- Multiply result by original sign
</thinking>
<answer>
The bug is on lines 15-20. The function uses `Math.abs()` but never restores the original sign. Here's the fix:
const sign = num < 0 ? -1 : 1; const absNum = Math.abs(num); // ... existing calculation ... return result * sign;
</answer>Example 2: Choosing Between Architectures
Prompt: "Should we use microservices or a monolith for this project?"
<thinking>
1. Context gathering:
- Team size: small (3 developers)
- Project scope: MVP with planned growth
- Timeline: 3 months to launch
- Infrastructure: cloud-based
2. Microservices analysis:
Pros:
- Scalability per service
- Independent deployment
- Technology flexibility
Cons:
- Operational complexity (DevOps overhead)
- Network latency
- Distributed debugging challenges
- Over-engineering for small team
3. Monolith analysis:
Pros:
- Simpler deployment
- Easier debugging
- Faster initial development
- Single codebase
Cons:
- Scaling requires scaling entire app
- Potential coupling issues
- May need to break apart later
4. Decision reasoning:
- Small team → simpler is better
- MVP timeline → need speed
- Planned growth → can refactor later
- Monolith-first approach is lower risk
5. Recommendation:
Start with modular monolith, design for eventual extraction
</thinking>
<answer>
For your project, I recommend starting with a **modular monolith**:
**Why:**
- Your small team will move faster without microservices overhead
- 3-month MVP timeline needs simplicity
- You can refactor to microservices later if needed
**Key principle:** Design modules with clear boundaries (separate folders, interfaces) so future extraction is easier.
**Action items:**
1. Structure code in domain modules (auth, payments, users)
2. Use dependency injection for loose coupling
3. Plan data models to avoid cross-module dependencies
</answer>Example 3: Multi-Step Implementation Planning
Prompt: "Add user authentication with OAuth to our app"
<thinking>
## Initial Analysis
Requirements:
- OAuth integration (which providers? assuming Google/GitHub)
- User session management
- Protected routes
- Existing app: appears to be Express.js based
## Plan Formation v1
1. Choose OAuth library
2. Set up OAuth credentials
3. Implement login/logout routes
4. Add session middleware
5. Protect existing routes
## Reflection
Issues with v1:
- Didn't consider token storage
- No user database integration mentioned
- Missing error handling strategy
- Should address CSRF protection
## Plan Formation v2
1. Research codebase for existing auth patterns
2. Choose OAuth library (passport.js likely best for Express)
3. Set up database schema for users
4. Configure OAuth providers (Google, GitHub)
5. Implement authentication routes
6. Add session management with secure tokens
7. Create auth middleware for protected routes
8. Add CSRF protection
9. Implement logout and session cleanup
10. Add error handling for auth failures
## Execution Strategy for Step 1
Need to:
- Check if passport.js already installed
- Look for existing user models
- Identify protected routes
- Check current session handling
</thinking>
<answer>
I'll implement OAuth authentication. Let me start by researching your current codebase to understand existing patterns, then proceed with the implementation plan:
1. Audit current auth patterns
2. Set up passport.js with OAuth strategies
3. Create user database schema
4. Implement login/logout flows
5. Add session management
6. Protect routes with auth middleware
7. Add security measures (CSRF, secure tokens)
Starting with codebase research...
</answer>Integration with Multi-Agent Systems
In multi-agent architectures like Manus AI, chain of thought enables:
- Agent reflection - Agents explicitly reason about their actions before executing
- Plan updating - Agents revise strategies based on intermediate results
- Inter-agent communication - Thinking blocks provide transparency for coordination
- Error recovery - Agents can detect issues during reasoning and adapt
Agents can maintain persistent thinking across multiple turns:
<thinking>
## Turn 1 Reflection
Previous attempt: [what was tried]
Result: [what happened]
Learning: [what we discovered]
## Updated Strategy
Based on the failure, trying new approach:
[revised plan]
</thinking>
<answer>
[Action based on updated thinking]
</answer>References
For detailed examples and advanced patterns, see:
- REFERENCE.md - Extended examples and patterns
- XML Guide Conventions - Proper XML tag usage
Summary
Chain of thought reasoning makes AI behavior more:
- Transparent - You can see how conclusions were reached
- Reliable - Step-by-step reduces errors
- Debuggable - Easy to spot where reasoning went wrong
- Adaptive - Reflection enables plan updates
Use this skill whenever explicit reasoning improves outcomes.
Chain of Thought - Extended Reference
Advanced Patterns and Real-World Examples
This document provides in-depth examples and advanced patterns for chain of thought reasoning.
---
Table of Contents
1. Multi-Turn Reasoning 2. Hierarchical Thinking 3. Collaborative Reasoning 4. Error Recovery Patterns 5. Domain-Specific Templates 6. Performance Optimization
---
Multi-Turn Reasoning
When a task spans multiple interactions, maintain continuity by referencing previous thinking.
Example: Iterative Bug Investigation
Turn 1:
<thinking>
## Initial Investigation
User reports: API returning 500 errors intermittently
Hypothesis 1: Database connection timeout
- Check: connection pool settings
- Evidence needed: error logs
Hypothesis 2: Race condition in concurrent requests
- Check: request handling logic
- Evidence needed: timing patterns
Next step: Examine error logs to narrow down
</thinking>
<answer>
Let me check the error logs to understand the pattern of failures.
</answer>Turn 2 (after reading logs):
<thinking>
## Previous Context
Turn 1: Identified two hypotheses (DB timeout vs race condition)
## New Evidence
Error logs show:
- All failures happen during high traffic (>100 req/sec)
- Error message: "Cannot read property 'data' of undefined"
- Stack trace points to requestHandler.js:45
## Updated Analysis
This is NOT a database issue. It's a race condition.
- Line 45 accesses request.body.data
- High traffic suggests concurrent modification
- The undefined suggests request object is being mutated
## Root Cause
Likely cause: shared mutable state in request handler
## Next Action
Examine requestHandler.js:45 and check for global state
</thinking>
<answer>
The error logs reveal this is a race condition, not a database issue. All failures occur during high traffic when accessing `request.body.data`. Let me examine the request handler code.
</answer>Turn 3 (after reading code):
<thinking>
## Investigation History
- Turn 1: Formed hypotheses
- Turn 2: Logs pointed to race condition
- Turn 3: Found the bug
## The Bug
Line 42-45 in requestHandler.js:let currentRequest = request; // PROBLEM: shared reference processAsync(() => { return currentRequest.body.data; // undefined when overwritten });
The `currentRequest` variable is overwritten by concurrent requests!
## Solution
Capture the data value immediately:const requestData = request.body.data; // immutable capture processAsync(() => { return requestData; // safe });
## Validation
This explains:
- Why it only fails under high traffic
- Why the error is intermittent
- Why the request object appears undefined
</thinking>
<answer>
Found the bug! The request handler uses a shared mutable reference that gets overwritten during concurrent requests. Here's the fix:
// Before (buggy): let currentRequest = request; processAsync(() => { return currentRequest.body.data; // undefined during concurrent requests });
// After (fixed): const requestData = request.body.data; processAsync(() => { return requestData; // immutable, safe });
This captures the data immediately before async processing, preventing race conditions.
</answer>---
Hierarchical Thinking
For complex tasks, use nested thinking levels to organize reasoning.
Example: System Architecture Design
<thinking>
# Level 1: High-Level Strategy
## Goal
Design a scalable e-commerce platform for 1M+ users
## Major Components
1. Frontend (web + mobile)
2. API Gateway
3. Backend services
4. Data layer
5. Infrastructure
# Level 2: Component Deep-Dive
## 2.1 Frontend Architecture
### Requirements Analysis
- Web: React (existing team expertise)
- Mobile: React Native (code sharing)
- State management: Redux vs Context API
### Decision Process
React Native enables 70% code reuse
- Pro: faster development
- Pro: consistent UX
- Con: some platform-specific features harder
- Decision: Use React Native with native modules for complex features
## 2.2 Backend Services
### Service Boundaries
Option A: Monolith with modules
Option B: Microservices from day 1
Option C: Modular monolith → gradual extraction
### Evaluation
Current team: 5 developers
Timeline: 6 months to MVP
Growth plan: 2x team size in year 2
Analysis:
- Microservices (Option B) = overkill for team size
- Pure monolith (Option A) = future pain
- Hybrid (Option C) = best balance
Decision: Modular monolith with clear service boundaries
### Critical Services to Isolate
1. Authentication (high security, stable)
2. Payment processing (PCI compliance, isolated)
3. Product catalog (high read, cacheable)
4. Order management (core business logic)
# Level 3: Implementation Details
## 3.1 Data Layer Design
### Database Selection
Products catalog:
- Read-heavy (90% reads)
- Semi-structured data (variants, attributes)
- Search requirements
→ PostgreSQL + Elasticsearch
Orders:
- ACID requirements
- Relational (orders → items → products)
→ PostgreSQL
Sessions/Cache:
- High throughput
- Ephemeral
→ Redis
## 3.2 API Gateway Strategy
### Requirements
- Rate limiting
- Authentication
- Request routing
- Response caching
### Options
Kong vs NGINX vs AWS API Gateway
Decision Matrix:
- Kong: feature-rich, self-hosted
- NGINX: lightweight, requires custom plugins
- AWS API Gateway: managed, AWS-specific
Given AWS infrastructure → AWS API Gateway
Reasoning: reduces operational burden, native integration
# Level 4: Risk Assessment
## Identified Risks
Risk 1: Database scaling at 1M users
- Mitigation: Read replicas + caching strategy
- Validation: Load testing at 100K user simulation
Risk 2: Frontend bundle size
- Mitigation: Code splitting, lazy loading
- Validation: Bundle analysis, performance budgets
Risk 3: Payment processing downtime
- Mitigation: Retry logic, fallback processor
- Validation: Chaos engineering tests
# Level 5: Final Validation
## Checklist
✓ Meets scalability requirements (1M+ users)
✓ Team can implement (existing skills)
✓ Within timeline (6 months)
✓ Costs reasonable (AWS tier estimate: $5K/month initial)
✓ Security addressed (PCI compliance, auth)
✓ Monitoring planned (CloudWatch, Sentry)
## Risks Accepted
- Some rework needed when extracting microservices later
- AWS vendor lock-in (acceptable trade-off for speed)
## Open Questions
- [ ] CDN strategy (CloudFront vs Cloudflare)
- [ ] CI/CD tooling (GitHub Actions vs CircleCI)
→ Can be decided during implementation
</thinking>
<answer>
## E-Commerce Platform Architecture
### Frontend
- **Web + Mobile**: React + React Native (70% code sharing)
- **State**: Redux for complex state, Context API for simple cases
### Backend
- **Pattern**: Modular monolith (clear service boundaries for future extraction)
- **Language**: Node.js (team expertise)
- **Key modules**: Auth, Payments, Products, Orders
### Data Layer
- **Primary DB**: PostgreSQL (orders, users, products)
- **Search**: Elasticsearch (product catalog)
- **Cache**: Redis (sessions, frequently accessed data)
### Infrastructure
- **Cloud**: AWS
- **API Gateway**: AWS API Gateway (managed, rate limiting, auth)
- **Hosting**: ECS (containerized services)
- **CDN**: TBD (CloudFront vs Cloudflare)
### Scalability Strategy
1. Database read replicas for read-heavy workloads
2. Redis caching layer
3. CDN for static assets
4. Horizontal scaling via ECS auto-scaling
### Timeline
- Months 1-2: Core services (auth, products, orders)
- Months 3-4: Frontend + payment integration
- Months 5-6: Testing, optimization, launch prep
### Cost Estimate
Initial: ~$5K/month (scales with usage)
### Next Steps
1. Set up AWS infrastructure (VPC, RDS, ECS)
2. Create service templates and repository structure
3. Implement authentication module (foundation)
</answer>---
Collaborative Reasoning
When multiple agents or perspectives are involved, use thinking blocks to coordinate.
Example: Code Review Discussion
Agent 1 (Reviewer):
<thinking>
## Code Review: Authentication Module
### Security Analysis
Line 45: Password hashingconst hash = md5(password);
🚨 CRITICAL: MD5 is cryptographically broken!
Recommendation: Use bcrypt or argon2
### Performance Analysis
Line 78: Database query in loopfor (user of users) { await db.getUserPermissions(user.id); }
⚠️ N+1 query problem, will cause performance issues
Recommendation: Batch query or use JOIN
### Code Quality
- Good: Clear variable names
- Good: Error handling present
- Issue: No input validation on line 23
## Severity Assessment
1. MD5 usage: BLOCKER (security)
2. N+1 queries: MAJOR (performance)
3. Missing validation: MINOR (correctness)
## Recommendation
Request changes before merge
</thinking>
<answer>
### Review: Request Changes
**BLOCKER - Security Issue:**
Line 45 uses MD5 for password hashing. MD5 is cryptographically broken and vulnerable to rainbow table attacks.
**Fix:** Use bcrypt:const hash = await bcrypt.hash(password, 10);
**MAJOR - Performance Issue:**
Line 78 has N+1 query problem that will cause slowdowns with many users.
**Fix:** Batch the query:const userIds = users.map(u => u.id); const permissions = await db.getUserPermissionsBatch(userIds);
**MINOR - Input Validation:**
Line 23 should validate email format before processing.
Please address the security and performance issues before merging.
</answer>Agent 2 (Developer):
<thinking>
## Reviewing Feedback
### Blocker: MD5 → bcrypt
Agree this is critical. However, considerations:
- We have 100K existing users with MD5 hashes
- Can't just switch without migration strategy
Migration plan:
1. Add `hash_version` field to users table
2. New users get bcrypt (version 2)
3. Existing users keep MD5 temporarily (version 1)
4. On next login, rehash with bcrypt and update version
5. After 90 days, force password reset for remaining MD5 users
This allows gradual migration without breaking existing users.
### Major: N+1 queries
Good catch. However:
- `getUserPermissionsBatch` doesn't exist yet
- Need to implement it or use JOIN
Checking schema... permissions table has user_id foreign key.
Better approach: JOIN in the original query
const usersWithPermissions = await db.query( SELECT users.*, permissions.* FROM users LEFT JOIN permissions ON users.id = permissions.user_id WHERE users.id IN (?) , userIds);
### Minor: Email validation
Agree. Will add validator.isEmail() check.
## Updated Implementation Plan
1. Implement hash migration strategy (MD5 → bcrypt)
2. Refactor query to use JOIN
3. Add email validation
4. Add tests for all three fixes
</thinking>
<answer>
Thanks for the thorough review! I agree with all points. Here's my implementation plan:
**1. MD5 → bcrypt (with migration strategy):**
I'll implement a gradual migration to avoid breaking existing users:
- Add `hash_version` field to track hash type
- New registrations use bcrypt immediately
- Existing users rehash on next login
- Force reset after 90 days for holdouts
**2. N+1 fix (using JOIN):**
I'll refactor to use a JOIN instead of separate queries:const usersWithPermissions = await db.query( SELECT users.*, permissions.* FROM users LEFT JOIN permissions ON users.id = permissions.user_id WHERE users.id IN (?) , userIds);
**3. Email validation:**
Adding `validator.isEmail()` check on line 23.
I'll push these fixes with tests shortly. ETA: 2 hours.
</answer>---
Error Recovery Patterns
When things go wrong, use thinking blocks to diagnose and adapt.
Example: Build Failure Recovery
<thinking>
## Build Attempt 1
Command: `npm run build`
Error:Module not found: Error: Can't resolve './utils/helper'
## Diagnosis
The import path is broken. Let me check:
- Does the file exist?
- Is the path correct?
- Case sensitivity issue?
Checking file system...
Found: `src/utils/Helper.js` (capital H)
Import: `import { foo } from './utils/helper'` (lowercase h)
Root cause: Case mismatch (Linux is case-sensitive, local dev on Mac was case-insensitive)
## Solution
Fix import to match actual filename
## Build Attempt 2
Command: `npm run build`
Error:TypeError: Cannot read property 'map' of undefined at ProductList.jsx:23
## New Diagnosis
Runtime error during build (SSR?). Checking ProductList.jsx:23...
Line 23: `products.map(p => ...)`
The `products` prop is undefined. This is happening during build, so it's SSR.
Root cause: Component assumes `products` exists but doesn't handle undefined case
## Solution
Add default props or guard:const { products = [] } = props;
## Build Attempt 3
Command: `npm run build`
Result: ✓ SUCCESS
## Reflection
Two issues fixed:
1. Case sensitivity in imports (development env difference)
2. Missing prop defaults for SSR
Learning: Always test builds on Linux before deploying (or use Docker for consistency)
</thinking>
<answer>
Build fixed! Two issues resolved:
1. **Import case mismatch**: `./utils/helper` → `./utils/Helper` (Linux is case-sensitive)
2. **SSR prop handling**: Added default for `products` prop in ProductList
The build now passes. To prevent future issues, consider using Docker for development to match the production environment's case sensitivity.
</answer>---
Domain-Specific Templates
Template: Algorithm Design
<thinking>
## Problem Statement
Input: [description]
Output: [description]
Constraints: [limitations]
## Examples
Example 1:
Input: [sample input]
Expected Output: [sample output]
Example 2:
Input: [edge case]
Expected Output: [expected result]
## Approach Analysis
### Brute Force
Algorithm: [description]
Time Complexity: O(?)
Space Complexity: O(?)
Pros: [advantages]
Cons: [disadvantages]
### Optimized Approach 1
Algorithm: [description]
Time Complexity: O(?)
Space Complexity: O(?)
Pros: [advantages]
Cons: [disadvantages]
### Optimized Approach 2
Algorithm: [description]
Time Complexity: O(?)
Space Complexity: O(?)
Pros: [advantages]
Cons: [disadvantages]
## Decision
Chosen: [approach]
Reasoning: [why this one]
## Implementation Plan
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Edge Cases to Handle
- [Edge case 1]
- [Edge case 2]
- [Edge case 3]
## Verification Strategy
- [Test case 1]
- [Test case 2]
- [Complexity verification]
</thinking>
<answer>
[Implementation with explanation]
</answer>Template: API Design
<thinking>
## Requirements
Functional:
- [Requirement 1]
- [Requirement 2]
Non-functional:
- Performance: [target]
- Security: [requirements]
- Scalability: [requirements]
## API Design Options
### RESTful Approach
Endpoints:
- GET /resource
- POST /resource
- PUT /resource/:id
- DELETE /resource/:id
Pros: [advantages]
Cons: [disadvantages]
### GraphQL Approach
Schema:type Resource { id: ID! field1: String field2: Int }
Pros: [advantages]
Cons: [disadvantages]
## Decision
Approach: [chosen design]
Reasoning: [justification]
## Endpoint Specification
[Detailed endpoint design]
## Security Considerations
- Authentication: [method]
- Authorization: [method]
- Rate limiting: [strategy]
- Input validation: [strategy]
## Error Handling
- 400: [scenarios]
- 401: [scenarios]
- 403: [scenarios]
- 404: [scenarios]
- 500: [scenarios]
## Documentation Plan
- OpenAPI/Swagger spec
- Usage examples
- Error codes reference
</thinking>
<answer>
[API specification with examples]
</answer>Template: Database Schema Design
<thinking>
## Data Requirements
Entities:
- [Entity 1] with attributes [list]
- [Entity 2] with attributes [list]
Relationships:
- [Entity 1] → [Entity 2]: [type]
## Access Patterns
Query 1: [description] - frequency: [high/medium/low]
Query 2: [description] - frequency: [high/medium/low]
## Normalization Analysis
Current form: [1NF/2NF/3NF]
Trade-offs:
- Normalized: [pros/cons]
- Denormalized: [pros/cons]
Decision: [approach and why]
## Index Strategy
Index 1: [columns] - justification: [query pattern]
Index 2: [columns] - justification: [query pattern]
## Schema DraftCREATE TABLE entity1 ( id PRIMARY KEY, ... );
## Migration Strategy
- [Step 1]
- [Step 2]
## Performance Validation
- Expected table size: [estimate]
- Query performance target: [target]
- Index overhead: [acceptable?]
</thinking>
<answer>
[Final schema with migration script]
</answer>---
Performance Optimization
When thinking blocks get large, optimize for clarity without sacrificing depth.
Guideline: Use Headings and Lists
Instead of:
<thinking>
So I need to figure out if we should use option A or option B. Option A has the advantage of being faster but it's more complex to implement and maintain. Option B is slower but it's simpler. Looking at our requirements, we need good performance but the team is small so maintenance matters. Also considering that this is an MVP so we want to ship quickly. Taking all of this into account I think option B makes more sense because...
</thinking>Do this:
<thinking>
## Options Comparison
### Option A
Pros:
- Faster performance
Cons:
- Complex implementation
- High maintenance burden
### Option B
Pros:
- Simple implementation
- Low maintenance
Cons:
- Slower performance
## Context
- Small team (3 developers)
- MVP timeline (3 months)
- Performance: important but not critical
## Decision
Choose Option B
Reasoning: Simplicity and speed to market outweigh performance gains for MVP
</thinking>Guideline: Reference Instead of Repeating
Instead of:
<thinking>
## Turn 5
So in turn 1 we discussed X and Y, then in turn 2 we found Z, and in turn 3 we discovered A, and in turn 4 we learned B, so now...
</thinking>Do this:
<thinking>
## Context (from turns 1-4)
- Identified issue: race condition
- Root cause: shared mutable state
- Attempted fix: immutable variables
## New Information (Turn 5)
[Focus on what's new]
</thinking>---
Summary
Chain of thought reasoning is most powerful when:
- Thinking is structured and organized
- Each step builds on previous insights
- Reflection enables course correction
- Final answers are clear and actionable
Use these patterns as starting points and adapt them to your specific needs.
XML Tag Conventions for Chain of Thought
Purpose
This guide explains the proper use of XML tags for chain of thought reasoning, based on Claude's native capabilities and best practices for structured output.
---
Core Tags
<thinking> and </thinking>
Purpose: Contains the model's internal reasoning process, working through problems step-by-step before providing a final answer.
When to use:
- Breaking down complex problems
- Evaluating multiple options
- Planning implementation steps
- Debugging and error analysis
- Reflecting on decisions
Characteristics:
- Can contain raw, unpolished reasoning
- May include false starts and corrections
- Markdown formatting supported
- Can be nested with sections
Example:
<thinking>
Let me analyze this problem step by step.
First, what do we know?
- Input: array of numbers
- Goal: find the median
Options:
1. Sort and pick middle - O(n log n)
2. Quickselect - O(n) average case
Given the requirement for efficiency with large datasets, quickselect is better.
Wait, do we need the median repeatedly? If so, we should sort once and reuse.
Checking requirements... yes, median is called multiple times.
Decision: Sort once, O(n log n), then O(1) for each median lookup.
</thinking><answer> and </answer>
Purpose: Contains the final, polished response to the user's query.
When to use:
- After completing reasoning in
<thinking> - For the user-facing output
- When you have a clear, actionable response
Characteristics:
- Should be clear and concise
- Well-formatted and professional
- Directly addresses the user's question
- May include code, explanations, or recommendations
Example:
<answer>
For this use case, I recommend sorting the array once and reusing it:
class MedianFinder { constructor(numbers) { this.sorted = [...numbers].sort((a, b) => a - b); }
getMedian() { const mid = Math.floor(this.sorted.length / 2); if (this.sorted.length % 2 === 0) { return (this.sorted[mid - 1] + this.sorted[mid]) / 2; } return this.sorted[mid]; } }
Time complexity: O(n log n) for initialization, O(1) for each median query.
</answer>---
Alternative and Extended Tags
<reflection> (Advanced)
Purpose: Explicit self-reflection on reasoning quality, assumptions, or potential errors.
When to use:
- When questioning your own reasoning
- Checking for logical errors
- Validating assumptions
- Considering alternative perspectives
Example:
<thinking>
Initial plan: Use a hash map to store frequencies.
<reflection>
Wait, is a hash map the right choice here?
- Pro: O(1) lookup
- Con: Uses more memory than an array
- Question: What's the range of values?
If values are 0-100, an array would be more efficient.
Let me reconsider...
</reflection>
Updated plan: Check value range first, then choose data structure.
</thinking><plan> (Advanced)
Purpose: Specifically demarcates planning sections within thinking blocks.
When to use:
- Breaking down implementation into steps
- Outlining approach before execution
- Creating task lists
Example:
<thinking>
<plan>
1. Set up database schema
2. Create API endpoints
3. Implement authentication
4. Add validation logic
5. Write tests
6. Deploy to staging
</plan>
Let me start with step 1...
</thinking><observation> (Advanced)
Purpose: Recording factual observations from code, logs, or data.
When to use:
- Analyzing code structure
- Reading log files
- Examining data patterns
Example:
<thinking>
<observation>
Looking at the error logs:
- All failures occur between 2am-3am
- Error code: ECONNREFUSED
- Affected service: database
</observation>
Hypothesis: Scheduled maintenance window causes connection drops.
</thinking>---
Nesting and Structure
Markdown Inside XML
You can use full markdown formatting inside XML tags:
<thinking>
## Problem Analysis
### Option 1: Breadth-First Search
- **Pros:** Finds shortest path
- **Cons:** Higher memory usage
### Option 2: Depth-First Search
- **Pros:** Lower memory
- **Cons:** May not find shortest path
**Decision:** Use BFS because finding the shortest path is critical.
</thinking>Nested Sections
For complex reasoning, nest sections with markdown headers:
<thinking>
# Phase 1: Understanding
## Requirements
- [Requirement 1]
- [Requirement 2]
## Constraints
- [Constraint 1]
- [Constraint 2]
# Phase 2: Design
## Architecture Options
[Analysis]
## Decision
[Chosen approach]
# Phase 3: Implementation Planning
## Steps
1. [Step 1]
2. [Step 2]
</thinking>---
Best Practices
1. Separate Concerns
Don't mix thinking and answer:
<!-- Bad -->
<thinking>
Let me figure this out... okay, the answer is X because Y.
So here's the solution: [code]
</thinking>Do this:
<!-- Good -->
<thinking>
Let me figure this out...
- Analysis: [reasoning]
- Conclusion: X because Y
</thinking>
<answer>
Here's the solution:
[code]
</answer>2. Show Work, Not Just Conclusions
Weak thinking:
<thinking>
The bug is on line 45. I should fix it.
</thinking>Strong thinking:
<thinking>
Looking for the bug...
Checking error message: "undefined is not a function"
Stack trace points to: line 45
Line 45 code:result.map(x => x * 2)
Wait, what is `result`? Tracing back...
Line 40: `const result = fetchData()`
Issue: `fetchData()` might return null/undefined
The code assumes `result` is always an array
Root cause: Missing null check before calling .map()
Fix: Add guard clause or default value
</thinking>3. Use Headings for Long Reasoning
<thinking>
## Step 1: Understand Requirements
[Analysis]
## Step 2: Evaluate Options
### Option A
[Details]
### Option B
[Details]
## Step 3: Make Decision
[Reasoning]
## Step 4: Plan Implementation
[Steps]
</thinking>4. Correct Errors Inline
If you make a mistake during reasoning, fix it in the thinking block:
<thinking>
Initial thought: Use a Set for fast lookup.
Wait, that won't work because we need to preserve order.
Correction: Use an array and keep track of seen items separately.
Actually, even better: Use a Map to preserve insertion order AND get O(1) lookup.
Final decision: Map
</thinking>5. Keep Answer Blocks Concise
The <answer> should be focused and user-friendly:
<answer>
Use the following approach:
const uniqueOrdered = [...new Map(items.map(item => [item.id, item])).values()];
This preserves insertion order while removing duplicates based on `id`.
</answer>---
Common Patterns
Pattern 1: Problem-Solution
<thinking>
Problem: [description]
Constraints: [limitations]
Approach: [method]
Verification: [how to validate]
</thinking>
<answer>
[Solution]
</answer>Pattern 2: Analysis-Recommendation
<thinking>
## Current State
[What exists now]
## Issues
[Problems identified]
## Options
[Alternatives considered]
## Recommendation
[Chosen path and why]
</thinking>
<answer>
I recommend [X] because [concise reasoning].
[Implementation details]
</answer>Pattern 3: Multi-Step Planning
<thinking>
## Phase 1: Research
[Findings]
## Phase 2: Design
[Architecture]
## Phase 3: Implementation Plan
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Phase 4: Validation
[How to verify success]
</thinking>
<answer>
I'll implement this in three steps:
1. **[Step 1]** - [description]
2. **[Step 2]** - [description]
3. **[Step 3]** - [description]
Starting with step 1...
</answer>Pattern 4: Iterative Refinement
<thinking>
## Initial Idea
[First approach]
## Issues with Initial Idea
[Problems found]
## Refined Approach
[Improved version]
## Final Validation
[Checking the refined approach]
✓ Meets requirements
✓ Handles edge cases
✓ Performant
</thinking>
<answer>
[Refined solution]
</answer>---
XML Tag Dos and Don'ts
Do:
- ✅ Use
<thinking>for all reasoning and problem-solving - ✅ Use
<answer>for final, user-facing responses - ✅ Include markdown formatting for readability
- ✅ Show your work, including false starts and corrections
- ✅ Structure long thinking blocks with headers
- ✅ Separate distinct phases of reasoning
Don't:
- ❌ Put user-facing content in
<thinking>tags - ❌ Put internal reasoning in
<answer>tags - ❌ Skip thinking for complex problems
- ❌ Make thinking blocks messy and unstructured
- ❌ Repeat the same information in both tags
- ❌ Use thinking as a way to "show off" - be genuine
---
Integration with Claude Code
In the Claude Code framework, chain of thought reasoning enables:
1. Transparent Decision Making
Users can see why you chose a particular approach.
2. Debuggable Reasoning
When something goes wrong, the thinking block shows where reasoning diverged.
3. Improved Accuracy
Step-by-step reasoning reduces errors compared to direct answers.
4. Learning and Improvement
Thinking blocks create a record of decision-making patterns.
5. Multi-Agent Coordination
Agents can share reasoning with each other for better collaboration.
---
Example: Full Workflow
User asks: "Why is my React component re-rendering so much?"
<thinking>
## Initial Analysis
User reports: excessive re-renders in React component
Need to understand:
1. What triggers re-renders in React?
- State changes
- Prop changes
- Parent re-renders
- Context changes
2. Common causes of excessive re-renders:
- New object/array references in render
- Inline function definitions
- Missing memo/useMemo/useCallback
- Context provider value changes
## Information Gathering
I should ask to see the component code to diagnose.
Actually, wait - let me check if they provided code already...
[Checking context]
No code provided yet. I'll need to ask for it.
## Response Strategy
1. Explain common causes
2. Ask for code
3. Provide diagnostic steps
</thinking>
<answer>
React components re-render excessively usually due to:
1. **New object references on each render**// Bad: new object every render <Child config={{theme: 'dark'}} />
// Good: stable reference const config = useMemo(() => ({theme: 'dark'}), []); <Child config={config} />
2. **Inline function definitions**// Bad: new function every render <button onClick={() => handleClick(id)}>
// Good: memoized callback const onClick = useCallback(() => handleClick(id), [id]); <button onClick={onClick}>
3. **Parent component re-renders**
- If parent re-renders, children re-render too
- Fix: Use `React.memo()` for expensive children
Could you share your component code? I'll identify the specific cause.
</answer>---
Summary
- Use
<thinking>for reasoning,<answer>for final output - Structure thinking with markdown for clarity
- Show your work, including corrections
- Keep answers concise and user-focused
- Apply patterns appropriate to the task type
These conventions make AI reasoning transparent, debuggable, and effective.