[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6VCC2CY420J7ZHD865VM766":3,"skill-same:01M6VCC2CY420J7ZHD865VM766":113},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":27,"publishedAt":48,"linkOnly":49,"markdownContent":50,"markdownBody":51,"frontMatter":52,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":13,"repositoryHtmlUrl":58,"repositoryHomepageUrl":6,"ownerHtmlUrl":59,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":60,"install":61,"resources":74},"01M6VCC2CY420J7ZHD865VM766","ui-demo",null,"Record polished UI demo videos using Playwright. Use when the user asks to create a demo, walkthrough, screen recording, or tutorial video of a web application. Produces WebM videos with visible cursor, natural pacing, and professional feel.","sakamoto-family-smile\u002Fagent_monorepo","sakamoto-family-smile","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F132812403?v=4","01M6RTAT3H8PMWX5SJ65KP3VYF","01M6RTAV321WB5RAHCWTZMX5CV",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fecc\u002Fui-demo\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"ui","demo","ui demo","tutorial","when","videos","recording","with","professional","screen","record","use","playwright","cursor","user","walkthrough","Video","screen recording","create","web","2026-11-10 10:12:30",false,"---\nname: prompt-engineering-patterns\ndescription: Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability in production. Use when optimizing prompts, improving LLM outputs, or designing production prompt templates.\n---\n\n# Prompt Engineering Patterns\n\nMaster advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability.\n\n## When to Use This Skill\n\n- Designing complex prompts for production LLM applications\n- Optimizing prompt performance and consistency\n- Implementing structured reasoning patterns (chain-of-thought, tree-of-thought)\n- Building few-shot learning systems with dynamic example selection\n- Creating reusable prompt templates with variable interpolation\n- Debugging and refining prompts that produce inconsistent outputs\n- Implementing system prompts for specialized AI assistants\n- Using structured outputs (JSON mode) for reliable parsing\n\n## Core Capabilities\n\n### 1. Few-Shot Learning\n\n- Example selection strategies (semantic similarity, diversity sampling)\n- Balancing example count with context window constraints\n- Constructing effective demonstrations with input-output pairs\n- Dynamic example retrieval from knowledge bases\n- Handling edge cases through strategic example selection\n\n### 2. Chain-of-Thought Prompting\n\n- Step-by-step reasoning elicitation\n- Zero-shot CoT with \"Let's think step by step\"\n- Few-shot CoT with reasoning traces\n- Self-consistency techniques (sampling multiple reasoning paths)\n- Verification and validation steps\n\n### 3. Structured Outputs\n\n- JSON mode for reliable parsing\n- Pydantic schema enforcement\n- Type-safe response handling\n- Error handling for malformed outputs\n\n### 4. Prompt Optimization\n\n- Iterative refinement workflows\n- A\u002FB testing prompt variations\n- Measuring prompt performance metrics (accuracy, consistency, latency)\n- Reducing token usage while maintaining quality\n- Handling edge cases and failure modes\n\n### 5. Template Systems\n\n- Variable interpolation and formatting\n- Conditional prompt sections\n- Multi-turn conversation templates\n- Role-based prompt composition\n- Modular prompt components\n\n### 6. System Prompt Design\n\n- Setting model behavior and constraints\n- Defining output formats and structure\n- Establishing role and expertise\n- Safety guidelines and content policies\n- Context setting and background information\n\n## Quick Start\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom pydantic import BaseModel, Field\n\n# Define structured output schema\nclass SQLQuery(BaseModel):\n    query: str = Field(description=\"The SQL query\")\n    explanation: str = Field(description=\"Brief explanation of what the query does\")\n    tables_used: list[str] = Field(description=\"List of tables referenced\")\n\n# Initialize model with structured output\nllm = ChatAnthropic(model=\"claude-sonnet-4-6\")\nstructured_llm = llm.with_structured_output(SQLQuery)\n\n# Create prompt template\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"\"\"You are an expert SQL developer. Generate efficient, secure SQL queries.\n    Always use parameterized queries to prevent SQL injection.\n    Explain your reasoning briefly.\"\"\"),\n    (\"user\", \"Convert this to SQL: {query}\")\n])\n\n# Create chain\nchain = prompt | structured_llm\n\n# Use\nresult = await chain.ainvoke({\n    \"query\": \"Find all users who registered in the last 30 days\"\n})\nprint(result.query)\nprint(result.explanation)\n```\n\n## Key Patterns\n\n### Pattern 1: Structured Output with Pydantic\n\n```python\nfrom anthropic import Anthropic\nfrom pydantic import BaseModel, Field\nfrom typing import Literal\nimport json\n\nclass SentimentAnalysis(BaseModel):\n    sentiment: Literal[\"positive\", \"negative\", \"neutral\"]\n    confidence: float = Field(ge=0, le=1)\n    key_phrases: list[str]\n    reasoning: str\n\nasync def analyze_sentiment(text: str) -> SentimentAnalysis:\n    \"\"\"Analyze sentiment with structured output.\"\"\"\n    client = Anthropic()\n\n    message = client.messages.create(\n        model=\"claude-sonnet-4-6\",\n        max_tokens=500,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": f\"\"\"Analyze the sentiment of this text.\n\nText: {text}\n\nRespond with JSON matching this schema:\n{{\n    \"sentiment\": \"positive\" | \"negative\" | \"neutral\",\n    \"confidence\": 0.0-1.0,\n    \"key_phrases\": [\"phrase1\", \"phrase2\"],\n    \"reasoning\": \"brief explanation\"\n}}\"\"\"\n        }]\n    )\n\n    return SentimentAnalysis(**json.loads(message.content[0].text))\n```\n\n### Pattern 2: Chain-of-Thought with Self-Verification\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\n\ncot_prompt = ChatPromptTemplate.from_template(\"\"\"\nSolve this problem step by step.\n\nProblem: {problem}\n\nInstructions:\n1. Break down the problem into clear steps\n2. Work through each step showing your reasoning\n3. State your final answer\n4. Verify your answer by checking it against the original problem\n\nFormat your response as:\n## Steps\n[Your step-by-step reasoning]\n\n## Answer\n[Your final answer]\n\n## Verification\n[Check that your answer is correct]\n\"\"\")\n```\n\n### Pattern 3: Few-Shot with Dynamic Example Selection\n\n```python\nfrom langchain_voyageai import VoyageAIEmbeddings\nfrom langchain_core.example_selectors import SemanticSimilarityExampleSelector\nfrom langchain_chroma import Chroma\n\n# Create example selector with semantic similarity\nexample_selector = SemanticSimilarityExampleSelector.from_examples(\n    examples=[\n        {\"input\": \"How do I reset my password?\", \"output\": \"Go to Settings > Security > Reset Password\"},\n        {\"input\": \"Where can I see my order history?\", \"output\": \"Navigate to Account > Orders\"},\n        {\"input\": \"How do I contact support?\", \"output\": \"Click Help > Contact Us or email support@example.com\"},\n    ],\n    embeddings=VoyageAIEmbeddings(model=\"voyage-3-large\"),\n    vectorstore_cls=Chroma,\n    k=2  # Select 2 most similar examples\n)\n\nasync def get_few_shot_prompt(query: str) -> str:\n    \"\"\"Build prompt with dynamically selected examples.\"\"\"\n    examples = await example_selector.aselect_examples({\"input\": query})\n\n    examples_text = \"\\n\".join(\n        f\"User: {ex['input']}\\nAssistant: {ex['output']}\"\n        for ex in examples\n    )\n\n    return f\"\"\"You are a helpful customer support assistant.\n\nHere are some example interactions:\n{examples_text}\n\nNow respond to this query:\nUser: {query}\nAssistant:\"\"\"\n```\n\n### Pattern 4: Progressive Disclosure\n\nStart with simple prompts, add complexity only when needed:\n\n```python\nPROMPT_LEVELS = {\n    # Level 1: Direct instruction\n    \"simple\": \"Summarize this article: {text}\",\n\n    # Level 2: Add constraints\n    \"constrained\": \"\"\"Summarize this article in 3 bullet points, focusing on:\n- Key findings\n- Main conclusions\n- Practical implications\n\nArticle: {text}\"\"\",\n\n    # Level 3: Add reasoning\n    \"reasoning\": \"\"\"Read this article carefully.\n1. First, identify the main topic and thesis\n2. Then, extract the key supporting points\n3. Finally, summarize in 3 bullet points\n\nArticle: {text}\n\nSummary:\"\"\",\n\n    # Level 4: Add examples\n    \"few_shot\": \"\"\"Read articles and provide concise summaries.\n\nExample:\nArticle: \"New research shows that regular exercise can reduce anxiety by up to 40%...\"\nSummary:\n• Regular exercise reduces anxiety by up to 40%\n• 30 minutes of moderate activity 3x\u002Fweek is sufficient\n• Benefits appear within 2 weeks of starting\n\nNow summarize this article:\nArticle: {text}\n\nSummary:\"\"\"\n}\n```\n\n### Pattern 5: Error Recovery and Fallback\n\n```python\nfrom pydantic import BaseModel, ValidationError\nimport json\n\nclass ResponseWithConfidence(BaseModel):\n    answer: str\n    confidence: float\n    sources: list[str]\n    alternative_interpretations: list[str] = []\n\nERROR_RECOVERY_PROMPT = \"\"\"\nAnswer the question based on the context provided.\n\nContext: {context}\nQuestion: {question}\n\nInstructions:\n1. If you can answer confidently (>0.8), provide a direct answer\n2. If you're somewhat confident (0.5-0.8), provide your best answer with caveats\n3. If you're uncertain (\u003C0.5), explain what information is missing\n4. Always provide alternative interpretations if the question is ambiguous\n\nRespond in JSON:\n{{\n    \"answer\": \"your answer or 'I cannot determine this from the context'\",\n    \"confidence\": 0.0-1.0,\n    \"sources\": [\"relevant context excerpts\"],\n    \"alternative_interpretations\": [\"if question is ambiguous\"]\n}}\n\"\"\"\n\nasync def answer_with_fallback(\n    context: str,\n    question: str,\n    llm\n) -> ResponseWithConfidence:\n    \"\"\"Answer with error recovery and fallback.\"\"\"\n    prompt = ERROR_RECOVERY_PROMPT.format(context=context, question=question)\n\n    try:\n        response = await llm.ainvoke(prompt)\n        return ResponseWithConfidence(**json.loads(response.content))\n    except (json.JSONDecodeError, ValidationError) as e:\n        # Fallback: try to extract answer without structure\n        simple_prompt = f\"Based on: {context}\\n\\nAnswer: {question}\"\n        simple_response = await llm.ainvoke(simple_prompt)\n        return ResponseWithConfidence(\n            answer=simple_response.content,\n            confidence=0.5,\n            sources=[\"fallback extraction\"],\n            alternative_interpretations=[]\n        )\n```\n\n### Pattern 6: Role-Based System Prompts\n\n```python\nSYSTEM_PROMPTS = {\n    \"analyst\": \"\"\"You are a senior data analyst with expertise in SQL, Python, and business intelligence.\n\nYour responsibilities:\n- Write efficient, well-documented queries\n- Explain your analysis methodology\n- Highlight key insights and recommendations\n- Flag any data quality concerns\n\nCommunication style:\n- Be precise and technical when discussing methodology\n- Translate technical findings into business impact\n- Use clear visualizations when helpful\"\"\",\n\n    \"assistant\": \"\"\"You are a helpful AI assistant focused on accuracy and clarity.\n\nCore principles:\n- Always cite sources when making factual claims\n- Acknowledge uncertainty rather than guessing\n- Ask clarifying questions when the request is ambiguous\n- Provide step-by-step explanations for complex topics\n\nConstraints:\n- Do not provide medical, legal, or financial advice\n- Redirect harmful requests appropriately\n- Protect user privacy\"\"\",\n\n    \"code_reviewer\": \"\"\"You are a senior software engineer conducting code reviews.\n\nReview criteria:\n- Correctness: Does the code work as intended?\n- Security: Are there any vulnerabilities?\n- Performance: Are there efficiency concerns?\n- Maintainability: Is the code readable and well-structured?\n- Best practices: Does it follow language idioms?\n\nOutput format:\n1. Summary assessment (approve\u002Frequest changes)\n2. Critical issues (must fix)\n3. Suggestions (nice to have)\n4. Positive feedback (what's done well)\"\"\"\n}\n```\n\n## Integration Patterns\n\n### With RAG Systems\n\n```python\nRAG_PROMPT = \"\"\"You are a knowledgeable assistant that answers questions based on provided context.\n\nContext (retrieved from knowledge base):\n{context}\n\nInstructions:\n1. Answer ONLY based on the provided context\n2. If the context doesn't contain the answer, say \"I don't have information about that in my knowledge base\"\n3. Cite specific passages using [1], [2] notation\n4. If the question is ambiguous, ask for clarification\n\nQuestion: {question}\n\nAnswer:\"\"\"\n```\n\n### With Validation and Verification\n\n```python\nVALIDATED_PROMPT = \"\"\"Complete the following task:\n\nTask: {task}\n\nAfter generating your response, verify it meets ALL these criteria:\n✓ Directly addresses the original request\n✓ Contains no factual errors\n✓ Is appropriately detailed (not too brief, not too verbose)\n✓ Uses proper formatting\n✓ Is safe and appropriate\n\nIf verification fails on any criterion, revise before responding.\n\nResponse:\"\"\"\n```\n\n## Performance Optimization\n\n### Token Efficiency\n\n```python\n# Before: Verbose prompt (150+ tokens)\nverbose_prompt = \"\"\"\nI would like you to please take the following text and provide me with a comprehensive\nsummary of the main points. The summary should capture the key ideas and important details\nwhile being concise and easy to understand.\n\"\"\"\n\n# After: Concise prompt (30 tokens)\nconcise_prompt = \"\"\"Summarize the key points concisely:\n\n{text}\n\nSummary:\"\"\"\n```\n\n### Caching Common Prefixes\n\n```python\nfrom anthropic import Anthropic\n\nclient = Anthropic()\n\n# Use prompt caching for repeated system prompts\nresponse = client.messages.create(\n    model=\"claude-sonnet-4-6\",\n    max_tokens=1000,\n    system=[\n        {\n            \"type\": \"text\",\n            \"text\": LONG_SYSTEM_PROMPT,\n            \"cache_control\": {\"type\": \"ephemeral\"}\n        }\n    ],\n    messages=[{\"role\": \"user\", \"content\": user_query}]\n)\n```\n\n## Best Practices\n\n1. **Be Specific**: Vague prompts produce inconsistent results\n2. **Show, Don't Tell**: Examples are more effective than descriptions\n3. **Use Structured Outputs**: Enforce schemas with Pydantic for reliability\n4. **Test Extensively**: Evaluate on diverse, representative inputs\n5. **Iterate Rapidly**: Small changes can have large impacts\n6. **Monitor Performance**: Track metrics in production\n7. **Version Control**: Treat prompts as code with proper versioning\n8. **Document Intent**: Explain why prompts are structured as they are\n\n## Common Pitfalls\n\n- **Over-engineering**: Starting with complex prompts before trying simple ones\n- **Example pollution**: Using examples that don't match the target task\n- **Context overflow**: Exceeding token limits with excessive examples\n- **Ambiguous instructions**: Leaving room for multiple interpretations\n- **Ignoring edge cases**: Not testing on unusual or boundary inputs\n- **No error handling**: Assuming outputs will always be well-formed\n- **Hardcoded values**: Not parameterizing prompts for reuse\n\n## Success Metrics\n\nTrack these KPIs for your prompts:\n\n- **Accuracy**: Correctness of outputs\n- **Consistency**: Reproducibility across similar inputs\n- **Latency**: Response time (P50, P95, P99)\n- **Token Usage**: Average tokens per request\n- **Success Rate**: Percentage of valid, parseable outputs\n- **User Satisfaction**: Ratings and feedback\n","# Prompt Engineering Patterns\n\nMaster advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability.\n\n## When to Use This Skill\n\n- Designing complex prompts for production LLM applications\n- Optimizing prompt performance and consistency\n- Implementing structured reasoning patterns (chain-of-thought, tree-of-thought)\n- Building few-shot learning systems with dynamic example selection\n- Creating reusable prompt templates with variable interpolation\n- Debugging and refining prompts that produce inconsistent outputs\n- Implementing system prompts for specialized AI assistants\n- Using structured outputs (JSON mode) for reliable parsing\n\n## Core Capabilities\n\n### 1. Few-Shot Learning\n\n- Example selection strategies (semantic similarity, diversity sampling)\n- Balancing example count with context window constraints\n- Constructing effective demonstrations with input-output pairs\n- Dynamic example retrieval from knowledge bases\n- Handling edge cases through strategic example selection\n\n### 2. Chain-of-Thought Prompting\n\n- Step-by-step reasoning elicitation\n- Zero-shot CoT with \"Let's think step by step\"\n- Few-shot CoT with reasoning traces\n- Self-consistency techniques (sampling multiple reasoning paths)\n- Verification and validation steps\n\n### 3. Structured Outputs\n\n- JSON mode for reliable parsing\n- Pydantic schema enforcement\n- Type-safe response handling\n- Error handling for malformed outputs\n\n### 4. Prompt Optimization\n\n- Iterative refinement workflows\n- A\u002FB testing prompt variations\n- Measuring prompt performance metrics (accuracy, consistency, latency)\n- Reducing token usage while maintaining quality\n- Handling edge cases and failure modes\n\n### 5. Template Systems\n\n- Variable interpolation and formatting\n- Conditional prompt sections\n- Multi-turn conversation templates\n- Role-based prompt composition\n- Modular prompt components\n\n### 6. System Prompt Design\n\n- Setting model behavior and constraints\n- Defining output formats and structure\n- Establishing role and expertise\n- Safety guidelines and content policies\n- Context setting and background information\n\n## Quick Start\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom pydantic import BaseModel, Field\n\n# Define structured output schema\nclass SQLQuery(BaseModel):\n    query: str = Field(description=\"The SQL query\")\n    explanation: str = Field(description=\"Brief explanation of what the query does\")\n    tables_used: list[str] = Field(description=\"List of tables referenced\")\n\n# Initialize model with structured output\nllm = ChatAnthropic(model=\"claude-sonnet-4-6\")\nstructured_llm = llm.with_structured_output(SQLQuery)\n\n# Create prompt template\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"\"\"You are an expert SQL developer. Generate efficient, secure SQL queries.\n    Always use parameterized queries to prevent SQL injection.\n    Explain your reasoning briefly.\"\"\"),\n    (\"user\", \"Convert this to SQL: {query}\")\n])\n\n# Create chain\nchain = prompt | structured_llm\n\n# Use\nresult = await chain.ainvoke({\n    \"query\": \"Find all users who registered in the last 30 days\"\n})\nprint(result.query)\nprint(result.explanation)\n```\n\n## Key Patterns\n\n### Pattern 1: Structured Output with Pydantic\n\n```python\nfrom anthropic import Anthropic\nfrom pydantic import BaseModel, Field\nfrom typing import Literal\nimport json\n\nclass SentimentAnalysis(BaseModel):\n    sentiment: Literal[\"positive\", \"negative\", \"neutral\"]\n    confidence: float = Field(ge=0, le=1)\n    key_phrases: list[str]\n    reasoning: str\n\nasync def analyze_sentiment(text: str) -> SentimentAnalysis:\n    \"\"\"Analyze sentiment with structured output.\"\"\"\n    client = Anthropic()\n\n    message = client.messages.create(\n        model=\"claude-sonnet-4-6\",\n        max_tokens=500,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": f\"\"\"Analyze the sentiment of this text.\n\nText: {text}\n\nRespond with JSON matching this schema:\n{{\n    \"sentiment\": \"positive\" | \"negative\" | \"neutral\",\n    \"confidence\": 0.0-1.0,\n    \"key_phrases\": [\"phrase1\", \"phrase2\"],\n    \"reasoning\": \"brief explanation\"\n}}\"\"\"\n        }]\n    )\n\n    return SentimentAnalysis(**json.loads(message.content[0].text))\n```\n\n### Pattern 2: Chain-of-Thought with Self-Verification\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\n\ncot_prompt = ChatPromptTemplate.from_template(\"\"\"\nSolve this problem step by step.\n\nProblem: {problem}\n\nInstructions:\n1. Break down the problem into clear steps\n2. Work through each step showing your reasoning\n3. State your final answer\n4. Verify your answer by checking it against the original problem\n\nFormat your response as:\n## Steps\n[Your step-by-step reasoning]\n\n## Answer\n[Your final answer]\n\n## Verification\n[Check that your answer is correct]\n\"\"\")\n```\n\n### Pattern 3: Few-Shot with Dynamic Example Selection\n\n```python\nfrom langchain_voyageai import VoyageAIEmbeddings\nfrom langchain_core.example_selectors import SemanticSimilarityExampleSelector\nfrom langchain_chroma import Chroma\n\n# Create example selector with semantic similarity\nexample_selector = SemanticSimilarityExampleSelector.from_examples(\n    examples=[\n        {\"input\": \"How do I reset my password?\", \"output\": \"Go to Settings > Security > Reset Password\"},\n        {\"input\": \"Where can I see my order history?\", \"output\": \"Navigate to Account > Orders\"},\n        {\"input\": \"How do I contact support?\", \"output\": \"Click Help > Contact Us or email support@example.com\"},\n    ],\n    embeddings=VoyageAIEmbeddings(model=\"voyage-3-large\"),\n    vectorstore_cls=Chroma,\n    k=2  # Select 2 most similar examples\n)\n\nasync def get_few_shot_prompt(query: str) -> str:\n    \"\"\"Build prompt with dynamically selected examples.\"\"\"\n    examples = await example_selector.aselect_examples({\"input\": query})\n\n    examples_text = \"\\n\".join(\n        f\"User: {ex['input']}\\nAssistant: {ex['output']}\"\n        for ex in examples\n    )\n\n    return f\"\"\"You are a helpful customer support assistant.\n\nHere are some example interactions:\n{examples_text}\n\nNow respond to this query:\nUser: {query}\nAssistant:\"\"\"\n```\n\n### Pattern 4: Progressive Disclosure\n\nStart with simple prompts, add complexity only when needed:\n\n```python\nPROMPT_LEVELS = {\n    # Level 1: Direct instruction\n    \"simple\": \"Summarize this article: {text}\",\n\n    # Level 2: Add constraints\n    \"constrained\": \"\"\"Summarize this article in 3 bullet points, focusing on:\n- Key findings\n- Main conclusions\n- Practical implications\n\nArticle: {text}\"\"\",\n\n    # Level 3: Add reasoning\n    \"reasoning\": \"\"\"Read this article carefully.\n1. First, identify the main topic and thesis\n2. Then, extract the key supporting points\n3. Finally, summarize in 3 bullet points\n\nArticle: {text}\n\nSummary:\"\"\",\n\n    # Level 4: Add examples\n    \"few_shot\": \"\"\"Read articles and provide concise summaries.\n\nExample:\nArticle: \"New research shows that regular exercise can reduce anxiety by up to 40%...\"\nSummary:\n• Regular exercise reduces anxiety by up to 40%\n• 30 minutes of moderate activity 3x\u002Fweek is sufficient\n• Benefits appear within 2 weeks of starting\n\nNow summarize this article:\nArticle: {text}\n\nSummary:\"\"\"\n}\n```\n\n### Pattern 5: Error Recovery and Fallback\n\n```python\nfrom pydantic import BaseModel, ValidationError\nimport json\n\nclass ResponseWithConfidence(BaseModel):\n    answer: str\n    confidence: float\n    sources: list[str]\n    alternative_interpretations: list[str] = []\n\nERROR_RECOVERY_PROMPT = \"\"\"\nAnswer the question based on the context provided.\n\nContext: {context}\nQuestion: {question}\n\nInstructions:\n1. If you can answer confidently (>0.8), provide a direct answer\n2. If you're somewhat confident (0.5-0.8), provide your best answer with caveats\n3. If you're uncertain (\u003C0.5), explain what information is missing\n4. Always provide alternative interpretations if the question is ambiguous\n\nRespond in JSON:\n{{\n    \"answer\": \"your answer or 'I cannot determine this from the context'\",\n    \"confidence\": 0.0-1.0,\n    \"sources\": [\"relevant context excerpts\"],\n    \"alternative_interpretations\": [\"if question is ambiguous\"]\n}}\n\"\"\"\n\nasync def answer_with_fallback(\n    context: str,\n    question: str,\n    llm\n) -> ResponseWithConfidence:\n    \"\"\"Answer with error recovery and fallback.\"\"\"\n    prompt = ERROR_RECOVERY_PROMPT.format(context=context, question=question)\n\n    try:\n        response = await llm.ainvoke(prompt)\n        return ResponseWithConfidence(**json.loads(response.content))\n    except (json.JSONDecodeError, ValidationError) as e:\n        # Fallback: try to extract answer without structure\n        simple_prompt = f\"Based on: {context}\\n\\nAnswer: {question}\"\n        simple_response = await llm.ainvoke(simple_prompt)\n        return ResponseWithConfidence(\n            answer=simple_response.content,\n            confidence=0.5,\n            sources=[\"fallback extraction\"],\n            alternative_interpretations=[]\n        )\n```\n\n### Pattern 6: Role-Based System Prompts\n\n```python\nSYSTEM_PROMPTS = {\n    \"analyst\": \"\"\"You are a senior data analyst with expertise in SQL, Python, and business intelligence.\n\nYour responsibilities:\n- Write efficient, well-documented queries\n- Explain your analysis methodology\n- Highlight key insights and recommendations\n- Flag any data quality concerns\n\nCommunication style:\n- Be precise and technical when discussing methodology\n- Translate technical findings into business impact\n- Use clear visualizations when helpful\"\"\",\n\n    \"assistant\": \"\"\"You are a helpful AI assistant focused on accuracy and clarity.\n\nCore principles:\n- Always cite sources when making factual claims\n- Acknowledge uncertainty rather than guessing\n- Ask clarifying questions when the request is ambiguous\n- Provide step-by-step explanations for complex topics\n\nConstraints:\n- Do not provide medical, legal, or financial advice\n- Redirect harmful requests appropriately\n- Protect user privacy\"\"\",\n\n    \"code_reviewer\": \"\"\"You are a senior software engineer conducting code reviews.\n\nReview criteria:\n- Correctness: Does the code work as intended?\n- Security: Are there any vulnerabilities?\n- Performance: Are there efficiency concerns?\n- Maintainability: Is the code readable and well-structured?\n- Best practices: Does it follow language idioms?\n\nOutput format:\n1. Summary assessment (approve\u002Frequest changes)\n2. Critical issues (must fix)\n3. Suggestions (nice to have)\n4. Positive feedback (what's done well)\"\"\"\n}\n```\n\n## Integration Patterns\n\n### With RAG Systems\n\n```python\nRAG_PROMPT = \"\"\"You are a knowledgeable assistant that answers questions based on provided context.\n\nContext (retrieved from knowledge base):\n{context}\n\nInstructions:\n1. Answer ONLY based on the provided context\n2. If the context doesn't contain the answer, say \"I don't have information about that in my knowledge base\"\n3. Cite specific passages using [1], [2] notation\n4. If the question is ambiguous, ask for clarification\n\nQuestion: {question}\n\nAnswer:\"\"\"\n```\n\n### With Validation and Verification\n\n```python\nVALIDATED_PROMPT = \"\"\"Complete the following task:\n\nTask: {task}\n\nAfter generating your response, verify it meets ALL these criteria:\n✓ Directly addresses the original request\n✓ Contains no factual errors\n✓ Is appropriately detailed (not too brief, not too verbose)\n✓ Uses proper formatting\n✓ Is safe and appropriate\n\nIf verification fails on any criterion, revise before responding.\n\nResponse:\"\"\"\n```\n\n## Performance Optimization\n\n### Token Efficiency\n\n```python\n# Before: Verbose prompt (150+ tokens)\nverbose_prompt = \"\"\"\nI would like you to please take the following text and provide me with a comprehensive\nsummary of the main points. The summary should capture the key ideas and important details\nwhile being concise and easy to understand.\n\"\"\"\n\n# After: Concise prompt (30 tokens)\nconcise_prompt = \"\"\"Summarize the key points concisely:\n\n{text}\n\nSummary:\"\"\"\n```\n\n### Caching Common Prefixes\n\n```python\nfrom anthropic import Anthropic\n\nclient = Anthropic()\n\n# Use prompt caching for repeated system prompts\nresponse = client.messages.create(\n    model=\"claude-sonnet-4-6\",\n    max_tokens=1000,\n    system=[\n        {\n            \"type\": \"text\",\n            \"text\": LONG_SYSTEM_PROMPT,\n            \"cache_control\": {\"type\": \"ephemeral\"}\n        }\n    ],\n    messages=[{\"role\": \"user\", \"content\": user_query}]\n)\n```\n\n## Best Practices\n\n1. **Be Specific**: Vague prompts produce inconsistent results\n2. **Show, Don't Tell**: Examples are more effective than descriptions\n3. **Use Structured Outputs**: Enforce schemas with Pydantic for reliability\n4. **Test Extensively**: Evaluate on diverse, representative inputs\n5. **Iterate Rapidly**: Small changes can have large impacts\n6. **Monitor Performance**: Track metrics in production\n7. **Version Control**: Treat prompts as code with proper versioning\n8. **Document Intent**: Explain why prompts are structured as they are\n\n## Common Pitfalls\n\n- **Over-engineering**: Starting with complex prompts before trying simple ones\n- **Example pollution**: Using examples that don't match the target task\n- **Context overflow**: Exceeding token limits with excessive examples\n- **Ambiguous instructions**: Leaving room for multiple interpretations\n- **Ignoring edge cases**: Not testing on unusual or boundary inputs\n- **No error handling**: Assuming outputs will always be well-formed\n- **Hardcoded values**: Not parameterizing prompts for reuse\n\n## Success Metrics\n\nTrack these KPIs for your prompts:\n\n- **Accuracy**: Correctness of outputs\n- **Consistency**: Reproducibility across similar inputs\n- **Latency**: Response time (P50, P95, P99)\n- **Token Usage**: Average tokens per request\n- **Success Rate**: Percentage of valid, parseable outputs\n- **User Satisfaction**: Ratings and feedback\n",{"name":53,"description":54},"prompt-engineering-patterns","Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability in production. Use when optimizing prompts, improving LLM outputs, or designing production prompt templates.","main","4418944aaff7696bfb2cec18db747ade50817966",".claude\u002Fskills\u002Fecc\u002Fui-demo","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile","2026-11-08 20:29:14",{"source":8,"skillName":53,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add sakamoto-family-smile\u002Fagent_monorepo --skill prompt-engineering-patterns",{"tool":67,"command":68},"bunx","bunx skills add sakamoto-family-smile\u002Fagent_monorepo --skill prompt-engineering-patterns",{"tool":70,"command":71},"pnpm","pnpm dlx skills add sakamoto-family-smile\u002Fagent_monorepo --skill prompt-engineering-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fecc\u002Fui-demo\u002FSKILL.md",true,[75,81,85,91,95,99,103,107],{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"assets\u002Ffew-shot-examples.json","ASSET","资产文件",4174,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Fassets\u002Ffew-shot-examples.json",{"path":82,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":83,"sourceHtmlUrl":84},"assets\u002Fprompt-template-library.md",3291,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Fassets\u002Fprompt-template-library.md",{"path":86,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Fchain-of-thought.md","REFERENCE","参考文档",9401,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fchain-of-thought.md",{"path":92,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Ffew-shot-learning.md",11188,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Ffew-shot-learning.md",{"path":96,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":97,"sourceHtmlUrl":98},"references\u002Fprompt-optimization.md",12792,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fprompt-optimization.md",{"path":100,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fprompt-templates.md",11409,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fprompt-templates.md",{"path":104,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":105,"sourceHtmlUrl":106},"references\u002Fsystem-prompts.md",5444,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fsystem-prompts.md",{"path":108,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":111,"sourceHtmlUrl":112},"scripts\u002Foptimize-prompt.py","SCRIPT","脚本",9159,"https:\u002F\u002Fgithub.com\u002FJsonLee12138\u002Fagent-team\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprompt-engineering-patterns\u002Fscripts\u002Foptimize-prompt.py",[114,144,152,170,192,218],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":124,"publishedAt":48},"01M6RW50THEFSKK42YNR8XFZA1","remotion-video-creation","Best practices for Remotion - Video creation in React. 29 domain-specific rules covering 3D, animations, audio, captions, charts, transitions, and more.","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fecc\u002Fremotion-video-creation\u002FSKILL.md",[120,123],{"categoryNo":121,"categoryName":122,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[44,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143],"remotion video","remotion video creation","creation","Remotion","Charts","Captions","Audio","3D","Composition","Animation","best practices","more","animations","domain-specific","domain","three","Rules","Lottie","for",{"skillNo":145,"name":146,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":48},"01M6VCJ23NPECPSZJKGY691F75","hotcook-recipes","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002Fhotcook-agent\u002Fdata\u002Fskills\u002Fhotcook-recipes\u002FSKILL.md",[],[150,151],"hotcook recipes","recipes",{"skillNo":153,"name":154,"nameZh":6,"description":155,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":164,"publishedAt":48},"01M6VCHHE00X5XHSDRD1KH1BW2","code-helper","Code review and assistance skill","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002Fagent-system-2\u002Fskills\u002Fcode-helper\u002Fskill.md",[158,161],{"categoryNo":159,"categoryName":160,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":162,"categoryName":163,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000030","开发工程师",[165,166,167,168,169],"code helper","helper","code","code review","review",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":182,"publishedAt":48},"01M6VCH3Q31A20H6SQ1H0J7JB2","research-assistant","Web research assistant skill using Brave Search MCP","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002Fagent-system-1\u002Fskills\u002Fresearch-assistant\u002Fskill.md",[176,179],{"categoryNo":177,"categoryName":178,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000021","资料检索与研究",{"categoryNo":180,"categoryName":181,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",[183,184,185,186,47,187,188,189,190,191],"research assistant","research","assistant","MCP","search","brave search","web research","brave","web research assistant",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":202,"publishedAt":48},"01M6VCGZZGPNVJSCZ1JTMNZAHY","x-api","X\u002FTwitter API integration for posting tweets, threads, reading timelines, search, and analytics. Covers OAuth auth patterns, rate limits, and platform-native content posting. Use when the user wants to interact with X programmatically.","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fecc\u002Fx-api\u002FSKILL.md",[198,201],{"categoryNo":199,"categoryName":200,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":162,"categoryName":163,"taxonomyType":25,"taxonomyTypeDesc":26},[203,204,35,32,205,206,143,207,208,209,210,211,212,213,214,39,215,216,187,217],"x api","api","limits","rate","threads","reading","native","posting","platform","patterns","api integration","twitter","auth","analytics","OAuth",{"skillNo":219,"name":220,"nameZh":6,"description":221,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":222,"categories":223,"keywords":225,"publishedAt":48},"01M6VCGVX6DGB1FKTA53QBBCQB","workspace-surface-audit","Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.","https:\u002F\u002Fgithub.com\u002Fsakamoto-family-smile\u002Fagent_monorepo\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fecc\u002Fworkspace-surface-audit\u002FSKILL.md",[224],{"categoryNo":180,"categoryName":181,"taxonomyType":20,"taxonomyTypeDesc":21},[226,227,228,229,186,230,231,167,232,233,234,235,39,236,237,238,239,209,240,32],"workspace surface audit","workspace","audit","hooks","workflows","connectors","capabilities","harness","repo","environment","up","harness setup","active","env","value"]