Files
laralog/app/Blog/Services/LlmClient.php
T
gouki 2e052498a5
Build and Deploy / verify (push) Successful in 10s
Build and Deploy / deploy (push) Successful in 20s
feat: AI 任务同步执行、评论垃圾管理、会员导航分组、多 AI 配置
- 评论 AI 审核/文章润色改为同步执行(站点无 queue worker,任务曾永久卡队列,
  导致垃圾评论滞留待审核、润色毫无效果);审核在响应结束后经 terminating 触发
- 评论表:修复 approve 闭包里误嵌入 recordUrl 的坏链;新增「非垃圾」恢复发布、
  批量「标为垃圾」、工具栏「清空垃圾评论」;各操作补充通知反馈
- 会员套餐/订阅/订单移入新导航组「会员」
- LlmClient 支持多服务商 profile;AI 设置页可添加多个 AI 并为审核/润色/封面
  分别指定服务商(不指定用默认配置);封面生成同步支持 profile
- AI 设置页:润色改同步并即时展示结果,按钮加 loading;删除无 workerman 的
  WebSocket 进度区块
2026-10-15 00:06:55 +00:00

108 lines
3.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Blog\Services;
use Illuminate\Support\Facades\Http;
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) ($this->overrides['base_url'] ?? blog_setting('llm_base_url', config('services.llm.base_url', env('LLM_BASE_URL')))), '/');
}
public function apiKey(): string
{
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) ($this->overrides['model'] ?? blog_setting('llm_model', config('services.llm.model', env('LLM_MODEL', 'gpt-4o-mini'))));
}
public function isConfigured(): bool
{
return $this->baseUrl() !== '' && $this->apiKey() !== '';
}
/**
* 已配置的额外 AI 服务商列表(后台 AI 设置维护)。
*
* @return list<array{name?: string, base_url?: string, api_key?: string, model?: string}>
*/
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;
}
/**
* 简单的聊天补全。
*
* @param array<int, array{role: string, content: string}> $messages
*/
public function chat(array $messages, array $options = []): string
{
if (! $this->isConfigured()) {
throw new \RuntimeException('LLM 未配置:请设置 LLM_BASE_URL 与 LLM_API_KEY');
}
$response = Http::timeout(60)
->withToken($this->apiKey())
->post($this->baseUrl().'/chat/completions', [
'model' => $options['model'] ?? $this->model(),
'messages' => $messages,
'temperature' => $options['temperature'] ?? 0.3,
'max_tokens' => $options['max_tokens'] ?? 1024,
]);
if ($response->failed()) {
Log::error('LLM 请求失败', ['status' => $response->status(), 'body' => $response->body()]);
throw new \RuntimeException('LLM 请求失败:HTTP '.$response->status());
}
$content = $response->json('choices.0.message.content', '');
return is_array($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : (string) $content;
}
}