From f9afb041e2db04a93845e2ab505e768c7a5cb626 Mon Sep 17 00:00:00 2001 From: ochafik Date: Wed, 10 Apr 2024 09:14:24 +0100 Subject: [PATCH] agent: python tool: test serializability of variables --- examples/agent/tools/unsafe_python_tools.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/examples/agent/tools/unsafe_python_tools.py b/examples/agent/tools/unsafe_python_tools.py index 0a3a2cb84..3473a9254 100644 --- a/examples/agent/tools/unsafe_python_tools.py +++ b/examples/agent/tools/unsafe_python_tools.py @@ -3,6 +3,13 @@ import sys import types from typing import Dict, Union +def _is_serializable(obj) -> bool: + try: + json.dumps(obj) + return True + except Exception as e: + return False + def execute_python(source: str) -> Union[Dict, str]: """ Evaluate a Python program and return the globals it declared. @@ -21,7 +28,11 @@ def execute_python(source: str) -> Union[Dict, str]: results = { k: v for k, v in namespace.items() - if not k.startswith('_') and not isinstance(v, type) and not callable(v) and not isinstance(v, types.ModuleType) + if not k.startswith('_') \ + and not isinstance(v, type) \ + and not isinstance(v, types.ModuleType) \ + and not callable(v) \ + and _is_serializable(v) } sys.stderr.write(f"Results: {json.dumps(results, indent=2)}\n")