Cannot or unable to end or close readable stream (Likely a Gemini API issue)

Hey all, I am currently implementing a chat stream logic, where I stream the content coming from the api, with the help of its stream method
But the issue am facing is that, my stream doesn’t end for long time or goes on continuously, this specifically happens because the gemini does not end emitting data after it has completing its stream, maybe am doing something wrong here.

Here is the code :

This is happening inside a POST method, in a endpoint (Using SvelteKit framework)

//other code
    let response = await chat.sendMessageStream(userPrompt, {
        signal: abortController.signal
    })

    let stream = new ReadableStream({
        async pull(controller) {
            try {
                for await (const chunk of response.stream) {
                    let chunkText = chunk.text()
                    chunked += chunkText
                    controller.enqueue(chunkText);
                    console.log("IN THE LOOP \n")
                }
                console.log("OUTSIDE THE LOOP \n")
                controller.close();

            } catch (streamError) {
                console.error('Stream error:', streamError);
                controller.error(streamError); // Propagate error to client
                abortController.abort()
            } finally {
                console.log('STREAM DONE \n')

                if (!abortController.signal.aborted) {
                    try {
                        let insertChats = await db.insert(chats).values({
                            prompt: userPrompt,
                            response: chunked.replaceAll('```html', '')
                                .replaceAll('```', '')
                                .replace('html', '')
                                .replaceAll('``', ''),
                            userId: 10101,
                            sequence,
                            chatId
                        })
                    } catch (dbError: any) {
                        console.error('Database error:', dbError);
                        error(400, { message: dbError.message ?? dbError.msg })
                    }
                }
                console.log('CHATS INSERTED \n')

            }


        },
        cancel() {
            console.log('Stream cancelled by client');
            abortController.abort();
        }
    })



    return new Response(stream, {
        headers: {
            'content-type': 'text/event-stream',
        }
    })

Can’t get it working, help would be really appreciated, Thanks.