logo

Claude Cheat Sheet


title: Claude date: 2024-12-01 10:00:00 background: bg-[#D97757] tags: - AI - Anthropic - Prompts - LLM categories: - AI intro: Claude AI cheat sheet with prompting techniques, model features, API usage and best practices plugins: - copyCode

Model Overview

Claude Model Family

ModelFeaturesBest For
Claude Sonnet 4Fast, cost-effectiveDaily tasks, coding
Claude HaikuFastest responseSimple tasks, real-time
Claude Opus 4Strongest reasoningComplex analysis, research

Context Window

  • 200K tokens: ~150K words or 500 pages
  • Supports long document analysis
  • Can process entire codebases

Core Capabilities

  • Text generation & editing
  • Code writing & debugging
  • Data analysis & summarization
  • Multi-language translation
  • Image understanding (Vision)
  • Long document processing

Prompt Structure

Basic Framework

[Role] [Task] [Context] [Format] [Constraints]

Example Structure

You are a senior Python developer.
Review the following code for bugs and security issues.
The code is part of a payment processing system.
Provide feedback in bullet points.
Focus only on critical issues.

Role Prompts {.cols-2}

Professional Roles

Expert Developer

You are a senior software engineer with 15 years
of experience in distributed systems. Review code
with focus on scalability and performance.

Technical Writer

You are a technical documentation specialist.
Explain complex concepts in simple, clear language
suitable for beginners.

Code Reviewer

You are a code reviewer at a Fortune 500 company.
Review code for best practices, security issues,
and maintainability.

Domain Specialists

Data Scientist

You are a data scientist specializing in machine
learning. Analyze datasets and suggest appropriate
ML models with their tradeoffs.

DevOps Engineer

You are a DevOps engineer with expertise in CI/CD,
containerization, and cloud infrastructure.
Provide production-ready solutions.

Security Expert

You are a cybersecurity specialist. Analyze code
and systems for vulnerabilities following OWASP
guidelines.

XML Tag Usage {.cols-2}

Document Tags

<document>
Your document content here
</document>

Summarize the key points from the above document.

Code Tags

<code language="python">
def calculate_total(items):
    return sum(item.price for item in items)
</code>

Explain what this function does and suggest improvements.

Multi-Section

<context>
We're building an e-commerce platform
</context>

<requirements>
- User authentication
- Shopping cart
- Payment processing
</requirements>

<constraints>
- Must use Python/Django
- Deploy on AWS
</constraints>

Design the system architecture.

Input/Output Tags

<input>
Raw sales data from Q1 2024
</input>

<expected_output>
- Monthly breakdown
- Top performing products
- Growth trends
</expected_output>

Analyze the sales data accordingly.

Prompting Techniques

Chain of Thought

Step-by-step reasoning

Solve this problem step by step:

1. First, identify the key variables
2. Then, establish relationships
3. Apply relevant formulas
4. Calculate the result
5. Verify your answer

Problem: [Your problem here]

Few-Shot Learning

Convert temperatures:

Input: 32°F
Output: 0°C

Input: 212°F
Output: 100°C

Input: 98.6°F
Output:

Self-Consistency

Solve this problem using three different approaches,
then compare the results to find the most reliable answer.

Problem: [Your problem here]

Structured Output

Analyze this text and respond in JSON format:

{
  "sentiment": "positive/negative/neutral",
  "confidence": 0.0-1.0,
  "key_topics": ["topic1", "topic2"],
  "summary": "brief summary"
}

Text: [Your text here]

Code Prompts {.cols-2}

Code Generation

Basic Function

Write a Python function that:
- Takes a list of integers
- Returns the two numbers that sum to a target
- Handle edge cases (empty list, no solution)
- Include type hints and docstring
- Time complexity should be O(n)

Full Implementation

Create a REST API endpoint in Node.js/Express that:
- Accepts POST requests to /api/users
- Validates email and password fields
- Hashes password using bcrypt
- Saves user to MongoDB
- Returns appropriate status codes
- Includes error handling

Code Review

Review this code for:
1. Bugs and logic errors
2. Security vulnerabilities
3. Performance issues
4. Code style and readability
5. Missing error handling

Provide specific line-by-line feedback.

<code>
[Your code here]
</code>

Debugging

Debug this code:

<code>
[Your buggy code]
</code>

Error message:
<error>
[Error output]
</error>

Expected behavior: [What should happen]
Actual behavior: [What's happening]

Refactoring

Refactor this code following these principles:
- Single Responsibility Principle
- DRY (Don't Repeat Yourself)
- Descriptive naming
- Proper error handling

<code>
[Your code here]
</code>

Test Generation

Generate comprehensive unit tests for this function:
- Happy path scenarios
- Edge cases
- Error conditions
- Use pytest/jest framework
- Include setup and teardown

<code>
[Your function here]
</code>

Code Explanation

Explain this code to a junior developer:
- What does each section do?
- Why were these design choices made?
- What are potential gotchas?
- How could it be improved?

<code>
[Complex code here]
</code>

Writing Prompts {.cols-2}

Content Creation

Blog Post

Write a blog post about [topic]:
- Target audience: [audience]
- Tone: [professional/casual/technical]
- Length: ~1000 words
- Include: introduction, 3-5 main points, conclusion
- Add relevant examples
- SEO keywords: [keywords]

Technical Documentation

Write documentation for this API endpoint:
- Overview and purpose
- Authentication requirements
- Request parameters (with types)
- Response format (with examples)
- Error codes and handling
- Code examples in Python and JavaScript

Editing & Rewriting

Rewrite this text to be:
- More concise (reduce by 50%)
- Professional tone
- Active voice
- Clear and direct

Original:
[Your text here]

Translation

Translate this text to [language]:
- Maintain technical accuracy
- Keep formatting intact
- Preserve code snippets unchanged
- Note any terms that don't translate well

<text>
[Your text here]
</text>

Analysis Prompts {.cols-2}

Data Analysis

Analyze this dataset:

<data>
[Your data here]
</data>

Provide:
1. Summary statistics
2. Key patterns and trends
3. Outliers and anomalies
4. Actionable insights
5. Visualization recommendations

Comparative Analysis

Compare these two approaches:

Option A: [Description]
Option B: [Description]

Evaluate based on:
- Performance
- Scalability
- Maintainability
- Cost
- Implementation complexity

Provide a recommendation with justification.

Root Cause Analysis

Analyze this incident:

<incident>
[Description of the problem]
</incident>

<symptoms>
[Observable symptoms]
</symptoms>

Perform root cause analysis:
1. Identify potential causes
2. Evaluate likelihood of each
3. Recommend investigation steps
4. Suggest preventive measures

Code Architecture Review

Review this system architecture:

<architecture>
[Architecture description or diagram]
</architecture>

Evaluate:
- Scalability bottlenecks
- Single points of failure
- Security concerns
- Performance implications
- Suggested improvements

Claude API

Basic Request (Python)

import anthropic

client = anthropic.Anthropic(api_key="your-key")

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello!"}
    ]
)
print(message.content)

With System Prompt

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system="You are a helpful coding assistant.",
    messages=[
        {"role": "user", "content": "Review my code"}
    ]
)

