@sylix/coworker 2.0.11 → 2.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/dist/commands/slash/config.d.ts.map +1 -1
  2. package/dist/commands/slash/config.js +22 -4
  3. package/dist/commands/slash/config.js.map +1 -1
  4. package/dist/core/CoWorkerAgent.d.ts.map +1 -1
  5. package/dist/core/CoWorkerAgent.js +6 -3
  6. package/dist/core/CoWorkerAgent.js.map +1 -1
  7. package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
  8. package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
  9. package/dist/skills/defaults/ai-ml/rag.md +276 -0
  10. package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
  11. package/dist/skills/defaults/backend-development/api-design.md +285 -0
  12. package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
  13. package/dist/skills/defaults/backend-development/async-python.md +237 -0
  14. package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
  15. package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
  16. package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
  17. package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
  18. package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
  19. package/dist/skills/defaults/backend-development/database-design.md +305 -0
  20. package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
  21. package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
  22. package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
  23. package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
  24. package/dist/skills/defaults/backend-development/fastapi.md +309 -0
  25. package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
  26. package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
  27. package/dist/skills/defaults/backend-development/microservices.md +284 -0
  28. package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
  29. package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
  30. package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
  31. package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
  32. package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
  33. package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
  34. package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
  35. package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
  36. package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
  37. package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
  38. package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
  39. package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
  40. package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
  41. package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
  42. package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
  43. package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
  44. package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
  45. package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
  46. package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
  47. package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
  48. package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
  49. package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
  50. package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
  51. package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
  52. package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
  53. package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
  54. package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
  55. package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
  56. package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
  57. package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
  58. package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
  59. package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
  60. package/dist/skills/defaults/data-engineering/airflow.md +519 -0
  61. package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
  62. package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
  63. package/dist/skills/defaults/data-engineering/dbt.md +556 -0
  64. package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
  65. package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
  66. package/dist/skills/defaults/data-engineering/spark.md +411 -0
  67. package/dist/skills/defaults/database/postgresql.md +202 -0
  68. package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
  69. package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
  70. package/dist/skills/defaults/devops/changelog-automation.md +580 -0
  71. package/dist/skills/defaults/devops/cicd.md +314 -0
  72. package/dist/skills/defaults/devops/cloud.md +263 -0
  73. package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
  74. package/dist/skills/defaults/devops/cost-optimization.md +295 -0
  75. package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
  76. package/dist/skills/defaults/devops/docker.md +281 -0
  77. package/dist/skills/defaults/devops/git-workflows.md +205 -0
  78. package/dist/skills/defaults/devops/github-actions.md +311 -0
  79. package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
  80. package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
  81. package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
  82. package/dist/skills/defaults/devops/kubernetes.md +339 -0
  83. package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
  84. package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
  85. package/dist/skills/defaults/devops/observability.md +243 -0
  86. package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
  87. package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
  88. package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
  89. package/dist/skills/defaults/devops/secrets-management.md +341 -0
  90. package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
  91. package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
  92. package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
  93. package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
  94. package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
  95. package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
  96. package/dist/skills/defaults/frontend/interaction-design.md +327 -0
  97. package/dist/skills/defaults/frontend/javascript.md +311 -0
  98. package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
  99. package/dist/skills/defaults/frontend/react-native-design.md +440 -0
  100. package/dist/skills/defaults/frontend/react.md +345 -0
  101. package/dist/skills/defaults/frontend/responsive-design.md +472 -0
  102. package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
  103. package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
  104. package/dist/skills/defaults/frontend/typescript.md +334 -0
  105. package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
  106. package/dist/skills/defaults/frontend/web-component-design.md +279 -0
  107. package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
  108. package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
  109. package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
  110. package/dist/skills/defaults/kubernetes/gitops.md +280 -0
  111. package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
  112. package/dist/skills/defaults/kubernetes/helm.md +343 -0
  113. package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
  114. package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
  115. package/dist/skills/defaults/kubernetes/manifests.md +330 -0
  116. package/dist/skills/defaults/kubernetes/security.md +337 -0
  117. package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
  118. package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
  119. package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
  120. package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
  121. package/dist/skills/defaults/llm-application/langchain.md +259 -0
  122. package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
  123. package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
  124. package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
  125. package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
  126. package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
  127. package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
  128. package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
  129. package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
  130. package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
  131. package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
  132. package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
  133. package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
  134. package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
  135. package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
  136. package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
  137. package/dist/skills/defaults/security/auditor.md +168 -0
  138. package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
  139. package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
  140. package/dist/skills/defaults/security/mtls-configuration.md +349 -0
  141. package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
  142. package/dist/skills/defaults/security/sast-configuration.md +182 -0
  143. package/dist/skills/defaults/security/security.md +313 -0
  144. package/dist/skills/defaults/security/stride-analysis.md +273 -0
  145. package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
  146. package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
  147. package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
  148. package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
  149. package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
  150. package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
  151. package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
  152. package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
  153. package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
  154. package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
  155. package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
  156. package/dist/skills/defaults/testing/testing.md +332 -0
  157. package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
  158. package/dist/skills/defaults/workflows/track-management.md +592 -0
  159. package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
  160. package/dist/skills/index.d.ts +11 -0
  161. package/dist/skills/index.d.ts.map +1 -0
  162. package/dist/skills/index.js +129 -0
  163. package/dist/skills/index.js.map +1 -0
  164. package/dist/utils/character.js +4 -4
  165. package/dist/utils/character.js.map +1 -1
  166. package/dist/utils/inputbar.d.ts.map +1 -1
  167. package/dist/utils/inputbar.js +7 -0
  168. package/dist/utils/inputbar.js.map +1 -1
  169. package/package.json +1 -1
