[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWH9XPF8RNE35PNP40ZS9R":3,"skill-same:01M7BWH9XPF8RNE35PNP40ZS9R":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWH9XPF8RNE35PNP40ZS9R","prompt-engineering-patterns",null,"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.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill prompt-engineering-patterns",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill prompt-engineering-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill prompt-engineering-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002FSKILL.md",true,[47,53,57,63,67,71,75,79],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"assets\u002Ffew-shot-examples.json","ASSET","资产文件",4174,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Fassets\u002Ffew-shot-examples.json",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"assets\u002Fprompt-template-library.md",3291,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Fassets\u002Fprompt-template-library.md",{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Fchain-of-thought.md","REFERENCE","参考文档",9401,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fchain-of-thought.md",{"path":64,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Ffew-shot-learning.md",11188,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Ffew-shot-learning.md",{"path":68,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fprompt-optimization.md",12792,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fprompt-optimization.md",{"path":72,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fprompt-templates.md",11409,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fprompt-templates.md",{"path":76,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fsystem-prompts.md",5444,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Freferences\u002Fsystem-prompts.md",{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"scripts\u002Foptimize-prompt.py","SCRIPT","脚本",9159,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fllm-application-dev\u002Fskills\u002Fprompt-engineering-patterns\u002Fscripts\u002Foptimize-prompt.py",[86,93,100,107,114,121],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]