Multi-Turn Conversation

messages = [
    {"role": "user", "content": "What is Python?"},
    {"role": "assistant", "content": "Python is..."},
    {"role": "user", "content": "Show me an example"}
]

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=messages
)

Streaming

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Tell me a story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Vision (Image Input)

import base64

with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": image_data
                }
            },
            {"type": "text", "text": "Describe this image"}
        ]
    }]
)

Prompt Examples

Email Writing

Professional Email

Write a professional email to a client:
- Purpose: Project delay notification
- Delay: 2 weeks
- Reason: Supply chain issues
- Tone: Apologetic but confident
- Include: New timeline, mitigation steps
- Length: 150-200 words

Follow-up Email

Write a follow-up email:
- Context: Sent proposal 1 week ago
- Goal: Schedule a meeting
- Tone: Friendly, not pushy
- Include: Value proposition reminder
- Call to action: Suggest 3 time slots

Meeting & Planning

Meeting Summary

Summarize this meeting transcript:

<transcript>
[Meeting transcript]
</transcript>

Include:
- Key discussion points
- Decisions made
- Action items with owners
- Next steps and deadlines
- Open questions

Project Plan

Create a project plan for:

Project: [Description]
Timeline: [Duration]
Team size: [Number]

Include:
- Phase breakdown
- Key milestones
- Resource allocation
- Risk assessment
- Dependencies

