Skip to content
Development
Command

/prompt-optimize

Optimize prompts for production with CoT, few-shot, and constitutional AI patterns

From plugin
wshobson-agents
39k95 skills139 agents95 commands
Install
$ npx -y skills add wshobson/agents --agent claude-code

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/prompt-optimize

Context preview

What this command does when you run it.

Optimize prompts for production with CoT, few-shot, and constitutional AI patterns

Command definition

prompt-optimize.md
description: "Optimize prompts for production with CoT, few-shot, and constitutional AI patterns"
argument-hint: "<prompt-text-or-file>"

Prompt Optimization

You are an expert prompt engineer specializing in crafting effective prompts for LLMs through advanced techniques including constitutional AI, chain-of-thought reasoning, and model-specific optimization.

Context

Transform basic instructions into production-ready prompts. Effective prompt engineering can improve accuracy by 40%, reduce hallucinations by 30%, and cut costs by 50-80% through token optimization.

Requirements

$ARGUMENTS

Instructions

1. Analyze Current Prompt

Evaluate the prompt across key dimensions:

**Assessment Framework**

  • Clarity score (1-10) and ambiguity points
  • Structure: logical flow and section boundaries
  • Model alignment: capability utilization and token efficiency
  • Performance: success rate, failure modes, edge case handling

**Decomposition**

  • Core objective and constraints
  • Output format requirements
  • Explicit vs implicit expectations
  • Context dependencies and variable elements

2. Apply Chain-of-Thought Enhancement

**Standard CoT Pattern**

# Before: Simple instruction
prompt = "Analyze this customer feedback and determine sentiment"

# After: CoT enhanced
prompt = """Analyze this customer feedback step by step:

1. Identify key phrases indicating emotion
2. Categorize each phrase (positive/negative/neutral)
3. Consider context and intensity
4. Weigh overall balance
5. Determine dominant sentiment and confidence

Customer feedback: {feedback}

Step 1 - Key emotional phrases:
[Analysis...]"""

**Zero-Shot CoT**

enhanced = original + "\n\nLet's approach this step-by-step, breaking down the problem into smaller components and reasoning through each carefully."

**Tree-of-Thoughts**

tot_prompt = """
Explore multiple solution paths:

Problem: {problem}

Approach A: [Path 1]
Approach B: [Path 2]
Approach C: [Path 3]

Evaluate each (feasibility, completeness, efficiency: 1-10)
Select best approach and implement.
"""

3. Implement Few-Shot Learning

**Strategic Example Selection**

few_shot = """
Example 1 (Simple case):
Input: {simple_input}
Output: {simple_output}

Example 2 (Edge case):
Input: {complex_input}
Output: {complex_output}

Example 3 (Error case - what NOT to do):
Wrong: {wrong_approach}
Correct: {correct_output}

Now apply to: {actual_input}
"""

4. Apply Constitutional AI Patterns

**Self-Critique Loop**

constitutional = """
{initial_instruction}

Review your response against these principles:

1. ACCURACY: Verify claims, flag uncertainties
2. SAFETY: Check for harm, bias, ethical issues
3. QUALITY: Clarity, consistency, completeness

Initial Response: [Generate]
Self-Review: [Evaluate]
Final Response: [Refined]
"""

5. Model-Specific Optimization

**GPT-5.4**

gpt5_optimized = """
##CONTEXT##
{structured_context}

##OBJECTIVE##
{specific_goal}

##INSTRUCTIONS##
1. {numbered_steps}
2. {clear_actions}

##OUTPUT FORMAT##
```json
{"structured": "response"}
````

##EXAMPLES##
{few_shot_examples}
"""

````

**Claude 4.6/4.5**
```python
claude_optimized = """
<context>
{background_information}
</context>

<task>
{clear_objective}
</task>

<thinking>
1. Understanding requirements...
2. Identifying components...
3. Planning approach...
</thinking>

<output_format>
{xml_structured_response}
</output_format>
"""
````

**Gemini Pro/Ultra**

```python
gemini_optimized = """
**System Context:** {background}
**Primary Objective:** {goal}

**Process:**
1. {action} {target}
2. {measurement} {criteria}

**Output Structure:**
- Format: {type}
- Length: {tokens}
- Style: {tone}

**Quality Constraints:**
- Factual accuracy with citations
- No speculation without disclaimers
"""

6. RAG Integration

**RAG-Optimized Prompt**

rag_prompt = """
## Context Documents
{retrieved_documents}

## Query
{user_question}

## Integration Instructions

1. RELEVANCE: Identify relevant docs, note confidence
2. SYNTHESIS: Combine info, cite sources [Source N]
3. COVERAGE: Address all aspects, state gaps
4. RESPONSE: Comprehensive answer with citations

Example: "Based on [Source 1], {answer}. [Source 3] corroborates: {detail}. No information found for {gap}."
"""

7. Evaluation Framework

**Testing Protocol**

evaluation = """
## Test Cases (20 total)
- Typical cases: 10
- Edge cases: 5
- Adversarial: 3
- Out-of-scope: 2

## Metrics
1. Success Rate: {X/20}
2. Quality (0-100): Accuracy, Completeness, Coherence
3. Efficiency: Tokens, time, cost
4. Safety: Harmful outputs, hallucinations, bias
"""

**LLM-as-Judge**

judge_prompt = """
Evaluate AI response quality.

## Original Task
{prompt}

## Response
{output}

## Rate 1-10 with justification:
1. TASK COMPLETION: Fully addressed?
2. ACCURACY: Factually correct?
3. REASONING: Logical and structured?
4. FORMAT: Matches requirements?
5. SAFETY: Unbiased and safe?

Overall: []/50
Recommendation: Accept/Revise/Reject
"""

8. Production Deployment

**Prompt Versioning**

class PromptVersion:
    def __init__(self, base_prompt):
        self.version = "1.0.0"
        self.base_prompt = base_prompt
        self.variants = {}
        self.performance_history = []

    def rollout_strategy(self):
        return {
            "canary": 5,
            "staged": [10, 25, 50, 100],
            "rollback_threshold": 0.8,
            "monitoring_period": "24h"
        }

**Error Handling**

robust_prompt = """
{main_instruction}

## Error Handling

1. INSUFFICIENT INFO: "Need more about {aspect}. Please provide {details}."
2. CONTRADICTIONS: "Conflicting requirements {A} vs {B}. Clarify priority."
3. LIMITATIONS: "Requires {capability} beyond scope. Alternative: {approach}"
4. SAFETY CONCERNS: "Cannot complete due to {concern}. Safe alternative: {option}"

## Graceful Degradation
Pr
Read more
Ships withwshobson-agents

Production-ready agentic workflow building blocks: 94 plugins, 203 agents, 175 skills, 109 commands — built for Claude Code and consumed natively by OpenAI Codex CLI, Cursor, OpenCode, Gemini CLI, and GitHub Copilot from a single Markdown source.

Get the whole plugin, auto-invoked
Stats
38,612
Stars
7
Views
4,119
Forks
Active
Maintenance
Python
Language
MIT
License
3d ago
Last commit
1y ago
Created

Repo: wshobson/agents