定制 iamgerwin/nova-ai-context-aware-input 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

iamgerwin/nova-ai-context-aware-input

Composer 安装命令:

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

包简介

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

README 文档

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.

iamgerwin/nova-ai-context-aware-input 适用场景与选型建议

iamgerwin/nova-ai-context-aware-input 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「nova」 「laravel」 「ai」 「laravel-nova」 「nova-field」 「openai」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 iamgerwin/nova-ai-context-aware-input 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 iamgerwin/nova-ai-context-aware-input 我们能提供哪些服务?
定制开发 / 二次开发

基于 iamgerwin/nova-ai-context-aware-input 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-03