@@ -13,21 +13,45 @@ chatForm.addEventListener("submit", async (e) => {
1313
1414    const  response  =  await  fetch ( "gptchat.php" ,  { 
1515        method : "POST" , 
16-         headers : { 
17-             "Content-Type" : "application/json" , 
18-         } , 
16+         headers : {  "Content-Type" : "application/json"  } , 
1917        body : JSON . stringify ( {  message } ) , 
2018    } ) ; 
2119
22-     if  ( response . ok )  { 
23-         const  data  =  await  response . json ( ) ; 
24-         if  ( data . choices  &&  data . choices [ 0 ]  &&  data . choices [ 0 ] . text )  { 
25-             chatOutput . innerHTML  +=  `<p class="bot-message">${ data . choices [ 0 ] . text }  </p>` ; 
26-         }  else  { 
27-             console . error ( "Error: Unexpected response format" ,  data ) ; 
28-         } 
29-         chatOutput . scrollTop  =  chatOutput . scrollHeight ; 
30-     }  else  { 
20+     if  ( ! response . ok )  { 
3121        console . error ( "Error communicating with GPTChat API" ) ; 
22+         return ; 
23+     } 
24+ 
25+     const  reader  =  response . body . getReader ( ) ; 
26+     let  botMessage  =  "" ; 
27+ 
28+     async  function  read ( )  { 
29+         const  {  done,  value }  =  await  reader . read ( ) ; 
30+         if  ( done )  { 
31+             chatOutput . innerHTML  +=  `<p class="bot-message">${ botMessage }  </p>` ; 
32+             chatOutput . scrollTop  =  chatOutput . scrollHeight ; 
33+             return ; 
34+         } 
35+ 
36+         const  text  =  new  TextDecoder ( ) . decode ( value ) ; 
37+         const  lines  =  text . split ( "\n" ) . filter ( line  =>  line . startsWith ( "data: " ) ) ; 
38+         for  ( const  line  of  lines )  { 
39+             const  json  =  line . replace ( "data: " ,  "" ) . trim ( ) ; 
40+             if  ( json  &&  json  !==  "[DONE]" )  { 
41+                 try  { 
42+                     const  data  =  JSON . parse ( json ) ; 
43+                     if  ( data . choices  &&  data . choices [ 0 ]  &&  data . choices [ 0 ] . delta  &&  data . choices [ 0 ] . delta . content )  { 
44+                         botMessage  +=  data . choices [ 0 ] . delta . content ; 
45+                         chatOutput . innerHTML  +=  `<span class="bot-message">${ data . choices [ 0 ] . delta . content }  </span>` ; 
46+                         chatOutput . scrollTop  =  chatOutput . scrollHeight ; 
47+                     } 
48+                 }  catch  ( err )  { 
49+                     console . error ( "JSON Parsing Error" ,  err ) ; 
50+                 } 
51+             } 
52+         } 
53+         read ( ) ; 
3254    } 
33- } ) ; 
55+ 
56+     read ( ) ; 
57+ } ) ; 
0 commit comments