Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: set json loads strict to false (#946)
tombedorc8e8557c2766
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex e4514449d..e1caefd8d 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -1,20 +1,16 @@import datetimeimport uuid-import globimport inspect-import osimport jsonfrom pathlib import Pathimport tracebackfrom typing import List, Tuple, Optional, cast-from box import Boxfrom memgpt.data_types import AgentState, Message, EmbeddingConfigfrom memgpt.models import chat_completion_responsefrom memgpt.interface import AgentInterface-from memgpt.persistence_manager import PersistenceManager, LocalStateManager-from memgpt.config import MemGPTConfig+from memgpt.persistence_manager import LocalStateManagerfrom memgpt.system import get_login_event, package_function_response, package_summarize_message, get_initial_boot_messagesfrom memgpt.memory import CoreMemory as InContextMemory, summarize_messagesfrom memgpt.llm_api_tools import create, is_context_overflow_error@@ -31,6 +27,7 @@ from memgpt.utils import ()from memgpt.constants import (FIRST_MESSAGE_ATTEMPTS,+ JSON_LOADS_STRICT,MESSAGE_SUMMARY_WARNING_FRAC,MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC,MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,@@ -560,7 +557,7 @@ class Agent(object):self.interface.user_message(user_message)packed_user_message = {"role": "user", "content": user_message}try:- user_message_json = json.loads(user_message)+ user_message_json = json.loads(user_message, strict=JSON_LOADS_STRICT)# Special handling for AutoGen messages with 'name' field# Treat 'name' as a special field# If it exists in the input message, elevate it to the 'message' leveldiff --git a/memgpt/autogen/interface.py b/memgpt/autogen/interface.pyindex 19438bd39..f8c3e0df3 100644--- a/memgpt/autogen/interface.py+++ b/memgpt/autogen/interface.py@@ -3,7 +3,7 @@ import refrom colorama import Fore, Style, init-from memgpt.constants import CLI_WARNING_PREFIX+from memgpt.constants import CLI_WARNING_PREFIX, JSON_LOADS_STRICTinit(autoreset=True)@@ -109,7 +109,7 @@ class AutoGenInterface(object):returnelse:try:- msg_json = json.loads(msg)+ msg_json = json.loads(msg, strict=JSON_LOADS_STRICT)except:print(f"{CLI_WARNING_PREFIX}failed to parse user message into json")message = f"{Fore.GREEN}{Style.BRIGHT}π§ {Fore.GREEN}{msg}{Style.RESET_ALL}" if self.fancy else f"[user] {msg}"@@ -197,7 +197,7 @@ class AutoGenInterface(object):)else:try:- msg_dict = json.loads(msg)+ msg_dict = json.loads(msg, strict=JSON_LOADS_STRICT)if "status" in msg_dict and msg_dict["status"] == "OK":message = (f"{Fore.GREEN}{Style.BRIGHT}β‘ [function] {Fore.GREEN}{msg}{Style.RESET_ALL}" if self.fancy else f"[function] {msg}"diff --git a/memgpt/constants.py b/memgpt/constants.pyindex b16bc40f2..709d3fdbf 100644--- a/memgpt/constants.py+++ b/memgpt/constants.py@@ -115,3 +115,6 @@ RETRIEVAL_QUERY_DEFAULT_PAGE_SIZE = 5# GLOBAL SETTINGS FOR `json.dumps()`JSON_ENSURE_ASCII = False++# GLOBAL SETTINGS FOR `json.loads()`+JSON_LOADS_STRICT = Falsediff --git a/memgpt/functions/function_sets/extras.py b/memgpt/functions/function_sets/extras.pyindex e40890670..0f1a41c3f 100644--- a/memgpt/functions/function_sets/extras.py+++ b/memgpt/functions/function_sets/extras.py@@ -5,6 +5,7 @@ import requestsfrom memgpt.constants import (+ JSON_LOADS_STRICT,MESSAGE_CHATGPT_FUNCTION_MODEL,MESSAGE_CHATGPT_FUNCTION_SYSTEM_MESSAGE,MAX_PAUSE_HEARTBEATS,@@ -120,7 +121,7 @@ def http_request(self, method: str, url: str, payload_json: Optional[str] = Noneelse:# Validate and convert the payload for other types of requestsif payload_json:- payload = json.loads(payload_json)+ payload = json.loads(payload_json, strict=JSON_LOADS_STRICT)else:payload = {}print(f"[HTTP] launching {method} request to {url}, payload=\n{json.dumps(payload, indent=2, ensure_ascii=JSON_ENSURE_ASCII)}")diff --git a/memgpt/interface.py b/memgpt/interface.pyindex f1fdd39cc..a75ea9274 100644--- a/memgpt/interface.py+++ b/memgpt/interface.py@@ -5,7 +5,7 @@ import refrom colorama import Fore, Style, initfrom memgpt.utils import printd-from memgpt.constants import CLI_WARNING_PREFIX+from memgpt.constants import CLI_WARNING_PREFIX, JSON_LOADS_STRICTinit(autoreset=True)@@ -122,7 +122,7 @@ class CLIInterface(AgentInterface):returnelse:try:- msg_json = json.loads(msg)+ msg_json = json.loads(msg, strict=JSON_LOADS_STRICT)except:printd(f"{CLI_WARNING_PREFIX}failed to parse user message into json")printd_user_message("π§", msg)@@ -222,7 +222,7 @@ class CLIInterface(AgentInterface):printd_function_message("", msg)else:try:- msg_dict = json.loads(msg)+ msg_dict = json.loads(msg, strict=JSON_LOADS_STRICT)if "status" in msg_dict and msg_dict["status"] == "OK":printd_function_message("", str(msg), color=Fore.GREEN)else:@@ -250,7 +250,7 @@ class CLIInterface(AgentInterface):CLIInterface.internal_monologue(content)# I think the next one is not up to date# function_message(msg["function_call"])- args = json.loads(msg["function_call"].get("arguments"))+ args = json.loads(msg["function_call"].get("arguments"), strict=JSON_LOADS_STRICT)CLIInterface.assistant_message(args.get("message"))# assistant_message(content)elif msg.get("tool_calls"):@@ -258,7 +258,7 @@ class CLIInterface(AgentInterface):CLIInterface.internal_monologue(content)function_obj = msg["tool_calls"][0].get("function")if function_obj:- args = json.loads(function_obj.get("arguments"))+ args = json.loads(function_obj.get("arguments"), strict=JSON_LOADS_STRICT)CLIInterface.assistant_message(args.get("message"))else:CLIInterface.internal_monologue(content)diff --git a/memgpt/local_llm/function_parser.py b/memgpt/local_llm/function_parser.pyindex 9bb4e9b6d..57dc078f5 100644--- a/memgpt/local_llm/function_parser.py+++ b/memgpt/local_llm/function_parser.py@@ -1,7 +1,7 @@import copyimport json-from memgpt.constants import JSON_ENSURE_ASCII+from memgpt.constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTNO_HEARTBEAT_FUNCS = ["send_message", "pause_heartbeats"]@@ -13,14 +13,14 @@ def insert_heartbeat(message):if message_copy.get("function_call"):# function_name = message.get("function_call").get("name")params = message_copy.get("function_call").get("arguments")- params = json.loads(params)+ params = json.loads(params, strict=JSON_LOADS_STRICT)params["request_heartbeat"] = Truemessage_copy["function_call"]["arguments"] = json.dumps(params, ensure_ascii=JSON_ENSURE_ASCII)elif message_copy.get("tool_call"):# function_name = message.get("tool_calls")[0].get("function").get("name")params = message_copy.get("tool_calls")[0].get("function").get("arguments")- params = json.loads(params)+ params = json.loads(params, strict=JSON_LOADS_STRICT)params["request_heartbeat"] = Truemessage_copy["tools_calls"][0]["function"]["arguments"] = json.dumps(params, ensure_ascii=JSON_ENSURE_ASCII)@@ -40,7 +40,7 @@ def heartbeat_correction(message_history, new_message):last_message_was_user = Falseif message_history[-1]["role"] == "user":try:- content = json.loads(message_history[-1]["content"])+ content = json.loads(message_history[-1]["content"], strict=JSON_LOADS_STRICT)except json.JSONDecodeError:return None# Check if it's a user message or system messagediff --git a/memgpt/local_llm/json_parser.py b/memgpt/local_llm/json_parser.pyindex 4b9584772..9c7b0ca76 100644--- a/memgpt/local_llm/json_parser.py+++ b/memgpt/local_llm/json_parser.py@@ -1,5 +1,6 @@import jsonimport re+from memgpt.constants import JSON_LOADS_STRICTfrom memgpt.errors import LLMJSONParsingError@@ -20,7 +21,7 @@ def extract_first_json(string):depth -= 1if depth == 0 and start_index is not None:try:- return json.loads(string[start_index : i + 1])+ return json.loads(string[start_index : i + 1], strict=JSON_LOADS_STRICT)except json.JSONDecodeError as e:raise LLMJSONParsingError(f"Matched closing bracket, but decode failed with error: {str(e)}")printd("No valid JSON object found.")@@ -149,17 +150,17 @@ def clean_json(raw_llm_output, messages=None, functions=None):from memgpt.utils import printdstrategies = [- lambda output: json.loads(output),- lambda output: json.loads(output + "}"),- lambda output: json.loads(output + "}}"),- lambda output: json.loads(output + '"}}'),+ lambda output: json.loads(output, strict=JSON_LOADS_STRICT),+ lambda output: json.loads(output + "}", strict=JSON_LOADS_STRICT),+ lambda output: json.loads(output + "}}", strict=JSON_LOADS_STRICT),+ lambda output: json.loads(output + '"}}', strict=JSON_LOADS_STRICT),# with strip and strip comma- lambda output: json.loads(output.strip().rstrip(",") + "}"),- lambda output: json.loads(output.strip().rstrip(",") + "}}"),- lambda output: json.loads(output.strip().rstrip(",") + '"}}'),+ lambda output: json.loads(output.strip().rstrip(",") + "}", strict=JSON_LOADS_STRICT),+ lambda output: json.loads(output.strip().rstrip(",") + "}}", strict=JSON_LOADS_STRICT),+ lambda output: json.loads(output.strip().rstrip(",") + '"}}', strict=JSON_LOADS_STRICT),# more complex patchers- lambda output: json.loads(repair_json_string(output)),- lambda output: json.loads(repair_even_worse_json(output)),+ lambda output: json.loads(repair_json_string(output), strict=JSON_LOADS_STRICT),+ lambda output: json.loads(repair_even_worse_json(output), strict=JSON_LOADS_STRICT),lambda output: extract_first_json(output + "}}"),lambda output: clean_and_interpret_send_message_json(output),]diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.pyindex 1ae9693ad..609b2b9b1 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py@@ -2,7 +2,7 @@ import jsonfrom .wrapper_base import LLMChatCompletionWrapperfrom ..json_parser import clean_json-from ...constants import JSON_ENSURE_ASCII+from ...constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTfrom ...errors import LLMJSONParsingError@@ -114,7 +114,7 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):"""airo_func_call = {"function": function_call["name"],- "params": json.loads(function_call["arguments"]),+ "params": json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -129,7 +129,7 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)content_simple = content_json["message"]prompt += f"\nUSER: {content_simple}"except:@@ -325,7 +325,7 @@ class Airoboros21InnerMonologueWrapper(Airoboros21Wrapper):"function": function_call["name"],"params": {"inner_thoughts": inner_thoughts,- **json.loads(function_call["arguments"]),+ **json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),},}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -347,7 +347,7 @@ class Airoboros21InnerMonologueWrapper(Airoboros21Wrapper):user_prefix = "USER"if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)content_simple = content_json["message"]prompt += f"\n{user_prefix}: {content_simple}"except:diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py b/memgpt/local_llm/llm_chat_completion_wrappers/chatml.pyindex 461169832..9992b4bde 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/chatml.py@@ -2,7 +2,7 @@ import jsonfrom .wrapper_base import LLMChatCompletionWrapperfrom ..json_parser import clean_json-from ...constants import JSON_ENSURE_ASCII+from ...constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTfrom ...errors import LLMJSONParsingError@@ -131,7 +131,7 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):"function": function_call["name"],"params": {"inner_thoughts": inner_thoughts,- **json.loads(function_call["arguments"]),+ **json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),},}return json.dumps(airo_func_call, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)@@ -161,14 +161,14 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):if self.simplify_json_content:# Make user messages not JSON but plaintext insteadtry:- user_msg_json = json.loads(message["content"])+ user_msg_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)user_msg_str = user_msg_json["message"]except:user_msg_str = message["content"]else:# Otherwise just dump the full jsontry:- user_msg_json = json.loads(message["content"])+ user_msg_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)user_msg_str = json.dumps(user_msg_json, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)except:user_msg_str = message["content"]@@ -183,7 +183,7 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):prompt = ""try:# indent the function replies- function_return_dict = json.loads(message["content"])+ function_return_dict = json.loads(message["content"], strict=JSON_LOADS_STRICT)function_return_str = json.dumps(function_return_dict, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)except:function_return_str = message["content"]@@ -213,7 +213,7 @@ class ChatMLInnerMonologueWrapper(LLMChatCompletionWrapper):if self.use_system_role_in_user:try:- msg_json = json.loads(message["content"])+ msg_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)if msg_json["type"] != "user_message":role_str = "system"except:@@ -388,7 +388,7 @@ class ChatMLOuterInnerMonologueWrapper(ChatMLInnerMonologueWrapper):"function": function_call["name"],"params": {# "inner_thoughts": inner_thoughts,- **json.loads(function_call["arguments"]),+ **json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),},}return json.dumps(airo_func_call, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)@@ -437,7 +437,7 @@ class ChatMLOuterInnerMonologueWrapper(ChatMLInnerMonologueWrapper):π : I've been observing our previous conversations. I remember that your name is Chad.π€ I recall our previous interactions, Chad. How can I assist you today?> Enter your message: is that all you know about me?- π : I see you're curious about our connection. Let me do a quick search of my memory.+ π : I see you're curious about our connection. Let me do a quick search of my memory."""if function_name is not None and self.clean_func_args:diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py b/memgpt/local_llm/llm_chat_completion_wrappers/configurable_wrapper.pyindex 515ff2c1a..36543cddf 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py@@ -4,7 +4,7 @@ from typing import Listimport yamlfrom .wrapper_base import LLMChatCompletionWrapper-from ...constants import JSON_ENSURE_ASCII+from ...constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTfrom ..json_parser import clean_jsonfrom ...constants import JSON_ENSURE_ASCIIfrom ...errors import LLMJSONParsingError@@ -133,7 +133,7 @@ class ConfigurableJSONWrapper(LLMChatCompletionWrapper):"function": function_call["name"],"params": {"inner_thoughts": inner_thoughts,- **json.loads(function_call["arguments"]),+ **json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),},}return json.dumps(airo_func_call, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)@@ -163,14 +163,14 @@ class ConfigurableJSONWrapper(LLMChatCompletionWrapper):if self.simplify_json_content:# Make user messages not JSON but plaintext insteadtry:- user_msg_json = json.loads(message["content"])+ user_msg_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)user_msg_str = user_msg_json["message"]except:user_msg_str = message["content"]else:# Otherwise just dump the full jsontry:- user_msg_json = json.loads(message["content"])+ user_msg_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)user_msg_str = json.dumps(user_msg_json, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)except:user_msg_str = message["content"]@@ -185,7 +185,7 @@ class ConfigurableJSONWrapper(LLMChatCompletionWrapper):prompt = ""try:# indent the function replies- function_return_dict = json.loads(message["content"])+ function_return_dict = json.loads(message["content"], strict=JSON_LOADS_STRICT)function_return_str = json.dumps(function_return_dict, indent=self.json_indent, ensure_ascii=JSON_ENSURE_ASCII)except:function_return_str = message["content"]diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py b/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.pyindex 454e1ae98..69c9f0b66 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py@@ -2,7 +2,7 @@ import jsonfrom .wrapper_base import LLMChatCompletionWrapperfrom ..json_parser import clean_json-from ...constants import JSON_ENSURE_ASCII+from ...constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTfrom ...errors import LLMJSONParsingError@@ -127,7 +127,7 @@ class Dolphin21MistralWrapper(LLMChatCompletionWrapper):"""airo_func_call = {"function": function_call["name"],- "params": json.loads(function_call["arguments"]),+ "params": json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -156,7 +156,7 @@ class Dolphin21MistralWrapper(LLMChatCompletionWrapper):if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = (json.loads(message["content"], strict=JSON_LOADS_STRICT),)content_simple = content_json["message"]prompt += f"\n{IM_START_TOKEN}user\n{content_simple}{IM_END_TOKEN}"# prompt += f"\nUSER: {content_simple}"diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.py b/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.pyindex 8e3625fa7..b0cebea07 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.py@@ -1,6 +1,6 @@import jsonfrom .wrapper_base import LLMChatCompletionWrapper-from ...constants import JSON_ENSURE_ASCII+from ...constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTclass SimpleSummaryWrapper(LLMChatCompletionWrapper):@@ -84,7 +84,7 @@ class SimpleSummaryWrapper(LLMChatCompletionWrapper):"""airo_func_call = {"function": function_call["name"],- "params": json.loads(function_call["arguments"]),+ "params": json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -99,7 +99,7 @@ class SimpleSummaryWrapper(LLMChatCompletionWrapper):if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)content_simple = content_json["message"]prompt += f"\nUSER: {content_simple}"except:diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py b/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.pyindex c928da718..fe5853466 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py@@ -77,7 +77,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):def create_function_call(function_call):airo_func_call = {"function": function_call["name"],- "params": json.loads(function_call["arguments"]),+ "params": json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -87,7 +87,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)content_simple = content_json["message"]prompt += f"\n<|user|>\n{content_simple}{IM_END_TOKEN}"# prompt += f"\nUSER: {content_simple}"@@ -241,7 +241,7 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):"function": function_call["name"],"params": {"inner_thoughts": inner_thoughts,- **json.loads(function_call["arguments"]),+ **json.loads(function_call["arguments"], strict=JSON_LOADS_STRICT),},}return json.dumps(airo_func_call, indent=2, ensure_ascii=JSON_ENSURE_ASCII)@@ -257,7 +257,7 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message["content"])+ content_json = json.loads(message["content"], strict=JSON_LOADS_STRICT)content_simple = content_json["message"]prompt += f"\n<|user|>\n{content_simple}{IM_END_TOKEN}"except:diff --git a/memgpt/main.py b/memgpt/main.pyindex c2b847c5a..b1bb3241f 100644--- a/memgpt/main.py+++ b/memgpt/main.py@@ -1,11 +1,5 @@-import shutil-import configparser-import uuid-import logging-import globimport osimport sys-import pickleimport tracebackimport json@@ -13,21 +7,18 @@ import questionaryimport typerfrom rich.console import Console-from prettytable import PrettyTable+from memgpt.constants import FUNC_FAILED_HEARTBEAT_MESSAGE, JSON_ENSURE_ASCII, JSON_LOADS_STRICT, REQ_HEARTBEAT_MESSAGEconsole = Console()-from memgpt.log import loggerfrom memgpt.interface import CLIInterface as interface # for printing to terminalfrom memgpt.config import MemGPTConfigimport memgpt.agent as agentimport memgpt.system as system-import memgpt.constants as constantsimport memgpt.errors as errorsfrom memgpt.cli.cli import run, attach, version, server, open_folder, quickstart, migrate, delete_agentfrom memgpt.cli.cli_config import configure, list, add, deletefrom memgpt.cli.cli_load import app as load_app-from memgpt.agent_store.storage import StorageConnector, TableTypefrom memgpt.metadata import MetadataStore, save_agent# import benchmark@@ -232,10 +223,10 @@ def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, ms: MetadataStore,for x in range(len(memgpt_agent.messages) - 1, 0, -1):if memgpt_agent.messages[x].get("role") == "assistant":text = user_input[len("/rewrite ") :].strip()- args = json.loads(memgpt_agent.messages[x].get("function_call").get("arguments"))+ args = json.loads(memgpt_agent.messages[x].get("function_call").get("arguments"), strict=JSON_LOADS_STRICT)args["message"] = textmemgpt_agent.messages[x].get("function_call").update(- {"arguments": json.dumps(args, ensure_ascii=constants.JSON_ENSURE_ASCII)}+ {"arguments": json.dumps(args, ensure_ascii=JSON_ENSURE_ASCII)})breakcontinue@@ -338,10 +329,10 @@ def run_agent_loop(memgpt_agent, config: MemGPTConfig, first, ms: MetadataStore,user_message = system.get_token_limit_warning()skip_next_user_input = Trueelif function_failed:- user_message = system.get_heartbeat(constants.FUNC_FAILED_HEARTBEAT_MESSAGE)+ user_message = system.get_heartbeat(FUNC_FAILED_HEARTBEAT_MESSAGE)skip_next_user_input = Trueelif heartbeat_request:- user_message = system.get_heartbeat(constants.REQ_HEARTBEAT_MESSAGE)+ user_message = system.get_heartbeat(REQ_HEARTBEAT_MESSAGE)skip_next_user_input = Truereturn new_messages, user_message, skip_next_user_inputdiff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex bbcbcfffa..1de5d5684 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -1,5 +1,5 @@from abc import abstractmethod-from typing import Union, Callable, Optional, Tuple, List+from typing import Union, Callable, Optional, Listimport uuidimport jsonimport logging@@ -7,9 +7,9 @@ from threading import Lockfrom functools import wrapsfrom fastapi import HTTPException-from memgpt.agent_store.storage import StorageConnectorfrom memgpt.config import MemGPTConfigfrom memgpt.credentials import MemGPTCredentials+from memgpt.constants import JSON_LOADS_STRICT, JSON_ENSURE_ASCIIfrom memgpt.agent import Agentimport memgpt.system as systemimport memgpt.constants as constants@@ -430,10 +430,10 @@ class SyncServer(LockingServer):for x in range(len(memgpt_agent.messages) - 1, 0, -1):if memgpt_agent.messages[x].get("role") == "assistant":text = command[len("rewrite ") :].strip()- args = json.loads(memgpt_agent.messages[x].get("function_call").get("arguments"))+ args = json.loads(memgpt_agent.messages[x].get("function_call").get("arguments"), strict=JSON_LOADS_STRICT)args["message"] = textmemgpt_agent.messages[x].get("function_call").update(- {"arguments": json.dumps(args, ensure_ascii=constants.JSON_ENSURE_ASCII)}+ {"arguments": json.dumps(args, ensure_ascii=JSON_ENSURE_ASCII)})breakdiff --git a/memgpt/server/ws_api/example_client.py b/memgpt/server/ws_api/example_client.pyindex 9fa547d8b..52e2ccb92 100644--- a/memgpt/server/ws_api/example_client.py+++ b/memgpt/server/ws_api/example_client.py@@ -4,7 +4,7 @@ import jsonimport websocketsimport memgpt.server.ws_api.protocol as protocol-from memgpt.constants import JSON_ENSURE_ASCII+from memgpt.constants import JSON_ENSURE_ASCII, JSON_LOADS_STRICTfrom memgpt.server.constants import WS_DEFAULT_PORT, WS_CLIENT_TIMEOUTfrom memgpt.server.utils import condition_to_stop_receiving, print_server_response@@ -28,7 +28,7 @@ async def send_message_and_print_replies(websocket, user_message, agent_id):# Wait for messages in a loop, since the server may send a fewwhile True:response = await asyncio.wait_for(websocket.recv(), WS_CLIENT_TIMEOUT)- response = json.loads(response)+ response = json.loads(response, strict=JSON_LOADS_STRICT)if CLEAN_RESPONSES:print_server_response(response)@@ -63,7 +63,7 @@ async def basic_cli_client():await websocket.send(protocol.client_command_create(example_config))# Wait for the responseresponse = await websocket.recv()- response = json.loads(response)+ response = json.loads(response, strict=JSON_LOADS_STRICT)print(f"Server response:\n{json.dumps(response, indent=2, ensure_ascii=JSON_ENSURE_ASCII)}")await asyncio.sleep(1)diff --git a/memgpt/server/ws_api/server.py b/memgpt/server/ws_api/server.pyindex 480e00f93..07fade11d 100644--- a/memgpt/server/ws_api/server.py+++ b/memgpt/server/ws_api/server.py@@ -57,7 +57,7 @@ class WebSocketServer:# Assuming the message is a JSON stringtry:- data = json.loads(message)+ data = json.loads(message, strict=JSON_LOADS_STRICT)except:print(f"[server] bad data from client:\n{data}")await websocket.send(protocol.server_command_response(f"Error: bad data from client - {str(data)}"))diff --git a/memgpt/utils.py b/memgpt/utils.pyindex 001513359..8ca73a12a 100644--- a/memgpt/utils.py+++ b/memgpt/utils.py@@ -25,6 +25,7 @@ import tiktokenimport memgptfrom memgpt.constants import (+ JSON_LOADS_STRICT,MEMGPT_DIR,FUNCTION_RETURN_CHAR_LIMIT,CLI_WARNING_PREFIX,@@ -840,7 +841,7 @@ def parse_json(string) -> dict:"""Parse JSON string into JSON with both json and demjson"""result = Nonetry:- result = json.loads(string)+ result = json.loads(string, strict=JSON_LOADS_STRICT)return resultexcept Exception as e:print(f"Error parsing json with json package: {e}")diff --git a/tests/test_agent_function_update.py b/tests/test_agent_function_update.pyindex 85a10ba26..4570a5e76 100644--- a/tests/test_agent_function_update.py+++ b/tests/test_agent_function_update.py@@ -85,7 +85,7 @@ def test_add_function_happy(agent, hello_world_function, ai_function_call):assert "hello_world" in agent.functions_python.keys()msgs, heartbeat_req, function_failed = agent._handle_ai_response(ai_function_call)- content = json.loads(msgs[-1].to_openai_dict()["content"])+ content = json.loads(msgs[-1].to_openai_dict()["content"], strict=constants.JSON_LOADS_STRICT)assert content["message"] == "hello, world!"assert content["status"] == "OK"assert not function_faileddiff --git a/tests/test_json_parsers.py b/tests/test_json_parsers.pyindex a0cef1d62..6a260e1fd 100644--- a/tests/test_json_parsers.py+++ b/tests/test_json_parsers.py@@ -1,4 +1,5 @@import json+from memgpt.constants import JSON_LOADS_STRICTimport memgpt.local_llm.json_parser as json_parser@@ -81,7 +82,7 @@ def test_json_parsers():for string in test_strings:try:- json.loads(string)+ json.loads(string, strict=JSON_LOADS_STRICT)assert False, f"Test JSON string should have failed basic JSON parsing:\n{string}"except:print("String failed (expectedly)")