> ## Documentation Index
> Fetch the complete documentation index at: https://docs.greenflash.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Prompt Optimization & Management

> Complete guide to recording, analyzing, managing, and optimizing prompts with Greenflash

Greenflash provides a comprehensive platform for managing and optimizing AI prompts based on real user interactions. This guide covers everything from basic prompt structure to advanced optimization strategies.

## Understanding Prompts in Greenflash

### Simple String Format (Quick Start)

The easiest way to get started with Greenflash is to submit your system prompt as a simple string:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
await greenflash.messages.log({
  conversationId: "conv_123",
  productId: "your_product_id",
  systemPrompt: "You are a helpful customer service assistant. Always be professional and empathetic.",
  messages: [
    { role: "user", content: "How do I reset my password?" },
    { role: "assistant", content: "I'll help you reset your password..." }
  ]
});
```

This simple format:

* ✅ Automatically tracks and versions your prompts
* ✅ Links prompts to conversation outcomes
* ✅ Generates optimization suggestions
* ✅ Provides performance analytics
* ❌ Can't use template variables or dynamic content
* ❌ Can't use component-level optimization

**Perfect for:** Teams wanting to start analyzing and optimizing prompts immediately without any structural changes.

### Advanced: Prompt Components

For more control and features, prompts in Greenflash can be built from **components** - modular pieces that can be combined, versioned, and optimized independently:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const systemPrompt = {
  components: [
    {
      type: "system",
      content: "You are a helpful customer service assistant.",
      name: "base_personality"
    },
    {
      type: "system",
      content: "Always be professional and empathetic.",
      name: "tone_guidelines"
    },
    {
      type: "rag",
      content: "Context: [Retrieved documents will be inserted here]",
      isDynamic: true,
      name: "rag_context"
    }
  ]
};
```

**Component Types:**

* `system` - Core instructions and behavior guidelines
* `user` - User-provided context or instructions
* `tool` - Tool outputs and function call results
* `guardrail` - Safety checks and content moderation rules
* `rag` - Retrieval-augmented generation context
* `agent` - Agent tool outputs and observations
* `other` - Custom or miscellaneous component types

### Templates and Variables

Greenflash supports variable interpolation using Handlebars-style syntax (`{{variableName}}`), allowing you to create reusable templates:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Define a template with variables
const promptTemplate = {
  components: [{
    type: "system",
    content: "You are an assistant for {{companyName}}. " +
             "The user's name is {{userName}} and their role is {{userRole}}.",
    isDynamic: false  // Template components are NOT dynamic
  }]
};

// Variables are passed inside the systemPrompt object
await greenflash.messages.log({
  conversationId: "conv_123",
  productId: "your_product_id",
  systemPrompt: {
    ...promptTemplate,
    variables: {
      companyName: "Acme Corp",
      userName: "Alice",
      userRole: "Manager"
    }
  },
  messages: [...]
});
```

### Dynamic Content Slots

The `isDynamic` flag indicates components with content that varies per conversation (like RAG results):

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const components = [
  {
    type: "system",
    content: "Base instructions for {{productName}}",
    isDynamic: false  // Template with variables - stable across conversations
  },
  {
    type: "rag",
    content: "Retrieved documents: [actual documents here]",
    isDynamic: true   // Content varies per conversation
  }
];
```

**Key distinction:**

* `isDynamic: false` - Template components (may have variables)
* `isDynamic: true` - Dynamic content slots (RAG, agent outputs)

Both types can contain variables that will be interpolated!

## Recording Prompts via API

### Simple String Format

