iamgerwin/nova-ai-context-aware-input

AI-assisted Nova field that seamlessly improves text with context, while respecting typical Nova workflows

Fund package maintenance!
John Gerwin De las Alas

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/iamgerwin/nova-ai-context-aware-input

v0.0.2 2025-11-03 19:22 UTC

This package is auto-updated.

Last update: 2025-11-03 19:28:44 UTC


README

Latest Version on Packagist Total Downloads License

A Laravel Nova field that brings the power of AI to your admin panel, enhancing text input with intelligent, context-aware suggestions. Seamlessly integrates with Nova's workflow while providing real-time text improvements powered by leading AI providers.

Think of it as having a professional editor looking over your shoulder, understanding the context of your entire form, and offering thoughtful improvements—without disrupting your natural writing flow.

Features

Core Capabilities

  • Multiple AI Providers: OpenAI, Anthropic Claude, DeepSeek, and Azure OpenAI support
  • Context-Aware Intelligence: Leverages form data, user information, and resource context for relevant suggestions
  • Real-Time Suggestions: Choose from blur, idle, or manual trigger modes
  • Visual Diff Mode: See exactly what changed with highlighted additions and deletions
  • Suggestion History: Navigate through previous AI suggestions with undo/redo support
  • Flexible Styling: Six built-in writing styles (professional, formal, friendly, succinct, marketing, technical)

Performance & Security

  • Intelligent Caching: Reduces API costs by caching similar improvements
  • Rate Limiting: Configurable per-user or global rate limits
  • PII Detection: Built-in detection to prevent sensitive data from being sent to AI providers
  • Input Validation: Maximum length enforcement and content filtering
  • Fallback Support: Automatic failover to backup providers

Developer Experience

  • Zero Configuration: Works out of the box with sensible defaults
  • Highly Customizable: Fine-tune every aspect through configuration or field methods
  • Event System: Hook into TextImproved and SuggestionDiscarded events
  • Comprehensive Logging: Track usage, errors, and performance metrics
  • Type-Safe: Full PHP 8.2+ type declarations

Requirements

  • PHP 8.2+ or 8.3+
  • Laravel 10.x, 11.x, or 12.x
  • Laravel Nova 4.x or 5.x
  • At least one AI provider API key (OpenAI, Anthropic, DeepSeek, or Azure OpenAI)

Installation

Install the package via Composer:

composer require iamgerwin/nova-ai-context-aware-input

Publish the configuration file:

php artisan vendor:publish --tag="nova-ai-context-aware-input-config"

Build the Nova assets:

cd vendor/iamgerwin/nova-ai-context-aware-input
npm install && npm run build

Or if you prefer using the root directory:

php artisan nova:publish

Quick Start

1. Configure Your AI Provider

Add your API key to your .env file:

# Choose your preferred provider
TEXT_IMPROVE_PROVIDER=openai:gpt-4o-mini
OPENAI_API_KEY=sk-...

# Or use Anthropic
TEXT_IMPROVE_PROVIDER=anthropic:claude-3-5-sonnet-20241022
ANTHROPIC_API_KEY=sk-ant-...

# Or DeepSeek
TEXT_IMPROVE_PROVIDER=deepseek:deepseek-chat
DEEPSEEK_API_KEY=sk-...

# Or Azure OpenAI
TEXT_IMPROVE_PROVIDER=azure_openai:gpt-4
AZURE_OPENAI_API_KEY=...
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4

2. Use the Field in Your Nova Resource

Replace the standard Textarea field with TextImprove:

use Iamgerwin\NovaAiContextAwareInput\Fields\TextImprove;

public function fields(Request $request)
{
    return [
        TextImprove::make('Description')
            ->style('professional')
            ->trigger('blur'),
    ];
}

That's it! Your field now has AI-powered text improvement capabilities.

Configuration

The package comes with extensive configuration options. Here are the key settings:

Default Provider

// config/nova-ai-context-aware-input.php
'provider' => env('TEXT_IMPROVE_PROVIDER', 'openai:gpt-4o-mini'),

