@@ -35,6 +35,15 @@ export async function generateAnswersWithGptCompletionApi(
3535 modelName ,
3636) {
3737 const controller = new AbortController ( )
38+ const stopListener = ( msg ) => {
39+ if ( msg . stop ) {
40+ console . debug ( 'stop generating' )
41+ port . postMessage ( { done : true } )
42+ controller . abort ( )
43+ port . onMessage . removeListener ( stopListener )
44+ }
45+ }
46+ port . onMessage . addListener ( stopListener )
3847 port . onDisconnect . addListener ( ( ) => {
3948 console . debug ( 'port disconnected' )
4049 controller . abort ( )
@@ -79,8 +88,12 @@ export async function generateAnswersWithGptCompletionApi(
7988 port . postMessage ( { answer : answer , done : false , session : null } )
8089 } ,
8190 async onStart ( ) { } ,
82- async onEnd ( ) { } ,
91+ async onEnd ( ) {
92+ port . onMessage . removeListener ( stopListener )
93+ } ,
8394 async onError ( resp ) {
95+ if ( resp instanceof Error ) throw resp
96+ port . onMessage . removeListener ( stopListener )
8497 if ( resp . status === 403 ) {
8598 throw new Error ( 'CLOUDFLARE' )
8699 }
@@ -99,6 +112,15 @@ export async function generateAnswersWithGptCompletionApi(
99112 */
100113export async function generateAnswersWithChatgptApi ( port , question , session , apiKey , modelName ) {
101114 const controller = new AbortController ( )
115+ const stopListener = ( msg ) => {
116+ if ( msg . stop ) {
117+ console . debug ( 'stop generating' )
118+ port . postMessage ( { done : true } )
119+ controller . abort ( )
120+ port . onMessage . removeListener ( stopListener )
121+ }
122+ }
123+ port . onMessage . addListener ( stopListener )
102124 port . onDisconnect . addListener ( ( ) => {
103125 console . debug ( 'port disconnected' )
104126 controller . abort ( )
@@ -142,8 +164,12 @@ export async function generateAnswersWithChatgptApi(port, question, session, api
142164 port . postMessage ( { answer : answer , done : false , session : null } )
143165 } ,
144166 async onStart ( ) { } ,
145- async onEnd ( ) { } ,
167+ async onEnd ( ) {
168+ port . onMessage . removeListener ( stopListener )
169+ } ,
146170 async onError ( resp ) {
171+ if ( resp instanceof Error ) throw resp
172+ port . onMessage . removeListener ( stopListener )
147173 if ( resp . status === 403 ) {
148174 throw new Error ( 'CLOUDFLARE' )
149175 }
0 commit comments