The quickest way to start - just pass your prompt as a string:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
await greenflash.messages.log({
  conversationId: "conv_456",
  productId: "product_123",
  systemPrompt: "You are a helpful assistant. Be concise and friendly.",
  messages: [
    { role: "user", content: "What's the weather?" },
    { role: "assistant", content: "I don't have access to real-time weather data..." }
  ]
});
```

Greenflash automatically converts this to a component internally and tracks all the same metrics. When you're ready for more features, you can switch to the component format.

### Component-Based Prompt Logging

For more control, structure your prompts using components:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
await greenflash.messages.log({
  conversationId: "conv_456",
  productId: "product_123",
  systemPrompt: {
    components: [
      {
        type: "system",
        content: "You are a helpful assistant.",
        name: "base_prompt"
      }
    ]
  },
  messages: [
    { role: "user", content: "How do I reset my password?" },
    { role: "assistant", content: "I'll help you reset your password..." }
  ]
});
```

### Using External IDs

Track prompts across different environments with external IDs:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
await greenflash.messages.log({
  conversationId: "conv_789",
  productId: "product_123",
  systemPrompt: {
    externalPromptId: "prod-v2.3.1",
    components: [
      {
        externalComponentId: "base-2024-01",
        type: "system",
        content: "Production prompt v2.3.1..."
      }
    ]
  },
  messages: [...]
});
```

### Component-Level Management

Mix and match components to create flexible prompt architectures:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const sharedComponents = {
  personality: {
    externalComponentId: "personality-friendly-v1",
    type: "system",
    content: "You are friendly and approachable.",
    name: "personality"
  },
  safety: {
    externalComponentId: "safety-standard-v2",
    type: "system",
    content: "Never provide harmful information.",
    name: "safety_guidelines"
  }
};

// Different products can use different combinations
const supportBotPrompt = {
  components: [
    sharedComponents.personality,
    sharedComponents.safety,
    {
      type: "system",
      content: "You specialize in technical support.",
      name: "specialization"
    }
  ]
};

const salesBotPrompt = {
  components: [
    sharedComponents.personality,
    sharedComponents.safety,
    {
      type: "system",
      content: "You help customers find the right products.",
      name: "specialization"
    }
  ]
};
```

## Managing Prompts via API

<Note>
  The management API endpoints require component format. Simple string prompts are automatically converted to components when logged, but explicit prompt creation/updates need the structured format.
</Note>

### Create a Prompt

Create and version prompts explicitly:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const response = await fetch('https://api.greenflash.ai/api/v1/prompts', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
    'x-product-id': 'product_123'
  },
  body: JSON.stringify({
    name: "Customer Support Prompt v2",
    components: [
      {
        type: "system",
        content: "You are a {{companyName}} support specialist.",
        name: "base_role",
        isDynamic: false  // Template component
      },
      {
        type: "rag",
        content: "",  // Will be filled with retrieved docs
        name: "knowledge_base",
        isDynamic: true  // Dynamic RAG slot
      }
    ]
  })
});
```

### Update a Prompt

Update existing prompts while maintaining version history:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const response = await fetch(`https://api.greenflash.ai/api/v1/prompts/${promptId}`, {
  method: 'PUT',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
    'x-product-id': 'product_123'
  },
  body: JSON.stringify({
    name: "Customer Support Prompt v2.1",
    components: [
      {
        componentId: "existing_component_id",  // Reuse existing
        type: "system",
        content: "Updated: You are a {{companyName}} support specialist."
      },
      {
        type: "system",
        content: "New: Always verify customer identity first.",
        name: "security_protocol"
      }
    ]
  })
});
```

### Retrieve a Prompt

Fetch prompts with optional variable interpolation:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Get raw template
const response = await fetch(
  `https://api.greenflash.ai/api/v1/prompts/${promptId}`,
  {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'x-product-id': 'product_123'
    }
  }
);

