success( $chat->histories()->get() ); } /** * Store a newly created resource in storage. */ public function store(Request $request, Chat $chat) { // 获取上一条记录 $last_history = $chat->histories()->orderBy('id', 'desc')->first(); // 如果存在 if ($last_history) { // 如果上一条是 user if ($last_history->role == 'user') { // 不允许发送消息 return $this->badRequest('你已经回复过了,请等待 AI 响应。'); } // 检查缓存是否存在 $last_stream_key = 'chat_history_id:'.$last_history->id; // 如果存在 if (Cache::has($last_stream_key)) { return $this->conflict('上一个流信息还没有获取,请等待一分钟后重试。'); } } $request->validate([ 'message' => 'required', ]); $chat->histories()->create([ 'content' => $request->input('message'), 'role' => 'user', ]); $random_id = Str::random(20); $last_stream_key = 'chat_history_id:'.$last_history->id; // 设置缓存 Cache::put($last_stream_key, $random_id, 60); Cache::put("chat_history_stream_id:$random_id", $last_history->id, 60); return $this->success([ 'stream_url' => route('chat-stream', $random_id), ]); } public function stream(string $stream_id) { return $stream_id; } }