Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Prompt Deck Laravel Package

veeqtoh/prompt-deck

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**:
   ```bash
   composer require promptphp/deck
   php artisan vendor:publish --provider="PromptPHP\Deck\Providers\DeckServiceProvider"
   php artisan migrate
  1. Create a prompt:

    php artisan make:prompt order-summary
    

    This generates a versioned structure in resources/prompts/order-summary/.

  2. Edit prompt files: Modify resources/prompts/order-summary/v1/system.md (or other role files) with your AI instructions, using {{ $variable }} syntax for dynamic values.

  3. Use the prompt:

    use PromptPHP\Deck\Facades\Deck;
    
    $prompt = Deck::get('order-summary');
    $messages = $prompt->toMessages(['tone' => 'friendly', 'order' => $orderDetails]);
    

First Use Case

AI Agent Integration: Create a prompt for a customer support agent, then integrate it with Laravel AI SDK:

use PromptPHP\Deck\Concerns\HasPromptTemplate;

class SupportAgent extends Agent {
    use HasPromptTemplate;
    // No need to define instructions() manually
}

Implementation Patterns

Core Workflows

  1. Versioned Prompt Management:

    • Use make:prompt to scaffold new versions (v1, v2, etc.).
    • Activate versions via CLI:
      php artisan prompt:activate order-summary v2
      
    • Load specific versions programmatically:
      $prompt = Deck::get('order-summary', 'v2');
      
  2. Dynamic Variable Interpolation:

    • Define variables in prompts using {{ $variable }} syntax.
    • Pass values when rendering:
      $prompt->system(['tone' => 'professional', 'user' => $user]);
      
  3. Role-Based Prompts:

    • Scaffold multiple roles (system, user, assistant, etc.) during creation:
      php artisan make:prompt code-reviewer --role=assistant --role=developer
      
    • Access roles programmatically:
      $system = $prompt->system(['var' => 'value']);
      $user = $prompt->user(['var' => 'value']);
      
  4. Laravel AI SDK Integration:

    • Add HasPromptTemplate trait to agents to auto-load prompts:
      class OrderAgent extends Agent {
          use HasPromptTemplate;
          // Prompt loaded automatically from `resources/prompts/order-agent/`
      }
      
    • Run make:agent to scaffold matching prompt directories.

Integration Tips

  • Configuration: Customize paths, file extensions, and default stubs in config/deck.php.
  • Environment-Specific Prompts: Use Deck::get() with environment-specific versions (e.g., staging-v1).
  • Prompt Validation: Extend the Prompt class to add validation logic for variables or content.
  • Testing: Mock prompts in tests using Deck::shouldReceive('get')->andReturn(...).
  • Performance Tracking: Enable tracking in config/deck.php to log prompt usage metrics.

Advanced Patterns

  1. A/B Testing:

    $version = request()->has('prompt_version') ? request('prompt_version') : 'v1';
    $prompt = Deck::get('order-summary', $version);
    

    Track conversions per version in your database.

  2. Dynamic Prompt Selection:

    $promptName = auth()->user()->preferred_prompt ?? 'default';
    $prompt = Deck::get($promptName);
    
  3. Prompt Inheritance: Create base prompts with common variables, then extend them in child prompts:

    # resources/prompts/base/system.md
    You are a {{ $tone }} assistant.
    
    # resources/prompts/support/v1/system.md
    {{ $base_prompt }}
    Specializing in customer support.
    

    (Requires custom interpolation logic.)


Gotchas and Tips

Common Pitfalls

  1. Namespace Mismatch:

    • After upgrading from veeqtoh/prompt-deck to promptphp/deck, update all use statements from Veeqtoh\PromptDeck to PromptPHP\Deck.
  2. Version Conflicts:

    • Overwriting versions with --force can silently replace critical prompts. Always verify the latest version before using --force.
  3. Variable Scope:

    • Variables are role-specific. Passing ['tone' => 'friendly'] to system() won’t affect user() unless explicitly passed again.
  4. File Permissions:

    • Ensure storage/logs/deck_*.log is writable if using performance tracking.
  5. Stub Overrides:

    • Custom stubs must be placed in resources/stubs/ (default) or configured in deck.stubs_path. Forgetting this causes default stubs to be used.

Debugging Tips

  1. Prompt Not Found:

    • Verify the prompt exists in resources/prompts/ and the name matches exactly (kebab-case).
    • Check metadata.json for typos in the name field.
  2. Variable Interpolation Failures:

    • Ensure variables use the exact syntax {{ $var }} (no spaces).
    • Debug with:
      $prompt->system(['debug' => true]); // Logs unprocessed variables
      
  3. Version Activation Issues:

    • Confirm the version directory exists (e.g., v2/).
    • Check config/deck.php for active_version overrides.
  4. Laravel AI SDK Integration:

    • Ensure the agent’s prompt_name matches the directory name (e.g., OrderAgentorder-agent/).
    • Verify HasPromptTemplate is used and no instructions() method conflicts.

Configuration Quirks

  1. File Extension:

    • Changing deck.extension from md to txt requires regenerating all prompts:
      php artisan make:prompt order-summary --force
      
  2. Prompts Directory:

    • Custom paths (e.g., app/Prompts/) must be writable by the web server.
  3. Metadata Updates:

    • Modifying metadata.json manually may break versioning. Use make:prompt --force to regenerate.

Extension Points

  1. Custom Prompt Classes: Extend PromptPHP\Deck\Prompt to add methods like:

    public function validateVariables(array $variables): void {
        if (!isset($variables['required_var'])) {
            throw new \InvalidArgumentException('Missing required variable.');
        }
    }
    
  2. Stub Customization: Override stubs in resources/stubs/ or publish them:

    php artisan vendor:publish --tag=deck-stubs
    
  3. Event Listeners: Listen for prompt events (e.g., PromptActivated) to log usage:

    Deck::get('order-summary')->on('activated', function ($prompt) {
        \Log::info("Prompt {$prompt->name} activated");
    });
    
  4. Variable Parsers: Extend PromptPHP\Deck\Parsers\VariableParser to support custom syntax (e.g., {{{var}}}).

Performance Tips

  1. Caching: Enable deck.cache_enabled to cache rendered prompts (useful for static prompts).

  2. Asset Optimization: For large prompts, split into multiple files and combine them:

    $prompt = Deck::get('complex-prompt');
    $messages = array_merge(
        $prompt->system()->toMessages(),
        $prompt->user()->toMessages()
    );
    
  3. A/B Testing: Use Deck::get()->trackUsage() to log which versions are used in production.

Security Considerations

  1. Variable Injection: Sanitize user-provided variables before interpolation to prevent template injection:

    $safeVars = array_map('htmlspecialchars', $userInput);
    $prompt->system($safeVars);
    
  2. Prompt Isolation: Avoid sharing prompts between environments (e.g., production-v1 vs. staging-v1) unless explicitly designed for it.

  3. Sensitive Data: Never store API keys or secrets in prompt files. Use environment variables and pass them via the $variables array.


```markdown
### Laravel AI SDK Integration Gotchas
1. **Trait Conflict**:
   If your agent extends a class that also uses `HasPromptTemplate`, the trait may be loaded twice. Use `insteadof` in your `composer.json`:
   ```json
   "autoload": {
       "psr-4": {
           "App\\": "app/",
           "Database\\Factories\\": "database/factories/"
       },
       "files": [
           "vendor/promptphp/deck/src/Concerns/HasPromptTemplate.php"
       ],
       "classmap": [
           "app/Models/"
       ],
       "psr-4": {
           "PromptPHP\\Deck
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui