From 4e1e4c0c5a54b96c5add1dbd8db245b0961e456e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?d=20=F0=9F=94=B9?= Date: Sun, 15 Mar 2026 02:04:43 +0800 Subject: [PATCH] fix(ts): extract content from code blocks instead of deleting it (#4317) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: d 🔹 <258577966+voidborne-d@users.noreply.github.com> --- mem0-ts/src/oss/src/prompts/index.ts | 6 +++- .../src/oss/tests/remove-code-blocks.test.ts | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 mem0-ts/src/oss/tests/remove-code-blocks.test.ts diff --git a/mem0-ts/src/oss/src/prompts/index.ts b/mem0-ts/src/oss/src/prompts/index.ts index e9694b3e5..03125cff1 100644 --- a/mem0-ts/src/oss/src/prompts/index.ts +++ b/mem0-ts/src/oss/src/prompts/index.ts @@ -278,5 +278,9 @@ export function parseMessages(messages: string[]): string { } export function removeCodeBlocks(text: string): string { - return text.replace(/```[^`]*```/g, ""); + // Extract content inside code fences instead of deleting it. + // The old regex /```[^`]*```/g replaced the entire block (including + // its content) with an empty string, so when an LLM returned JSON + // wrapped in ```json ... ``` the actual payload was discarded. + return text.replace(/```(?:\w+)?\n?([\s\S]*?)```/g, "$1").trim(); } diff --git a/mem0-ts/src/oss/tests/remove-code-blocks.test.ts b/mem0-ts/src/oss/tests/remove-code-blocks.test.ts new file mode 100644 index 000000000..25960b396 --- /dev/null +++ b/mem0-ts/src/oss/tests/remove-code-blocks.test.ts @@ -0,0 +1,29 @@ +import { removeCodeBlocks } from "../src/prompts"; + +describe("removeCodeBlocks", () => { + it("extracts JSON from ```json code fence", () => { + const input = '```json\n{"facts": ["hello"]}\n```'; + expect(removeCodeBlocks(input)).toBe('{"facts": ["hello"]}'); + }); + + it("extracts content from bare ``` code fence", () => { + const input = '```\n{"key": "value"}\n```'; + expect(removeCodeBlocks(input)).toBe('{"key": "value"}'); + }); + + it("returns plain text unchanged", () => { + const input = '{"facts": ["hello"]}'; + expect(removeCodeBlocks(input)).toBe('{"facts": ["hello"]}'); + }); + + it("handles multiple code blocks", () => { + const input = '```json\n{"a":1}\n```\nsome text\n```json\n{"b":2}\n```'; + expect(removeCodeBlocks(input)).toBe('{"a":1}\n\nsome text\n{"b":2}'); + }); + + it("handles Claude-style response with surrounding text", () => { + const input = 'Here is the JSON:\n```json\n{"facts": ["user likes TypeScript"]}\n```'; + expect(removeCodeBlocks(input)).toContain('"facts"'); + expect(removeCodeBlocks(input)).not.toContain("```"); + }); +});