From 2e052498a5ae864fb9befe9463dced26fe00b891 Mon Sep 17 00:00:00 2001 From: gouki Date: Thu, 15 Oct 2026 00:06:55 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20AI=20=E4=BB=BB=E5=8A=A1=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E6=89=A7=E8=A1=8C=E3=80=81=E8=AF=84=E8=AE=BA=E5=9E=83?= =?UTF-8?q?=E5=9C=BE=E7=AE=A1=E7=90=86=E3=80=81=E4=BC=9A=E5=91=98=E5=AF=BC?= =?UTF-8?q?=E8=88=AA=E5=88=86=E7=BB=84=E3=80=81=E5=A4=9A=20AI=20=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 评论 AI 审核/文章润色改为同步执行(站点无 queue worker,任务曾永久卡队列, 导致垃圾评论滞留待审核、润色毫无效果);审核在响应结束后经 terminating 触发 - 评论表:修复 approve 闭包里误嵌入 recordUrl 的坏链;新增「非垃圾」恢复发布、 批量「标为垃圾」、工具栏「清空垃圾评论」;各操作补充通知反馈 - 会员套餐/订阅/订单移入新导航组「会员」 - LlmClient 支持多服务商 profile;AI 设置页可添加多个 AI 并为审核/润色/封面 分别指定服务商(不指定用默认配置);封面生成同步支持 profile - AI 设置页:润色改同步并即时展示结果,按钮加 loading;删除无 workerman 的 WebSocket 进度区块 --- app/Blog/Jobs/AiJob.php | 3 +- app/Blog/Services/CoverGenerator.php | 24 +++++-- app/Blog/Services/LlmClient.php | 47 +++++++++++- .../Comments/Tables/CommentsTable.php | 58 +++++++++++++-- app/Providers/Filament/AdminPanelProvider.php | 1 + .../src/Filament/Pages/AiSettings.php | 71 ++++++++++++++++++- .../src/Jobs/AiModerateCommentJob.php | 2 + .../src/Jobs/AiPolishContentJob.php | 2 + .../src/ServiceProvider.php | 9 ++- .../views/ai-settings.blade.php | 65 ++--------------- .../Resources/MembershipPlanResource.php | 2 +- .../Resources/SubscriptionResource.php | 2 +- .../Filament/Resources/PaymentResource.php | 2 +- tests/Feature/AiModerationTest.php | 16 +++-- 14 files changed, 221 insertions(+), 83 deletions(-) diff --git a/app/Blog/Jobs/AiJob.php b/app/Blog/Jobs/AiJob.php index 303f9a9..2d2a258 100644 --- a/app/Blog/Jobs/AiJob.php +++ b/app/Blog/Jobs/AiJob.php @@ -8,7 +8,8 @@ namespace App\Blog\Jobs; use App\Blog\Services\LlmClient; /** - * 由 Workerman 消费者执行的 AI 任务统一接口。 + * AI 任务统一接口。站点无常驻 queue worker,任务在响应结束后同步执行 + * (comment.created 钩子经 app()->terminating 触发,后台操作直接 dispatchSync)。 */ interface AiJob { diff --git a/app/Blog/Services/CoverGenerator.php b/app/Blog/Services/CoverGenerator.php index d4853bf..2f503fa 100644 --- a/app/Blog/Services/CoverGenerator.php +++ b/app/Blog/Services/CoverGenerator.php @@ -18,17 +18,29 @@ class CoverGenerator public function isConfigured(): bool { - return $this->llm->isConfigured(); + return $this->llm()->isConfigured(); } public function model(?string $override = null): string { - return $override ?: (string) blog_setting('llm_image_model', 'image-01'); + // 优先级:命令行参数 > llm_image_model 设置 > 图片 profile 的模型 > image-01 + $profileModel = blog_setting('llm_profile_image') ? $this->llm()->model() : null; + + return $override + ?: (string) (blog_setting('llm_image_model') ?: $profileModel ?: 'image-01'); + } + + /** + * 封面生成使用的 LLM 配置(可在 AI 设置里指定独立的服务商)。 + */ + private function llm(): LlmClient + { + return $this->llm->forProfile((string) blog_setting('llm_profile_image', '')); } public function generateFor(Post $post, ?string $model = null, ?string $style = null): void { - if (! $this->llm->isConfigured()) { + if (! $this->llm()->isConfigured()) { throw new \RuntimeException('LLM 未配置:请先在后台「AI 设置」配置 Base URL / API Key'); } @@ -102,9 +114,11 @@ class CoverGenerator private function requestImage(string $prompt, ?string $model = null): \Illuminate\Http\Client\Response { + $llm = $this->llm(); + return Http::timeout(120) - ->withToken($this->llm->apiKey()) - ->post($this->llm->baseUrl().'/image_generation', [ + ->withToken($llm->apiKey()) + ->post($llm->baseUrl().'/image_generation', [ 'model' => $this->model($model), 'prompt' => $prompt, 'aspect_ratio' => '16:9', diff --git a/app/Blog/Services/LlmClient.php b/app/Blog/Services/LlmClient.php index 56bcc11..48e4267 100644 --- a/app/Blog/Services/LlmClient.php +++ b/app/Blog/Services/LlmClient.php @@ -10,22 +10,26 @@ use Illuminate\Support\Facades\Log; /** * OpenAI 兼容 LLM 客户端(支持 OpenAI / DeepSeek / 通义 / 自建代理)。 + * 支持多服务商:后台「AI 设置」可配置 llm_profiles,用 forProfile('名称') 切换。 */ class LlmClient { + /** @var array{base_url?: string, api_key?: string, model?: string} */ + private array $overrides = []; + public function baseUrl(): string { - return rtrim((string) blog_setting('llm_base_url', config('services.llm.base_url', env('LLM_BASE_URL'))), '/'); + return rtrim((string) ($this->overrides['base_url'] ?? blog_setting('llm_base_url', config('services.llm.base_url', env('LLM_BASE_URL')))), '/'); } public function apiKey(): string { - return (string) blog_setting('llm_api_key', config('services.llm.api_key', env('LLM_API_KEY'))); + return (string) ($this->overrides['api_key'] ?? blog_setting('llm_api_key', config('services.llm.api_key', env('LLM_API_KEY')))); } public function model(): string { - return (string) blog_setting('llm_model', config('services.llm.model', env('LLM_MODEL', 'gpt-4o-mini'))); + return (string) ($this->overrides['model'] ?? blog_setting('llm_model', config('services.llm.model', env('LLM_MODEL', 'gpt-4o-mini')))); } public function isConfigured(): bool @@ -33,6 +37,43 @@ class LlmClient return $this->baseUrl() !== '' && $this->apiKey() !== ''; } + /** + * 已配置的额外 AI 服务商列表(后台 AI 设置维护)。 + * + * @return list + */ + public static function profiles(): array + { + $profiles = json_decode((string) blog_setting('llm_profiles', '[]'), true); + + return is_array($profiles) ? $profiles : []; + } + + /** + * 切换到指定名称的服务商配置;名称为空或不存在时返回默认配置。 + */ + public function forProfile(?string $name): static + { + if (! $name) { + return $this; + } + + foreach (self::profiles() as $profile) { + if (($profile['name'] ?? '') === $name) { + $clone = clone $this; + $clone->overrides = array_filter([ + 'base_url' => $profile['base_url'] ?? null, + 'api_key' => $profile['api_key'] ?? null, + 'model' => $profile['model'] ?? null, + ], fn ($value) => filled($value)); + + return $clone; + } + } + + return $this; + } + /** * 简单的聊天补全。 * diff --git a/app/Filament/Resources/Comments/Tables/CommentsTable.php b/app/Filament/Resources/Comments/Tables/CommentsTable.php index 65a9f82..c1f8714 100644 --- a/app/Filament/Resources/Comments/Tables/CommentsTable.php +++ b/app/Filament/Resources/Comments/Tables/CommentsTable.php @@ -7,12 +7,15 @@ namespace App\Filament\Resources\Comments\Tables; use App\Models\Comment; use Filament\Actions\Action; +use Filament\Actions\BulkAction; use Filament\Actions\BulkActionGroup; use Filament\Actions\DeleteBulkAction; use Filament\Actions\EditAction; +use Filament\Notifications\Notification; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\SelectFilter; use Filament\Tables\Table; +use Illuminate\Support\Collection; class CommentsTable { @@ -74,21 +77,68 @@ class CommentsTable ->color('success') ->visible(fn (Comment $record) => $record->status !== 'published') ->action(function (Comment $record): void { - $record->update(['status' => 'published']) - ->recordUrl(null) - ->recordAction(null); + $record->update(['status' => 'published']); $record->post?->increment('comment_count'); + Notification::make()->title('评论已通过')->success()->send(); }), Action::make('spam') ->label('垃圾') ->icon('heroicon-o-x-mark') ->color('danger') ->visible(fn (Comment $record) => $record->status !== 'spam') - ->action(fn (Comment $record) => $record->update(['status' => 'spam'])), + ->action(function (Comment $record): void { + if ($record->status === 'published') { + $record->post?->decrement('comment_count'); + } + $record->update(['status' => 'spam']); + Notification::make()->title('已标记为垃圾评论')->success()->send(); + }), + Action::make('notSpam') + ->label('非垃圾') + ->icon('heroicon-o-check-badge') + ->color('success') + ->requiresConfirmation() + ->modalHeading('标记为非垃圾') + ->modalDescription('该评论将恢复为已发布状态。') + ->visible(fn (Comment $record) => $record->status === 'spam') + ->action(function (Comment $record): void { + $record->update(['status' => 'published']); + $record->post?->increment('comment_count'); + Notification::make()->title('已恢复发布')->success()->send(); + }), EditAction::make(), ]) + ->recordUrl(null) + ->recordAction(null) ->toolbarActions([ + Action::make('purgeSpam') + ->label('清空垃圾评论') + ->icon('heroicon-o-trash') + ->color('danger') + ->requiresConfirmation() + ->modalHeading('清空垃圾评论') + ->modalDescription(fn (): string => '将永久删除全部 '.Comment::query()->where('status', 'spam')->count().' 条垃圾评论,不可恢复。') + ->visible(fn (): bool => Comment::query()->where('status', 'spam')->exists()) + ->action(function (): void { + $count = Comment::query()->where('status', 'spam')->count(); + Comment::query()->where('status', 'spam')->delete(); + Notification::make()->title("已删除 {$count} 条垃圾评论")->success()->send(); + }), BulkActionGroup::make([ + BulkAction::make('markSpam') + ->label('标为垃圾') + ->icon('heroicon-o-x-mark') + ->color('danger') + ->requiresConfirmation() + ->action(function (Collection $records): void { + $records->each(function (Comment $record): void { + if ($record->status === 'published') { + $record->post?->decrement('comment_count'); + } + $record->update(['status' => 'spam']); + }); + Notification::make()->title('已标记 '.$records->count().' 条为垃圾评论')->success()->send(); + }), DeleteBulkAction::make(), ]), ]) diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 83558a5..866e0d7 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -83,6 +83,7 @@ class AdminPanelProvider extends PanelProvider ) ->navigationGroups([ NavigationGroup::make('内容'), + NavigationGroup::make('会员'), NavigationGroup::make('管理'), NavigationGroup::make('插件'), ]) diff --git a/plugins/neatstudio.ai-moderation/src/Filament/Pages/AiSettings.php b/plugins/neatstudio.ai-moderation/src/Filament/Pages/AiSettings.php index 90b1240..c9d94c7 100644 --- a/plugins/neatstudio.ai-moderation/src/Filament/Pages/AiSettings.php +++ b/plugins/neatstudio.ai-moderation/src/Filament/Pages/AiSettings.php @@ -5,9 +5,11 @@ declare(strict_types=1); namespace Plugins\Neatstudio\AiModeration\Filament\Pages; +use App\Blog\Services\LlmClient; use App\Models\Post; use App\Models\Setting; use Filament\Actions\Action; +use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; @@ -46,9 +48,24 @@ class AiSettings extends Page 'cover_prompt_style' => Setting::get('cover_prompt_style', '扁平插画风格,色调柔和,构图简洁'), 'ai_moderation_enabled' => (int) Setting::get('ai_moderation_enabled', 1) === 1, 'ai_moderation_system_prompt' => Setting::get('ai_moderation_system_prompt', '你是博客评论审核员。判断评论是否包含:广告/垃圾、人身攻击、违法内容、无关灌水。只回复 JSON:{"verdict":"approved|rejected|spam","reason":"简短理由"}'), + 'llm_profiles' => LlmClient::profiles(), + 'llm_profile_moderation' => Setting::get('llm_profile_moderation'), + 'llm_profile_polish' => Setting::get('llm_profile_polish'), + 'llm_profile_image' => Setting::get('llm_profile_image'), ]); } + /** + * @return array + */ + private function profileOptions(): array + { + return collect(LlmClient::profiles()) + ->pluck('name', 'name') + ->filter() + ->toArray(); + } + public function form(Schema $schema): Schema { return $schema @@ -63,6 +80,34 @@ class AiSettings extends Page ->helperText('供 php artisan covers:generate 批量生成封面使用(接口:{Base URL}/image_generation)'), TextInput::make('cover_prompt_style')->label('封面风格')->default('扁平插画风格,色调柔和,构图简洁'), ]), + \Filament\Schemas\Components\Section::make('多 AI 配置') + ->description('可配置多个 AI 服务商,并给不同任务指定独立的服务商;不指定则统一使用上方默认配置') + ->schema([ + Repeater::make('llm_profiles') + ->label('AI 服务商') + ->schema([ + TextInput::make('name')->label('名称')->required()->placeholder('deepseek'), + TextInput::make('base_url')->label('Base URL')->required()->placeholder('https://api.deepseek.com/v1'), + TextInput::make('api_key')->label('API Key')->password()->required(), + TextInput::make('model')->label('模型')->placeholder('deepseek-chat'), + ]) + ->columns(4) + ->addActionLabel('添加 AI 服务商') + ->defaultItems(0) + ->columnSpanFull(), + Select::make('llm_profile_moderation') + ->label('评论审核使用') + ->options(fn (): array => $this->profileOptions()) + ->placeholder('默认配置'), + Select::make('llm_profile_polish') + ->label('文章润色使用') + ->options(fn (): array => $this->profileOptions()) + ->placeholder('默认配置'), + Select::make('llm_profile_image') + ->label('封面生成使用') + ->options(fn (): array => $this->profileOptions()) + ->placeholder('默认配置'), + ]), \Filament\Schemas\Components\Section::make('评论审核') ->schema([ Toggle::make('ai_moderation_enabled')->label('新评论启用 AI 自动审核'), @@ -77,7 +122,17 @@ class AiSettings extends Page $data = $this->form->getState(); foreach ($data as $key => $value) { - Setting::set($key, is_bool($value) ? (string) (int) $value : (string) $value); + if (is_bool($value)) { + $value = (string) (int) $value; + } elseif (is_array($value)) { + // Repeater(llm_profiles)等数组配置存 JSON,丢弃未填名称的行 + $value = json_encode( + array_values(array_filter($value, fn ($row) => filled($row['name'] ?? null))), + JSON_UNESCAPED_UNICODE + ); + } + + Setting::set($key, (string) $value); } Notification::make()->title('AI 设置已保存')->success()->send(); @@ -93,8 +148,18 @@ class AiSettings extends Page return; } - dispatch(new AiPolishContentJob($post->id))->onQueue('ai'); - Notification::make()->title('润色任务已提交(由 Workerman 异步执行)')->info()->send(); + // 同步执行(站点无常驻 queue worker),几十秒内出结果并直接展示 + try { + AiPolishContentJob::dispatchSync($post->id); + $this->polishResult = $post->fresh()->meta['ai_polished'] ?? null; + + Notification::make() + ->title($this->polishResult ? '润色完成,下方预览后可采纳' : '润色未返回结果') + ->{$this->polishResult ? 'success' : 'warning'}() + ->send(); + } catch (\Throwable $e) { + Notification::make()->title('润色失败')->body($e->getMessage())->danger()->send(); + } } public function acceptPolish(Post $post): void diff --git a/plugins/neatstudio.ai-moderation/src/Jobs/AiModerateCommentJob.php b/plugins/neatstudio.ai-moderation/src/Jobs/AiModerateCommentJob.php index 82700b9..792b930 100644 --- a/plugins/neatstudio.ai-moderation/src/Jobs/AiModerateCommentJob.php +++ b/plugins/neatstudio.ai-moderation/src/Jobs/AiModerateCommentJob.php @@ -29,6 +29,8 @@ class AiModerateCommentJob implements AiJob, ShouldQueue return; } + $llm = $llm->forProfile((string) blog_setting('llm_profile_moderation', '')); + WorkermanBroadcaster::send('ai.moderation.started', ['comment_id' => $this->commentId]); $system = (string) blog_setting('ai_moderation_system_prompt', '你是博客评论审核员。判断评论是否包含:广告/垃圾、人身攻击、违法内容、无关灌水。只回复 JSON:{"verdict":"approved|rejected|spam","reason":"简短理由"}'); diff --git a/plugins/neatstudio.ai-moderation/src/Jobs/AiPolishContentJob.php b/plugins/neatstudio.ai-moderation/src/Jobs/AiPolishContentJob.php index 1e9b2ec..401504c 100644 --- a/plugins/neatstudio.ai-moderation/src/Jobs/AiPolishContentJob.php +++ b/plugins/neatstudio.ai-moderation/src/Jobs/AiPolishContentJob.php @@ -32,6 +32,8 @@ class AiPolishContentJob implements AiJob, ShouldQueue ? $post->content : (new \League\HTMLToMarkdown\HtmlConverter())->convert($post->content); + $llm = $llm->forProfile((string) blog_setting('llm_profile_polish', '')); + $polished = $llm->chat([ ['role' => 'system', 'content' => '你是中文博客编辑。润色下面的文章,保持原意、事实、Markdown 结构不变,改进表达、语法、可读性。直接输出润色后的完整 Markdown。'], ['role' => 'user', 'content' => $source], diff --git a/plugins/neatstudio.ai-moderation/src/ServiceProvider.php b/plugins/neatstudio.ai-moderation/src/ServiceProvider.php index 4da92b9..95d0b6d 100644 --- a/plugins/neatstudio.ai-moderation/src/ServiceProvider.php +++ b/plugins/neatstudio.ai-moderation/src/ServiceProvider.php @@ -28,7 +28,14 @@ class ServiceProvider extends PluginServiceProvider return; } - dispatch(new Jobs\AiModerateCommentJob($comment->id))->onQueue('ai'); + // 站点无常驻 queue worker:响应结束后同步执行审核,避免任务永远卡在队列里 + $job = fn () => Jobs\AiModerateCommentJob::dispatchSync($comment->id); + + if (app()->runningInConsole()) { + $job(); + } else { + app()->terminating($job); + } }, 10); } } diff --git a/plugins/neatstudio.ai-moderation/views/ai-settings.blade.php b/plugins/neatstudio.ai-moderation/views/ai-settings.blade.php index 2886672..05d9642 100644 --- a/plugins/neatstudio.ai-moderation/views/ai-settings.blade.php +++ b/plugins/neatstudio.ai-moderation/views/ai-settings.blade.php @@ -6,13 +6,16 @@ - +
@foreach(\App\Models\Post::query()->latest()->limit(20)->get(['id','title']) as $post)
{{ $post->title }} -
- AI 润色 +
+ + + AI 润色 + @if($post->meta['ai_polished'] ?? null) 采纳 @endif @@ -28,60 +31,4 @@
@endif - - -
-

等待事件…

-
-
- - diff --git a/plugins/neatstudio.membership/src/Filament/Resources/MembershipPlanResource.php b/plugins/neatstudio.membership/src/Filament/Resources/MembershipPlanResource.php index cc070bb..640c5f7 100644 --- a/plugins/neatstudio.membership/src/Filament/Resources/MembershipPlanResource.php +++ b/plugins/neatstudio.membership/src/Filament/Resources/MembershipPlanResource.php @@ -21,7 +21,7 @@ use Plugins\Neatstudio\Membership\Models\MembershipPlan; class MembershipPlanResource extends Resource { - protected static \UnitEnum|string|null $navigationGroup = '管理'; + protected static \UnitEnum|string|null $navigationGroup = '会员'; protected static ?string $model = MembershipPlan::class; diff --git a/plugins/neatstudio.membership/src/Filament/Resources/SubscriptionResource.php b/plugins/neatstudio.membership/src/Filament/Resources/SubscriptionResource.php index 2651595..90d8b0d 100644 --- a/plugins/neatstudio.membership/src/Filament/Resources/SubscriptionResource.php +++ b/plugins/neatstudio.membership/src/Filament/Resources/SubscriptionResource.php @@ -17,7 +17,7 @@ use Plugins\Neatstudio\Membership\Models\Subscription; class SubscriptionResource extends Resource { - protected static \UnitEnum|string|null $navigationGroup = '管理'; + protected static \UnitEnum|string|null $navigationGroup = '会员'; protected static ?string $model = Subscription::class; diff --git a/plugins/neatstudio.payment/src/Filament/Resources/PaymentResource.php b/plugins/neatstudio.payment/src/Filament/Resources/PaymentResource.php index 3e39150..9a6988a 100644 --- a/plugins/neatstudio.payment/src/Filament/Resources/PaymentResource.php +++ b/plugins/neatstudio.payment/src/Filament/Resources/PaymentResource.php @@ -15,7 +15,7 @@ use Plugins\Neatstudio\Payment\Models\Payment; class PaymentResource extends Resource { - protected static \UnitEnum|string|null $navigationGroup = '管理'; + protected static \UnitEnum|string|null $navigationGroup = '会员'; protected static ?string $model = Payment::class; diff --git a/tests/Feature/AiModerationTest.php b/tests/Feature/AiModerationTest.php index da895a3..c42fbaa 100644 --- a/tests/Feature/AiModerationTest.php +++ b/tests/Feature/AiModerationTest.php @@ -27,10 +27,8 @@ class AiModerationTest extends TestCase Setting::set('llm_model', 'test-model'); } - public function test_comment_created_dispatches_moderation_job(): void + public function test_comment_created_runs_moderation_after_response(): void { - \Illuminate\Support\Facades\Queue::fake(); - $post = Post::create([ 'title' => '评论审核', 'slug' => 'ai-comment', @@ -40,12 +38,20 @@ class AiModerationTest extends TestCase 'published_at' => now(), ]); + $llm = $this->mock(LlmClient::class); + $llm->shouldReceive('isConfigured')->andReturn(true); + $llm->shouldReceive('forProfile')->andReturnSelf(); + $llm->shouldReceive('chat')->andReturn('{"verdict":"approved","reason":"正常"}'); + $this->post('/posts/'.$post->id.'/comments', [ 'author_name' => '访客', 'content' => '这是一条需要审核的评论', ]); - \Illuminate\Support\Facades\Queue::assertPushed(AiModerateCommentJob::class); + // 审核在响应结束后同步执行(app()->terminating),测试请求周期内即完成 + $comment = Comment::query()->latest('id')->first(); + $this->assertSame('published', $comment->status); + $this->assertStringContainsString('approved', $comment->ai_review['raw'] ?? ''); } public function test_moderation_job_approves_comment(): void @@ -68,6 +74,7 @@ class AiModerationTest extends TestCase ]); $llm = $this->mock(LlmClient::class); + $llm->shouldReceive('forProfile')->andReturnSelf(); $llm->shouldReceive('chat')->once()->andReturn('{"verdict":"approved","reason":"正常"}'); (new AiModerateCommentJob($comment->id))->handle($llm); @@ -97,6 +104,7 @@ class AiModerationTest extends TestCase ]); $llm = $this->mock(LlmClient::class); + $llm->shouldReceive('forProfile')->andReturnSelf(); $llm->shouldReceive('chat')->once()->andReturn('{"verdict":"spam","reason":"广告"}'); (new AiModerateCommentJob($comment->id))->handle($llm);