From 67f6e5c89dcbdcf67e5e7cbeebcc25ac0a972040 Mon Sep 17 00:00:00 2001 From: Donnie Adams Date: Tue, 13 Aug 2024 18:39:39 -0400 Subject: [PATCH] fix: stop crash when parsing empty files and strings Signed-off-by: Donnie Adams --- gptscript/gptscript.py | 4 ++++ tests/fixtures/empty.gpt | 0 tests/test_gptscript.py | 13 +++++++++++++ 3 files changed, 17 insertions(+) create mode 100644 tests/fixtures/empty.gpt diff --git a/gptscript/gptscript.py b/gptscript/gptscript.py index 504b5c6..8f20a2f 100644 --- a/gptscript/gptscript.py +++ b/gptscript/gptscript.py @@ -97,12 +97,16 @@ def run( async def parse(self, file_path: str, disable_cache: bool = False) -> list[Text | Tool]: out = await self._run_basic_command("parse", {"file": file_path, "disableCache": disable_cache}) parsed_nodes = json.loads(out) + if parsed_nodes is None or parsed_nodes.get("nodes", None) is None: + return [] return [Text(**node["textNode"]) if "textNode" in node else Tool(**node.get("toolNode", {}).get("tool", {})) for node in parsed_nodes.get("nodes", [])] async def parse_tool(self, tool_def: str) -> list[Text | Tool]: out = await self._run_basic_command("parse", {"content": tool_def}) parsed_nodes = json.loads(out) + if parsed_nodes is None or parsed_nodes.get("nodes", None) is None: + return [] return [Text(**node["textNode"]) if "textNode" in node else Tool(**node.get("toolNode", {}).get("tool", {})) for node in parsed_nodes.get("nodes", [])] diff --git a/tests/fixtures/empty.gpt b/tests/fixtures/empty.gpt new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_gptscript.py b/tests/test_gptscript.py index f7bab9e..69dcf6e 100644 --- a/tests/test_gptscript.py +++ b/tests/test_gptscript.py @@ -259,6 +259,19 @@ async def test_parse_simple_file(gptscript): "Unexpected output from parsing simple file" +@pytest.mark.asyncio +async def test_parse_empty_file(gptscript): + wd = os.getcwd() + tools = await gptscript.parse(wd + "/tests//fixtures/empty.gpt") + assert len(tools) == 0, "Unexpected number of tools for parsing emtpy file" + + +@pytest.mark.asyncio +async def test_parse_empty_str(gptscript): + tools = await gptscript.parse_tool("") + assert len(tools) == 0, "Unexpected number of tools for parsing empty string" + + @pytest.mark.asyncio async def test_parse_tool_with_metadata(gptscript): wd = os.getcwd()