@@ -0,0 +1,449 @@
1
+ ---
2
+ name: prompt-engineering-patterns
3
+ description: Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability in production
4
+ ---
5
+
6
+ # Prompt Engineering Patterns
7
+
8
+ Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Designing complex prompts for production LLM applications
13
+ - Optimizing prompt performance and consistency
14
+ - Implementing structured reasoning patterns (chain-of-thought, tree-of-thought)
15
+ - Building few-shot learning systems with dynamic example selection
16
+ - Creating reusable prompt templates with variable interpolation
17
+ - Debugging and refining prompts that produce inconsistent outputs
18
+ - Implementing system prompts for specialized AI assistants
19
+ - Using structured outputs (JSON mode) for reliable parsing
20
+
21
+ ## Core Capabilities
22
+
23
+ ### 1. Few-Shot Learning
24
+
25
+ - Example selection strategies (semantic similarity, diversity sampling)
26
+ - Balancing example count with context window constraints
27
+ - Constructing effective demonstrations with input-output pairs
28
+ - Dynamic example retrieval from knowledge bases
29
+ - Handling edge cases through strategic example selection
30
+
31
+ ### 2. Chain-of-Thought Prompting
32
+
33
+ - Step-by-step reasoning elicitation
34
+ - Zero-shot CoT with "Let's think step by step"
35
+ - Few-shot CoT with reasoning traces
36
+ - Self-consistency techniques (sampling multiple reasoning paths)
37
+ - Verification and validation steps
38
+
39
+ ### 3. Structured Outputs
40
+
41
+ - JSON mode for reliable parsing
42
+ - Pydantic schema enforcement
43
+ - Type-safe response handling
44
+ - Error handling for malformed outputs
45
+
46
+ ### 4. Prompt Optimization
47
+
48
+ - Iterative refinement workflows
49
+ - A/B testing prompt variations
50
+ - Measuring prompt performance metrics (accuracy, consistency, latency)
51
+ - Reducing token usage while maintaining quality
52
+ - Handling edge cases and failure modes
53
+
54
+ ### 5. Template Systems
55
+
56
+ - Variable interpolation and formatting
57
+ - Conditional prompt sections
58
+ - Multi-turn conversation templates
59
+ - Role-based prompt composition
60
+ - Modular prompt components
61
+
62
+ ### 6. System Prompt Design
63
+
64
+ - Setting model behavior and constraints
65
+ - Defining output formats and structure
66
+ - Establishing role and expertise
67
+ - Safety guidelines and content policies
68
+ - Context setting and background information
69
+
70
+ ## Quick Start
71
+
72
+ ```python
73
+ from langchain_anthropic import ChatAnthropic
74
+ from langchain_core.prompts import ChatPromptTemplate
75
+ from pydantic import BaseModel, Field
76
+
77
+ class SQLQuery(BaseModel):
78
+ query: str = Field(description="The SQL query")
79
+ explanation: str = Field(description="Brief explanation of what the query does")
80
+ tables_used: list[str] = Field(description="List of tables referenced")
81
+
82
+ llm = ChatAnthropic(model="claude-sonnet-4-6")
83
+ structured_llm = llm.with_structured_output(SQLQuery)
84
+
85
+ prompt = ChatPromptTemplate.from_messages([
86
+ ("system", """You are an expert SQL developer. Generate efficient, secure SQL queries.
87
+ Always use parameterized queries to prevent SQL injection.
88
+ Explain your reasoning briefly."""),
89
+ ("user", "Convert this to SQL: {query}")
90
+ ])
91
+
92
+ chain = prompt | structured_llm
93
+
94
+ result = await chain.ainvoke({
95
+ "query": "Find all users who registered in the last 30 days"
96
+ })
97
+ print(result.query)
98
+ ```
99
+
100
+ ## Key Patterns
101
+
102
+ ### Pattern 1: Structured Output with Pydantic
103
+
104
+ ```python
105
+ from anthropic import Anthropic
106
+ from pydantic import BaseModel, Field
107
+ from typing import Literal
108
+ import json
109
+
110
+ class SentimentAnalysis(BaseModel):
111
+ sentiment: Literal["positive", "negative", "neutral"]
112
+ confidence: float = Field(ge=0, le=1)
113
+ key_phrases: list[str]
114
+ reasoning: str
115
+
116
+ async def analyze_sentiment(text: str) -> SentimentAnalysis:
117
+ client = Anthropic()
118
+
119
+ message = client.messages.create(
120
+ model="claude-sonnet-4-6",
121
+ max_tokens=500,
122
+ messages=[{
123
+ "role": "user",
124
+ "content": f"""Analyze the sentiment of this text.
125
+
126
+ Text: {text}
127
+
128
+ Respond with JSON matching this schema:
129
+ {{
130
+ "sentiment": "positive" | "negative" | "neutral",
131
+ "confidence": 0.0-1.0,
132
+ "key_phrases": ["phrase1", "phrase2"],
133
+ "reasoning": "brief explanation"
134
+ }}"""
135
+ }]
136
+ )
137
+
138
+ return SentimentAnalysis(**json.loads(message.content[0].text))
139
+ ```
140
+
141
+ ### Pattern 2: Chain-of-Thought with Self-Verification
142
+
143
+ ```python
144
+ from langchain_core.prompts import ChatPromptTemplate
145
+
146
+ cot_prompt = ChatPromptTemplate.from_template("""
147
+ Solve this problem step by step.
148
+
149
+ Problem: {problem}
150
+
151
+ Instructions:
152
+ 1. Break down the problem into clear steps
153
+ 2. Work through each step showing your reasoning
154
+ 3. State your final answer
155
+ 4. Verify your answer by checking it against the original problem
156
+
157
+ Format your response as:
158
+ ## Steps
159
+ [Your step-by-step reasoning]
160
+
161
+ ## Answer
162
+ [Your final answer]
163
+
164
+ ## Verification
165
+ [Check that your answer is correct]
166
+ """)
167
+ ```
168
+
169
+ ### Pattern 3: Few-Shot with Dynamic Example Selection
170
+
171
+ ```python
172
+ from langchain_voyageai import VoyageAIEmbeddings
173
+ from langchain_core.example_selectors import SemanticSimilarityExampleSelector
174
+ from langchain_chroma import Chroma
175
+
176
+ example_selector = SemanticSimilarityExampleSelector.from_examples(
177
+ examples=[
178
+ {"input": "How do I reset my password?", "output": "Go to Settings > Security > Reset Password"},
179
+ {"input": "Where can I see my order history?", "output": "Navigate to Account > Orders"},
180
+ {"input": "How do I contact support?", "output": "Click Help > Contact Us or email support@example.com"},
181
+ ],
182
+ embeddings=VoyageAIEmbeddings(model="voyage-3-large"),
183
+ vectorstore_cls=Chroma,
184
+ k=2
185
+ )
186
+
187
+ async def get_few_shot_prompt(query: str) -> str:
188
+ examples = await example_selector.aselect_examples({"input": query})
189
+
190
+ examples_text = "\n".join(
191
+ f"User: {ex['input']}\nAssistant: {ex['output']}"
192
+ for ex in examples
193
+ )
194
+
195
+ return f"""You are a helpful customer support assistant.
196
+
197
+ Here are some example interactions:
198
+ {examples_text}
199
+
200
+ Now respond to this query:
201
+ User: {query}
202
+ Assistant:"""
203
+ ```
204
+
205
+ ### Pattern 4: Progressive Disclosure
206
+
207
+ ```python
208
+ PROMPT_LEVELS = {
209
+ "simple": "Summarize this article: {text}",
210
+
211
+ "constrained": """Summarize this article in 3 bullet points, focusing on:
212
+ - Key findings
213
+ - Main conclusions
214
+ - Practical implications
215
+
216
+ Article: {text}""",
217
+
218
+ "reasoning": """Read this article carefully.
219
+ 1. First, identify the main topic and thesis
220
+ 2. Then, extract the key supporting points
221
+ 3. Finally, summarize in 3 bullet points
222
+
223
+ Article: {text}
224
+
225
+ Summary:""",
226
+
227
+ "few_shot": """Read articles and provide concise summaries.
228
+
229
+ Example:
230
+ Article: "New research shows that regular exercise can reduce anxiety by up to 40%..."
231
+ Summary:
232
+ • Regular exercise reduces anxiety by up to 40%
233
+ • 30 minutes of moderate activity 3x/week is sufficient
234
+ • Benefits appear within 2 weeks of starting
235
+
236
+ Now summarize this article:
237
+ Article: {text}
238
+
239
+ Summary:"""
240
+ }
241
+ ```
242
+
243
+ ### Pattern 5: Error Recovery and Fallback
244
+
245
+ ```python
246
+ from pydantic import BaseModel, ValidationError
247
+ import json
248
+
249
+ class ResponseWithConfidence(BaseModel):
250
+ answer: str
251
+ confidence: float
252
+ sources: list[str]
253
+ alternative_interpretations: list[str] = []
254
+
255
+ ERROR_RECOVERY_PROMPT = """
256
+ Answer the question based on the context provided.
257
+
258
+ Context: {context}
259
+ Question: {question}
260
+
261
+ Instructions:
262
+ 1. If you can answer confidently (>0.8), provide a direct answer
263
+ 2. If you're somewhat confident (0.5-0.8), provide your best answer with caveats
264
+ 3. If you're uncertain (<0.5), explain what information is missing
265
+ 4. Always provide alternative interpretations if the question is ambiguous
266
+
267
+ Respond in JSON:
268
+ {{
269
+ "answer": "your answer or 'I cannot determine this from the context'",
270
+ "confidence": 0.0-1.0,
271
+ "sources": ["relevant context excerpts"],
272
+ "alternative_interpretations": ["if question is ambiguous"]
273
+ }}
274
+ """
275
+
276
+ async def answer_with_fallback(context: str, question: str, llm) -> ResponseWithConfidence:
277
+ prompt = ERROR_RECOVERY_PROMPT.format(context=context, question=question)
278
+
279
+ try:
280
+ response = await llm.ainvoke(prompt)
281
+ return ResponseWithConfidence(**json.loads(response.content))
282
+ except (json.JSONDecodeError, ValidationError) as e:
283
+ simple_prompt = f"Based on: {context}\n\nAnswer: {question}"
284
+ simple_response = await llm.ainvoke(simple_prompt)
285
+ return ResponseWithConfidence(
286
+ answer=simple_response.content,
287
+ confidence=0.5,
288
+ sources=["fallback extraction"],
289
+ alternative_interpretations=[]
290
+ )
291
+ ```
292
+
293
+ ### Pattern 6: Role-Based System Prompts
294
+
295
+ ```python
296
+ SYSTEM_PROMPTS = {
297
+ "analyst": """You are a senior data analyst with expertise in SQL, Python, and business intelligence.
298
+
299
+ Your responsibilities:
300
+ - Write efficient, well-documented queries
301
+ - Explain your analysis methodology
302
+ - Highlight key insights and recommendations
303
+ - Flag any data quality concerns
304
+
305
+ Communication style:
306
+ - Be precise and technical when discussing methodology
307
+ - Translate technical findings into business impact
308
+ - Use clear visualizations when helpful""",
309
+
310
+ "assistant": """You are a helpful AI assistant focused on accuracy and clarity.
311
+
312
+ Core principles:
313
+ - Always cite sources when making factual claims
314
+ - Acknowledge uncertainty rather than guessing
315
+ - Ask clarifying questions when the request is ambiguous
316
+ - Provide step-by-step explanations for complex topics
317
+
318
+ Constraints:
319
+ - Do not provide medical, legal, or financial advice
320
+ - Redirect harmful requests appropriately
321
+ - Protect user privacy""",
322
+
323
+ "code_reviewer": """You are a senior software engineer conducting code reviews.
324
+
325
+ Review criteria:
326
+ - Correctness: Does the code work as intended?
327
+ - Security: Are there any vulnerabilities?
328
+ - Performance: Are there efficiency concerns?
329
+ - Maintainability: Is the code readable and well-structured?
330
+ - Best practices: Does it follow language idioms?
331
+
332
+ Output format:
333
+ 1. Summary assessment (approve/request changes)
334
+ 2. Critical issues (must fix)
335
+ 3. Suggestions (nice to have)
336
+ 4. Positive feedback (what's done well)"""
337
+ }
338
+ ```
339
+
340
+ ## Integration Patterns
341
+
342
+ ### With RAG Systems
343
+
344
+ ```python
345
+ RAG_PROMPT = """You are a knowledgeable assistant that answers questions based on provided context.
346
+
347
+ Context (retrieved from knowledge base):
348
+ {context}
349
+
350
+ Instructions:
351
+ 1. Answer ONLY based on the provided context
352
+ 2. If the context doesn't contain the answer, say "I don't have information about that in my knowledge base"
353
+ 3. Cite specific passages using [1], [2] notation
354
+ 4. If the question is ambiguous, ask for clarification
355
+
356
+ Question: {question}
357
+
358
+ Answer:"""
359
+ ```
360
+
361
+ ### With Validation and Verification
362
+
363
+ ```python
364
+ VALIDATED_PROMPT = """Complete the following task:
365
+
366
+ Task: {task}
367
+
368
+ After generating your response, verify it meets ALL these criteria:
369
+ ✓ Directly addresses the original request
370
+ ✓ Contains no factual errors
371
+ ✓ Is appropriately detailed (not too brief, not too verbose)
372
+ ✓ Uses proper formatting
373
+ ✓ Is safe and appropriate
374
+
375
+ If verification fails on any criterion, revise before responding.
376
+
377
+ Response:"""
378
+ ```
379
+
380
+ ## Performance Optimization
381
+
382
+ ### Token Efficiency
383
+
384
+ ```python
385
+ # Before: Verbose prompt (150+ tokens)
386
+ verbose_prompt = """
387
+ I would like you to please take the following text and provide me with a comprehensive
388
+ summary of the main points. The summary should capture the key ideas and important details
389
+ while being concise and easy to understand.
390
+ """
391
+
392
+ # After: Concise prompt (30 tokens)
393
+ concise_prompt = """Summarize the key points concisely:
394
+
395
+ {text}
396
+
397
+ Summary:"""
398
+ ```
399
+
400
+ ### Caching Common Prefixes
401
+
402
+ ```python
403
+ from anthropic import Anthropic
404
+
405
+ client = Anthropic()
406
+
407
+ response = client.messages.create(
408
+ model="claude-sonnet-4-6",
409
+ max_tokens=1000,
410
+ system=[
411
+ {
412
+ "type": "text",
413
+ "text": LONG_SYSTEM_PROMPT,
414
+ "cache_control": {"type": "ephemeral"}
415
+ }
416
+ ],
417
+ messages=[{"role": "user", "content": user_query}]
418
+ )
419
+ ```
420
+
421
+ ## Best Practices
422
+
423
+ 1. **Be Specific**: Vague prompts produce inconsistent results
424
+ 2. **Show, Don't Tell**: Examples are more effective than descriptions
425
+ 3. **Use Structured Outputs**: Enforce schemas with Pydantic for reliability
426
+ 4. **Test Extensively**: Evaluate on diverse, representative inputs
427
+ 5. **Iterate Rapidly**: Small changes can have large impacts
428
+ 6. **Monitor Performance**: Track metrics in production
429
+ 7. **Version Control**: Treat prompts as code with proper versioning
430
+ 8. **Document Intent**: Explain why prompts are structured as they are
431
+
432
+ ## Common Pitfalls
433
+
434
+ - **Over-engineering**: Starting with complex prompts before trying simple ones
435
+ - **Example pollution**: Using examples that don't match the target task
436
+ - **Context overflow**: Exceeding token limits with excessive examples
437
+ - **Ambiguous instructions**: Leaving room for multiple interpretations
438
+ - **Ignoring edge cases**: Not testing on unusual or boundary inputs
439
+ - **No error handling**: Assuming outputs will always be well-formed
440
+ - **Hardcoded values**: Not parameterizing prompts for reuse
441
+
442
+ ## Success Metrics
443
+
444
+ - **Accuracy**: Correctness of outputs
445
+ - **Consistency**: Reproducibility across similar inputs
446
+ - **Latency**: Response time (P50, P95, P99)
447
+ - **Token Usage**: Average tokens per request
448
+ - **Success Rate**: Percentage of valid, parseable outputs
449
+ - **User Satisfaction**: Ratings and feedback
@@ -0,0 +1,219 @@
1
+ ---
2
+ name: prompt-engineering-patterns
3
+ description: 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.
4
+ ---
5
+
6
+ # Prompt Engineering Patterns
7
+
8
+ Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Designing complex prompts for production LLM applications
13
+ - Optimizing prompt performance and consistency
14
+ - Implementing structured reasoning patterns (chain-of-thought, tree-of-thought)
15
+ - Building few-shot learning systems with dynamic example selection
16
+ - Creating reusable prompt templates with variable interpolation
17
+ - Debugging and refining prompts that produce inconsistent outputs
18
+ - Implementing system prompts for specialized AI assistants
19
+ - Using structured outputs (JSON mode) for reliable parsing
20
+
21
+ ## Core Capabilities
22
+
23
+ ### 1. Few-Shot Learning
24
+
25
+ - Example selection strategies (semantic similarity, diversity sampling)
26
+ - Balancing example count with context window constraints
27
+ - Constructing effective demonstrations with input-output pairs
28
+ - Dynamic example retrieval from knowledge bases
29
+ - Handling edge cases through strategic example selection
30
+
31
+ ### 2. Chain-of-Thought Prompting
32
+
33
+ - Step-by-step reasoning elicitation
34
+ - Zero-shot CoT with "Let's think step by step"
35
+ - Few-shot CoT with reasoning traces
36
+ - Self-consistency techniques (sampling multiple reasoning paths)
37
+ - Verification and validation steps
38
+
39
+ ### 3. Structured Outputs
40
+
41
+ - JSON mode for reliable parsing
42
+ - Pydantic schema enforcement
43
+ - Type-safe response handling
44
+ - Error handling for malformed outputs
45
+
46
+ ### 4. Prompt Optimization
47
+
48
+ - Iterative refinement workflows
49
+ - A/B testing prompt variations
50
+ - Measuring prompt performance metrics (accuracy, consistency, latency)
51
+ - Reducing token usage while maintaining quality
52
+ - Handling edge cases and failure modes
53
+
54
+ ### 5. Template Systems
55
+
56
+ - Variable interpolation and formatting
57
+ - Conditional prompt sections
58
+ - Multi-turn conversation templates
59
+ - Role-based prompt composition
60
+ - Modular prompt components
61
+
62
+ ### 6. System Prompt Design
63
+
64
+ - Setting model behavior and constraints
65
+ - Defining output formats and structure
66
+ - Establishing role and expertise
67
+ - Safety guidelines and content policies
68
+ - Context setting and background information
69
+
70
+ ## Quick Start
71
+
72
+ ```python
73
+ from langchain_anthropic import ChatAnthropic
74
+ from langchain_core.prompts import ChatPromptTemplate
75
+ from pydantic import BaseModel, Field
76
+
77
+ class SQLQuery(BaseModel):
78
+ query: str = Field(description="The SQL query")
79
+ explanation: str = Field(description="Brief explanation of what the query does")
80
+ tables_used: list[str] = Field(description="List of tables referenced")
81
+
82
+ llm = ChatAnthropic(model="claude-sonnet-4-6")
83
+ structured_llm = llm.with_structured_output(SQLQuery)
84
+
85
+ prompt = ChatPromptTemplate.from_messages([
86
+ ("system", """You are an expert SQL developer. Generate efficient, secure SQL queries.
87
+ Always use parameterized queries to prevent SQL injection.
88
+ Explain your reasoning briefly."""),
89
+ ("user", "Convert this SQL: {query}")
90
+ ])
91
+
92
+ chain = prompt | structured_llm
93
+
94
+ result = await chain.ainvoke({
95
+ "query": "Find all users who registered in the last 30 days"
96
+ })
97
+ ```
98
+
99
+ ## Key Patterns
100
+
101
+ ### Pattern 1: Structured Output with Pydantic
102
+
103
+ ```python
104
+ from anthropic import Anthropic
105
+ from pydantic import BaseModel, Field
106
+ from typing import Literal
107
+ import json
108
+
109
+ class SentimentAnalysis(BaseModel):
110
+ sentiment: Literal["positive", "negative", "neutral"]
111
+ confidence: float = Field(ge=0, le=1)
112
+ key_phrases: list[str]
113
+ reasoning: str
114
+
115
+ async def analyze_sentiment(text: str) -> SentimentAnalysis:
116
+ client = Anthropic()
117
+ message = client.messages.create(
118
+ model="claude-sonnet-4-6",
119
+ max_tokens=500,
120
+ messages=[{
121
+ "role": "user",
122
+ "content": f"""Analyze sentiment of: {text}
123
+ Respond with JSON:
124
+ {{
125
+ "sentiment": "positive" | "negative" | "neutral",
126
+ "confidence": 0.0-1.0,
127
+ "key_phrases": ["phrase1"],
128
+ "reasoning": "explanation"
129
+ }}"""
130
+ }]
131
+ )
132
+ return SentimentAnalysis(**json.loads(message.content[0].text))
133
+ ```
134
+
135
+ ### Pattern 2: Chain-of-Thought with Self-Verification
136
+
137
+ ```python
138
+ cot_prompt = """
139
+ Solve this problem step by step.
140
+
141
+ Problem: {problem}
142
+
143
+ Instructions:
144
+ 1. Break down into clear steps
145
+ 2. Work through each step showing reasoning
146
+ 3. State final answer
147
+ 4. Verify by checking against original problem
148
+
149
+ Format:
150
+ ## Steps
151
+ [reasoning]
152
+
153
+ ## Answer
154
+ [final answer]
155
+
156
+ ## Verification
157
+ [check correctness]
158
+ """
159
+ ```
160
+
161
+ ### Pattern 3: Few-Shot with Dynamic Example Selection
162
+
163
+ ```python
164
+ from langchain_voyageai import VoyageAIEmbeddings
165
+ from langchain_core.example_selectors import SemanticSimilarityExampleSelector
166
+
167
+ example_selector = SemanticSimilarityExampleSelector.from_examples(
168
+ examples=[
169
+ {"input": "How do I reset password?", "output": "Settings > Security > Reset Password"},
170
+ {"input": "Where is my order?", "output": "Account > Orders"},
171
+ ],
172
+ embeddings=VoyageAIEmbeddings(model="voyage-3-large"),
173
+ vectorstore_cls=Chroma,
174
+ k=2
175
+ )
176
+ ```
177
+
178
+ ### Pattern 4: Progressive Disclosure
179
+
180
+ ```python
181
+ PROMPT_LEVELS = {
182
+ "simple": "Summarize: {text}",
183
+ "constrained": "Summarize in 3 bullets: {text}",
184
+ "reasoning": "Read carefully, identify thesis, summarize: {text}",
185
+ "few_shot": """Example: Article: "Research shows exercise reduces anxiety..."
186
+ Summary: • Reduces anxiety up to 40%\n• 30 min 3x/week sufficient\n• Benefits within 2 weeks
187
+
188
+ Now: {text}"""
189
+ }
190
+ ```
191
+
192
+ ### Pattern 5: Error Recovery and Fallback
193
+
194
+ ```python
195
+ ERROR_RECOVERY_PROMPT = """
196
+ Answer based on context.
197
+
198
+ Context: {context}
199
+ Question: {question}
200
+
201
+ Instructions:
202
+ 1. Confident (>0.8): direct answer
203
+ 2. Somewhat (0.5-0.8): best answer with caveats
204
+ 3. Uncertain (<0.5): explain missing info
205
+
206
+ JSON response:
207
+ {{"answer": "...", "confidence": 0.0-1.0, "sources": []}}
208
+ """
209
+ ```
210
+
211
+ ## Best Practices
212
+
213
+ 1. **Use structured outputs** - Pydantic schemas for reliable parsing
214
+ 2. **Implement chain-of-thought** - For complex reasoning tasks
215
+ 3. **Few-shot with examples** - But limit to 3-5 to save tokens
216
+ 4. **Iterate and test** - A/B test prompt variations
217
+ 5. **Handle failures gracefully** - Parse errors, fallbacks
218
+ 6. **Token budgeting** - Balance quality vs context length
219
+ 7. **System prompts matter** - Set behavior explicitly