Learning & Explanation

Explain Concept

Explain [concept] to me:
- Assume I'm a beginner
- Use simple analogies
- Provide practical examples
- Include common misconceptions
- Suggest next topics to learn

Create Tutorial

Create a step-by-step tutorial for [topic]:
- Prerequisites needed
- Learning objectives
- Hands-on exercises
- Common mistakes to avoid
- Practice problems with solutions

Best Practices

Do's

  • Be specific and clear
  • Provide sufficient context
  • Use structured formats
  • Give examples when possible
  • Break complex tasks into steps
  • Specify output format
  • Include constraints

Don'ts

  • Vague or ambiguous requests
  • Overloaded single prompts
  • Missing necessary context
  • Assuming prior knowledge
  • Skipping format requirements
  • Conflicting instructions

Iteration Tips

If the first response isn't right:
1. Point out specific issues
2. Provide additional context
3. Give examples of desired output
4. Ask for specific modifications
5. Try rephrasing the request

Keyboard Shortcuts (Claude.ai)

General

ShortcutAction
Cmd/Ctrl + KNew conversation
Cmd/Ctrl + Shift + CCopy last response
Cmd/Ctrl + Shift + ;Copy last code block
Cmd/Ctrl + /Show shortcuts

Input

ShortcutAction
Shift + EnterNew line
EnterSend message
Cmd/Ctrl + Shift + 1Switch model
🤖 AI 工具

Claude

Claude Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · AI 工具🧭 Markdown 速查🏷️ 3 个标签
#ai#prompts#anthropic
向下滚动查看内容
返回全部 Cheat Sheets

Model Overview

Claude Model Family
ModelFeaturesBest For
Claude Sonnet 4Fast, cost-effectiveDaily tasks, coding
Claude HaikuFastest responseSimple tasks, real-time
Claude Opus 4Strongest reasoningComplex analysis, research
Context Window
  • 200K tokens: ~150K words or 500 pages
  • Supports long document analysis
  • Can process entire codebases
Core Capabilities
  • Text generation & editing
  • Code writing & debugging
  • Data analysis & summarization
  • Multi-language translation
  • Image understanding (Vision)
  • Long document processing

Prompt Structure

Basic Framework
CODE
滚动查看更多
[Role] [Task] [Context] [Format] [Constraints]
Example Structure
CODE
滚动查看更多
You are a senior Python developer.
Review the following code for bugs and security issues.
The code is part of a payment processing system.
Provide feedback in bullet points.
Focus only on critical issues.

Role Prompts

Professional Roles

Expert Developer

CODE
滚动查看更多
You are a senior software engineer with 15 years
of experience in distributed systems. Review code
with focus on scalability and performance.

Technical Writer

CODE
滚动查看更多
You are a technical documentation specialist.
Explain complex concepts in simple, clear language
suitable for beginners.

Code Reviewer

CODE
滚动查看更多
You are a code reviewer at a Fortune 500 company.
Review code for best practices, security issues,
and maintainability.
Domain Specialists

Data Scientist

CODE
滚动查看更多
You are a data scientist specializing in machine
learning. Analyze datasets and suggest appropriate
ML models with their tradeoffs.

DevOps Engineer

CODE
滚动查看更多
You are a DevOps engineer with expertise in CI/CD,
containerization, and cloud infrastructure.
Provide production-ready solutions.

Security Expert

CODE
滚动查看更多
You are a cybersecurity specialist. Analyze code
and systems for vulnerabilities following OWASP
guidelines.

XML Tag Usage

Document Tags
XML
滚动查看更多
<document>
Your document content here
</document>

Summarize the key points from the above document.
Code Tags
XML
滚动查看更多
<code language="python">
def calculate_total(items):
    return sum(item.price for item in items)
</code>

Explain what this function does and suggest improvements.
Multi-Section
XML
滚动查看更多
<context>
We're building an e-commerce platform
</context>

<requirements>
- User authentication
- Shopping cart
- Payment processing
</requirements>

<constraints>
- Must use Python/Django
- Deploy on AWS
</constraints>

