From df2761e49039a3726a8bc4a9a0e80366bcb030dc Mon Sep 17 00:00:00 2001 From: Nick Mitchell Date: Thu, 6 Mar 2025 10:04:54 -0500 Subject: [PATCH] fix: workaround buggy traces that specify parser: json but have non-json value Signed-off-by: Nick Mitchell --- pdl-live-react/src/helpers.ts | 9 +++++++++ pdl-live-react/src/view/code/Code.tsx | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/pdl-live-react/src/helpers.ts b/pdl-live-react/src/helpers.ts index 011af55e..352d0c61 100644 --- a/pdl-live-react/src/helpers.ts +++ b/pdl-live-react/src/helpers.ts @@ -209,6 +209,15 @@ function tryJson(s: unknown) { return s } +export function tryJsonPrettyPrint(s: string) { + try { + return JSON.stringify(JSON.parse(s), undefined, 2) + } catch (_err) { + // intentional fall-through + } + return s +} + export function extractStructuredModelResponse({ pdl__result, parser, diff --git a/pdl-live-react/src/view/code/Code.tsx b/pdl-live-react/src/view/code/Code.tsx index 54f3f62b..e15890a2 100644 --- a/pdl-live-react/src/view/code/Code.tsx +++ b/pdl-live-react/src/view/code/Code.tsx @@ -3,6 +3,7 @@ import { lazy, Suspense } from "react" import { stringify } from "yaml" import { match, P } from "ts-pattern" +import { tryJsonPrettyPrint } from "../../helpers" import { type PdlBlock } from "../../pdl_ast" import { map_block_children } from "../../pdl_ast_utils" @@ -34,7 +35,7 @@ export default function Code({ const value = typeof block === "string" ? language === "json" - ? JSON.stringify(JSON.parse(block), undefined, 2) + ? tryJsonPrettyPrint(block) : block : stringify(raw ? block : block_code_cleanup(block))