Skip to content

Commit

Permalink
Merge pull request #67 from microsoft/jameshotfix
Browse files Browse the repository at this point in the history
Fixed invalid JSON Response issue
  • Loading branch information
andrewldesousa authored Sep 6, 2024
2 parents b4ca021 + e33349d commit 891bbbe
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions frontend/src/pages/chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,9 @@ const Chat = ({ type = ChatType.Browse }: Props) => {

const processTemplateResponse = () => {
if (type === ChatType.Template) {
let lines: string[]
let jsonString = ''
if (assistantMessage.role === ASSISTANT) {
lines = assistantContent.split('\n')
jsonString = cleanJSON(assistantContent)
} else {
let latestChat = appStateContext?.state.currentChat
if (!latestChat) return
Expand All @@ -221,17 +221,11 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
const mostRecentAssistantMessage =
assistantMessages.length > 0 ? assistantMessages[assistantMessages.length - 1] : undefined
if (mostRecentAssistantMessage) {
lines = mostRecentAssistantMessage.content.split('\n')
jsonString = cleanJSON(mostRecentAssistantMessage.content)
} else return
}
if (!lines) return
if (jsonString === '') return

let jsonString = ''
lines?.forEach((line: string) => {
if (!line.includes('json') && !line.includes('```')) {
jsonString += line.trim()
}
})
setJSONDraftDocument(jsonString) // use in the Answer response
try {
const jsonObject = JSON.parse(jsonString)
Expand Down Expand Up @@ -662,6 +656,22 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
setClearingChat(false)
}

const cleanJSON = (jsonString: string) => {
try {
let lines: string[]
let cleanString = ''
lines = jsonString.split('\n')
lines?.forEach((line: string) => {
if (!line.includes('json') && !line.includes('```')) {
cleanString += line.trim()
}
})
return cleanString
} catch (e) {
return ''
}
}

const tryGetRaiPrettyError = (errorMessage: string) => {
try {
// Using a regex to extract the JSON part that contains "innererror"
Expand Down Expand Up @@ -864,7 +874,8 @@ const Chat = ({ type = ChatType.Browse }: Props) => {
const generateTemplateSections = (jsonString: string) => {
let jsonResponse
try {
jsonResponse = JSON.parse(jsonString)
let cleanString = cleanJSON(jsonString)
jsonResponse = JSON.parse(cleanString)
} catch (e) {
return contentTemplateSections.JSONParseError
}
Expand Down

0 comments on commit 891bbbe

Please sign in to comment.