From 9e63ab889b9663a744eb75fc1b82fb63ef316932 Mon Sep 17 00:00:00 2001 From: vedant381 Date: Thu, 16 Oct 2025 01:34:57 +0530 Subject: [PATCH] fix: handle JSON parsing errors in prompts --- mem0-ts/src/oss/src/memory/index.ts | 10 +++++++--- mem0-ts/src/oss/src/prompts/index.ts | 8 ++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/mem0-ts/src/oss/src/memory/index.ts b/mem0-ts/src/oss/src/memory/index.ts index 1b43747ce4..0049827676 100644 --- a/mem0-ts/src/oss/src/memory/index.ts +++ b/mem0-ts/src/oss/src/memory/index.ts @@ -241,9 +241,13 @@ export class Memory { } const parsedMessages = messages.map((m) => m.content).join("\n"); - const [systemPrompt, userPrompt] = this.customPrompt - ? [this.customPrompt, `Input:\n${parsedMessages}`] - : getFactRetrievalMessages(parsedMessages); + let systemPrompt: string; + let userPrompt: string; + + [systemPrompt, userPrompt] = getFactRetrievalMessages( + parsedMessages, + this.customPrompt + ); const response = await this.llm.generateResponse( [ diff --git a/mem0-ts/src/oss/src/prompts/index.ts b/mem0-ts/src/oss/src/prompts/index.ts index ef8c797564..0f88ec9434 100644 --- a/mem0-ts/src/oss/src/prompts/index.ts +++ b/mem0-ts/src/oss/src/prompts/index.ts @@ -34,6 +34,7 @@ export const MemoryUpdateSchema = z.object({ export function getFactRetrievalMessages( parsedMessages: string, + customPrompt?: string, ): [string, string] { const systemPrompt = `You are a Personal Information Organizer, specialized in accurately storing facts, user memories, and preferences. Your primary role is to extract relevant pieces of information from conversations and organize them into distinct, manageable facts. This allows for easy retrieval and personalization in future interactions. Below are the types of information you need to focus on and the detailed instructions on how to handle the input data. @@ -89,6 +90,13 @@ export function getFactRetrievalMessages( const userPrompt = `Following is a conversation between the user and the assistant. You have to extract the relevant facts and preferences about the user, if any, from the conversation and return them in the JSON format as shown above.\n\nInput:\n${parsedMessages}`; + const customPromptWithJsonHandling = customPrompt ? ` ${customPrompt} Your response must be a valid JSON.` : ""; + + // If custom prompt is provided, that will be your system prompt now and user prompt will be parsed message [ based on existing functionality ] + if (customPrompt) { + return [customPromptWithJsonHandling, "Input:\n" + parsedMessages]; + } + return [systemPrompt, userPrompt]; }