优化:AI对话改为公开广播,所有人可见
- ChatBotController 将用户提问和AI回复都广播到聊天室 - 前端不再本地渲染AI消息,由WebSocket广播统一处理 - AI小助手加入系统用户列表(公告样式展示) - 思考中提示延迟500ms显示在包厢窗口,避免排序混乱
This commit is contained in:
@@ -13,8 +13,11 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Events\MessageSent;
|
||||
use App\Jobs\SaveMessageJob;
|
||||
use App\Models\Sysparam;
|
||||
use App\Services\AiChatService;
|
||||
use App\Services\ChatStateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
@@ -22,10 +25,11 @@ use Illuminate\Support\Facades\Auth;
|
||||
class ChatBotController extends Controller
|
||||
{
|
||||
/**
|
||||
* 构造函数:注入 AI 聊天服务
|
||||
* 构造函数:注入 AI 聊天服务和聊天状态服务
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly AiChatService $aiChat,
|
||||
private readonly ChatStateService $chatState,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -59,8 +63,40 @@ class ChatBotController extends Controller
|
||||
$roomId = $request->input('room_id');
|
||||
|
||||
try {
|
||||
// 先广播用户的提问消息
|
||||
$userMsg = [
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => $user->username,
|
||||
'to_user' => 'AI小助手',
|
||||
'content' => $message,
|
||||
'is_secret' => false,
|
||||
'font_color' => '#000000',
|
||||
'action' => '',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$this->chatState->pushMessage($roomId, $userMsg);
|
||||
broadcast(new MessageSent($roomId, $userMsg));
|
||||
SaveMessageJob::dispatch($userMsg);
|
||||
|
||||
$result = $this->aiChat->chat($user->id, $message, $roomId);
|
||||
|
||||
// 广播 AI 回复消息
|
||||
$botMsg = [
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => 'AI小助手',
|
||||
'to_user' => $user->username,
|
||||
'content' => $result['reply'],
|
||||
'is_secret' => false,
|
||||
'font_color' => '#16a34a',
|
||||
'action' => '',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$this->chatState->pushMessage($roomId, $botMsg);
|
||||
broadcast(new MessageSent($roomId, $botMsg));
|
||||
SaveMessageJob::dispatch($botMsg);
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'reply' => $result['reply'],
|
||||
|
||||
Reference in New Issue
Block a user