// Get with variables interpolated
const interpolated = await fetch(
  `https://api.greenflash.ai/api/v1/prompts/${promptId}?` +
  `companyName=Acme&userName=Bob`,
  {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'x-product-id': 'product_123'
    }
  }
);
```

### List Prompts

Browse and filter your prompt library:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const response = await fetch(
  'https://api.greenflash.ai/api/v1/prompts?' +
  'limit=20&cursor=next_page_token',
  {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'x-product-id': 'product_123'
    }
  }
);

const data = await response.json();
// Returns:
// {
//   data: [
//     {
//       id: "prompt_123",
//       name: "Support Bot v2",
//       createdAt: "2024-01-15T10:00:00Z",
//       components: [...],
//       metrics: {
//         usageCount: 1523,
//         avgQualityScore: 0.92
//       }
//     }
//   ],
//   cursor: "next_page_token"
// }
```

## Template Matching and Deduplication

Greenflash automatically deduplicates prompts based on their template content, not the hydrated values. When you use `variables`, the template (with `{{placeholders}}`) is what gets hashed and versioned — different variable values reuse the same template.

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Best practice: use variables for per-conversation values
const prompt1 = {
  components: [{
    content: "Hello {{userName}}, welcome to {{product}}"
  }],
  variables: { userName: "Alice", product: "Greenflash" }
};

const prompt2 = {
  components: [{
    content: "Hello {{userName}}, welcome to {{product}}"
  }],
  variables: { userName: "Bob", product: "DataTool" }
};
// Both use the same template — no version explosion!

// Auto-detection: if you send hydrated content without variables,
// Greenflash will attempt to match it against existing templates:
const prompt3 = {
  components: [{
    content: "Hello Charlie, welcome to Greenflash"
  }]
};
// If a matching template exists, Greenflash extracts variables automatically
// and returns templateMatch info in the response.
```

This ensures:

* Consistent versioning across variable values
* No prompt/version explosion from per-user content
* Accurate performance metrics
* Efficient storage
* Better optimization insights

## UI Features

The Greenflash dashboard provides powerful prompt management capabilities:

### Prompt Library

* Browse all prompts across products
* Filter by type, usage, performance
* View version history
* Compare prompt versions side-by-side

### Performance Analytics

* **Usage metrics** - How often each prompt is used
* **Quality scores** - Average CQI per prompt version
* **Sentiment analysis** - User satisfaction by prompt
* **Error rates** - Hallucination and failure patterns
* **Latency impact** - Response time by prompt complexity

### Optimization Suggestions

* AI-generated improvements based on conversation analysis
* A/B testing recommendations
* Side-by-side comparisons with expected impact
* Evidence from actual conversations

### Collaboration Tools

* Name and organize prompts
* Add descriptions and documentation
* Tag prompts for easy discovery
* Share prompts across teams

## Active Optimization

### How Greenflash Improves Prompts

Greenflash continuously analyzes conversations to identify optimization opportunities:

1. **Pattern Recognition**
   * Detects recurring user confusion
   * Identifies successful interaction patterns
   * Finds correlation between prompts and outcomes

2. **Failure Analysis**
   * Tracks where conversations go wrong
   * Identifies prompt ambiguities
   * Detects missing instructions

3. **Success Modeling**
   * Learns from high-quality conversations
   * Identifies effective prompt patterns
   * Suggests proven improvements

### Optimization Examples

**Before optimization:**

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
{
  type: "system",
  content: "You are a helpful assistant."
}
```

**After Greenflash analysis:**

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
{
  type: "system",
  content: "You are a helpful assistant for {{companyName}}. " +
           "When users ask about pricing, always mention the free trial. " +
           "If technical issues arise, offer to create a support ticket. " +
           "Keep responses concise - aim for 2-3 sentences unless more detail is requested."
}
// Reasoning: Analysis of 1,000 conversations showed:
// - 34% of users asked about pricing without getting trial info
// - 28% had technical issues with no clear next steps
// - 67% of users preferred shorter initial responses
```

### Implementing Suggestions

Review and apply optimizations through the UI or API:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Get optimization suggestions
const suggestions = await fetch(
  `https://api.greenflash.ai/api/v1/prompts/${promptId}/suggestions`,
  {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'x-product-id': 'product_123'
    }
  }
);

