Manage AI Prompts Laravel Development Package

Managing AI prompts in your Laravel application just got significantly easier with this easy to use package.

As artificial intelligence becomes increasingly integrated into web applications, developers face a growing challenge: how to effectively manage, version, and maintain AI prompts across their codebase.

The Prompt package for Laravel by @chimit offers an elegant solution by allowing developers to manage AI prompts as Markdown files whilst harnessing the full power of Laravel’s Blade templating engine.

Prompt Management Challenges

When building AI-powered features into Laravel applications, developers typically face several pain points. Prompts often end up hardcoded within controller methods or service classes, making them difficult to locate, update, and maintain.

As your application grows and you refine your prompts based on user feedback and AI responses, tracking changes becomes cumbersome without a structured approach.

Complex prompts frequently require dynamic content insertion product details, user preferences, contextual information which can lead to unwieldy string concatenation or awkward heredoc syntax scattered throughout your application logic.

This approach not only impacts code readability but also makes it challenging for non-technical team members, such as prompt engineers or content specialists, to contribute to prompt development.

Introducing the Prompt Package

The Prompt package addresses these concerns by treating AI prompts as first-class citizens in your Laravel application. By storing prompts in dedicated Markdown files within your resources/prompts directory.

You gain the benefits of proper organisation, version control, and separation of concerns. The package’s integration with Blade means you can leverage Laravel’s familiar templating syntax to create dynamic, conditional prompts without sacrificing clarity.

Installation & Setup

Getting started with the Prompt package is straightforward. Install it via Composer:

composer require chimit/prompt
JavaScript

Once installed, create a prompts directory within your resources folder. This is where all your prompt templates will reside. You can organise prompts into subdirectories based on functionality, feature, or any structure that suits your application’s architecture.

resources/
└── prompts/
    ├── content/
    │   └── article-writer.md
    ├── customer-service/
    │   └── response-generator.md
    └── analytics/
        └── sentiment-analysis.md
JavaScript

Basic Usage with Dynamic Content

At its core, the package allows you to define prompt templates that accept variables, just as you would with Blade views. Let’s explore a practical example for a content generation feature.

Create a file at resources/prompts/content/blog-outline.md:

You are an experienced content strategist and writer. Create a detailed blog post outline based on the following requirements.

**Topic:** {{ $topic }}
**Target Audience:** {{ $audience }}
**Desired Tone:** {{ $tone }}

@if(isset($keywords) && count($keywords) > 0)
**SEO Keywords to Include:**
@foreach($keywords as $keyword)
- {{ $keyword }}
@endforeach
@endif

**Content Goals:**
{{ $goals }}

Please provide:
1. A compelling headline (5 variations)
2. An engaging introduction approach
3. Main section headings with brief descriptions
4. Key points to cover in each section
5. A conclusion strategy
6. Suggested call-to-action

The outline should support a {{ $wordCount }}-word article.

To render this prompt in your application:

use Chimit\Prompt\Prompt;

class BlogOutlineGenerator
{
    public function generate(array $parameters): string
    {
        return Prompt::get('content/blog-outline', [
            'topic' => $parameters['topic'],
            'audience' => $parameters['audience'],
            'tone' => $parameters['tone'] ?? 'professional',
            'keywords' => $parameters['keywords'] ?? [],
            'goals' => $parameters['goals'],
            'wordCount' => $parameters['wordCount'] ?? 1500,
        ]);
    }
}
JavaScript

Leveraging Blade’s Full Power

The true strength of this package lies in its Blade integration. You can utilise conditional statements, loops, and even custom Blade directives to create sophisticated prompts that adapt based on context.

Consider a customer support scenario where the prompt should vary based on the customer’s history and issue severity:

You are a customer support specialist for our SaaS platform.

**Customer:** {{ $customer->name }} (Account: {{ $customer->account_id }})
**Issue Type:** {{ $issue->category }}
**Priority:** {{ $issue->priority }}

@if($customer->is_premium)
Note: This is a premium customer. Prioritise comprehensive solutions and offer proactive assistance.
@endif

**Issue Description:**
{{ $issue->description }}

@if($previousInteractions->count() > 0)
**Previous Interactions:**
@foreach($previousInteractions as $interaction)
- {{ $interaction->created_at->format('d/m/Y') }}: {{ $interaction->summary }}
@endforeach
@endif

