@@ -209,9 +209,9 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
209209
210210 const processTemplateResponse = ( ) => {
211211 if ( type === ChatType . Template ) {
212- let lines : string [ ]
212+ let jsonString = ''
213213 if ( assistantMessage . role === ASSISTANT ) {
214- lines = assistantContent . split ( '\n' )
214+ jsonString = cleanJSON ( assistantContent )
215215 } else {
216216 let latestChat = appStateContext ?. state . currentChat
217217 if ( ! latestChat ) return
@@ -221,17 +221,11 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
221221 const mostRecentAssistantMessage =
222222 assistantMessages . length > 0 ? assistantMessages [ assistantMessages . length - 1 ] : undefined
223223 if ( mostRecentAssistantMessage ) {
224- lines = mostRecentAssistantMessage . content . split ( '\n' )
224+ jsonString = cleanJSON ( mostRecentAssistantMessage . content )
225225 } else return
226226 }
227- if ( ! lines ) return
227+ if ( jsonString === '' ) return
228228
229- let jsonString = ''
230- lines ?. forEach ( ( line : string ) => {
231- if ( ! line . includes ( 'json' ) && ! line . includes ( '```' ) ) {
232- jsonString += line . trim ( )
233- }
234- } )
235229 setJSONDraftDocument ( jsonString ) // use in the Answer response
236230 try {
237231 const jsonObject = JSON . parse ( jsonString )
@@ -662,6 +656,22 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
662656 setClearingChat ( false )
663657 }
664658
659+ const cleanJSON = ( jsonString : string ) => {
660+ try {
661+ let lines : string [ ]
662+ let cleanString = ''
663+ lines = jsonString . split ( '\n' )
664+ lines ?. forEach ( ( line : string ) => {
665+ if ( ! line . includes ( 'json' ) && ! line . includes ( '```' ) ) {
666+ cleanString += line . trim ( )
667+ }
668+ } )
669+ return cleanString
670+ } catch ( e ) {
671+ return ''
672+ }
673+ }
674+
665675 const tryGetRaiPrettyError = ( errorMessage : string ) => {
666676 try {
667677 // Using a regex to extract the JSON part that contains "innererror"
@@ -864,7 +874,8 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
864874 const generateTemplateSections = ( jsonString : string ) => {
865875 let jsonResponse
866876 try {
867- jsonResponse = JSON . parse ( jsonString )
877+ let cleanString = cleanJSON ( jsonString )
878+ jsonResponse = JSON . parse ( cleanString )
868879 } catch ( e ) {
869880 return contentTemplateSections . JSONParseError
870881 }
0 commit comments