Training_CPU / pattern_weaving_dataset.jsonl
kirikir13's picture
Upload 55 files
dcc845c verified
Raw History Blame Contribute Delete
116 kB
{"id": "pw-001", "pattern_name": "ReAct (Reasoning + Acting)", "category": "AI Agent Architectures", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "115-200", "description": "Combines reasoning and acting in a loop: the agent generates a Thought (reasoning about what to do), performs an Action (tool execution), and records an Observation (the result), repeating until a final answer is reached or max_iterations is exhausted.", "problem_solved": "Enables agents to break complex problems into manageable steps, interact with external systems via tools, and adapt behavior based on intermediate observations.", "key_components": ["Thought: internal reasoning about the next step", "Action: tool execution via function calling", "Observation: result fed back into the conversation", "Loop: bounded by max_iterations (default 10)", "Tools: OpenAI function-calling schema + handler per tool"], "code_snippet": "class ReActAgent:\n def __init__(self, llm_client, tools):\n self.client = llm_client\n self.tools = tools\n self.max_iterations = 10\n\n def run(self, query):\n thoughts = []\n for i in range(self.max_iterations):\n thought_response = self.client.chat.completions.create(\n model=\"gpt-4\",\n messages=[{\"role\": \"system\", \"content\": self.get_system_prompt()},\n *thoughts, {\"role\": \"user\", \"content\": query}],\n tools=self.tools)\n thought = thought_response.choices[0].message.content\n thoughts.append({\"role\": \"assistant\", \"content\": thought})\n if thought_response.choices[0].finish_reason == \"function_calls\":\n fc = thought_response.choices[0].message.function_calls[0]\n tool_result = self.execute_tool(fc.name, fc.arguments)\n observation = f\"Tool {fc.name} returned: {json.dumps(tool_result)}\"\n thoughts.append({\"role\": \"assistant\", \"content\": observation})\n else:\n break\n return thoughts", "advantages": "Highly adaptive and flexible; efficient for tasks requiring tool interaction and iterative refinement; the Thought/Action/Observation trace is inspectable.", "disadvantages": "Can loop without progress or generate suboptimal thoughts unless carefully prompted; requires robust error handling for tool failures.", "related_patterns": ["Plan-and-Execute", "Tree of Thoughts", "Reflexion", "Function Calling Pattern"], "weaves_with": [["Langroid done_sequences (pw-042)", "same loop-termination concern, solved with a DSL instead of iteration caps"], ["LLM Rate Limiting & Retry (pw-022)", "ReAct loops multiply LLM calls; production ReAct needs rate limiting and retries"], ["CoT with Self-Verification (pw-045)", "the Thought phase is chain-of-thought; verification raises loop quality"]]}
{"id": "pw-002", "pattern_name": "Plan-and-Execute", "category": "AI Agent Architectures", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "202-284", "description": "Separates operation into phases: a planning phase generates a numbered list of steps, an execution phase runs each step (optionally calling tools), and a synthesis phase consolidates results into a final answer.", "problem_solved": "Imposes structure on complex multi-step tasks, reducing the cognitive burden on the LLM during execution by pre-defining the sequence of actions.", "key_components": ["Planning Phase: LLM produces numbered, actionable steps using available tools", "Execution Phase: parse_plan() + execute_step() loop through steps", "Synthesis Phase: separate LLM call consolidates results into the final answer", "Tools: same registry consumed by the planner prompt"], "code_snippet": "class PlanAndExecuteAgent:\n def run(self, query):\n # Phase 1: Planning\n plan_response = self.client.chat.completions.create(\n model=\"gpt-4\",\n messages=[{\"role\": \"system\",\n \"content\": \"You are a planning agent. Break down the user's \"\n \"request into a numbered list of steps...\"},\n {\"role\": \"user\", \"content\": query}],\n tools=self.tools)\n plan_text = plan_response.choices[0].message.content\n steps = self.parse_plan(plan_text)\n # Phase 2: Execution\n results = []\n for step in steps:\n result = self.execute_step(step)\n results.append(result)\n # Phase 3: Synthesis\n synthesis_response = self.client.chat.completions.create(\n model=\"gpt-4\",\n messages=[{\"role\": \"system\", \"content\": \"Synthesize the results into a final answer.\"},\n {\"role\": \"user\", \"content\": query},\n {\"role\": \"assistant\", \"content\": plan_text},\n *[{\"role\": \"assistant\", \"content\": f\"Step {i+1} result: {json.dumps(r)}\"}\n for i, r in enumerate(results)]])\n return synthesis_response.choices[0].message.content", "advantages": "Clear structure for complex tasks; easier to debug and audit; each phase is a separate, inspectable LLM call.", "disadvantages": "Less adaptive if reality deviates from the initial plan; output quality depends heavily on plan completeness.", "related_patterns": ["ReAct", "Tree of Thoughts", "Planner (Core Component)", "Prompt Chaining"], "weaves_with": [["Prompt Chaining (pw-019)", "Plan-and-Execute is a specialized prompt chain with plan/execute/synthesize stages"], ["LLM Caching (pw-022)", "deterministic plan steps are cacheable, cutting cost of repeated runs"], ["Cross-Pollination Engine (pw-036)", "plan quality improves by borrowing workflow shapes from other industries"]]}
{"id": "pw-003", "pattern_name": "Tree of Thoughts (ToT)", "category": "AI Agent Architectures / Reasoning", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "286-368", "description": "Generates multiple candidate reasoning paths (max_branches=5) for a query, evaluates each thought against criteria (clarity, completeness, efficiency), selects the best-scoring thought, and executes it.", "problem_solved": "Improves deliberation quality by considering several approaches instead of committing to the first reasoning path.", "key_components": ["Thought Generation: prompt asks for N different possible paths", "Thought Evaluation: evaluate_thought() scores clarity (+2), completeness (+2), efficiency (+1)", "Thought Selection: max() over evaluation scores", "Thought Execution: extract and run tool calls implied by the chosen thought"], "code_snippet": "class TreeOfThoughtsAgent:\n def __init__(self, llm_client, tools):\n self.client = llm_client\n self.tools = tools\n self.max_depth = 3\n self.max_branches = 5\n\n def run(self, query):\n thoughts_response = self.client.chat.completions.create(\n model=\"gpt-4\",\n messages=[{\"role\": \"system\",\n \"content\": f\"You are a thoughtful agent. Generate \"\n f\"{self.max_branches} different possible \"\n f\"thoughts/paths to answer the query...\"},\n {\"role\": \"user\", \"content\": query}],\n tools=self.tools)\n thoughts = thoughts_response.choices[0].message.content.split('\\n')\n evaluations = [self.evaluate_thought(t, query) for t in thoughts]\n best = max(evaluations, key=lambda x: x)\n best_thought = thoughts[best]\n return self.execute_thought(best_thought)", "advantages": "Robust, higher-quality solutions by exploring a broader solution space; explicit consideration of alternatives.", "disadvantages": "Computationally intensive (one LLM call per candidate plus execution); requires domain-appropriate evaluation criteria.", "related_patterns": ["ReAct", "Reflexion", "Chain-of-Thought with Self-Verification"], "weaves_with": [["Self-Consistency CoT (pw-045)", "same idea at prompt level: sample multiple reasoning chains, vote/verify"], ["Parallel Sampling Best-of-N (pw-024)", "ToT is best-of-N over reasoning paths; llm-tuning makes the sampling policy explicit"], ["Explore-Then-Implement (pw-035)", "obra's alternatives exploration is ToT applied to engineering decisions"]]}
{"id": "pw-004", "pattern_name": "Reflexion", "category": "AI Agent Architectures / Learning & Adaptation", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "370-460", "description": "The agent acts, then reflects on whether the action succeeded. Reflections are stored and injected back into memory; if the reflection says the action failed, the agent retries, otherwise it produces the final answer.", "problem_solved": "Enables self-correction and continuous improvement without retraining, making agents resilient to tool failures.", "key_components": ["Act Phase: generate action via chat.completions with tools", "Reflection Phase: reflect() analyzes action vs result (goal, error, improvement)", "Memory Integration: reflections appended as system-role messages", "Self-Correction: retry loop while 'failed' appears in the reflection"], "code_snippet": "class ReflexionAgent:\n def run(self, query):\n while True:\n action_response = self.client.chat.completions.create(\n model=\"gpt-4\", tools=self.tools,\n messages=[{\"role\": \"system\", \"content\": \"You are a helpful assistant...\"},\n *self.memory, {\"role\": \"user\", \"content\": query}])\n action = action_response.choices[0].message\n self.memory.append({\"role\": \"assistant\", \"content\": action})\n if action_response.choices[0].finish_reason == \"function_calls\":\n fc = action_response.choices[0].message.function_calls[0]\n result = self.execute_tool(fc.name, fc.arguments)\n reflection = self.reflect(action, result)\n self.reflections.append(reflection)\n self.memory.append({\"role\": \"system\", \"content\": f\"Reflection: {reflection}\"})\n if \"failed\" in reflection.lower():\n continue\n # Success - generate final answer ...", "advantages": "Robustness and graceful error recovery; learns from experience within a session.", "disadvantages": "Well-designed reflection prompts are essential; the reflection step adds overhead and latency.", "related_patterns": ["ReAct", "Agent Memory Management", "ReflectionEngine", "Learning from Failures"], "weaves_with": [["Stateful Tool Handler (pw-037)", "Langroid encodes the same retry-with-reflection idea as a max_retries counter per tool handler"], ["Prompt Optimization Loop (pw-049)", "Reflexion at the meta level: the optimizer reflects on failure cases to improve the prompt"], ["Memory Patterns (pw-009)", "reflections only help if memory persists them across episodes"]]}
{"id": "pw-005", "pattern_name": "Agent Memory Management (Short-term, Long-term, Episodic)", "category": "AI Agent Core Components", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "464-536", "description": "Defines how an agent stores and retrieves information: short_term (rolling conversation history capped at 10 messages), long_term (key-value persistent knowledge with access counts), and episodic (timestamped experiences). Retrieval uses keyword matching scored by Jaccard similarity.", "problem_solved": "Makes agents stateful: they recall relevant knowledge, maintain conversation context, and learn from specific episodes.", "key_components": ["Short-term: add_to_short_term() keeps last 10 messages", "Long-term: add_to_long_term() stores value, timestamp, access_count", "Episodic: add_episode() records type, data, timestamp", "Retrieval: retrieve_relevant() with Jaccard-similarity ranking", "Context: get_context() returns recent window for the prompt"], "code_snippet": "class AgentMemory:\n def __init__(self):\n self.short_term = [] # Conversation history\n self.long_term = {} # Persistent knowledge\n self.episodic = [] # Specific episodes/experiences\n\n def add_to_short_term(self, role, content):\n self.short_term.append({\"role\": role, \"content\": content,\n \"timestamp\": datetime.now().isoformat()})\n if len(self.short_term) > 10:\n self.short_term = self.short_term[-10:]\n\n def add_episode(self, episode_type, data):\n self.episodic.append({\"type\": episode_type, \"data\": data,\n \"timestamp\": datetime.now().isoformat()})\n\n def retrieve_relevant(self, query, max_results=5):\n relevant = []\n for key, value in self.long_term.items():\n relevant.append({\"key\": key, \"value\": value[\"value\"],\n \"relevance\": self.calculate_relevance(query, key)})\n relevant.sort(key=lambda x: x[\"relevance\"], reverse=True)\n return relevant[:max_results]", "advantages": "Coherence across long interactions; leverages accumulated knowledge; episodes feed Reflexion-style learning.", "disadvantages": "Keyword/Jaccard retrieval is weak vs semantic search; consistency and retrieval efficiency degrade at scale.", "related_patterns": ["Reflexion", "Memory Patterns (Buffer/Summary/Vector)", "RAG Pipeline"], "weaves_with": [["Vector Memory (pw-009)", "upgrade path: swap Jaccard keyword matching for embeddings"], ["RAG Pipeline (pw-015)", "semantic memory is RAG applied to the agent's own knowledge base"], ["Clone Learning System (pw-027)", "Alfred clones persist per-task learnings the same way episodic memory does"]]}
{"id": "pw-006", "pattern_name": "Planner (Core Component)", "category": "AI Agent Core Components", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "538-628", "description": "A dedicated planning component: create_plan() asks the LLM for a numbered, operation-tagged plan (with constraints and available operations), parse_plan() structures it, and update_plan() renumbers steps after completion or replanning.", "problem_solved": "Bridges high-level goals and concrete tool actions; the explicit plan object can be audited, versioned, and revised.", "key_components": ["Goal Definition and Constraints injected into the system prompt", "Available Operations enumerated for the planner", "Step Generation: numbered 'Operation - Description' lines", "Plan Update: skip completed steps, insert new steps, renumber"], "code_snippet": "class Planner:\n def __init__(self, llm_client):\n self.client = llm_client\n\n def create_plan(self, goal, constraints=None):\n system_prompt = (\"You are a planning agent.\\n\"\n \"Create a detailed plan to achieve the goal: \" + goal + \"\\n\"\n \"Constraints: \" + (constraints or \"None\") + \"\\n\"\n \"Available operations: search, query_database, calculate, api_call\\n\"\n \"Format your plan as:\\n1. [Operation] - [Description]\\n\"\n \"2. [Operation] - [Description]\")\n response = self.client.chat.completions.create(\n model=\"gpt-4\",\n messages=[{\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": goal}])\n return self.parse_plan(response.choices[0].message.content)\n\n def update_plan(self, plan, completed_step, new_step=None):\n # Skip completed step, optionally insert new step, renumber\n ...", "advantages": "Transparent, auditable decision process; plans survive across executor restarts.", "disadvantages": "Plan quality depends on the LLM's planning ability, prompt clarity, and tool descriptions; renumbering logic is fiddly.", "related_patterns": ["Plan-and-Execute", "ReAct", "Prompt Templates with Variables"], "weaves_with": [["Proof Plan Prompt (pw-023)", "llm-tuning found planning-before-tactics lifts proof success β€” same 'plan first' principle"], ["Explore-Then-Implement (pw-035)", "a plan generated from 2-3 compared alternatives beats the first idea plan"], ["Prompt Chaining (pw-019)", "a plan is a prompt chain with explicit step dependencies"]]}
{"id": "pw-007", "pattern_name": "ToolRegistry (Tool Use)", "category": "AI Agent Core Components", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "630-704", "description": "A registry that registers tools with name/handler/description/JSON-schema, executes them by name with validated arguments, and exports the whole catalog as OpenAI function-calling schema.", "problem_solved": "Centralizes tool registration, validation, and execution so agents consume a consistent, safe tool interface.", "key_components": ["register(name, handler, description, parameters)", "execute(name, arguments) with ValueError on unknown tool", "get_openai_schema(): converts registry to function-calling format", "Tool naming conventions: good names are specific and imperative; bad names are vague", "Tool documentation: docstrings double as the LLM-facing description"], "code_snippet": "class ToolRegistry:\n def __init__(self):\n self.tools: Dict[str, Dict] = {}\n\n def register(self, name, handler, description, parameters):\n self.tools[name] = {\"handler\": handler, \"description\": description,\n \"parameters\": parameters}\n\n def execute(self, name, arguments):\n tool = self.get_tool(name)\n if not tool:\n raise ValueError(f\"Tool not found: {name}\")\n return tool[\"handler\"](**arguments)\n\n def get_openai_schema(self):\n return [{\"type\": \"function\",\n \"function\": {\"name\": name, \"description\": tool[\"description\"],\n \"parameters\": tool[\"parameters\"]}}\n for name, tool in self.tools.items()]", "advantages": "Single source of truth for tools; schema validation before execution; easy OpenAI integration.", "disadvantages": "No sandboxing or rate limiting built in β€” pair with Error Handling in Tools (ToolError, safe_tool_execute, validate_tool_arguments).", "related_patterns": ["MCP Tool Integration", "Function Calling Pattern", "Output Validation"], "weaves_with": [["MCP Tool Integration (pw-040)", "MCP externalizes the registry across process boundaries with transport-level wrapping"], ["Layered Architecture (pw-029)", "registry is the agent-side twin of the controller/service/repository layering"], ["FallbackManager (pw-011)", "registry lists primary tools; FallbackManager pairs them with fallbacks"]]}
{"id": "pw-008", "pattern_name": "ReflectionEngine", "category": "AI Agent Core Components", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "706-762", "description": "A reusable component that prompts the LLM to analyze an action/result/context and return a structured reflection (Analysis + Recommendation), then mines reflection history for improvement suggestions.", "problem_solved": "Decouples reflection from the agent loop so any component can request post-hoc analysis of actions.", "key_components": ["reflect_on_action(action, result, context): structured 5-question prompt", "get_improvement_suggestion(recent_reflections): extracts Recommendation lines", "reflection_history: accumulating log of reflections"], "code_snippet": "class ReflectionEngine:\n def reflect_on_action(self, action, result, context):\n reflection_prompt = (\n \"You are a reflection engine. Analyze the following action and result:\\n\"\n f\"Action: {action} Result: {result} Context: {context}\\n\"\n \"Provide a reflection that includes:\\n\"\n \"1. What was the goal of this action? 2. Was the action successful?\\n\"\n \"3. If not successful, what went wrong? 4. How could this be improved?\\n\"\n \"5. Should we try a different approach?\\n\"\n \"Format: Analysis: [...] Recommendation: [...]\"\n )\n response = self.client.chat.completions.create(\n model=\"gpt-4\", messages=[{\"role\": \"user\", \"content\": reflection_prompt}])\n reflection = response.choices[0].message.content\n self.reflection_history.append(reflection)\n return reflection", "advantages": "Separation of concerns; reusable across agents; builds a corpus of reflections.", "disadvantages": "Adds an LLM call per reflection; suggestion extraction is keyword-based and brittle.", "related_patterns": ["Reflexion", "Learning from Failures", "Prompt Optimization Loop"], "weaves_with": [["Prompt Optimization Loop (pw-049)", "ReflectionEngine is the runtime twin of the offline optimizer's failure analysis"], ["LearningAgent (pw-011)", "records failures into patterns; ReflectionEngine explains them"]]}
{"id": "pw-009", "pattern_name": "Memory Patterns (Buffer, Summary, Vector)", "category": "AI Agent Core Components", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1099-1267", "description": "Three production memory strategies: ConversationBuffer (fixed-size rolling window), SummaryMemory (LLM-summarized older messages with a summary key), and VectorMemory (embeddings stored in a vector DB with cached lookups).", "problem_solved": "Manages the context window as a resource: keep recent turns raw, compress history into summaries, and retrieve long-term knowledge by similarity.", "key_components": ["ConversationBuffer: max_messages=20, add/get_recent/clear/get_context_string", "SummaryMemory: add_messages -> create_summary via LLM, keyed by first message", "VectorMemory: add(key, value) -> generate embedding -> store; search(query, top_k)", "Embedding cache to avoid regenerating embeddings"], "code_snippet": "class ConversationBuffer:\n def __init__(self, max_messages=20):\n self.messages = []\n def add(self, role, content):\n self.messages.append({\"role\": role, \"content\": content})\n if len(self.messages) > self.max_messages:\n self.messages = self.messages[-self.max_messages:]\n\nclass SummaryMemory:\n def add_messages(self, messages):\n summary = self.create_summary(messages) # LLM call\n self.summaries[self.generate_key(messages)] = summary\n\nclass VectorMemory:\n def add(self, key: str, value: str, metadata: dict = None):\n embedding = self.generate_embedding(value) # cached when possible\n self.vector_db.insert(embedding=embedding, metadata={\"key\": key, **metadata})\n def search(self, query: str, top_k: int = 5):\n return self.vector_db.search(self.generate_embedding(query), top_k)", "advantages": "Token-efficient context management; summaries preserve long-range meaning; vector memory scales knowledge retrieval.", "disadvantages": "Summary quality depends on the LLM; vector memory needs an embedding model and DB; three systems to keep consistent.", "related_patterns": ["Agent Memory Management", "RAG Pipeline", "Reflexion"], "weaves_with": [["RAG Pipeline (pw-015)", "VectorMemory is RAG retrieval applied to agent memory; identical chunking/tradeoff questions"], ["LLM Caching (pw-022)", "embedding caches and response caches share the same TTL/invalidation reasoning"], ["Token Efficiency (pw-044)", "summary compression is prompt-engineering token efficiency applied to memory"]]}
{"id": "pw-010", "pattern_name": "Multi-Agent Systems (Collaboration, Delegation, Supervisor)", "category": "AI Agent Architectures", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1269-1417", "description": "Three coordination patterns: MultiAgentSystem routes messages between named agents (send_message/broadcast), DelegatingAgent scores and selects the best sub-agent per task, and SupervisorAgent assigns tasks to the lowest-load capable worker and reports status.", "problem_solved": "Lets multiple specialized agents divide labor, route information, and scale throughput beyond a single agent.", "key_components": ["Collaboration: message routing between agents (researcher -> analyzer -> writer)", "Delegation: select_agent() keyword-scoring to pick a specialist", "Supervisor: select_worker() filters by capability then least load; get_status() reporting", "Frameworks: LangChain, AutoGPT, CrewAI (agents + tasks + crew), Semantic Kernel (plugins)"], "code_snippet": "class MultiAgentSystem:\n def send_message(self, from_agent: str, to_agent: str, message: dict):\n self.messages.append({\"from\": from_agent, \"to\": to_agent,\n \"message\": message, \"timestamp\": ...})\n\nclass DelegatingAgent:\n def delegate_task(self, task: str, context: dict):\n agent_name = self.select_agent(task, context) # keyword scoring\n return self.sub_agents[agent_name].run(task, context)\n\nclass SupervisorAgent:\n def assign_task(self, task: dict):\n worker = self.select_worker(task) # capable + lowest load\n return worker.execute(task)", "advantages": "Specialization per sub-task; parallelism; supervisor patterns give load balancing and status reporting.", "disadvantages": "Coordination overhead; message routing must be designed or agents duplicate/conflict; debugging is harder.", "related_patterns": ["Master-Clone Pattern", "Cross-Pollination Engine", "Prompt Chaining"], "weaves_with": [["Master-Clone Pattern (pw-026)", "clones are ephemeral multi-agent workers with a master orchestrator and shared learning store"], ["run_batch_tasks (pw-042)", "batch cloning = multi-agent fan-out with guaranteed state isolation"], ["CrewAI/Semantic Kernel (pw-010)", "framework-level expression of the same delegation pattern"]]}
{"id": "pw-011", "pattern_name": "Error Recovery and Self-Correction", "category": "AI Agent Operations", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1419-1591", "description": "Three resilience patterns: RetryHandler (exponential backoff with jitter, max 3), FallbackManager (primary tool + simpler, more reliable fallback), and LearningAgent (records failures/successes, extracts patterns, recommends fixes from similar past failures).", "problem_solved": "Keeps agents running through transient tool failures, degrades gracefully, and converts failures into institutional knowledge.", "key_components": ["RetryHandler: execute_with_retry with base_delay=1, max_delay=60, jitter", "FallbackManager: register_tool(name, primary, fallback); execute falls back on primary failure", "LearningAgent: record_failure/record_success -> failure_patterns -> get_recommendation by most common error"], "code_snippet": "class RetryHandler:\n def __init__(self, max_retries=3, base_delay=1, max_delay=60): ...\n def execute_with_retry(self, func, *args, **kwargs):\n for attempt in range(self.max_retries + 1):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n if attempt == self.max_retries:\n raise\n delay = min(self.max_delay, self.base_delay * 2 ** attempt)\n time.sleep(delay + random.uniform(0, 0.1 * delay))\n\nclass FallbackManager:\n def execute(self, tool_name, arguments):\n try:\n return self.tools[tool_name][\"primary\"](**arguments)\n except Exception:\n return self.tools[tool_name][\"fallback\"](**arguments)", "advantages": "Graceful degradation; retries absorb transient faults; learning avoids repeating mistakes.", "disadvantages": "Retries add latency; fallbacks may return lower-quality results; pattern extraction is simplistic keyword matching.", "related_patterns": ["Reflexion", "LLM Rate Limiting & Retry", "Stateful Tool Handler"], "weaves_with": [["call_llm_with_retry (pw-022)", "identical exponential-backoff recipe applied to LLM API calls"], ["QueryExecutorAgent (pw-037)", "encodes retry limits in agent state β€” same idea, agent-framework-native"], ["LLMWithFallback (pw-022)", "model-level fallback chain mirrors FallbackManager at the provider level"]]}
{"id": "pw-012", "pattern_name": "Guardrails and Safety (Output Validation, Action Limits, Human-in-the-Loop)", "category": "AI Agent Operations / Safety", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1593-1773", "description": "Three safety layers: OutputValidator (blocks code execution attempts, PII leakage, over-length, non-allowed patterns), ActionLimiter (per-minute and per-hour action quotas), and HumanApprovalFlow (pending approvals with approve/reject and audit records).", "problem_solved": "Constrains agent behavior: validate outputs before they escape, rate-limit actions, and require human sign-off for consequential operations.", "key_components": ["Output Validation: check for code execution, PII, length, allowed patterns", "Action Limits: max 10 actions/minute, 100/hour, 24h log retention", "Human-in-the-Loop: request_approval -> notify -> approve/reject with recorded reasons"], "code_snippet": "class OutputValidator:\n def validate(self, output: str) -> dict:\n # Check for code execution, PII, length, allowed patterns\n return {\"valid\": True, \"issues\": []}\n\nclass ActionLimiter:\n def __init__(self, max_actions_per_minute=10, max_actions_per_hour=100): ...\n def check_limit(self, action_type: str) -> bool:\n # Count actions in the last minute and hour\n ...\n\nclass HumanApprovalFlow:\n def request_approval(self, agent_name: str, action: dict, user_id: str):\n approval_id = str(uuid.uuid4())\n self.pending[approval_id] = {\"agent\": agent_name, \"action\": action, ...}\n # Notify user; wait for approve_action/reject_action\n return approval_id", "advantages": "Defense in depth; audit trail for approvals; quotas stop runaway agents.", "disadvantages": "Validators are rule-based and need domain tuning; approval flows add latency to time-sensitive tasks.", "related_patterns": ["Error Recovery", "Role-Based System Prompts", "Rate Limiting Middleware"], "weaves_with": [["Rate Limiting Middleware (pw-030)", "identical quota pattern enforced at the HTTP layer for backends"], ["System Prompt Constraints (pw-048)", "behavioral rules belong in the prompt; hard limits belong in ActionLimiter β€” use both"], ["Clone Safety Mechanisms (pw-027)", "clone constraints mirror guardrails for autonomous worker instances"]]}
{"id": "pw-013", "pattern_name": "Agent Evaluation and Cost Tracking", "category": "AI Agent Operations / Testing", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1775-1877", "description": "Testing patterns for agents: unit tests with mocked LLM responses verifying tool calls, integration tests running end-to-end workflows, and AgentCostTracker that prices tool calls and LLM calls (prompt/completion tokens) against example GPT-4 pricing.", "problem_solved": "Agents are nondeterministic systems β€” they need dedicated test harnesses and cost telemetry before production.", "key_components": ["Unit Testing: mock chat.completions, assert the right tool was called", "Integration Testing: run the workflow, verify tools called and final answer", "Cost Tracking: track_tool_call + track_llm_call (token pricing), get_total_cost", "Observability: AgentLogger logs thought/action/tool_call/error/completion; AgentDebugger traces and visualizes steps"], "code_snippet": "class AgentCostTracker:\n def track_llm_call(self, prompt_tokens: int, completion_tokens: int):\n # GPT-4 pricing (example)\n cost = (prompt_tokens * 0.03 / 1000 +\n completion_tokens * 0.06 / 1000)\n self.total_cost += cost\n\n def get_total_cost(self):\n return {\"total_cost\": self.total_cost,\n \"tool_calls\": len(self.tool_calls)}\n\nclass AgentLogger:\n def log_tool_call(self, tool_name, arguments, result): ...\n def log_error(self, error: str, context: dict): ...", "advantages": "Nondeterminism made measurable; cost per run becomes a first-class metric; logs enable debugging.", "disadvantages": "Mocked tests can't catch model drift; pricing tables need maintenance; tracing adds I/O overhead.", "related_patterns": ["LLM Evaluation Framework", "Prompt A/B Testing", "Agent Observability"], "weaves_with": [["LLMEvaluator (pw-021)", "agent tests are the pipeline twin of the response-level evaluator"], ["Prompt A/B Testing (pw-020)", "agent behavior changes with prompts β€” A/B belongs at both levels"], ["PromptOptimizer (pw-049)", "the optimizer consumes exactly these metrics to drive refinement"]]}
{"id": "pw-014", "pattern_name": "Production Deployment and Scaling", "category": "AI Agent Operations", "source_file": "ai-agent-patterns/SKILL.md", "source_lines": "1989-2080", "description": "Production readiness for agents: ProductionAgentConfig (LLM settings, agent settings, safety settings, monitoring, performance β€” with validate()), deployment via FastAPI/Docker/Kubernetes, and AgentPool (pre-initialized agent pool, pool_size=5) for throughput.", "problem_solved": "Turns an agent prototype into a scalable, validated, containerized service.", "key_components": ["ProductionAgentConfig: validated config object (required settings, value ranges)", "Deployment Patterns: FastAPI server, Docker, Kubernetes with GPU support", "AgentPool: initialize_pool/get_agent to amortize agent construction", "Scaling strategies: pool warm-up, config validation before deploy"], "code_snippet": "class ProductionAgentConfig:\n def __init__(self):\n # LLM settings / agent settings / safety settings\n # monitoring / performance\n ...\n def validate(self) -> bool:\n # Check for required settings; validate values\n return True\n def get_llm_config(self) -> dict: ...\n\nclass AgentPool:\n def __init__(self, agent_factory, pool_size=5):\n self.agent_factory = agent_factory\n self.pool_size = pool_size\n def initialize_pool(self):\n self.agents = [self.agent_factory() for _ in range(self.pool_size)]\n def get_agent(self) -> object:\n return self.agents.pop() if self.agents else self.agent_factory()", "advantages": "Config validation catches misdeploys; pooling cuts cold-start latency; standard container tooling applies.", "disadvantages": "GPU/Kubernetes adds ops complexity; pool sizing is static; stateful agents complicate pooling.", "related_patterns": ["Layered Architecture", "LLMOps Observability", "Caching Strategy"], "weaves_with": [["Fastify/DI (pw-029)", "the same dependency-injection discipline that makes backends testable makes agents deployable"], ["AgentPool + clone factory (pw-042)", "both pre-fabricate worker instances to avoid per-request construction cost"]]}
{"id": "pw-015", "pattern_name": "RAG Pipeline Architecture", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2386-2553", "description": "End-to-end retrieval-augmented generation: document ingestion with chunking strategies (fixed-size, semantic, recursive, document-aware), embedding and vector DB selection, retrieval strategies (semantic, hybrid with reciprocal rank fusion, multi-query, contextual compression), and generation with citations.", "problem_solved": "Grounds LLM answers in external, current knowledge instead of model memory, with citations for trust.", "key_components": ["1.1 Document Ingestion: chunking strategies + recommended settings", "1.2 Embedding & Storage: vector DB selection, embedding model selection", "1.3 Retrieval: semantic_search, hybrid_search (RRF), multi_query_retrieval, compressed_retrieval", "1.4 Generation: retrieve -> generate -> return with citations"], "code_snippet": "def semantic_search(query: str, top_k: int = 5):\n query_embedding = embed(query)\n return vector_db.search(query_embedding, top_k=top_k)\n\ndef hybrid_search(query: str, top_k: int = 5, alpha: float = 0.5):\n semantic = semantic_search(query, top_k)\n keyword = keyword_search(query, top_k)\n # Reciprocal Rank Fusion\n return rr_fusion(semantic, keyword, alpha)\n\ndef generate_with_rag(question: str):\n context = semantic_search(question)\n prompt = f\"Context: {context}\\n\\nQuestion: {question}\\nAnswer with citations.\"\n return llm.generate(prompt)", "advantages": "Grounded, citable answers; knowledge updates without retraining; retrieval strategy is tunable per domain.", "disadvantages": "Chunking quality gates everything; hybrid search adds latency; retrieval failures silently degrade answers.", "related_patterns": ["Vector Memory", "Few-Shot Dynamic Selection", "RAG Template (prompt-engineering)"], "weaves_with": [["AgentMemory/VectorMemory (pw-005)", "same embeddings + similarity retrieval applied to agent state instead of documents"], ["SemanticExampleSelector (pw-046)", "few-shot example selection is RAG over a prompt library"], ["RAG integration pattern (pw-044)", "prompt-engineering SKILL.md explicitly integrates its templates with RAG systems"]]}
{"id": "pw-016", "pattern_name": "Function Calling Pattern", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2613-2672", "description": "The OpenAI-native tool pattern: define tools as functions with JSON schemas, pass them to the model, and dispatch the returned function calls to handlers. ReAct, Plan-and-Execute, and multi-agent patterns all build on this primitive.", "problem_solved": "The standard interface between LLM reasoning and executable code β€” every agent architecture in this library consumes it.", "key_components": ["Tools as functions with JSON schema definitions", "Model returns function calls with structured arguments", "FunctionCallingAgent.run(): dispatch loop over tool calls", "Shared foundation for ReAct, Plan-and-Execute, AgentTeam"], "code_snippet": "class FunctionCallingAgent:\n def run(self, question: str) -> str:\n response = llm.chat(messages=[...], tools=self.tool_schemas)\n while response.tool_calls:\n results = []\n for tc in response.tool_calls:\n result = self.handlers[tc.name](**tc.arguments)\n results.append({\"tool_call_id\": tc.id, \"output\": result})\n response = llm.chat(messages=messages + results,\n tools=self.tool_schemas)\n return response.content", "advantages": "Native, schema-validated, model-provider-supported; the lingua franca of tool use.", "disadvantages": "Schemas must be maintained; argument hallucination requires validation; vendor-specific format.", "related_patterns": ["ReAct", "ToolRegistry", "MCP Tool Integration"], "weaves_with": [["ToolRegistry (pw-007)", "ToolRegistry.get_openai_schema() is exactly this pattern with a registry front-end"], ["MCP Tool Integration (pw-040)", "MCP moves the same contract across process boundaries with transport management"]]}
{"id": "pw-017", "pattern_name": "Prompt Templates with Variables", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2751-2774", "description": "PromptTemplate holds a template string plus a variable list; format() validates that all variables are provided and fills them; with_examples() appends few-shot examples.", "problem_solved": "Makes prompts reusable, testable artifacts instead of ad-hoc string concatenation.", "key_components": ["Template string + declared variables", "format(**kwargs): raises if a variable is missing", "with_examples(examples): few-shot attachment", "Usage: 'Analyze the sentiment of: {text}' with variables=['text']"], "code_snippet": "class PromptTemplate:\n def __init__(self, template: str, variables: list[str]):\n self.template = template\n self.variables = variables\n\n def format(self, **kwargs) -> str:\n # Validate all variables provided\n missing = set(self.variables) - set(kwargs.keys())\n if missing:\n raise ValueError(f\"Missing variables: {missing}\")\n return self.template.format(**kwargs)\n\n def with_examples(self, examples: list[dict]) -> str:\n example_text = \"\\n\".join(f\"Input: {e['input']}\\nOutput: {e['output']}\"\n for e in examples)\n return f\"{self.template}\\n\\nExamples:\\n{example_text}\"", "advantages": "Reusability, validation before render, composability with examples.", "disadvantages": "Static templates grow brittle; versioning and A/B must be layered on (see Prompt Registry).", "related_patterns": ["Prompt Versioning & A/B Testing", "Template Systems", "Planner"], "weaves_with": [["Template Systems (pw-050)", "the prompt-engineering reference extends this with conditionals, inheritance, caching"], ["Planner (pw-006)", "create_plan's prompt is a template over goal + constraints + operations"], ["Prompt Versioning (pw-018)", "templates need registries to become deployable artifacts"]]}
{"id": "pw-018", "pattern_name": "Prompt Versioning & A/B Testing", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2788-2818", "description": "PromptRegistry stores named, versioned prompts in a database; get() retrieves by version (default latest); ab_test() assigns variants by user for experimentation; record_outcome() logs results per prompt id.", "problem_solved": "Treats prompts as versioned, testable software artifacts with measured outcomes rather than hand-edited strings.", "key_components": ["register(name, template, version)", "get(name, version='latest')", "ab_test(name, user_id): 50/50 variant assignment", "record_outcome(prompt_id, outcome): feeds the experiment log"], "code_snippet": "class PromptRegistry:\n def __init__(self, db):\n self.db = db\n\n def register(self, name: str, template: str, version: str):\n self.db.save_prompt(name, version, template)\n\n def get(self, name: str, version: str = \"latest\") -> str:\n return self.db.get_prompt(name, version)\n\n def ab_test(self, name: str, user_id: str) -> str:\n variant = \"A\" if hash(user_id) % 2 == 0 else \"B\"\n return self.get(f\"{name}:{variant}\")\n\n def record_outcome(self, prompt_id: str, outcome: dict):\n self.db.log_outcome(prompt_id, outcome)", "advantages": "Rollback to known-good prompts; statistically grounded prompt changes; experiment history.", "disadvantages": "Requires DB infrastructure; hashing-based assignment needs consistency checks; outcomes need volume.", "related_patterns": ["Prompt Templates", "Prompt Optimization Loop", "Agent Evaluation"], "weaves_with": [["PromptABTest (pw-049)", "the prompt-engineering optimizer implements the same A/B discipline with significance testing"], ["AgentCostTracker (pw-013)", "A/B outcomes should include cost, not just accuracy"], ["PromptVersionControl (pw-049)", "save_version/rollback/compare β€” file-based variant of the same governance"]]}
{"id": "pw-019", "pattern_name": "Prompt Chaining", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2820-2875", "description": "PromptChain runs a list of steps, each with a prompt template and optional output parser, passing each step's output into the next step's input. Canonical example: Research -> Analyze -> Summarize.", "problem_solved": "Decomposes complex generation into a pipeline of focused, individually testable LLM calls.", "key_components": ["Steps: list of {name, prompt_template, output_parser?}", "run(initial_input): loop steps, parse outputs, feed forward", "Example chain: Research -> Analyze -> Summarize"], "code_snippet": "class PromptChain:\n def __init__(self, steps: list[dict]):\n self.steps = steps\n\n def run(self, initial_input: str) -> dict:\n current = initial_input\n results = {}\n for step in self.steps:\n prompt = step[\"prompt_template\"].format(input=current)\n output = llm.generate(prompt)\n # Parse output if needed\n current = step.get(\"output_parser\", lambda x: x)(output)\n results[step[\"name\"]] = current\n return results", "advantages": "Each step is small and debuggable; intermediate results are inspectable; steps can be reused across chains.", "disadvantages": "Errors compound downstream; latency accumulates per step; parsers are fragile without schemas.", "related_patterns": ["Plan-and-Execute", "Least-to-Most Prompting", "Template Systems"], "weaves_with": [["Plan-and-Execute (pw-002)", "P&E is a chain with a plan-shaped first stage and synthesis-shaped last stage"], ["Least-to-Most (pw-045)", "prompt-level decomposition: solve sub-problems sequentially then integrate"], ["PromptOptimizer (pw-049)", "optimize each chain step separately, then the chain end-to-end"]]}
{"id": "pw-020", "pattern_name": "LLMOps Metrics, Logging & Tracing", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2876-3000", "description": "Operational telemetry for LLM apps: track performance (latency, throughput), quality (relevance, coherence), cost (tokens, per-request), and reliability (error rate) metrics; LLMLogger logs requests/responses with request ids; distributed tracing wraps each LLM call.", "problem_solved": "You cannot operate what you cannot see β€” LLM apps need the same observability discipline as microservices.", "key_components": ["4.1 Metrics: performance / quality / cost / reliability", "4.2 Logging: log_request, log_response keyed by request_id", "4.3 Evaluation: LLMEvaluator scores relevance, coherence, groundedness, accuracy, harmfulness", "Distributed tracing: wrap call sites with span context"], "code_snippet": "class LLMLogger:\n def log_request(self, request_id: str, data: dict):\n self.log.info(\"llm_request\", extra={\"request_id\": request_id, **data})\n def log_response(self, request_id: str, data: dict):\n self.log.info(\"llm_response\", extra={\"request_id\": request_id, **data})\n\n# Distributed tracing\n@trace(\"llm_call\")\ndef call_llm(prompt: str) -> str:\n with tracer.span(\"generate\"):\n return llm.generate(prompt)", "advantages": "Per-request correlation; cost and quality become dashboards; tracing localizes latency.", "disadvantages": "Logging PII requires redaction policy; metric cardinality explodes without discipline.", "related_patterns": ["Agent Evaluation and Cost Tracking", "Agent Observability", "Request Logging Middleware"], "weaves_with": [["AgentLogger/AgentDebugger (pw-013)", "the agent-native twin: logs thoughts/actions/tool calls instead of HTTP requests"], ["Request Logging Middleware (pw-030)", "identical structured-logging pattern at the backend layer (pino)"], ["LLMEvaluator (pw-021)", "metrics only matter if an evaluator defines them"]]}
{"id": "pw-021", "pattern_name": "LLM Evaluation Framework", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "2952-3000", "description": "LLMEvaluator.evaluate_response() scores a response on five axes (relevance, coherence, groundedness, accuracy, harmfulness); run_benchmark() executes test cases and aggregates results.", "problem_solved": "Standardizes how LLM output quality is judged so improvements are measurable rather than vibes.", "key_components": ["Relevance: does it answer the question?", "Coherence: is it well-structured?", "Groundedness: is it based on the provided context?", "Accuracy: does it match ground truth?", "Harmfulness: is it safe?", "run_benchmark(test_cases): aggregate scoring"], "code_snippet": "class LLMEvaluator:\n def evaluate_response(self, response: str, context: str,\n question: str, ground_truth: str = None):\n # Relevance / Coherence / Groundedness / Accuracy / Harmfulness\n return {\"relevance\": score, \"coherence\": score,\n \"groundedness\": score, \"accuracy\": score,\n \"harmfulness\": 0.0}\n\n def run_benchmark(self, test_cases: list[dict]) -> dict:\n results = [self.evaluate_response(**tc) for tc in test_cases]\n return {\"mean_scores\": aggregate(results),\n \"num_cases\": len(test_cases)}", "advantages": "Multi-axis scoring beats single accuracy numbers; benchmark suites enable regression detection.", "disadvantages": "LLM-judged metrics have their own biases; ground truth is often unavailable; harmfulness needs human review.", "related_patterns": ["Agent Evaluation", "Prompt A/B Testing", "Prompt Optimization Loop"], "weaves_with": [["evaluate_prompt_comprehensively (pw-049)", "the optimizer's harness measures accuracy, consistency, success rate β€” same axes"], ["Agent integration tests (pw-013)", "end-to-end agent tests should assert on these evaluator dimensions"]]}
{"id": "pw-022", "pattern_name": "Production LLM Patterns (Caching, Rate Limiting, Fallback)", "category": "LLM Application Patterns", "source_file": "llm-app-patterns/SKILL.md", "source_lines": "3002-3104", "description": "Three production patterns for LLM calls: LLMCache (Redis, TTL=3600, cache key from prompt+model+kwargs, only caches deterministic outputs), RateLimiter (requests-per-minute with timestamp sliding window) plus retry with exponential backoff, and LLMWithFallback (ordered fallback models when the primary fails).", "problem_solved": "Makes LLM calls cheap, bounded, and resilient at production traffic.", "key_components": ["5.1 Caching: get_or_generate with Redis TTL; cache only deterministic outputs", "5.2 Rate Limiting: acquire() sliding window; call_llm_with_retry exponential backoff", "5.3 Fallback: ordered list of models; generate() walks the list on failure", "Architecture Decision Matrix: pattern selection guidance"], "code_snippet": "class LLMCache:\n def get_or_generate(self, prompt: str, model: str, **kwargs) -> str:\n key = self._cache_key(prompt, model, **kwargs)\n if cached := self.redis.get(key):\n return cached\n result = self.llm.generate(prompt, model, **kwargs)\n # Cache (only cache deterministic outputs)\n self.redis.setex(key, self.ttl_seconds, result)\n return result\n\nclass LLMWithFallback:\n def generate(self, prompt: str, **kwargs) -> str:\n for model in [self.primary, *self.fallbacks]:\n try:\n return self.llm.generate(prompt, model=model, **kwargs)\n except Exception:\n continue\n raise AllModelsFailedError()", "advantages": "Caching cuts repeat-traffic cost dramatically; rate limits protect quotas; fallbacks survive provider outages.", "disadvantages": "Non-deterministic outputs (temp>0) poison caches; fallback models change output character; limiter needs thread-safety.", "related_patterns": ["Error Recovery and Self-Correction", "LLMOps Metrics", "Rate Limiting Middleware"], "weaves_with": [["RetryHandler (pw-011)", "the same backoff recipe in the agent layer"], ["Rate Limiting Middleware (pw-030)", "HTTP-layer twin using express-rate-limit + Redis"], ["Caching Common Prefixes (pw-044)", "prompt-engineering's prefix caching is the provider-side version of LLMCache"]]}
{"id": "pw-023", "pattern_name": "Task-Tuned LLM Configuration (Plan-First Proofs)", "category": "LLM Tuning Patterns", "source_file": "llm-tuning-patterns/SKILL.md", "source_lines": "3130-3204", "description": "Evidence-based parameter settings per task type, from APOLLO and Godel-Prover research: theorem proving wants max_tokens=4096, temperature=0.6, top_p=0.95 (proofs need chain-of-thought space and creative tactic exploration); code generation wants 2048 tokens, temperature 0.2-0.4 (deterministic); creative tasks 4096 tokens, temperature 0.8-1.0. Always request a proof plan before tactics. Anti-patterns: 512-token proofs truncate CoT; temperature 0.2 for proofs misses tactic paths; jumping to tactics without a plan reduces success.", "problem_solved": "Configures the model to the task's reasoning structure instead of using one default setting everywhere.", "key_components": ["Theorem Proving: 4096 tokens, temp 0.6, top_p 0.95 + proof plan prompt first", "Code Generation: 2048 tokens, temp 0.2-0.4", "Creative/Exploration: 4096 tokens, temp 0.8-1.0", "Anti-Patterns: too few tokens for proofs, too-cold sampling, no plan"], "code_snippet": "# Theorem proving (APOLLO parity analysis)\n{\"max_tokens\": 4096, \"temperature\": 0.6, \"top_p\": 0.95}\n\n# Proof Plan Prompt - always request a plan before tactics:\n# \"Given the theorem to prove: [statement]\n# First, write a high-level proof plan explaining your approach.\n# Then, suggest Lean 4 tactics to implement each step.\"\n\n# Code generation\n{\"max_tokens\": 2048, \"temperature\": 0.2} # deterministic preferred", "advantages": "Evidence-based; plan-first prompting measurably improves tactic quality; explicit anti-patterns prevent known failures.", "disadvantages": "Findings are domain-specific (Lean proofs, code) and may not transfer; parameters interact with model versions.", "related_patterns": ["Planner", "Parallel Sampling Best-of-N", "Chain-of-Thought"], "weaves_with": [["Planner (pw-006)", "'plan before tactics' is the Planner pattern proven effective in formal reasoning"], ["Self-Consistency (pw-045)", "temperature 0.6-0.8 + N samples is exactly the sampling regime self-consistency assumes"], ["Tree of Thoughts (pw-003)", "ToT's diverse branches need this same 'warm' sampling configuration"]]}
{"id": "pw-024", "pattern_name": "Parallel Sampling / Best-of-N", "category": "LLM Tuning Patterns", "source_file": "llm-tuning-patterns/SKILL.md", "source_lines": "3169-3175", "description": "For hard problems (proofs), generate N=8-32 candidate attempts at temperature 0.6-0.8 and select the best (best-of-N selection).", "problem_solved": "Buys success rate with compute when single-shot quality is insufficient.", "key_components": ["N=8-32 candidate generations", "Temperature 0.6-0.8 per sample", "Best-of-N selection over candidates"], "code_snippet": "# For hard proofs, use parallel sampling:\n# - Generate N=8-32 candidate proof attempts\n# - Use best-of-N selection\n# - Each sample at temperature 0.6-0.8", "advantages": "Large success-rate gains on hard tasks; embarrassingly parallel.", "disadvantages": "Linear cost scaling with N; needs a selection/verification mechanism; wasteful for easy tasks.", "related_patterns": ["Self-Consistency CoT", "Tree of Thoughts", "Task-Tuned LLM Configuration"], "weaves_with": [["Self-Consistency (pw-045)", "majority vote instead of best-of-N scoring β€” same sampling, different selection"], ["ToT (pw-003)", "ToT adds branch evaluation; best-of-N is the degenerate depth-1 case"], ["Verification Step (pw-045)", "best-of-N needs a verifier to pick the best; CoT verification provides it"]]}
{"id": "pw-025", "pattern_name": "Formal Logic Foundations (Expert Skill)", "category": "Reasoning Foundations", "source_file": "mathematical-logic-expert/SKILL.md + modules/core-guidance.md", "source_lines": "3220-3406", "description": "An expert skill covering logical connectives (AND, OR, NOT, implication, biconditional), quantifiers (universal/existential), De Morgan's Laws, and Goedel's First Incompleteness Theorem, with a teaching philosophy and response guidelines for explaining them.", "problem_solved": "Provides the rigorous reasoning substrate that proof planning, verification, and agent logic patterns build on.", "key_components": ["Logical Connectives: truth-functional operators", "Quantifiers: universal and existential", "De Morgan's Laws: negation transformations", "Goedel's First Incompleteness Theorem: limits of formal systems", "Instructions / Response Guidelines / Teaching Philosophy for expert delivery"], "code_snippet": "# Core content structure (concept -> truth rules -> worked examples)\n## De Morgan's Laws\n- ~(P AND Q) == ~P OR ~Q\n- ~(P OR Q) == ~P AND ~Q\n\n## Quantifiers\n- Universal: forall x, P(x)\n- Existential: exists x, P(x)", "advantages": "Grounds reasoning patterns in formal correctness; the reference skill teaches with worked examples.", "disadvantages": "Formal logic coverage is reference material, not an executable pattern; gaps are tracked in known-gaps.md.", "related_patterns": ["Proof Plan Prompt", "CoT with Verification", "Mathematician thinking tool"], "weaves_with": [["Proof Plan Prompt (pw-023)", "tactic suggestions are only as good as the underlying logic competence"], ["Verification Step (pw-045)", "verification is applied De Morgan/quantifier discipline"], ["Mathematician tool (pw-028)", "the neversight toolbox's 'Can I prove this rigorously?' question operationalizes this skill"]]}
{"id": "pw-026", "pattern_name": "Master-Clone Pattern", "category": "Autonomous Worker Patterns", "source_file": "moai-alfred-clone-pattern/SKILL.md + README.md", "source_lines": "3407-3807", "description": "A master agent (Alfred) creates autonomous clone instances for large, parallelizable, domain-general tasks. should_create_clone(task) gates creation (no specialization needed AND meets criteria like large-scale or parallel work); create_clone(task_description, context_scope, learning_enabled) builds a scoped clone that executes autonomously (analyze, plan, backup, apply, validate, handle conflicts, create PR, save learnings).", "problem_solved": "Scales a single agent's capacity by spawning self-directed workers with explicit creation conditions and safety constraints.", "key_components": ["Task Analysis: should_create_clone() decision gate", "Clone Creation: create_clone() with context_scope and learning_enabled", "Autonomous Execution: 8-step workflow (analyze -> ... -> PR -> save learnings)", "Decision Matrix: when to clone vs use a specialist", "Constraints: clones cannot create other clones, limited scope, resource caps"], "code_snippet": "def should_create_clone(task) -> bool:\n # No domain specialization needed AND\n # task is large-scale/parallel/repetitive AND\n # autonomous execution is safe\n return (not task.needs_specialist\n and task.is_parallelizable\n and task.risk_level <= MEDIUM)\n\ndef create_clone(task_description, context_scope=\"full\", learning_enabled=True):\n # Clone executes autonomously:\n # 1. Analyzes current structure 2. Creates migration plan\n # 3. Backs up critical files 4. Applies migration incrementally\n # 5. Validates each step 6. Handles conflicts automatically\n # 7. Creates PR for review 8. Saves learnings to memory\n return CloneInstance(task_description, context_scope, learning_enabled)", "advantages": "Massive parallel throughput; explicit decision criteria; learnings compound across tasks.", "disadvantages": "Only fits domain-general work; clones need resource monitoring; failure recovery must escalate to master.", "related_patterns": ["Multi-Agent Systems", "run_batch_tasks", "AgentPool"], "weaves_with": [["run_batch_tasks (pw-042)", "Langroid's batch cloning is this pattern with per-item state isolation guaranteed by the framework"], ["AgentPool (pw-014)", "pooling pre-fabricates instances; cloning fabricates them per task with learning enabled"], ["LearningAgent (pw-011)", "both persist failure patterns; clones scope learnings per task type"]]}
{"id": "pw-027", "pattern_name": "Clone Learning & Recovery System", "category": "Autonomous Worker Patterns", "source_file": "moai-alfred-clone-pattern/examples.md + reference.md", "source_lines": "3808-4331", "description": "The operational side of clones: save_learning(task_type, learnings) persists structured outcomes; failed clones auto-recover (analyze conflict, apply resolution, save state, escalate to main Alfred on repeated failure); resource-aware clones batch work and adjust batch size from performance monitoring; GitFlow integration keeps clone work in proper branches; @TAG integrity checks and debug commands support troubleshooting.", "problem_solved": "Makes autonomous workers reliable: they learn from every run, recover from failures, respect resources, and stay auditable.", "key_components": ["Learning: save_learning() with per-task-type storage structure", "Recovery: analyze -> auto-resolve -> escalate on repeated failure", "Resource Awareness: create_resource_aware_clone(), batch sizing from performance", "Safety: clone constraints, safety mechanisms, TRUST 5 principles, @TAG system", "Debugging: check clone learnings / verify permissions / check @TAG integrity"], "code_snippet": "def save_learning(task_type: str, learnings: dict):\n # Clone learning storage structure\n memory.append({\n \"task_type\": task_type,\n \"learnings\": learnings, # approach, pitfalls, timings\n \"timestamp\": now(),\n \"success_rate\": compute_rate(task_type)\n })\n\n# Clone failure recovery:\n# 1. Analyze conflict 2. Apply automatic resolution\n# 3. If repeated failure: save state, escalate to main Alfred", "advantages": "Compounding performance; graceful degradation; audit trail via Git + learnings.", "disadvantages": "Learning quality depends on structured storage discipline; recovery paths must be maintained.", "related_patterns": ["Reflexion", "Error Recovery", "Master-Clone Pattern"], "weaves_with": [["Reflexion (pw-004)", "reflection-with-retry is the in-run version of clone learning across runs"], ["LearningAgent (pw-011)", "identical failure-pattern bookkeeping in a single-agent context"]]}
{"id": "pw-028", "pattern_name": "Cross-Domain Thinking Toolbox (25 Professional Mental Models)", "category": "Cross-Domain Thinking", "source_file": "neversight-cross-domain-thinking-toolbox/SKILL.md", "source_lines": "4332-4445", "description": "Borrow thinking tools from 25 professions (Artist, Economist, Engineer, Doctor, Journalist, Scientist, Mathematician, Programmer, Architect, Chess Master, Plumber, Hacker, and more), each with a core question ('What would I find by examining directly?' β€” Plumber; 'What's really happening underneath?' β€” Hacker). Four usage patterns: Problem Diagnosis, Multi-Angle Analysis, Perspective Shift, Practical Application. Includes problem-type-to-tools mapping (debugging -> Doctor/Plumber/Engineer; creativity -> Artist/Entrepreneur/Designer).", "problem_solved": "Breaks single-minded approaches by systematically applying diverse professional perspectives to one problem.", "key_components": ["25 tools, each: profession + core question + best-for", "Problem Diagnosis: type the problem, recommend 2-3 tools, explain fit, give guiding questions", "Multi-Angle Analysis: 3-5 diverse tools -> analyze -> synthesize -> trade-offs", "Perspective Shift: identify current mode, suggest contrasting tools", "Principles: don't give answers directly, guide with questions; combine tools; stay practical"], "code_snippet": "# Usage Pattern 1: Problem Diagnosis\n1. Identify the problem type\n2. Recommend 2-3 most relevant thinking tools\n3. Explain why each tool fits\n4. Provide guiding questions for application\n\n# Problem-type mapping (excerpt)\n# Debugging issues -> Doctor, Plumber, Engineer\n# Need creativity -> Artist, Entrepreneur, Designer\n# Making predictions -> Engineer, Chess Master, Scientist\n# Finding assumptions -> Philosopher, Mathematician, Critic\n# Risk management -> Soldier, Accountant, Engineer", "advantages": "Fast perspective diversification; questions (not answers) preserve user agency; practical problem-type routing.", "disadvantages": "Shallow application per tool; requires judgment to pick tools; not a substitute for domain expertise.", "related_patterns": ["Cross-Pollination Engine", "Explore-Then-Implement", "Multi-Angle Analysis"], "weaves_with": [["Cross-Pollination Engine (pw-036)", "the toolbox supplies the perspectives; the engine supplies the process for borrowing across industries"], ["Explore-Then-Implement (pw-035)", "the Philosopher/Critic tools are the red-flag checks that trigger exploration"], ["Plumber tool (pw-028)", "'examine directly' β€” hands-on investigation is the debugging discipline behind every pattern here"]]}
{"id": "pw-029", "pattern_name": "Layered Architecture (Express / Fastify)", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/SKILL.md", "source_lines": "4554-4751", "description": "Layered server design with framework choice: Express.js (minimalist, helmet/cors/compression/json limits, middleware stack) or Fastify (high performance, schema-typed routes); code organized as UserController -> UserService -> UserRepository so each layer is independently testable.", "problem_solved": "Separates HTTP concerns, business logic, and data access so backends stay testable and replaceable.", "key_components": ["Framework setup: Express middleware chain or Fastify typed routes", "Controller layer: HTTP request/response handling", "Service layer: business logic", "Repository layer: data access", "Best practices + testing patterns per layer"], "code_snippet": "// Express core setup\nconst app = express();\napp.use(helmet());\napp.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(\",\") }));\napp.use(compression());\napp.use(express.json({ limit: \"10mb\" }));\n\n// Layered: Controller -> Service -> Repository\nexport class UserController {\n async createUser(req: Request, res: Response) {\n const user = await this.userService.create(req.body);\n res.status(201).json(ApiResponse.success(user));\n }\n}\nexport class UserService { /* business logic */ }\nexport class UserRepository { /* data access */ }", "advantages": "Independent testability per layer; framework substitution is localized; security middleware is standard.", "disadvantages": "Boilerplate per layer; over-layering slows small services; DI is needed to keep layers decoupled.", "related_patterns": ["Dependency Injection", "Middleware Patterns", "Error Handling"], "weaves_with": [["DI Container (pw-031)", "layers only stay decoupled if dependencies are injected, not imported"], ["AgentLayered thinking (pw-014)", "the same controller/service/repository discipline appears in ProductionAgentConfig + ToolRegistry"], ["Global Error Handler (pw-032)", "layering is what lets one error handler catch everything at the edge"]]}
{"id": "pw-030", "pattern_name": "Middleware Patterns (Auth, Validation, Rate Limiting, Logging)", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/SKILL.md", "source_lines": "4756-4939", "description": "Composable Express middleware: authenticate (JWT verification), authorize(...roles) role checks, validate(schema) Zod validation wired as router.post('/users', validate(createUserSchema), handler), rate limiting (Redis-backed express-rate-limit with separate apiLimiter/authLimiter), and pino-based request logging.", "problem_solved": "Encapsulates cross-cutting concerns as reusable pipeline stages applied to routes.", "key_components": ["Authentication Middleware: verify token, attach user", "Validation Middleware: Zod schema per route, 400 on failure", "Rate Limiting: apiLimiter + authLimiter (Redis store)", "Request Logging: pino structured logs per request"], "code_snippet": "export const validate = (schema: AnyZodObject) => {\n return async (req, res, next) => {\n try {\n await schema.parseAsync(req.body);\n next();\n } catch (error) {\n res.status(400).json({ error: error.errors });\n }\n };\n};\n\nconst createUserSchema = z.object({ email: z.string().email(), /* ... */ });\nrouter.post(\"/users\", validate(createUserSchema), userController.createUser);\n\nexport const apiLimiter = rateLimit({ store: redisStore, windowMs: 60000, max: 100 });", "advantages": "Declarative per-route behavior; validation before handlers run; uniform logging and quotas.", "disadvantages": "Middleware order matters and is easy to get wrong; rate-limit stores need shared infrastructure.", "related_patterns": ["Rate Limiting (LLM)", "Action Limits", "Layered Architecture"], "weaves_with": [["ActionLimiter (pw-012)", "agent guardrails are the agent-side port of rate-limiting middleware"], ["LLM RateLimiter (pw-022)", "identical sliding-window logic applied to LLM API quotas"], ["Validation Middleware + Zod (pw-030)", "same schema-validation-before-execution rule as ToolRegistry.validate_tool_arguments"]]}
{"id": "pw-031", "pattern_name": "Dependency Injection / DI Container", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/references/advanced-patterns.md", "source_lines": "5091-5172", "description": "A hand-rolled Container class: register dependencies by token, resolve with constructor injection and singleton scoping; export a shared container instance.", "problem_solved": "Inverts dependencies so services are constructed with their collaborators β€” enabling unit tests with mocks.", "key_components": ["Container: register/resolve/singleton semantics", "Constructor injection in services", "Shared container instance wired at startup"], "code_snippet": "class Container {\n private services = new Map();\n register(token, factory, options = { singleton: true }) { ... }\n resolve(token) {\n // instantiate with resolved dependencies\n }\n}\nexport const container = new Container();\n\n// constructor injection\nexport class OrderService {\n constructor(private db: Database, private cache: CacheService) {}\n}", "advantages": "Testable units; late binding of implementations; clear ownership of lifetimes.", "disadvantages": "DI indirection complicates stack traces; overuse hides the actual dependency graph.", "related_patterns": ["Layered Architecture", "ToolRegistry", "Testing Patterns"], "weaves_with": [["ToolRegistry (pw-007)", "a registry that resolves handlers by name is a DI container specialized for tools"], ["Agent frameworks (pw-010)", "CrewAI/Semantic Kernel wire agents and plugins via the same inversion"]]}
{"id": "pw-032", "pattern_name": "Error Handling (Custom Errors + Global Handler)", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/SKILL.md", "source_lines": "4940-5043", "description": "A typed error hierarchy (AppError base with ValidationError, NotFoundError, UnauthorizedError, ForbiddenError, ConflictError), an asyncHandler wrapper that routes rejected promises to the error middleware, and a global errorHandler that maps error types to status codes and consistent response shapes.", "problem_solved": "Converts every failure β€” sync, async, expected, unexpected β€” into one typed, loggable response path.", "key_components": ["Custom Error Classes: AppError + typed subclasses with statusCode", "asyncHandler: catches promise rejections for Express", "Global Error Handler: maps AppError subclasses to status codes; 500 + log for unknowns"], "code_snippet": "export class AppError extends Error {\n constructor(message: string, public statusCode: number, public isOperational = true) {\n super(message);\n }\n}\nexport class ValidationError extends AppError { constructor(m) { super(m, 400); } }\nexport class NotFoundError extends AppError { constructor(m) { super(m, 404); } }\n\nexport const asyncHandler = (fn) => (req, res, next) =>\n Promise.resolve(fn(req, res, next)).catch(next);\n\nexport const errorHandler = (err, req, res, next) => {\n if (err instanceof AppError) {\n return res.status(err.statusCode).json(ApiResponse.error(err.message));\n }\n logger.error(err);\n res.status(500).json(ApiResponse.error(\"Internal server error\"));\n};", "advantages": "One code path for all failures; typed errors self-document status codes; operational vs programmer errors distinguished.", "disadvantages": "Requires discipline to always throw typed errors; the catch-all 500 path can mask bugs if logging is weak.", "related_patterns": ["FallbackManager", "RetryHandler", "API Response Format"], "weaves_with": [["FallbackManager (pw-011)", "both translate failures into typed, recoverable paths instead of crashes"], ["OutputValidator (pw-012)", "agent guardrails are the validation-before-escape twin of route validation"]]}
{"id": "pw-033", "pattern_name": "Database Patterns (PostgreSQL Pool, Mongoose, Transactions)", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/references/advanced-patterns.md", "source_lines": "5173-5317", "description": "PostgreSQL with a configured connection Pool (poolConfig with limits, closeDatabase for graceful shutdown), MongoDB with typed Mongoose models (Schema<IUser> -> model), and a Transaction pattern for multi-operation consistency (begin, operations, commit/rollback).", "problem_solved": "Manages connections, typing, and atomicity for data access layers.", "key_components": ["PostgreSQL: Pool with max connections, idle timeouts, closeDatabase()", "MongoDB: Schema<IUser> with typed model exports", "Transactions: OrderService executes multi-step operations atomically"], "code_snippet": "const poolConfig: PoolConfig = {\n max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000,\n};\nexport const pool = new Pool(poolConfig);\nexport const closeDatabase = async () => await pool.end();\n\nconst userSchema = new Schema<IUser>({ email: String, /* ... */ });\nexport const User = model<IUser>(\"User\", userSchema);\n\n// Transaction pattern\nexport class OrderService {\n async createOrder(items) {\n const client = await pool.connect();\n try {\n await client.query(\"BEGIN\");\n // ...operations...\n await client.query(\"COMMIT\");\n } catch (e) {\n await client.query(\"ROLLBACK\");\n throw e;\n } finally {\n client.release();\n }\n }\n}", "advantages": "Connection reuse; compile-time typing; atomic multi-step operations.", "disadvantages": "Pool tuning is workload-specific; transaction scope errors leak locks; Mongoose typing needs maintenance.", "related_patterns": ["Layered Architecture", "Query Executor Agent", "Caching Strategies"], "weaves_with": [["QueryExecutorAgent (pw-037)", "the Langroid pattern adds retry limits and state to exactly this kind of query execution"], ["CacheService (pw-034)", "caches sit in front of these data layers with TTL tradeoffs"]]}
{"id": "pw-034", "pattern_name": "JWT Auth, Caching & API Response Format", "category": "Backend Architecture", "source_file": "nodejs-backend-patterns/references/advanced-patterns.md", "source_lines": "5318-5526", "description": "JWT authentication flow (AuthService issuing/verifying tokens), CacheService with a @Cacheable(ttl) decorator and Redis, and a uniform ApiResponse envelope (success/error with metadata) for every endpoint.", "problem_solved": "Standardizes the three things every API needs: identity, speed, and consistent response shape.", "key_components": ["JWT Authentication: AuthService, token issue/verify, route guards", "CacheService: Redis get/set + @Cacheable(ttl=300) decorator", "API Response Format: ApiResponse envelope for all endpoints"], "code_snippet": "export class CacheService {\n async get(key: string) { return this.redis.get(key); }\n async set(key: string, value: string, ttl: number = 300) {\n await this.redis.setex(key, ttl, value);\n }\n}\n\nexport function Cacheable(ttl: number = 300) {\n return (target, key, descriptor) => {\n const original = descriptor.value;\n descriptor.value = async function (...args) {\n const cacheKey = `${target.constructor.name}:${key}:${JSON.stringify(args)}`;\n if (cached = await this.cache.get(cacheKey)) return cached;\n const result = await original.apply(this, args);\n await this.cache.set(cacheKey, result, ttl);\n return result;\n };\n };\n}\n\nexport class ApiResponse {\n static success(data, meta = {}) { return { success: true, data, meta }; }\n static error(message, code) { return { success: false, error: message, code }; }\n}", "advantages": "Decorator-based caching is transparent to callers; uniform responses simplify clients; JWT is stateless.", "disadvantages": "Redis dependency and TTL tuning; decorator caching hides I/O; response envelope needs client buy-in.", "related_patterns": ["LLM Caching", "Auth Middleware", "Database Patterns"], "weaves_with": [["LLMCache (pw-022)", "identical key+TTL design, different backend call"], ["VectorMemory cache (pw-009)", "embedding caches follow the same 'avoid recomputation' principle"]]}
{"id": "pw-035", "pattern_name": "Explore-Then-Implement (Alternatives Exploration)", "category": "Engineering Decision Patterns", "source_file": "obra-exploring-alternatives/SKILL.md", "source_lines": "5527-5911", "description": "A five-step process before implementing: understand the problem, generate 2-3 alternatives (e.g., manual validation vs Pydantic model vs validator class), compare trade-offs, pick the best, implement. Includes red flags that force exploration ('I'll just...', 'the first approach that comes to mind'), common rationalizations to reject, a verification checklist, and when to stop exploring.", "problem_solved": "Prevents the first idea from being the only idea β€” a discipline layer before any non-trivial implementation.", "key_components": ["Step 1: Understand the Problem (constraints, success criteria)", "Step 2: Generate 2-3 Alternatives (different mechanisms, not variations)", "Step 3: Compare Trade-offs (explicit table: complexity, performance, maintainability)", "Step 4: Pick the Best; Step 5: Implement", "Red Flags: 'just', 'simply', 'obviously' β€” STOP and explore", "If you already implemented the first idea: explore retroactively before extending it"], "code_snippet": "## Quick Exploration Template\n## Problem\n[What needs to be solved + constraints]\n\n## Alternative 1: [Name]\n- How it works / Trade-offs / Best when ...\n\n## Alternative 2: [Name]\n- How it works / Trade-offs / Best when ...\n\n## Decision\n[Chosen alternative + why + rejected alternatives' key weakness]\n\n# Red flags - STOP and explore:\n# - \"I'll just add a flag\" - \"The simplest approach is...\"\n# - \"We don't have time to explore\" - \"This is the obvious solution\"", "advantages": "Cheaper than rewriting; surfaces hidden assumptions; creates an auditable decision record.", "disadvantages": "Over-exploring trivial tasks wastes time; alternatives need genuine diversity; the checklist must be enforced by habit.", "related_patterns": ["Tree of Thoughts", "Cross-Domain Thinking Toolbox", "Planner"], "weaves_with": [["ToT (pw-003)", "explore-then-implement is ToT as an engineering discipline with a fixed 2-3 branch budget"], ["Cross-Pollination Engine (pw-036)", "when your own domain lacks alternatives, borrow them from other industries"], ["PromptOptimizer variations (pw-049)", "the optimizer's generate_variations is explore-then-implement applied to prompts"]]}
{"id": "pw-036", "pattern_name": "Cross-Pollination Engine", "category": "Innovation Patterns", "source_file": "openclaw-cross-pollination-engine/SKILL.md + references/examples.md", "source_lines": "5912-6204", "description": "Systematically borrow solutions from unrelated industries: define the core job stripped of industry context, find who else solves it (Industry Inspiration Library: trust -> banking/healthcare/aviation; engagement -> gaming/fitness; onboarding -> hotels/theme parks; simplicity -> Apple/IKEA), extract principles (not surface features), and translate to your context. Historical examples: resistance wheels -> rollerblades; gaming XP -> Duolingo; hotel concierge -> software onboarding.", "problem_solved": "Generates innovation by transferring proven solutions between domains instead of inventing from scratch.", "key_components": ["Define the core job (strip industry context)", "Find who else solves it (inspiration library by need)", "Extract principles, not features", "Translate to your context (adapt, don't copy)", "Output format: PROBLEM / CORE JOB / FROM industry x2 / SYNTHESIS / NEXT STEP", "Compounds with: jtbd-analyzer, first-principles-decomposer, six-thinking-hats"], "code_snippet": "# The Process\n1. Define the core job (strip away industry context)\n2. Find who else solves it (often surprising industries)\n3. Extract principles (not surface features)\n4. Translate to your context (adapt, don't copy)\n\n# Inspiration library (excerpt)\n# Trust -> Banking, Healthcare, Aviation (verification, credentials, checklists)\n# Engagement-> Gaming, Fitness apps, Streaming (XP, streaks, personalization)\n# Onboarding-> Hotels, Theme parks, Luxury retail (concierge, anticipation)\n# Simplicity-> Apple, IKEA, Google (feature cutting, hidden complexity)", "advantages": "Fast novelty; principles transfer better than features; library gives concrete starting points.", "disadvantages": "Borrowed patterns can misfit culture/context; translation quality depends on principle extraction; risk of metaphor-driven design.", "related_patterns": ["Cross-Domain Thinking Toolbox", "Explore-Then-Implement", "Few-Shot Learning"], "weaves_with": [["Thinking Toolbox (pw-028)", "25 perspectives are the 'who else solves this' step, internalized as professions"], ["Few-shot examples (pw-046)", "cross-pollination is few-shot learning at the civilization scale β€” solutions as examples"], ["Pattern-weaving itself (this dataset)", "the cross-pollination engine is the meta-pattern this whole dataset operationalizes"]]}
{"id": "pw-037", "pattern_name": "Stateful Tool Handler as Agent Method", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/agent-tool-handler-with-state.md", "source_lines": "6482-6645", "description": "Define tool handlers as methods on the agent class itself; the agent's init_state() creates per-run state (e.g., a failure counter) that the handler mutates. QueryExecutorAgent retries failed queries up to max_retries=3, then gives up; APIAgent validates before calling external APIs. State is per-run: batch processing clones the agent so each item gets fresh state with no leakage.", "problem_solved": "Gives tool execution memory and retry policy without global variables β€” state lives on the agent instance.", "key_components": ["ToolMessage subclass defines the tool", "Handler is an agent method: execute_query(self, msg) -> str | DoneTool", "init_state() creates per-run state (failure counters, cached connections)", "Error string returned to LLM = automatic retry; DoneTool = terminate with result", "Batch integration: cloned agent per item, no state leakage"], "code_snippet": "class QueryExecutorAgent(lr.ChatAgent):\n def __init__(self, config, db_connection, max_retries: int = 3):\n super().__init__(config)\n self.db = db_connection\n self.max_retries = max_retries\n\n def init_state(self):\n self.state.update(failure_count=0)\n\n def execute_query(self, msg: QueryTool) -> Union[str, DoneTool]:\n try:\n result = self.db.query(msg.query)\n return DoneTool(content=result) # terminate with result\n except Exception as e:\n self.state.failure_count += 1\n if self.state.failure_count >= self.max_retries:\n return DoneTool(content=\"\") # give up gracefully\n return f\"Query failed: {e}\" # LLM sees error, retries", "advantages": "Retry policy per tool; state is visible and testable; graceful give-up; safe under batching via cloning.", "disadvantages": "Framework-specific (Langroid); handler methods grow large; state must be reset carefully per run.", "related_patterns": ["Reflexion", "RetryHandler", "run_batch_tasks"], "weaves_with": [["Reflexion (pw-004)", "handler-state retry is Reflexion's self-correction compiled into code"], ["RetryHandler (pw-011)", "same backoff idea with an explicit failure counter instead of delays"], ["Clone per item (pw-042)", "the batching section guarantees the no-leakage property clones provide"]]}
{"id": "pw-038", "pattern_name": "Validate Tool Output Against Agent State", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/agent-handler-validation-with-state.md", "source_lines": "6329-6481", "description": "Use done_sequences ('T[ToolName], A') so the agent's handler runs before the task terminates; the handler compares the tool output against reserved content in agent state (e.g., placeholders in the original text that must survive replacement) and returns an error string for retry or DoneTool to finish.", "problem_solved": "Enforces invariants on LLM-generated tool output before it can end the task β€” validation with automatic retry.", "key_components": ["done_sequences: 'T[ToolName], A' β€” specific tool, then agent handles it", "Handler validates output vs agent state (init_state stores the original)", "Error string -> LLM retries automatically; DoneTool -> task terminates successfully", "Reserved content that must be preserved is checked explicitly"], "code_snippet": "class LineEditorAgent(lr.ChatAgent):\n def init_state(self):\n self.state.update(original_text=self._load_original())\n\n def emit_line_replacement(self, msg: LineReplacementTool) -> str | AgentDoneTool:\n # Check if any reserved placeholder in original is missing from replacement\n missing = [p for p in self.state.reserved_placeholders\n if p not in msg.replacement]\n if missing:\n return f\"Error: missing reserved placeholders: {missing}\" # LLM retries\n # Validation passed - terminate task successfully\n return AgentDoneTool(tools=[msg])", "advantages": "LLM cannot end the task with invalid output; retries are automatic; invariants are explicit code.", "disadvantages": "Requires done_sequences wiring; validation logic per tool needs writing; wrong bracket notation is a common mistake.", "related_patterns": ["done_sequences DSL", "Stateful Tool Handler", "Output Validation"], "weaves_with": [["OutputValidator (pw-012)", "agent-level output validation vs this pattern's state-aware validation β€” combine both"], ["done_sequences (pw-039)", "the DSL that makes the handler run pre-termination"]]}
{"id": "pw-039", "pattern_name": "done_sequences DSL (Terminate on Specific Tool)", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/done-sequences-specific-tool.md", "source_lines": "6646-6791", "description": "Configure task termination on a specific tool rather than any tool: 'T[FinalAnswerTool]' exits only when FinalAnswerTool is emitted (SearchTool can run many times without exiting). Two variants (exit on tool vs tool-with-content), complex patterns (sequence of two tools, OR logic, tool AND content), and a documented common mistake: bracket notation specifies the RETURN TYPE, it does not filter which tools trigger exit.", "problem_solved": "Controls exactly when an agent loop ends β€” the framework-level answer to ReAct's termination problem.", "key_components": ["Variant 1: done_sequences=['T[FinalAnswerTool]'] β€” exit only on that tool", "Variant 2: exit on tool AND specific content", "Complex: sequence exit, OR logic over multiple tools", "Common mistake: brackets filter return type, not triggering tools"], "code_snippet": "def create_agent() -> ChatAgent:\n agent = ChatAgent(config)\n agent.enable_message(SearchTool) # usable many times, never exits\n agent.enable_message(FinalAnswerTool) # only this ends the task\n return agent\n\ndef research(question: str) -> str | None:\n task = Task(agent, question,\n done_sequences=[\"T[FinalAnswerTool]\"]) # only exit on this tool\n result = task.run()\n # Agent can use SearchTool multiple times without exiting\n # Task only exits when FinalAnswerTool is emitted", "advantages": "Precise loop termination; search-style tools can repeat freely; return type is type-safe.", "disadvantages": "DSL syntax is subtle; the bracket-mistake is common enough to be documented; over-constraining can deadlock.", "related_patterns": ["Stateful Tool Handler", "Task Return Tool", "ReAct"], "weaves_with": [["ReAct max_iterations (pw-001)", "ReAct bounds the loop with a counter; done_sequences bounds it semantically β€” the better fix"], ["TaskConfig done_if_tool (pw-043)", "the twin pattern for returning the tool object itself"]]}
{"id": "pw-040", "pattern_name": "MCP Tool Integration", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/mcp-tool-integration.md", "source_lines": "6792-6975", "description": "Wrap MCP server tools as Langroid ToolMessages: set up transport, then either enable ALL tools from a server (quick start) or wrap SPECIFIC tools (preferred) as small ToolMessage classes with async handle(); Option 3 adds custom result processing (parse tuples, transform output). A Server Factory pattern (make_transport per call) avoids shared-state issues in concurrent scenarios. Includes a complete file-editor agent example over Claude Code MCP tools.", "problem_solved": "Safely imports external tool servers into an agent with per-tool control and result post-processing.", "key_components": ["Transport setup for the MCP server", "Option 1: enable all tools (fast, coarse)", "Option 2: enable specific tools β€” wrap each as a ToolMessage (preferred)", "Option 3: custom result processing (parse tuples/text, transform)", "Server Factory pattern for concurrency; available Claude Code MCP tools documented"], "code_snippet": "class ReadTool(lr.ToolMessage):\n async def handle_async(self):\n result = await mcp_session.call_tool(\"Read\", self.arguments)\n return result # wrap only the tools you want\n\nclass GrepTool(lr.ToolMessage):\n async def handle_async(self):\n result = await mcp_session.call_tool(\"Grep\", self.arguments)\n # Result may be tuple (text, files) or just text\n if isinstance(result, tuple):\n text, files = result\n return custom_format(text, files)\n return result\n\ndef make_transport():\n # Factory: use when creating tools for concurrent scenarios\n return MCPTransport(server_config)", "advantages": "Least privilege (specific tools preferred); result normalization before the LLM sees output; concurrency-safe factory.", "disadvantages": "Wrapper boilerplate per tool; MCP server availability is a new failure mode; transport lifecycle needs care.", "related_patterns": ["ToolRegistry", "Function Calling Pattern", "Quiet Mode"], "weaves_with": [["ToolRegistry (pw-007)", "MCP is the registry distributed across a transport; the pattern is identical"], ["custom result processing (pw-040)", "the structured-output rule for tool results, applied at the boundary"]]}
{"id": "pw-041", "pattern_name": "Quiet Mode (Suppress Verbose Agent Output)", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/quiet-mode.md", "source_lines": "6976-7067", "description": "Suppress verbose agent output with a quiet_mode context manager (recommended) or a global setting; used in a multi-step workflow pattern that shows progress while silencing per-step chatter; thread-safe β€” once enabled it stays enabled through nesting; documents what gets suppressed and the key Langroid repo files.", "problem_solved": "Keeps multi-step agent workflows readable: progress without drowning the user in intermediate traces.", "key_components": ["Context manager: with quiet_mode(): agent.run() (recommended)", "Global setting alternative", "Multi-Step Workflow with Progress pattern", "Thread safety: nesting keeps quiet enabled"], "code_snippet": "from langroid.utils.output import quiet_mode\n\n# Context manager (recommended)\nwith quiet_mode():\n agent.run(\"analyze this codebase\")\n\n# Multi-step workflow with progress\ndef run_workflow():\n for i, step in enumerate(steps):\n print(f\"[{i+1}/{len(steps)}] {step.name}...\")\n with quiet_mode():\n step.execute()", "advantages": "Readable workflow output; thread-safe nesting; progress reporting stays visible.", "disadvantages": "Suppression hides debugging detail when you need it; global mode can leak across components.", "related_patterns": ["Agent Observability", "Multi-Step Workflow", "MCP Tool Integration"], "weaves_with": [["AgentLogger (pw-013)", "quiet mode for humans, structured logs for machines β€” use both"], ["Streaming output guidance (pw-014)", "production agents want visible progress; quiet mode is the inverse knob"]]}
{"id": "pw-042", "pattern_name": "Batch Processing with run_batch_tasks()", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/run-batch-tasks.md", "source_lines": "7068-7269", "description": "Process many items by cloning the agent per item: run_batch_tasks() for the simple case, run_batch_task_gen() for custom task generation; cloning guarantees fresh state per item (no leakage between items); supports structured output per item (AnswerTool with done_if_tool) and stateful handlers (each query gets a cloned agent with a fresh failure counter).", "problem_solved": "Fan out one agent configuration over N items safely and in parallel.", "key_components": ["run_batch_tasks(agent, tasks): simple case", "run_batch_task_gen(task_gen): custom task generation", "How cloning works: each item gets a cloned agent, fresh state", "Q&A with structured output: AnswerTool + TaskConfig(done_if_tool=True)", "Parameters reference + important notes"], "code_snippet": "def task_gen(i: int) -> Task:\n return Task(agent, f\"Analyze file {files[i]}\")\n\n# Simple case: each item gets a cloned agent - no state leakage between items\nresults = run_batch_tasks(agent, [f\"Analyze {f}\" for f in files])\n\n# With structured output per item\nclass AnswerTool(lr.ToolMessage):\n answer: str\n\n# answers = [\"4\", \"Paris\", \"Jupiter\"] -- each task returns the tool directly", "advantages": "Guaranteed state isolation; parallel throughput; structured per-item results.", "disadvantages": "Clone overhead per item; error handling per item needs design; results order needs tracking.", "related_patterns": ["Master-Clone Pattern", "Stateful Tool Handler", "AgentPool"], "weaves_with": [["Master-Clone (pw-026)", "batch cloning is Alfred's pattern with framework-enforced isolation"], ["AgentPool (pw-014)", "pools avoid construction cost; clones pay it for correctness"], ["QueryExecutorAgent (pw-037)", "the stateful-handler example explicitly documents its batch cloning integration"]]}
{"id": "pw-043", "pattern_name": "Task Return Tool (Bracket Notation + done_if_tool)", "category": "Agent Framework Patterns (Langroid)", "source_file": "patterns/task-return-tool.md", "source_lines": "7270-7496", "description": "Make a task return a specific ToolMessage directly instead of digging through message_history: create TaskConfig(done_if_tool=True), use bracket notation Task(...)[ToolClass] to specify the return type, run the task (returns the tool or None), then access typed fields directly. Documents three common mistakes: forgetting done_if_tool=True, not checking for None, and searching message_history anyway.", "problem_solved": "Type-safe structured results from agent tasks without brittle history parsing.", "key_components": ["TaskConfig(done_if_tool=True): task ends when the tool is emitted", "Bracket notation: Task(...)[EmitPrunedModelTool] sets return type", "Type-safe result: tool or None; check before field access", "Anti-pattern: searching message_history negates the point of bracket notation"], "code_snippet": "# 1. Create TaskConfig with done_if_tool=True\nconfig = TaskConfig(done_if_tool=True)\n# 2. Use bracket notation to specify return type\ntask = Task(agent, prompt, config)[EmitPrunedModelTool]\n# 3. Run task - returns the tool or None\nresult = task.run()\n# 4. Check if tool was emitted\nif result is None:\n ... # agent didn't emit the tool\n# 5. Access tool data directly (type-safe)\ndata = result.model_fields", "advantages": "Typed structured output; no history scraping; explicit None handling forces edge-case thinking.", "disadvantages": "Mistake-prone API (three documented mistakes); requires the agent to reliably emit the tool.", "related_patterns": ["done_sequences DSL", "Stateful Tool Handler", "Structured Output with Pydantic"], "weaves_with": [["Pydantic structured output (pw-044)", "bracket notation is the framework mechanism that enforces the Pydantic contract"], ["done_sequences (pw-039)", "both control termination β€” return-tool also carries the payload out"]]}
{"id": "pw-044", "pattern_name": "Structured Output with Pydantic (+ Error Recovery, Progressive Disclosure)", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/SKILL.md", "source_lines": "7497-7982", "description": "Core prompt-engineering capabilities: few-shot learning, chain-of-thought, structured outputs (Pydantic models as the response schema), prompt optimization, template systems, and system prompt design. Key patterns include structured output with Pydantic (SentimentAnalysis model), CoT with self-verification, few-shot with dynamic example selection, progressive disclosure (4 levels: instruction -> constraints -> reasoning -> examples), error recovery with fallback (ResponseWithConfidence -> retry without structure), role-based system prompts, and token efficiency (150+ tokens -> 30) with prompt prefix caching.", "problem_solved": "Turns free-text prompting into engineered, validated, cost-trimmed components.", "key_components": ["Structured Output: Pydantic schema enforced on the model", "Progressive Disclosure: 4 escalating prompt levels", "Error Recovery: ResponseWithConfidence, fallback to unstructured", "Token Efficiency: verbose 150-token prompt -> 30 tokens; cache common prefixes", "Integration: with RAG systems, with validation and verification"], "code_snippet": "class SentimentAnalysis(BaseModel):\n sentiment: Literal[\"positive\", \"negative\", \"neutral\"]\n confidence: float\n reasoning: str\n\nasync def analyze_sentiment(text: str) -> SentimentAnalysis:\n return await llm.with_structured_output(SentimentAnalysis).ainvoke(\n prompt.format(text=text))\n\n# Error recovery and fallback\nclass ResponseWithConfidence(BaseModel):\n answer: str\n confidence: float\n\n# Progressive disclosure: L1 direct instruction ->\n# L2 +constraints -> L3 +reasoning -> L4 +examples", "advantages": "Validated, typed outputs; escalating complexity on demand; graceful fallback when structure fails.", "disadvantages": "Schema maintenance; fallback path loses structure; progressive disclosure needs judgment on level.", "related_patterns": ["Function Calling Pattern", "Task Return Tool", "Template Systems"], "weaves_with": [["Task Return Tool (pw-043)", "Langroid enforces the same Pydantic contract at the task level"], ["LLMCache (pw-022)", "prefix caching is the provider-side twin of token trimming"], ["RAG integration (pw-015)", "the skill's integration section composes these patterns with RAG retrieval"]]}
{"id": "pw-045", "pattern_name": "Chain-of-Thought Family (Zero-Shot, Self-Consistency, Least-to-Most, ToT, Verification)", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/references/chain-of-thought.md", "source_lines": "8365-8782", "description": "The CoT reference: zero-shot CoT ('Let's think step by step'), few-shot CoT, self-consistency (N=5 samples at temperature 0.7, majority vote), least-to-most prompting (decompose -> solve sub-problems sequentially -> integrate), Tree-of-Thought (generate branches, evaluate, select), CoT with verification (generate -> verify the reasoning -> revise), domain-specific CoT (math, code debugging, logical reasoning), plus performance optimization (ReasoningCache with similarity threshold 0.85, adaptive reasoning depth) and evaluation metrics for reasoning quality.", "problem_solved": "Improves reasoning reliability by externalizing, sampling, verifying, and caching chain-of-thought.", "key_components": ["Zero-Shot CoT: trigger phrase only", "Self-Consistency: n=5 samples, temperature=0.7, majority vote", "Least-to-Most: decompose -> sequential sub-problems -> integrate", "Verification Step: generate answer -> verify reasoning -> revise if needed", "ReasoningCache: reuse reasoning for similar problems (0.85 threshold)", "Adaptive CoT: increase depth only when the solution seems incomplete"], "code_snippet": "def self_consistency_cot(query, n=5, temperature=0.7):\n responses = [llm.generate(cot_prompt(query), temperature=temperature)\n for _ in range(n)]\n answers = [extract_answer(r) for r in responses]\n return majority_vote(answers) # take majority vote\n\ndef cot_with_verification(query):\n reasoning = llm.generate(f\"{query}\\nLet's think step by step:\")\n answer = extract_answer(reasoning)\n verification = llm.generate(f\"Verify this reasoning:\\n{reasoning}\")\n if \"error\" in verification.lower():\n return llm.generate(f\"{query}\\nRevise the flawed reasoning: {reasoning}\")\n return answer", "advantages": "Measurable reasoning gains; verification catches flawed chains; caching cuts repeat cost.", "disadvantages": "N-sample methods multiply cost; cache poisoning on bad reasoning; verification adds a call per answer.", "related_patterns": ["Tree of Thoughts", "Self-Consistency", "Parallel Sampling"], "weaves_with": [["ToT (pw-003)", "the prompt-level ToT here is the same algorithm as the agent-level TreeOfThoughtsAgent"], ["Best-of-N (pw-024)", "self-consistency is best-of-N with majority-vote selection"], ["Reflexion (pw-004)", "verification -> revise is Reflexion at the single-answer scale"]]}
{"id": "pw-046", "pattern_name": "Few-Shot Dynamic Example Selection", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/references/few-shot-learning.md", "source_lines": "8783-9174", "description": "Select few-shot examples dynamically rather than fixing them: semantic similarity (embed query, pick nearest), diversity sampling (k-means cluster centers), difficulty-based selection (linearly increasing difficulty scores), and error-based selection (examples that demonstrate correct handling of known error patterns). Covers example construction (format consistency, input-output alignment, complexity balance), token-budget-aware truncation (TokenAwareSelector, max 1500 tokens), edge-case examples (empty/long/ambiguous/invalid input), evaluation of example quality, A/B testing example sets, and meta-learning selectors trained on (query, example, success) tuples.", "problem_solved": "Makes few-shot prompting adaptive: the examples become a retrieval problem over a curated library.", "key_components": ["SemanticExampleSelector: embedding similarity, k=3", "DiversityExampleSelector: k-means cluster centers", "ProgressiveExampleSelector: linearly increasing difficulty", "ErrorGuidedSelector: examples that fix known error patterns", "TokenAwareSelector: fill a 1500-token budget, truncate examples", "Boundary examples: empty, very long, ambiguous, invalid inputs"], "code_snippet": "class SemanticExampleSelector:\n def __init__(self, examples, model_name='all-MiniLM-L6-v2'):\n self.embeddings = model.encode([e[\"input\"] for e in examples])\n def select(self, query, k=3):\n q = model.encode([query])\n sims = cosine_similarity(q, self.embeddings)[0]\n return top_k(examples, sims, k)\n\nclass TokenAwareSelector:\n def select(self, query, k=5):\n # Start with most relevant examples,\n # include until the 1500-token budget is exhausted", "advantages": "Examples tuned per query; token budget respected; edge cases demonstrated explicitly.", "disadvantages": "Needs an embedding model + curated example library; selection quality gates output quality.", "related_patterns": ["RAG Pipeline", "Prompt Templates", "Cross-Pollination Engine"], "weaves_with": [["RAG (pw-015)", "example selection is retrieval over a prompt library β€” same machinery"], ["PromptTemplate.with_examples (pw-017)", "the template API that consumes selected examples"], ["AdaptiveExampleSelector (pw-046)", "adaptive count + difficulty echoes progressive disclosure (pw-044)"]]}
{"id": "pw-047", "pattern_name": "System Prompt Design (Role-Based + Adaptive)", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/references/system-prompts.md", "source_lines": "10099-10299", "description": "Effective system prompts have a defined structure (identity, capabilities, constraints, output format, examples); a pattern library covers customer support agent, data analyst, and content editor prompts; advanced techniques include dynamic role adaptation (build_adaptive_system_prompt(task_type, difficulty)) and explicit constraint specification; includes testing system prompts against test cases and common pitfalls.", "problem_solved": "The system prompt is the agent's constitution β€” designed, constrained, and tested like code.", "key_components": ["Core structure: identity / capabilities / constraints / output format / examples", "Pattern library: Customer Support, Data Analyst, Content Editor", "Dynamic Role Adaptation: adapt prompt to task type and difficulty", "Constraint Specification: explicit MUST/MUST NOT rules", "Testing: test_system_prompt(system_prompt, test_cases)"], "code_snippet": "def build_adaptive_system_prompt(task_type, difficulty):\n base = ROLE_LIBRARY[task_type]\n if difficulty == \"hard\":\n base += \"\\nFor complex tasks, reason step by step before answering.\"\n if difficulty == \"simple\":\n base += \"\\nAnswer directly and concisely.\"\n return base", "advantages": "Consistent agent behavior; constraints are enforceable; testable like any component.", "disadvantages": "Prompt length costs tokens per call; role libraries need maintenance; adaptation logic needs testing.", "related_patterns": ["Guardrails", "Role-Based Prompts", "Agent Design"], "weaves_with": [["Guardrails (pw-012)", "prompt constraints are the soft layer; ActionLimiter/OutputValidator are the hard layer"], ["Token efficiency (pw-044)", "concise system prompts cut cost on every single call β€” highest-leverage trim target"]]}
{"id": "pw-048", "pattern_name": "Prompt Optimization Loop", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/references/prompt-optimization.md + scripts/optimize-prompt.py", "source_lines": "9175-10584", "description": "A systematic refinement workflow: establish a baseline (establish_baseline over test cases), iterate (PromptOptimizer.optimize: test -> stop if good enough -> analyze failures -> generate refinements -> apply best), A/B test variants with statistical significance, and optimize for tokens (remove redundancy), latency, or accuracy (constraints for failures, examples for edge cases, verification steps). Includes failure categorization (FailureAnalyzer -> generate_fixes), prompt version control (save_version, rollback, compare_versions), and a runnable optimize-prompt.py with parallel test execution, variation generators (add format instruction / step-by-step / verification / conciseness / examples), and Bolt optimization to avoid re-evaluation.", "problem_solved": "Closes the loop: prompts improve through measured iteration, not intuition.", "key_components": ["Baseline: establish_baseline(prompt, test_cases)", "Iterative loop: test -> analyze failures -> refine -> retest (max_iterations=10)", "A/B testing with 50/50 split and significance testing", "Optimization targets: tokens, latency, accuracy", "FailureAnalyzer: categorize_failures -> generate_fixes", "Version control: save_version / rollback / compare_versions"], "code_snippet": "class PromptOptimizer:\n def __init__(self, initial_prompt, test_suite): ...\n def optimize(self, max_iterations=10):\n metrics = self.evaluate(self.current_prompt)\n for i in range(max_iterations):\n if metrics.accuracy >= self.target:\n break\n failures = self.analyze_failures(self.test_results)\n refinements = self.generate_variations(self.current_prompt, metrics)\n best = max(refinements, key=lambda p: self.evaluate(p).accuracy)\n self.current_prompt = best", "advantages": "Measurable improvement; failure-driven fixes; rollback safety; runnable script included.", "disadvantages": "Evaluation harness cost per iteration; variations can overfit the test suite; significance needs volume.", "related_patterns": ["Prompt Versioning & A/B", "LLM Evaluation Framework", "Reflexion"], "weaves_with": [["PromptRegistry A/B (pw-018)", "the registry runs the experiments; the optimizer designs them"], ["Reflexion (pw-004)", "optimization is Reflexion at the artifact level β€” reflect on failures, revise, retry"], ["Explore-Then-Implement (pw-035)", "generate_variations is a 5-branch exploration of prompt space"]]}
{"id": "pw-049", "pattern_name": "Template Systems (Conditional, Modular, Inheritance, Stateful)", "category": "Prompt Engineering Patterns", "source_file": "prompt-engineering-patterns/references/prompt-templates.md", "source_lines": "9609-10098", "description": "A full template architecture: basic PromptTemplate (render with variables), ConditionalTemplate ({{#if}} blocks and {{#each}} loops), ModularTemplate (register components and compose per scenario), template inheritance (child overwrites parent sections), ValidatedTemplate (variable schema with type/range/enum validation), CachedTemplate (render cache keyed on variables), and stateful multi-turn templates (ConversationTemplate, StatefulTemplate with state-dependent rendering).", "problem_solved": "Industrial-strength prompt templating: composition, inheritance, validation, caching, and conversation state.", "key_components": ["Basic render with variables; conditional if/each blocks", "Modular composition: register_component + render(structure)", "Inheritance: child merges over parent sections", "ValidatedTemplate: schema validation before render", "CachedTemplate: cache render results by variable hash", "StatefulTemplate: state_name -> template mapping for multi-step workflows"], "code_snippet": "class ValidatedTemplate:\n def __init__(self, template, schema):\n self.template, self.schema = template, schema\n def validate_vars(self, **kwargs):\n # Type validation / range validation / enum validation\n ...\n def render(self, **kwargs):\n self.validate_vars(**kwargs)\n return self.template.render(**kwargs)\n\nclass StatefulTemplate:\n def set_state(self, **kwargs): self.state = kwargs\n def register_state_template(self, state_name, template): ...\n def render(self):\n return self.templates[self.current_state].render(**self.state)", "advantages": "Reusable, validated, cached prompts; state machines for multi-turn flows.", "disadvantages": "Template engines add a debugging layer; caching invalidation on template edits; inheritance complexity.", "related_patterns": ["Prompt Templates with Variables", "Prompt Chaining", "System Prompt Design"], "weaves_with": [["PromptTemplate (pw-017)", "the llm-app version is the simple case; this reference system is the full architecture"], ["StatefulTemplate (pw-049)", "the multi-turn twin of the agent's ConversationBuffer (pw-009)"]]}
{"id": "pw-050", "pattern_name": "Unity ECS: Systems, Queries, Command Buffers", "category": "Game Development / ECS", "source_file": "unity-ecs-patterns/SKILL.md", "source_lines": "10585-11191", "description": "Unity DOTS/ECS patterns: basic setup (IComponentData structs like Speed/Health/Target, tags, buffers, shared components), systems as ISystem partial structs with [BurstCompile] (recommended over classes), entity queries with filtering, Entity Command Buffers for deferred structural changes (spawn/destroy mid-iteration), and IJobEntity jobs (MoveJob, ParallelSpawnJob) for parallelism.", "problem_solved": "Data-oriented design for game engines: components are data, systems are logic, jobs are parallelism.", "key_components": ["Components: IComponentData structs, IBufferElementData, ISharedComponentData", "Systems: [BurstCompile] partial struct : ISystem (recommended)", "Entity Queries: filter by component presence/value", "Entity Command Buffers: defer structural changes (spawn/destroy) safely", "Jobs: IJobEntity + Native Collections for parallel updates"], "code_snippet": "[BurstCompile]\npublic partial struct MovementSystem : ISystem\n{\n [BurstCompile]\n public void OnUpdate(ref SystemState state)\n {\n foreach (var (transform, speed) in\n SystemAPI.Query<RefRW<LocalTransform>, RefRO<Speed>>())\n {\n transform.ValueRW.Position += speed.ValueRO.Value * dt;\n }\n }\n}\n\n// Entity Command Buffer: defer spawn/destroy during iteration\nvar ecb = commandBufferSystem.CreateCommandBuffer();\necb.AddComponent<DeadTag>(entity);", "advantages": "Cache-friendly data layout; Burst-compiled parallel performance; structural changes made safe via ECBs.", "disadvantages": "Paradigm shift from OOP; debugging data flow is harder; authoring workflow needs baking.", "related_patterns": ["Baking Pattern", "Jobs with Native Collections", "Aspects & Singletons"], "weaves_with": [["Baking (pw-051)", "bridges the MonoBehaviour authoring world into ECS data"], ["AgentPool/batching (pw-042)", "ECS and agent batching share the fan-out-with-isolation instinct: entities are independent data, clones are isolated agents"], ["Struct components (pw-050)", "IComponentData structs are the data-oriented sibling of Pydantic models (pw-044) β€” schema-first design"]]}
{"id": "pw-051", "pattern_name": "Unity ECS: Aspects, Singletons, Baking, Jobs", "category": "Game Development / ECS", "source_file": "unity-ecs-patterns/SKILL.md", "source_lines": "10842-11191", "description": "Advanced ECS patterns: Aspects (readonly partial structs grouping components for reuse across systems), Singleton components (GameConfig, GameState as single-entity data accessed via SystemAPI), Baking (Baker<EnemyAuthoring> converts MonoBehaviour authoring objects into entities at edit-time), and Jobs with Native Collections (Burst-compiled jobs over NativeArray/NativeList with safety checks). Includes performance tips, do's and don'ts.", "problem_solved": "Caps off the ECS pattern set: grouping, global state, authoring pipeline, and parallel data processing.", "key_components": ["Aspect: readonly partial struct CharacterAspect : IAspect", "Singleton: GameConfig/GameState IComponentData accessed via SystemAPI.GetSingleton", "Baking: Baker<TAuthoring> with Authoring MonoBehaviours", "Jobs: IJobEntity with NativeArray/NativeList, [BurstCompile]"], "code_snippet": "// Aspect: grouping components for reuse\npublic readonly partial struct CharacterAspect : IAspect\n{\n public readonly Entity Entity;\n readonly RefRW<LocalTransform> Transform;\n readonly RefRO<Speed> Speed;\n}\n\n// Baking: convert GameObjects to entities\npublic class EnemyAuthoring : MonoBehaviour { public float Speed = 1; }\n\npublic class Baker : Baker<EnemyAuthoring>\n{\n public override void Bake(EnemyAuthoring authoring)\n {\n var entity = GetEntity(TransformUsageFlags.Dynamic);\n AddComponent(entity, new Speed { Value = authoring.Speed });\n }\n}", "advantages": "Aspects reduce duplication; singletons give clean global state; baking automates conversion; jobs scale across cores.", "disadvantages": "Aspect misuse hides data access; singletons can become service locators; bake pipeline must be kept in sync with authoring.", "related_patterns": ["Unity ECS Systems", "Layered Architecture", "DI Container"], "weaves_with": [["DI Container (pw-031)", "aspects and DI both group dependencies β€” one for data, one for services"], ["Baker pipeline (pw-051)", "an authoring->runtime compiler; the same shape as prompt template -> rendered prompt (pw-049)"]]}