@switch($issue->priority)
    @case('critical')
        Response Requirements: Immediate action plan, escalation path, and personal follow-up commitment.
    @break

    @case('high')
        Response Requirements: Detailed solution within 2 hours, workaround if available.
    @break

    @default
        Response Requirements: Helpful solution within 24 hours, self-service resources where applicable.
@endswitch

Provide a response that is empathetic, solution-focused, and maintains our brand voice.
JavaScript

Real-World Use Cases

E-commerce Product Descriptions

For an online shop needing to generate unique product descriptions at scale:

Generate a compelling product description for our online marketplace.

**Category:** {{ $product->category->name }}
**Product Name:** {{ $product->title }}
**Key Features:**
@foreach($product->features as $feature)
- {{ $feature }}
@endforeach

**Price Point:** £{{ number_format($product->price, 2) }}

@if($product->compareAtPrice > $product->price)
**Promotion:** Currently {{ round((($product->compareAtPrice - $product->price) / $product->compareAtPrice) * 100) }}% off the regular price of £{{ number_format($product->compareAtPrice, 2) }}
@endif

**Target Customer:** {{ $targetDemographic }}

The description should:
- Be between 150-200 words
- Highlight unique selling points
- Address customer pain points
- Include a subtle call-to-action
- Maintain an {{ $toneOfVoice }} tone
JavaScript

Data Analysis and Reporting

For automated report generation with AI:

Analyse the following dataset and provide actionable insights.

**Analysis Period:** {{ $startDate->format('d/m/Y') }} to {{ $endDate->format('d/m/Y') }}
**Metrics:**

@foreach($metrics as $metric => $value)
- {{ $metric }}: {{ $value }}
@endforeach

**Key Events During Period:**
@forelse($events as $event)
- {{ $event->date->format('d/m/Y') }}: {{ $event->description }}
@empty
- No significant events recorded
@endforelse

Please provide:
1. Trend analysis and patterns identified
2. Performance compared to previous period
3. Anomalies or concerns requiring attention
4. Recommendations for improvement
5. Predicted trends for next period
JavaScript

Best Practices for Organising Prompts

As your collection of prompts grows, maintaining a clear organisational structure becomes essential:

  • Group by functionality: Create subdirectories for different features (marketing, analytics, content, support).
  • Use descriptive naming: Name files clearly to indicate their purpose (customer-onboarding-email.md, product-review-summariser.md).
  • Version control: Since prompts are plain text files, they integrate seamlessly with Git, allowing you to track changes, review modifications, and roll back if needed.
  • Document variables: Add comments at the top of each prompt file listing expected variables and their types.
  • Extract common patterns: If you find yourself repeating certain instructions across multiple prompts, consider creating partial templates or shared components.

Current Limitations & Considerations

As the package is relatively new, it’s worth noting some current limitations. There’s no built-in Artisan command for scaffolding new prompt templates, though this would be a welcome addition. Configuration options are also minimal at present, meaning you cannot easily customise the prompts directory location or implement custom rendering logic without extending the package.

Whilst Blade’s templating power is advantageous, complex prompts with extensive logic might benefit from additional abstraction layers to keep templates maintainable. Consider moving complicated conditional logic into dedicated presenter classes that prepare data before passing it to the prompt template.

The Road Ahead

The concept behind this package represents an excellent foundation for AI prompt management in Laravel applications. The community could benefit from additional features such as:

  • Prompt versioning and A/B testing capabilities
  • Built-in validation for required variables
  • Caching mechanisms for frequently-used prompts
  • Integration with popular AI service providers
  • Testing utilities for prompt outputs

The Prompt package offers Laravel developers a clean, maintainable approach to managing AI prompts within their applications. By treating prompts as templates rather than scattered strings throughout your codebase, you gain better organisation, easier collaboration, and the flexibility to iterate on your AI interactions without diving into application logic.

Whilst the package is still maturing and lacks some advanced features, its core concept is sound and addresses a genuine need in modern Laravel development. For teams building AI-powered features, adopting a structured approach to prompt management early can save considerable technical debt down the line.

Whether you’re generating content, analysing data, or building conversational interfaces, giving your AI prompts the same care and structure you afford to your views is a practice worth embracing.

Get started with the Prompt package: github.com/chimit/prompt

With over 15 years experience in software engineering, consulting, ethical hacking and website development, I've continuously honed my skills as a problem-solving wizard. With expertise spanning the dynamic worlds of Laravel, WordPress, and PHP 8, I'm not just a programmer; I'm an avid explorer of innovative solutions, discovering something new every day.

Post Comment