// Review suggestion details
const data = await suggestions.json();
console.log(data.suggestions[0]);
// {
//   suggestedContent: "Improved prompt text...",
//   reasoning: "Based on 523 conversations, users frequently...",
//   expectedImpact: {
//     qualityIndex: "+12%",
//     userSatisfaction: "+8%",
//     avgConversationLength: "-2.3 messages"
//   },
//   evidence: [
//     { conversationId: "conv_123", issue: "User confusion about..." },
//     { conversationId: "conv_456", issue: "Assistant too verbose..." }
//   ]
// }
```

## Best Practices

### 1. Use Components Strategically

* Separate concerns into different components
* Share common components across prompts
* Version components independently

### 2. Leverage Variables

* Use variables for customer-specific information
* Keep templates generic and reusable
* Document required variables clearly

### 3. Track Everything

* Include prompts with every conversation
* Use consistent external IDs
* Monitor performance metrics

### 4. Iterate Based on Data

* Review optimization suggestions weekly
* Test improvements with small user segments
* Measure impact before full rollout

### 5. Organize for Scale

* Use clear naming conventions
* Document prompt purposes
* Maintain a prompt changelog

## Advanced Features

### Conditional Components

Use metadata to conditionally include components:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
const components = [
  {
    type: "system",
    content: "Base instructions...",
    name: "base"
  },
  userIsPremium ? {
    type: "system",
    content: "Premium features available: ...",
    name: "premium_features"
  } : null,
  isComplexQuery ? {
    type: "system",
    content: "Use step-by-step reasoning...",
    name: "chain_of_thought"
  } : null
].filter(Boolean);
```

### Prompt Chains

Track multi-turn prompt strategies:

```javascript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Initial prompt
const analysisPrompt = {
  components: [{
    type: "system",
    content: "Analyze the user's request and identify key topics."
  }]
};

// Follow-up prompt based on analysis
const responsePrompt = {
  components: [
    {
      type: "system",
      content: "Based on the analysis: {{analysisResult}}"
    },
    {
      type: "system",
      content: "Provide a detailed response about: {{identifiedTopics}}"
    }
  ]
};
```

## Getting Started Checklist

### Quick Start (Simple String)

1. **Log with string prompts** - Pass your prompt as a simple string
2. **Monitor metrics** - Review performance in the dashboard
3. **Review suggestions** - Apply AI-generated improvements
4. **Graduate to components** - Add structure when you need more features

### Full Implementation (Components)

1. **Set up component logging** - Structure prompts into logical components
2. **Add variables** - Use templates for customer-specific content
3. **Set external IDs** - Track prompts across environments
4. **Configure dynamic slots** - Mark RAG/agent components appropriately
5. **Monitor metrics** - Review detailed performance analytics
6. **Review suggestions** - Apply component-level optimizations
7. **Iterate and improve** - Continuously optimize based on data

## API Reference

Full API documentation for prompt management:

* [Create Prompt](https://docs.greenflash.ai/api-reference/prompts/create-prompt)
* [Update Prompt](https://docs.greenflash.ai/api-reference/prompts/update-prompt)
* [Get Prompt](https://docs.greenflash.ai/api-reference/prompts/get-prompt)
* [List Prompts](https://docs.greenflash.ai/api-reference/prompts/list-prompts)
* [Get Optimization Suggestions](https://docs.greenflash.ai/api-reference/prompts/get-prompt-optimization-suggestions)

## Next

<CardGroup cols={2}>
  <Card title="AI Product Analysis" icon="chart-line" href="/intro/ai-product-analysis">
    Understand conversation metrics and performance insights.
  </Card>

  <Card title="Webhooks" icon="webhook" href="/intro/webhooks">
    Set up real-time alerts for prompt performance changes.
  </Card>

  <Card title="SDK Integration" icon="code" href="/sdks">
    Language-specific examples for implementing prompt optimization.
  </Card>
</CardGroup>