Design the system architecture.
Input/Output Tags
XML
滚动查看更多
<input>
Raw sales data from Q1 2024
</input>

<expected_output>
- Monthly breakdown
- Top performing products
- Growth trends
</expected_output>

Analyze the sales data accordingly.

Prompting Techniques

Chain of Thought

Step-by-step reasoning

CODE
滚动查看更多
Solve this problem step by step:

1. First, identify the key variables
2. Then, establish relationships
3. Apply relevant formulas
4. Calculate the result
5. Verify your answer

Problem: [Your problem here]
Few-Shot Learning
CODE
滚动查看更多
Convert temperatures:

Input: 32°F
Output: 0°C

Input: 212°F
Output: 100°C

Input: 98.6°F
Output:
Self-Consistency
CODE
滚动查看更多
Solve this problem using three different approaches,
then compare the results to find the most reliable answer.

Problem: [Your problem here]
Structured Output
CODE
滚动查看更多
Analyze this text and respond in JSON format:

{
  "sentiment": "positive/negative/neutral",
  "confidence": 0.0-1.0,
  "key_topics": ["topic1", "topic2"],
  "summary": "brief summary"
}

Text: [Your text here]

Code Prompts

Code Generation

Basic Function

CODE
滚动查看更多
Write a Python function that:
- Takes a list of integers
- Returns the two numbers that sum to a target
- Handle edge cases (empty list, no solution)
- Include type hints and docstring
- Time complexity should be O(n)

Full Implementation

CODE
滚动查看更多
Create a REST API endpoint in Node.js/Express that:
- Accepts POST requests to /api/users
- Validates email and password fields
- Hashes password using bcrypt
- Saves user to MongoDB
- Returns appropriate status codes
- Includes error handling
Code Review
CODE
滚动查看更多
Review this code for:
1. Bugs and logic errors
2. Security vulnerabilities
3. Performance issues
4. Code style and readability
5. Missing error handling

Provide specific line-by-line feedback.

<code>
[Your code here]
</code>
Debugging
CODE
滚动查看更多
Debug this code:

<code>
[Your buggy code]
</code>

Error message:
<error>
[Error output]
</error>

Expected behavior: [What should happen]
Actual behavior: [What's happening]
Refactoring
CODE
滚动查看更多
Refactor this code following these principles:
- Single Responsibility Principle
- DRY (Don't Repeat Yourself)
- Descriptive naming
- Proper error handling

<code>
[Your code here]
</code>
Test Generation
CODE
滚动查看更多
Generate comprehensive unit tests for this function:
- Happy path scenarios
- Edge cases
- Error conditions
- Use pytest/jest framework
- Include setup and teardown

<code>
[Your function here]
</code>
Code Explanation
CODE
滚动查看更多
Explain this code to a junior developer:
- What does each section do?
- Why were these design choices made?
- What are potential gotchas?
- How could it be improved?

<code>
[Complex code here]
</code>

Writing Prompts

Content Creation

Blog Post

CODE
滚动查看更多
Write a blog post about [topic]:
- Target audience: [audience]
- Tone: [professional/casual/technical]
- Length: ~1000 words
- Include: introduction, 3-5 main points, conclusion
- Add relevant examples
- SEO keywords: [keywords]

Technical Documentation

CODE
滚动查看更多
Write documentation for this API endpoint:
- Overview and purpose
- Authentication requirements
- Request parameters (with types)
- Response format (with examples)
- Error codes and handling
- Code examples in Python and JavaScript
Editing & Rewriting
CODE
滚动查看更多
Rewrite this text to be:
- More concise (reduce by 50%)
- Professional tone
- Active voice
- Clear and direct

Original:
[Your text here]
Translation
CODE
滚动查看更多
Translate this text to [language]:
- Maintain technical accuracy
- Keep formatting intact
- Preserve code snippets unchanged
- Note any terms that don't translate well

<text>
[Your text here]
</text>

Analysis Prompts

Data Analysis
CODE
滚动查看更多
Analyze this dataset:

<data>
[Your data here]
</data>

Provide:
1. Summary statistics
2. Key patterns and trends
3. Outliers and anomalies
4. Actionable insights
5. Visualization recommendations
Comparative Analysis
CODE
滚动查看更多
Compare these two approaches:

Option A: [Description]
Option B: [Description]

Evaluate based on:
- Performance
- Scalability
- Maintainability
- Cost
- Implementation complexity

Provide a recommendation with justification.
Root Cause Analysis
CODE
滚动查看更多
Analyze this incident:

<incident>
[Description of the problem]
</incident>

<symptoms>
[Observable symptoms]
</symptoms>

Perform root cause analysis:
1. Identify potential causes
2. Evaluate likelihood of each
3. Recommend investigation steps
4. Suggest preventive measures
Code Architecture Review
CODE
滚动查看更多
Review this system architecture:

<architecture>
[Architecture description or diagram]
</architecture>

Evaluate:
- Scalability bottlenecks
- Single points of failure
- Security concerns
- Performance implications
- Suggested improvements

Claude API

Basic Request (Python)
PYTHON
滚动查看更多
import anthropic

client = anthropic.Anthropic(api_key="your-key")

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello!"}
    ]
)
print(message.content)
With System Prompt
PYTHON
滚动查看更多
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system="You are a helpful coding assistant.",
    messages=[
        {"role": "user", "content": "Review my code"}
    ]
)
Multi-Turn Conversation
PYTHON
滚动查看更多
messages = [
    {"role": "user", "content": "What is Python?"},
    {"role": "assistant", "content": "Python is..."},
    {"role": "user", "content": "Show me an example"}
]

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=messages
)
Streaming
PYTHON
滚动查看更多
with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Tell me a story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
Vision (Image Input)
PYTHON
滚动查看更多
import base64

