PHPackages                             iamgerwin/nova-ai-context-aware-input - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. iamgerwin/nova-ai-context-aware-input

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

iamgerwin/nova-ai-context-aware-input
=====================================

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

v0.0.2(6mo ago)06MITPHPPHP ^8.2|^8.3CI failing

Since Nov 3Pushed 6mo agoCompare

[ Source](https://github.com/iamgerwin/nova-ai-context-aware-input)[ Packagist](https://packagist.org/packages/iamgerwin/nova-ai-context-aware-input)[ Docs](https://github.com/iamgerwin/nova-ai-context-aware-input)[ GitHub Sponsors]()[ RSS](/packages/iamgerwin-nova-ai-context-aware-input/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (17)Versions (3)Used By (0)

Nova AI Context-Aware Input
===========================

[](#nova-ai-context-aware-input)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e1788d9934b0fe5be9843862381c9c9001876bba3ce678ff4a20865215ff075f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69616d67657277696e2f6e6f76612d61692d636f6e746578742d61776172652d696e7075742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamgerwin/nova-ai-context-aware-input)[![Total Downloads](https://camo.githubusercontent.com/40659c617a47eafa8e61fadc1e8c51d07b421f902590a246aa4e1c7da2af0319/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69616d67657277696e2f6e6f76612d61692d636f6e746578742d61776172652d696e7075742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamgerwin/nova-ai-context-aware-input)[![License](https://camo.githubusercontent.com/b5c9007b6043f7d7dfa8ba0812a6c94c2894930fe3673a5c94bd19c660031e1e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f69616d67657277696e2f6e6f76612d61692d636f6e746578742d61776172652d696e7075742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamgerwin/nova-ai-context-aware-input)

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
--------

[](#features)

### Core Capabilities

[](#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 &amp; Security

[](#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

[](#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
------------

[](#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
------------

[](#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
-----------

[](#quick-start)

### 1. Configure Your AI Provider

[](#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

[](#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
-------------

[](#configuration)

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

### Default Provider

[](#default-provider)

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

### Field Defaults

[](#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-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

[](#caching)

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

### Security

[](#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
--------------

[](#usage-examples)

### Basic Usage

[](#basic-usage)

```
use Iamgerwin\NovaAiContextAwareInput\Fields\TextImprove;

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

### Advanced Configuration

[](#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

[](#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

[](#context-aware-improvements)

Leverage contextual information for smarter suggestions:

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

Available Providers
-------------------

[](#available-providers)

### OpenAI

[](#openai)

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

Environment variables:

```
OPENAI_API_KEY=sk-...
```

### Anthropic Claude

[](#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

[](#deepseek)

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

Environment variables:

```
DEEPSEEK_API_KEY=sk-...
```

### Azure OpenAI

[](#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)

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

### Sibling Fields Provider

[](#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

[](#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

[](#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

[](#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

[](#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
-----------------

[](#security-features)

### PII Detection

[](#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

[](#input-validation)

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

### Rate Limiting

[](#rate-limiting-1)

Prevent abuse with configurable rate limits:

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

### Caching

[](#caching-1)

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
------

[](#events)

The package dispatches events you can listen to:

### TextImproved Event

[](#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

[](#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
-------------------

[](#customizing-prompts)

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

```
// config/nova-ai-context-aware-input.php
'templates' => [
    'system' =>
