From d8c7ad912c16b50c737e26b17d9696bc1b7b165b Mon Sep 17 00:00:00 2001 From: Fuwn Date: Tue, 30 Sep 2025 01:41:14 -0700 Subject: fix(gateway:moderationAgent): Update model response handling --- .../src/listeners/moderationAgent/utilities.ts | 42 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) (limited to 'packages/gateway/src') diff --git a/packages/gateway/src/listeners/moderationAgent/utilities.ts b/packages/gateway/src/listeners/moderationAgent/utilities.ts index 2e6542e..a5e6aec 100644 --- a/packages/gateway/src/listeners/moderationAgent/utilities.ts +++ b/packages/gateway/src/listeners/moderationAgent/utilities.ts @@ -359,18 +359,50 @@ Remember: Only enforce the exact rules provided. Do not make assumptions or inte } jsonContent = jsonContent - .replace(/\\'/g, "'") - .replace(/'/g, '"') - .replace(/(\w+):/g, '"$1":') .replace(/,\s*}/g, "}") - .replace(/,\s*]/g, "]"); + .replace(/,\s*]/g, "]") + .replace(/(\w+):/g, '"$1":'); + + if (jsonContent.includes("'") && !jsonContent.includes('"')) { + jsonContent = jsonContent.replace(/'/g, '"'); + } else if (jsonContent.includes("'") && jsonContent.includes('"')) { + jsonContent = jsonContent.replace(/\\'/g, "'"); + } return JSON.parse(jsonContent); } catch (parseError) { console.error("Failed to parse OpenRouter response as JSON:", content); console.error("Parse error:", parseError); - return null; + try { + let fallbackContent = content; + + if (fallbackContent.includes("```json")) { + const match = fallbackContent.match(/```json\s*([\s\S]*?)\s*```/); + + if (match) fallbackContent = match[1].trim(); + } else if (fallbackContent.includes("```")) { + const match = fallbackContent.match(/```\s*([\s\S]*?)\s*```/); + + if (match) fallbackContent = match[1].trim(); + } + + const jsonMatch = fallbackContent.match(/\{[\s\S]*\}/); + + if (jsonMatch) fallbackContent = jsonMatch[0]; + + fallbackContent = fallbackContent + .replace(/,\s*}/g, "}") + .replace(/,\s*]/g, "]") + .replace(/(\w+):/g, '"$1":') + .replace(/'/g, '"') + .replace(/\\"/g, '"'); + + return JSON.parse(fallbackContent); + } catch (fallbackError) { + console.error("Fallback parsing also failed:", fallbackError); + return null; + } } } catch (error) { console.error("Error in AI analysis:", error); -- cgit v1.2.3