with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": image_data
                }
            },
            {"type": "text", "text": "Describe this image"}
        ]
    }]
)

Prompt Examples

Email Writing

Professional Email

CODE
滚动查看更多
Write a professional email to a client:
- Purpose: Project delay notification
- Delay: 2 weeks
- Reason: Supply chain issues
- Tone: Apologetic but confident
- Include: New timeline, mitigation steps
- Length: 150-200 words

Follow-up Email

CODE
滚动查看更多
Write a follow-up email:
- Context: Sent proposal 1 week ago
- Goal: Schedule a meeting
- Tone: Friendly, not pushy
- Include: Value proposition reminder
- Call to action: Suggest 3 time slots
Meeting & Planning

Meeting Summary

CODE
滚动查看更多
Summarize this meeting transcript:

<transcript>
[Meeting transcript]
</transcript>

Include:
- Key discussion points
- Decisions made
- Action items with owners
- Next steps and deadlines
- Open questions

Project Plan

CODE
滚动查看更多
Create a project plan for:

Project: [Description]
Timeline: [Duration]
Team size: [Number]

Include:
- Phase breakdown
- Key milestones
- Resource allocation
- Risk assessment
- Dependencies
Learning & Explanation

Explain Concept

CODE
滚动查看更多
Explain [concept] to me:
- Assume I'm a beginner
- Use simple analogies
- Provide practical examples
- Include common misconceptions
- Suggest next topics to learn

Create Tutorial

CODE
滚动查看更多
Create a step-by-step tutorial for [topic]:
- Prerequisites needed
- Learning objectives
- Hands-on exercises
- Common mistakes to avoid
- Practice problems with solutions

Best Practices

Do's
  • Be specific and clear
  • Provide sufficient context
  • Use structured formats
  • Give examples when possible
  • Break complex tasks into steps
  • Specify output format
  • Include constraints
Don'ts
  • Vague or ambiguous requests
  • Overloaded single prompts
  • Missing necessary context
  • Assuming prior knowledge
  • Skipping format requirements
  • Conflicting instructions
Iteration Tips
CODE
滚动查看更多
If the first response isn't right:
1. Point out specific issues
2. Provide additional context
3. Give examples of desired output
4. Ask for specific modifications
5. Try rephrasing the request

Keyboard Shortcuts (Claude.ai)

General
ShortcutAction
Cmd/Ctrl + KNew conversation
Cmd/Ctrl + Shift + CCopy last response
Cmd/Ctrl + Shift + ;Copy last code block
Cmd/Ctrl + /Show shortcuts
Input
ShortcutAction
Shift + EnterNew line
EnterSend message
Cmd/Ctrl + Shift + 1Switch model

相关 Cheat Sheets