Field Defaults

'min_length' => 12,           // Minimum characters before AI triggers
'history_size' => 3,          // Number of suggestions to keep
'trigger' => 'blur',          // blur|idle|manual
'style' => 'professional',    // Default writing style
'debounce_ms' => 600,        // Milliseconds to wait before processing

Rate Limiting

'rate_limit' => env('TEXT_IMPROVE_RATE_LIMIT', 'user:10,1'),

Format: scope:max_attempts,decay_minutes

  • user:10,1 - 10 attempts per user per minute
  • global:100,60 - 100 attempts globally per hour

Caching

'cache' => [
    'enabled' => true,
    'ttl' => 3600,              // Cache for 1 hour
    'driver' => env('CACHE_DRIVER', 'file'),
],

Security

'security' => [
    'max_input_length' => 5000,
    'enable_pii_detection' => true,
    'pii_patterns' => [
        // Email detection
        '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/',
        // Phone numbers
        '/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/',
        // Credit card numbers
        '/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/',
    ],
],

Usage Examples

Basic Usage

use Iamgerwin\NovaAiContextAwareInput\Fields\TextImprove;

TextImprove::make('Content')
    ->style('professional')
    ->trigger('blur')
    ->minLength(20);

Advanced Configuration

TextImprove::make('Product Description')
    ->provider('anthropic:claude-3-5-sonnet-20241022')
    ->fallback('openai:gpt-4o-mini')
    ->style('marketing')
    ->trigger('idle')
    ->context(['title', 'category', 'price'])
    ->minLength(30)
    ->maxTokens(500)
    ->history(5)
    ->rateLimit('user:20,1')
    ->diff(true);

Custom Styling

TextImprove::make('Blog Post')
    ->style('technical')  // Built-in styles
    ->trigger('manual');  // Only improve when user clicks button

Available styles:

  • professional - Professional and clear business writing
  • formal - Formal and academic tone
  • friendly - Warm and approachable tone
  • succinct - Brief and to the point
  • marketing - Persuasive marketing copy
  • technical - Technical and precise language

Context-Aware Improvements

Leverage contextual information for smarter suggestions:

TextImprove::make('Email Body')
    ->context(['subject', 'recipient_name', 'sender_role'])
    ->style('professional');

Available Providers

OpenAI

'provider' => 'openai:gpt-4o-mini',
// or
'provider' => 'openai:gpt-4',
'provider' => 'openai:gpt-4-turbo',

Environment variables:

OPENAI_API_KEY=sk-...

Anthropic Claude

'provider' => 'anthropic:claude-3-5-sonnet-20241022',
// or
'provider' => 'anthropic:claude-3-opus-20240229',
'provider' => 'anthropic:claude-3-haiku-20240307',

Environment variables:

ANTHROPIC_API_KEY=sk-ant-...

DeepSeek

'provider' => 'deepseek:deepseek-chat',

Environment variables:

DEEPSEEK_API_KEY=sk-...

Azure OpenAI

'provider' => 'azure_openai:gpt-4',

Environment variables:

AZURE_OPENAI_API_KEY=...
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4

Context Providers

Context providers enrich AI suggestions by providing relevant information about the form, user, and resource being edited.

Sibling Fields Provider

Includes data from other fields in the form:

TextImprove::make('Description')
    ->context(['title', 'category', 'tags']);

This helps the AI understand the broader context. For example, when improving a product description, it knows the product's title and category.

User Persona Provider

Includes information about the authenticated user:

// Automatically includes:
// - User role
// - Locale/language preference
// - Timezone

Helps tailor suggestions to the user's context and language.

Resource Snapshot Provider

Provides context about the resource being edited:

// Automatically includes:
// - Resource type (e.g., "Article", "Product")
// - Resource ID
// - Common fields (title, name, description, category, type, status)

Policy Hints Provider

Enforces content policies and guidelines:

