Medusssa.Prompt.Shared.v300 3.5.3

dotnet add package Medusssa.Prompt.Shared.v300 --version 3.5.3
                    
NuGet\Install-Package Medusssa.Prompt.Shared.v300 -Version 3.5.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Medusssa.Prompt.Shared.v300" Version="3.5.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Medusssa.Prompt.Shared.v300" Version="3.5.3" />
                    
Directory.Packages.props
<PackageReference Include="Medusssa.Prompt.Shared.v300" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Medusssa.Prompt.Shared.v300 --version 3.5.3
                    
#r "nuget: Medusssa.Prompt.Shared.v300, 3.5.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Medusssa.Prompt.Shared.v300@3.5.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Medusssa.Prompt.Shared.v300&version=3.5.3
                    
Install as a Cake Addin
#tool nuget:?package=Medusssa.Prompt.Shared.v300&version=3.5.3
                    
Install as a Cake Tool
# Medusa.Prompt.Shared

**AI Prompt Management for MythSuite**

Medusa.Prompt.Shared is a distributed prompt management library that enables runtime storage, retrieval, and synchronization of AI prompts across the MythSuite neural network. Named after the Gorgon Medusa, this library ensures your AI prompts remain **consistent, versioned, and immutable** until deliberately changed.

---

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Benefits](#benefits)
- [Architecture](#architecture)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage Examples](#usage-examples)
- [Prompt Structure](#prompt-structure)
- [MythSuite Ecosystem](#mythsuite-ecosystem)
- [Use Cases](#use-cases)
- [Security](#security)
- [API Reference](#api-reference)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

---

## Overview

Medusa.Prompt.Shared provides a unified interface for managing AI prompts across distributed microservices in the MythSuite cognitive architecture. It supports two distinct prompt categories—**System Prompts** (for model behavior) and **Normal Prompts** (for user interactions)—with runtime updates, version control, and seamless integration with Ollama, Claude, and other AI models.

### What are Prompts in MythSuite?

Prompts are **text instructions** that guide AI model behavior:

- **System Prompts**: Define model personality, constraints, capabilities (e.g., "You are a helpful sales analyst")
- **Normal Prompts**: Templates for user interactions, workflows, responses (e.g., "Generate a report for {timeframe}")

These prompts form the **behavioral layer** of the MythSuite neural network, controlling how AI models interpret and respond to requests.

---

## Features

### Dual Prompt Categories

- **System Prompts**: Model-level instructions stored separately (e.g., Gemma2 intent extraction, DeepSeek reflection)
- **Normal Prompts**: Application-level templates for user interactions
- **Type-Safe Retrieval**: Get prompts by key and type with compile-time safety
- **Separate Storage**: System and Normal prompts stored in different directories/collections

### Prompt Management

- **Hierarchical Keys**: Organize prompts with colon-separated namespaces (e.g., `gemma2:intent`, `greeting:morning`)
- **Version Control**: Track prompt changes over time with timestamps
- **Bulk Operations**: Create, update, delete, and list prompts efficiently
- **File System Integration**: Edit prompts locally during development
- **Distributed Storage**: Store prompts in CouchDB via Zeus.Server messaging

### Real-Time Synchronization

- **Event-Driven Updates**: `PromptChanged` event fires when prompts are created, updated, or deleted
- **Change Type Detection**: Know whether a prompt was created, updated, or deleted
- **Automatic Propagation**: Changes made by one service instantly visible to all others
- **Type Awareness**: Events include prompt type (System vs Normal)

### Resilience & Performance

- **Dual-Mode Operation**: Zeus.Server (primary) with file system fallback
- **In-Memory Caching**: Fast prompt access with configurable TTL
- **Offline Capability**: Continue operating when Zeus.Server is unavailable
- **Graceful Degradation**: Automatic fallback to local file storage

### Developer Experience

- **Simple API**: `GetPromptAsync("key", PromptType.System)`, `PublishPromptAsync("key", content, PromptType.Normal)`
- **Type Filtering**: List prompts by type (System only, Normal only, or all)
- **Lifecycle Management**: Start, Stop, Pause, Resume for complete control
- **Dependency Injection Ready**: Implements `IMedusaPromptService` for DI containers

---

## Benefits

### For AI Engineers

✅ **Centralized Prompt Management** - All AI prompts in one place  
✅ **A/B Testing** - Update prompts without redeploying models  
✅ **Model-Specific Prompts** - Separate system prompts for Gemma2, DeepSeek, Llama3  
✅ **Prompt Versioning** - Track changes and rollback if needed  
✅ **Hot Reload** - Update model behavior at runtime without restarts

### For Developers

✅ **Type-Safe Prompts** - Strongly-typed retrieval with PromptType enum  
✅ **Template Support** - Use placeholders in prompts (e.g., `{username}`, `{timeframe}`)  
✅ **Consistent Interface** - Same API across all MythSuite services  
✅ **Easy Testing** - Mock `IMedusaPromptService` for unit tests  
✅ **File System Compatibility** - Edit prompts as `.txt` or `.md` files locally

### For DevOps

✅ **Zero-Downtime Updates** - Change prompts across all AI services instantly  
✅ **Centralized Management** - Single source of truth in CouchDB  
✅ **Audit Trail** - Track every prompt change with timestamps  
✅ **Disaster Recovery** - File-based fallback ensures services stay operational  
✅ **Environment Separation** - Different prompts for Dev/Staging/Production

### For System Architects

✅ **Separation of Concerns** - Prompts isolated from code logic  
✅ **Event-Driven Architecture** - Prompt changes propagate via Zeus.Server  
✅ **Scalable** - Supports hundreds of prompts with efficient caching  
✅ **Observable** - Integration with Clio.Shared for comprehensive logging  
✅ **Model Agnostic** - Works with any AI model (Ollama, OpenAI, Claude, etc.)

---

## Architecture

### How It Works

┌─────────────────────────────────────────────────────────────────┐ │ MythSuite AI Services │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ │ KronosAIATA │ │CognitiveEngine │ │ WorkflowEngine │ │ │ │(Medusa.Prompt) │ │(Medusa.Prompt) │ │(Medusa.Prompt) │ │ │ └───────┬────────┘ └───────┬────────┘ └───────┬────────┘ │ │ │ │ │ │ │ └────────────────────┼────────────────────┘ │ │ │ │ │ ┌────────▼────────┐ │ │ │ Zeus.Server │ │ │ │ (gRPC Pub/Sub) │ │ │ └────────┬────────┘ │ │ │ │ │ ┌────────▼────────┐ │ │ │ CouchDB │ │ │ │(Prompt Storage) │ │ │ │ │ │ │ │ /system/ │ ← System Prompts │ │ │ /normal/ │ ← Normal Prompts │ │ └─────────────────┘ │ └─────────────────────────────────────────────────────────────────┘

Prompt Flow:

  1. KronosAIATA needs Gemma2 intent extraction prompt
  2. GetPromptAsync("gemma2:intent", PromptType.System)
  3. Medusa checks Zeus.Server cache (fast path)
  4. If not found, queries CouchDB via Zeus.Server
  5. If Zeus unavailable, reads from local file (fallback)
  6. PromptChanged event fires when admin updates prompts

### Prompt Categories

System Prompts (PromptType.System) ├── Model behavior definitions ├── Personality constraints ├── Role instructions └── Capability boundaries

Normal Prompts (PromptType.Normal) ├── User interaction templates ├── Workflow step instructions ├── Response formatting └── Application-level guidance


### Storage Layout

**File System:**

prompts/ ├── system/ │ ├── gemma2/ │ │ ├── intent.txt │ │ └── extraction.txt │ ├── deepseek/ │ │ ├── reflection.txt │ │ └── morality.txt │ └── llama3/ │ └── generation.txt └── normal/ ├── greeting/ │ ├── morning.txt │ └── evening.txt └── workflow/ └── sales-report.txt


**CouchDB:**
```json
{
  "_id": "prompt:system:gemma2:intent",
  "type": "SystemPrompt",
  "key": "gemma2:intent",
  "content": "You are an intent extraction specialist...",
  "metadata": {
    "createdAt": "2025-02-19T10:00:00Z",
    "updatedAt": "2025-02-19T14:30:00Z",
    "version": "2.1",
    "author": "AI Team"
  }
}

Components

  • MedusaPromptClient: Public facade implementing IMedusaPromptService
  • MedusaPromptMessagingSubscriber: Handles Zeus.Server communication (gRPC)
  • MedusaPromptFileSubscriber: Manages local file-based prompt storage
  • MedusaPromptSettings: Configuration POCO for Medusa.Prompt

Installation

NuGet Package

dotnet add package Medusa.Prompt.Shared --version 1.0.0

Dependencies

Medusa.Prompt.Shared requires:

  • Mercury.Shared (Interfaces and shared types)
  • Clio.Shared (Logging)
  • Zeus.Shared (Optional: For Zeus.Server connectivity)
  • Grpc.Net.Client (For gRPC communication)
  • System.Text.Json (For JSON serialization)

Quick Start

1. Configure MedusaPromptSettings

var promptSettings = new MedusaPromptSettings
{
    // Zeus.Server connection
    ZeusGrpcEndpoint = "https://zeus.mythsuite.local:5001",
    AccessToken = "your-auth-token",
    
    // Application identity
    Tenant = "MythCorp",
    Application = "KronosAIATA",
    
    // Enable both message and file services
    MessageServiceEnabled = true,
    FileServiceEnabled = true,
    
    // File-based fallback
    SystemPromptDirectoryPath = "prompts/system",
    NormalPromptDirectoryPath = "prompts/normal",
    FileExtension = ".txt",
    
    // Zeus.Server topics
    PromptTopic = "Medusa.Prompt.Topics.Global",
    PromptQueue = "Medusa.Prompt.Queue"
};

2. Initialize Medusa Prompt Client

// Inject Clio logger
var clioService = serviceProvider.GetRequiredService<IClioService>();

// Create Medusa Prompt client
var promptClient = new MedusaPromptClient(promptSettings, clioService);
await promptClient.StartAsync();

// Register as singleton
services.AddSingleton<IMedusaPromptService>(promptClient);

3. Retrieve and Use Prompts

public class IntentExtractionService
{
    private readonly IMedusaPromptService _prompts;
    
    public IntentExtractionService(IMedusaPromptService prompts)
    {
        _prompts = prompts;
    }
    
    public async Task<string> ExtractIntent(string userMessage)
    {
        // Get system prompt for Gemma2 model
        var systemPrompt = await _prompts.GetPromptAsync(
            "gemma2:intent", 
            PromptType.System
        );
        
        // Call Ollama with system prompt
        var response = await _ollama.GenerateAsync(new
        {
            Model = "gemma2:2b",
            System = systemPrompt,
            Prompt = userMessage
        });
        
        return response.Intent;
    }
}

4. React to Prompt Changes

promptClient.PromptChanged += async (sender, e) =>
{
    Console.WriteLine($"Prompt {e.ChangeType}: {e.Key} ({e.PromptType})");
    
    if (e.Key == "gemma2:intent" && e.PromptType == PromptType.System)
    {
        // Reload model with new system prompt
        await ReloadIntentExtractor(e.Content);
    }
};

Usage Examples

Example 1: System Prompts for AI Models

// Store system prompt for Gemma2 intent extraction
var intentPrompt = @"
You are an expert intent extraction specialist. 
Analyze the user's message and identify:
1. Primary intent (e.g., sales-analysis, report-generation, question-answering)
2. Entities mentioned (dates, products, people, locations)
3. Urgency level (low, medium, high)

Respond ONLY with a JSON object:
{
  ""intent"": ""<intent-name>"",
  ""entities"": [""<entity1>"", ""<entity2>""],
  ""urgency"": ""<level>""
}
";

await _prompts.PublishPromptAsync(
    "gemma2:intent", 
    intentPrompt, 
    PromptType.System
);

// Retrieve system prompt
var prompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);

// Use with Ollama
var response = await _ollama.GenerateAsync(new
{
    Model = "gemma2:2b",
    System = prompt,
    Prompt = "Show me Q4 sales for the West region"
});

Example 2: Model-Specific System Prompts

// Gemma2: Intent extraction
await _prompts.PublishPromptAsync(
    "gemma2:intent",
    "You are an intent extraction specialist...",
    PromptType.System
);

// DeepSeek: Reflection and morality
await _prompts.PublishPromptAsync(
    "deepseek:reflection",
    "You are a reasoning evaluator. Assess the logic and ethics of the following response...",
    PromptType.System
);

// Llama3: Response generation
await _prompts.PublishPromptAsync(
    "llama3:generation",
    "You are a helpful business intelligence assistant. Provide clear, concise answers...",
    PromptType.System
);

// Retrieve model-specific prompts
var gemmaPrompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);
var deepseekPrompt = await _prompts.GetPromptAsync("deepseek:reflection", PromptType.System);
var llamaPrompt = await _prompts.GetPromptAsync("llama3:generation", PromptType.System);

Example 3: Normal Prompts for User Interactions

// Store greeting prompts
await _prompts.PublishPromptAsync(
    "greeting:morning",
    "Good morning! How can I help you today?",
    PromptType.Normal
);

await _prompts.PublishPromptAsync(
    "greeting:evening",
    "Good evening! What can I assist you with?",
    PromptType.Normal
);

// Store workflow step prompts
await _prompts.PublishPromptAsync(
    "workflow:sales-report:step1",
    "I'm gathering Q4 sales data from the database. This will take a moment...",
    PromptType.Normal
);

// Retrieve and use in application
var hour = DateTime.Now.Hour;
var greeting = await _prompts.GetPromptAsync(
    hour < 12 ? "greeting:morning" : "greeting:evening",
    PromptType.Normal
);

Console.WriteLine(greeting);

Example 4: Templated Prompts

// Store template with placeholders
var reportTemplate = @"
Generate a {reportType} report for {timeframe}.

Include the following sections:
- Executive Summary
- Key Metrics
- {customSection}
- Recommendations

Format: {format}
";

await _prompts.PublishPromptAsync(
    "template:report",
    reportTemplate,
    PromptType.Normal
);

// Retrieve and populate template
var template = await _prompts.GetPromptAsync("template:report", PromptType.Normal);
var finalPrompt = template
    .Replace("{reportType}", "sales")
    .Replace("{timeframe}", "Q4 2024")
    .Replace("{customSection}", "Regional Performance")
    .Replace("{format}", "PowerPoint");

// Use populated prompt with AI
var report = await _ai.GenerateAsync(finalPrompt);

Example 5: A/B Testing Prompts

// Version A: Concise prompt
await _prompts.PublishPromptAsync(
    "gemma2:intent:v1",
    "Extract intent and entities from the user message. Return JSON.",
    PromptType.System
);

// Version B: Detailed prompt
await _prompts.PublishPromptAsync(
    "gemma2:intent:v2",
    "You are an expert intent analyst. Carefully read the user's message...",
    PromptType.System
);

// Test both versions
var intentV1 = await TestIntent("gemma2:intent:v1", userMessage);
var intentV2 = await TestIntent("gemma2:intent:v2", userMessage);

// Compare accuracy and choose winner
if (intentV2.Accuracy > intentV1.Accuracy)
{
    // Promote V2 to production
    var v2Prompt = await _prompts.GetPromptAsync("gemma2:intent:v2", PromptType.System);
    await _prompts.PublishPromptAsync("gemma2:intent", v2Prompt, PromptType.System);
}

Example 6: List and Manage Prompts

// List all system prompts
var systemPrompts = await _prompts.ListPromptKeysAsync(null, PromptType.System);
Console.WriteLine($"Found {systemPrompts.Length} system prompts");

// List prompts for specific model
var gemmaPrompts = await _prompts.ListPromptKeysAsync("gemma2:", PromptType.System);
foreach (var key in gemmaPrompts)
{
    Console.WriteLine($"Gemma2 prompt: {key}");
}

// List all normal prompts
var normalPrompts = await _prompts.ListPromptKeysAsync(null, PromptType.Normal);

// Delete old prompts
await _prompts.DeletePromptAsync("gemma2:intent:v1");

Example 7: Runtime Prompt Updates

// Admin updates system prompt (via admin UI or script)
var improvedPrompt = @"
You are an advanced intent extraction system.
[New improved instructions...]
";

await _prompts.PublishPromptAsync(
    "gemma2:intent",
    improvedPrompt,
    PromptType.System
);

// All AI services automatically receive update
promptClient.PromptChanged += async (sender, e) =>
{
    if (e.Key == "gemma2:intent" && e.PromptType == PromptType.System)
    {
        _logger.Log("Intent extraction prompt updated - reloading model");
        
        // Reload model configuration
        await _gemma2Service.UpdateSystemPrompt(e.Content);
        
        _logger.Log("Model reloaded with new prompt");
    }
};

Prompt Structure

Hierarchical Key Format

Prompts are organized using colon-separated hierarchical keys:

<Model>:<Purpose>:<Variant>

System Prompt Examples:
gemma2:intent                  → Gemma2 intent extraction
gemma2:intent:v2              → Version 2 of intent extraction
deepseek:reflection           → DeepSeek reflection evaluation
deepseek:morality             → DeepSeek ethical assessment
llama3:generation             → Llama3 response generation
llama3:generation:formal      → Formal variant

Normal Prompt Examples:
greeting:morning              → Morning greeting
greeting:evening              → Evening greeting
workflow:sales-report:step1   → Sales report workflow step 1
template:report               → Report generation template
error:not-found              → Error message for not found

System Prompt Template

You are a [role description].

Your capabilities:
- [Capability 1]
- [Capability 2]
- [Capability 3]

Your constraints:
- [Constraint 1]
- [Constraint 2]

Response format:
[Expected output format]

Examples:
[Example input/output pairs]

Normal Prompt Template

[User-facing message with optional placeholders]

Placeholders: {variable1}, {variable2}, {variable3}

Example:
"Hello {username}, your {reportType} report for {timeframe} is ready!"

MythSuite Ecosystem

Where Medusa.Prompt Fits

┌─────────────────────────────────────────────────────────────┐
│                    MythSuite Architecture                     │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ Clio.Shared  │  │ Athena.Shared│  │ Zeus.Shared  │      │
│  │  (Logging)   │  │   (Tokens)   │  │ (Messaging)  │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│                                                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │Medusa.Config │  │ Medusa.Dsl   │  │Medusa.Prompt │      │
│  │  .Shared     │  │   .Shared    │  │  .Shared     │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│                                            ▲                  │
│                                            │                  │
│  ┌─────────────────────────────────────────┴────────┐       │
│  │              AI Services                          │       │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐ │       │
│  │  │ Gemma2     │  │ DeepSeek   │  │ Llama3     │ │       │
│  │  │ (Intent)   │  │(Reflection)│  │(Generation)│ │       │
│  │  └────────────┘  └────────────┘  └────────────┘ │       │
│  └──────────────────────────────────────────────────┘       │
│                                                               │
│  ┌──────────────────────────────────────────────────┐       │
│  │            Mercury.Shared (Interfaces)            │       │
│  └──────────────────────────────────────────────────┘       │
└─────────────────────────────────────────────────────────────┘

Medusa.Prompt is the "instruction layer" of MythSuite,
controlling how AI models interpret and respond to requests.

Integration Points

KronosAIATA (Intent Extraction)
// Load Gemma2 system prompt
var systemPrompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);

// Extract intent with Ollama
var intent = await _ollama.GenerateAsync("gemma2:2b", systemPrompt, userMessage);
CognitiveEngine (Reflection)
// Load DeepSeek reflection prompt
var reflectionPrompt = await _prompts.GetPromptAsync("deepseek:reflection", PromptType.System);

// Evaluate reasoning quality
var evaluation = await _ollama.GenerateAsync("deepseek-r2-distilled", reflectionPrompt, reasoning);
WorkflowEngine (Response Generation)
// Load Llama3 generation prompt
var generationPrompt = await _prompts.GetPromptAsync("llama3:generation", PromptType.System);

// Generate user-facing response
var response = await _ollama.GenerateAsync("llama3.2:3b", generationPrompt, context);
User Interface (Normal Prompts)
// Load greeting based on time
var greeting = await _prompts.GetPromptAsync(
    DateTime.Now.Hour < 12 ? "greeting:morning" : "greeting:evening",
    PromptType.Normal
);

Console.WriteLine(greeting);

Use Cases

1. Model Behavior Control

Control AI model personality and capabilities:

// Gemma2 for intent extraction (precise, structured)
await _prompts.PublishPromptAsync(
    "gemma2:intent",
    "You are a precise intent extraction system. Return only JSON.",
    PromptType.System
);

// Llama3 for user interaction (friendly, conversational)
await _prompts.PublishPromptAsync(
    "llama3:generation",
    "You are a friendly business assistant. Be warm and helpful.",
    PromptType.System
);

2. Multi-Model Pipeline

Different prompts for different pipeline stages:

// Stage 1: Intent extraction (Gemma2)
var intentPrompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);
var intent = await ExtractIntent(userMessage, intentPrompt);

// Stage 2: Reflection (DeepSeek)
var reflectionPrompt = await _prompts.GetPromptAsync("deepseek:reflection", PromptType.System);
var quality = await EvaluateIntent(intent, reflectionPrompt);

// Stage 3: Response generation (Llama3)
var generationPrompt = await _prompts.GetPromptAsync("llama3:generation", PromptType.System);
var response = await GenerateResponse(intent, generationPrompt);

3. Prompt Experimentation

Test different prompts without code changes:

// Current production prompt
var currentPrompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);

// Test new experimental prompt
var experimentalPrompt = await _prompts.GetPromptAsync("gemma2:intent:experimental", PromptType.System);

// Run A/B test
var results = await RunABTest(currentPrompt, experimentalPrompt, testDataset);

// If experimental wins, promote to production
if (results.ExperimentalAccuracy > results.CurrentAccuracy)
{
    await _prompts.PublishPromptAsync("gemma2:intent", experimentalPrompt, PromptType.System);
}

4. Localization

Different prompts for different languages:

// English
await _prompts.PublishPromptAsync(
    "greeting:en",
    "Hello! How can I help you today?",
    PromptType.Normal
);

// Spanish
await _prompts.PublishPromptAsync(
    "greeting:es",
    "¡Hola! ¿Cómo puedo ayudarte hoy?",
    PromptType.Normal
);

// Get localized prompt
var userLanguage = GetUserLanguage();
var greeting = await _prompts.GetPromptAsync($"greeting:{userLanguage}", PromptType.Normal);

5. Prompt Version Control

Track and rollback prompt changes:

// Save current prompt as backup before updating
var currentPrompt = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);
await _prompts.PublishPromptAsync("gemma2:intent:backup-2025-02-19", currentPrompt, PromptType.System);

// Deploy new prompt
await _prompts.PublishPromptAsync("gemma2:intent", newPrompt, PromptType.System);

// If issues occur, rollback to backup
var backup = await _prompts.GetPromptAsync("gemma2:intent:backup-2025-02-19", PromptType.System);
await _prompts.PublishPromptAsync("gemma2:intent", backup, PromptType.System);

Security

Best Practices

✅ Separate System and Normal Prompts - Different access controls for each type
✅ Encrypt Sensitive Prompts - Use encryption for proprietary prompt engineering
✅ Limit Write Access - Only admins/AI engineers can update system prompts
✅ Version Control - Track all prompt changes with timestamps and authors
✅ Audit Prompt Usage - Log which prompts are used and when
✅ File Permissions - Secure local prompt directories (chmod 700)

Access Control

// Example: Only AI engineers can update system prompts
if (_appSettings.Application != "PromptManagementUI" && 
    promptType == PromptType.System)
{
    throw new UnauthorizedAccessException("Only authorized admins can update system prompts");
}

await _prompts.PublishPromptAsync(key, content, promptType);

Prompt Injection Prevention

// Validate system prompts before deployment
public bool ValidateSystemPrompt(string prompt)
{
    // Check for prompt injection attempts
    var dangerousPatterns = new[]
    {
        "ignore previous instructions",
        "disregard all rules",
        "you are now",
        "forget everything"
    };
    
    foreach (var pattern in dangerousPatterns)
    {
        if (prompt.ToLower().Contains(pattern))
        {
            return false;
        }
    }
    
    return true;
}

Encryption

// Encrypt proprietary system prompts
var proprietaryPrompt = "Our secret prompt engineering technique...";
var encryptedPrompt = EncryptionHelper.Encrypt(proprietaryPrompt);

await _prompts.PublishPromptAsync(
    "gemma2:proprietary",
    encryptedPrompt,
    PromptType.System
);

// Decrypt when using
var encrypted = await _prompts.GetPromptAsync("gemma2:proprietary", PromptType.System);
var decrypted = EncryptionHelper.Decrypt(encrypted);

API Reference

IMedusaPromptService Interface

public interface IMedusaPromptService
{
    // Lifecycle
    Task StartAsync();
    Task StopAsync();
    Task PauseAsync();
    Task ResumeAsync();
    
    // Prompt retrieval
    Task<string?> GetPromptAsync(string key);
    Task<T?> GetPromptAsync<T>(string key) where T : class, new();
    Task<string?> GetPromptAsync(string key, PromptType promptType);
    
    // Prompt publishing
    Task PublishPromptAsync(string key, string promptContent, PromptType promptType = PromptType.Normal);
    Task PublishPromptAsync<T>(string key, T prompt, PromptType promptType = PromptType.Normal) where T : class;
    
    // Prompt deletion
    Task DeletePromptAsync(string key);
    
    // List prompt keys (by prefix and/or type)
    Task<string[]> ListPromptKeysAsync(string? prefix = null, PromptType? promptType = null);
    
    // Events
    event PromptChangedEventHandler? PromptChanged;
}

MedusaPromptSettings

public class MedusaPromptSettings
{
    public string ZeusGrpcEndpoint { get; set; }
    public string AccessToken { get; set; }
    public string Tenant { get; set; }
    public string Application { get; set; }
    public bool FileServiceEnabled { get; set; }
    public bool MessageServiceEnabled { get; set; }
    public string SystemPromptDirectoryPath { get; set; }
    public string NormalPromptDirectoryPath { get; set; }
    public string FileExtension { get; set; }
    public string PromptTopic { get; set; }
    public string PromptQueue { get; set; }
    public int CacheDurationMinutes { get; set; }
}

PromptChangedEventArgs

public class PromptChangedEventArgs : EventArgs
{
    public string Key { get; }
    public string? Content { get; }
    public PromptType PromptType { get; }
    public PromptChangeType ChangeType { get; }
    public DateTime Timestamp { get; }
}

public enum PromptType
{
    System,
    Normal
}

public enum PromptChangeType
{
    Created,
    Updated,
    Deleted
}

Best Practices

1. Use Descriptive Keys

// Good: Clear, hierarchical
"gemma2:intent:extraction"
"deepseek:reflection:morality"
"llama3:generation:formal"
"greeting:morning:friendly"

// Bad: Opaque, flat
"prompt1"
"sys_prompt"
"p123"

2. Separate System and Normal Prompts

// System prompts: Model behavior
await _prompts.PublishPromptAsync(
    "gemma2:intent",
    modelBehaviorPrompt,
    PromptType.System
);

// Normal prompts: User interactions
await _prompts.PublishPromptAsync(
    "greeting:morning",
    userGreeting,
    PromptType.Normal
);

3. Version System Prompts

// Save current version before updating
var current = await _prompts.GetPromptAsync("gemma2:intent", PromptType.System);
await _prompts.PublishPromptAsync($"gemma2:intent:v{version}", current, PromptType.System);

// Deploy new version
await _prompts.PublishPromptAsync("gemma2:intent", newPrompt, PromptType.System);

4. Subscribe to Prompt Changes

promptClient.PromptChanged += async (sender, e) =>
{
    _logger.Log($"Prompt {e.ChangeType}: {e.Key} ({e.PromptType})");
    
    // Reload AI models when system prompts change
    if (e.PromptType == PromptType.System)
    {
        await ReloadAIModels();
    }
};

5. Use Templates for Dynamic Content

// Store template
var template = "Hello {username}, your {reportType} for {timeframe} is ready!";
await _prompts.PublishPromptAsync("notification:report-ready", template, PromptType.Normal);

// Use template
var prompt = await _prompts.GetPromptAsync("notification:report-ready", PromptType.Normal);
var message = prompt
    .Replace("{username}", "John")
    .Replace("{reportType}", "sales report")
    .Replace("{timeframe}", "Q4 2024");

Troubleshooting

Issue: Prompt Not Saving

Symptoms: PublishPromptAsync() completes but prompt not retrievable

Solutions:

  1. Check Zeus.Server is running
  2. Verify CouchDB is accessible
  3. Ensure authentication token is valid
  4. Check prompt type is specified correctly
  5. Review Clio logs for errors

Issue: PromptChanged Event Not Firing

Symptoms: Prompt updates don't trigger events

Solutions:

  1. Verify MessageServiceEnabled = true
  2. Check Zeus.Server subscription is active
  3. Ensure PromptTopic matches publisher topic
  4. Restart client: await promptClient.StopAsync(); await promptClient.StartAsync();

Issue: Wrong Prompt Type Retrieved

Symptoms: System prompt returned when expecting Normal prompt

Solutions:

  1. Always specify PromptType parameter: GetPromptAsync(key, PromptType.System)
  2. Check file structure (system prompts in /system/, normal in /normal/)
  3. Verify prompt was saved with correct type

Issue: File Watcher Not Detecting Changes

Symptoms: Local prompt file changes not reflected

Solutions:

  1. Verify WatchFileChanges = true
  2. Check correct directory path (SystemPromptDirectoryPath vs NormalPromptDirectoryPath)
  3. Ensure file extension matches (FileExtension)
  4. Verify file permissions

Contributing

We welcome contributions to Medusa.Prompt.Shared! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/mythsuite/medusa-prompt-shared.git
cd medusa-prompt-shared
dotnet restore
dotnet build
dotnet test

Running Tests

dotnet test --filter Category=Unit
dotnet test --filter Category=Integration

License

Medusa.Prompt.Shared is licensed undera Enterprise User License that requires the puchase of equipment that containers the software. Pleae see the terms at ``Binary.com


Support


Changelog

Version 1.0.0 (2025-02-19)

  • Initial release
  • Dual prompt types (System and Normal)
  • Dual-mode operation (file + message)
  • Zeus.Server integration
  • Event-driven prompt updates
  • Type-safe prompt retrieval
  • Separate storage directories for prompt types
  • Automatic failover to file fallback
  • In-memory caching
  • Clio.Shared integration
  • Support for Gemma2, DeepSeek, Llama3, and other AI models

Built with ❤️ by the MythSuite Team

"Instructing intelligence, one prompt at a time."


---

This README provides:

✅ **Comprehensive Overview** - What prompts are and why they matter in AI systems  
✅ **Dual Prompt Types** - Clear distinction between System and Normal prompts  
✅ **Feature Highlights** - Type-safe retrieval, runtime updates, version control  
✅ **Benefits by Role** - AI Engineer, Developer, DevOps, Architect  
✅ **Architecture Diagrams** - Visual understanding of prompt flow  
✅ **Quick Start Guide** - Get running in minutes  
✅ **Real-World Examples** - System prompts, templates, A/B testing, localization  
✅ **API Reference** - Complete interface documentation  
✅ **Best Practices** - How to manage prompts effectively  
✅ **Troubleshooting** - Common issues and solutions  
✅ **Ecosystem Context** - Integration with Ollama, Gemma2, DeepSeek, Llama3  

Ready to publish to NuGet! 🚀
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.5.3 130 6/15/2026
3.5.0 132 2/19/2026