// config/nova-ai-context-aware-input.php
'policy_hints' => [
    'Avoid using profanity or offensive language.',
    'Maintain professional tone and clarity.',
    'Preserve factual accuracy of the original text.',
],

You can also add custom hints per field:

use Iamgerwin\NovaAiContextAwareInput\Context\PolicyHintsProvider;

TextImprove::make('Comment')
    ->context([
        (new PolicyHintsProvider())->addHints([
            'Be respectful and constructive.',
            'Avoid personal attacks.',
        ])
    ]);

Disabling Context Providers

// config/nova-ai-context-aware-input.php
'context_providers' => [
    'sibling_fields' => true,
    'user_persona' => false,      // Disable user context
    'resource_snapshot' => true,
    'policy_hints' => true,
],

Security Features

PII Detection

The package automatically detects and warns about potential PII (Personally Identifiable Information) before sending data to AI providers:

  • Email addresses
  • Phone numbers
  • Credit card numbers
  • Custom patterns (configurable)

When PII is detected, the request is blocked and an error is returned.

Input Validation

  • Maximum input length enforcement (default: 5000 characters)
  • Content sanitization
  • API key validation

Rate Limiting

Prevent abuse with configurable rate limits:

TextImprove::make('Content')
    ->rateLimit('user:10,1');  // 10 requests per user per minute

Caching

Reduce costs and improve performance by caching improvements:

// Cache key is based on: hash(input + context + style)
// Same input with same context = cache hit

Events

The package dispatches events you can listen to:

TextImproved Event

Fired when text is successfully improved:

use Iamgerwin\NovaAiContextAwareInput\Events\TextImproved;

class LogTextImprovement
{
    public function handle(TextImproved $event): void
    {
        // $event->originalText
        // $event->improvedText
        // $event->provider
        // $event->style
        // $event->user
    }
}

SuggestionDiscarded Event

Fired when a user discards an AI suggestion:

use Iamgerwin\NovaAiContextAwareInput\Events\SuggestionDiscarded;

class LogDiscardedSuggestion
{
    public function handle(SuggestionDiscarded $event): void
    {
        // $event->originalText
        // $event->suggestedText
        // $event->user
    }
}

Customizing Prompts

You can customize the system and user prompts sent to AI providers:

// config/nova-ai-context-aware-input.php
'templates' => [
    'system' => <<<'TXT'
You are an expert editor improving business text for clarity and professionalism.
Your task is to enhance the given text while:
- Preserving all factual information
- Respecting domain-specific terminology
- Maintaining the original intent and meaning
- Following the specified style guidelines
Return ONLY the improved text without explanations, quotes, or additional commentary.
TXT,
    'user' => <<<'TXT'
Please improve the following text:

{{ user_input }}

Context: {{ context }}
Desired Style: {{ style }}
Language: {{ language }}
TXT,
],

Available placeholders:

  • {{ user_input }} - The text to improve
  • {{ context }} - Contextual information from providers
  • {{ style }} - The selected writing style
  • {{ language }} - User's language/locale

Testing

Run the test suite:

composer test

Run tests with coverage:

composer test-coverage

Run static analysis:

composer analyse

Format code (PSR-12):

composer format

Performance Tips

  1. Enable caching to reduce API calls for similar content
  2. Use rate limiting to control costs
  3. Choose appropriate models: Smaller models (gpt-4o-mini, claude-3-haiku) for simple improvements, larger models for complex content
  4. Set reasonable minLength to avoid processing very short inputs
  5. Use trigger='manual' for fields where AI assistance is optional

Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Development Setup

  1. Clone the repository
  2. Install dependencies: composer install && npm install
  3. Copy .env.example to .env and add your API keys
  4. Run tests: composer test

Changelog

Please see CHANGELOG.md for recent changes.

Security

If you discover any security-related issues, please email iamgerwin@live.com instead of using the issue tracker.

License

The MIT License (MIT). Please see LICENSE.md for more information.

Credits

Acknowledgments

Special thanks to the Laravel and Nova communities for their excellent frameworks and tools that made this package possible.

Made with care for the Laravel community.