From 9aae8ef416150fd665a0fc2e913ac2096deb903f Mon Sep 17 00:00:00 2001 From: Eun Hye Kim Date: Sat, 20 Jul 2024 02:31:00 +0900 Subject: [PATCH] core[patch]: Fix utils.json_schema.dereference_refs (#24335 KeyError: 400 in JSON schema processing) (#24337) Description: This PR fixes a KeyError: 400 that occurs in the JSON schema processing within the reduce_openapi_spec function. The _retrieve_ref function in json_schema.py was modified to handle missing components gracefully by continuing to the next component if the current one is not found. This ensures that the OpenAPI specification is fully interpreted and the agent executes without errors. Issue: Fixes issue #24335 Dependencies: No additional dependencies are required for this change. Twitter handle: @lunara_x --- libs/core/langchain_core/utils/json_schema.py | 6 ++-- .../unit_tests/utils/test_json_schema.py | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/libs/core/langchain_core/utils/json_schema.py b/libs/core/langchain_core/utils/json_schema.py index 3368f83813..be5c8e25ba 100644 --- a/libs/core/langchain_core/utils/json_schema.py +++ b/libs/core/langchain_core/utils/json_schema.py @@ -13,10 +13,12 @@ def _retrieve_ref(path: str, schema: dict) -> dict: ) out = schema for component in components[1:]: - if component.isdigit(): + if component in out: + out = out[component] + elif component.isdigit() and int(component) in out: out = out[int(component)] else: - out = out[component] + raise KeyError(f"Reference '{path}' not found.") return deepcopy(out) diff --git a/libs/core/tests/unit_tests/utils/test_json_schema.py b/libs/core/tests/unit_tests/utils/test_json_schema.py index 44ad61609b..cb2add7476 100644 --- a/libs/core/tests/unit_tests/utils/test_json_schema.py +++ b/libs/core/tests/unit_tests/utils/test_json_schema.py @@ -183,6 +183,38 @@ def test_dereference_refs_integer_ref() -> None: assert actual == expected +def test_dereference_refs_string_ref() -> None: + schema = { + "type": "object", + "properties": { + "error_400": {"$ref": "#/$defs/400"}, + }, + "$defs": { + "400": { + "type": "object", + "properties": {"description": "Bad Request"}, + }, + }, + } + expected = { + "type": "object", + "properties": { + "error_400": { + "type": "object", + "properties": {"description": "Bad Request"}, + }, + }, + "$defs": { + "400": { + "type": "object", + "properties": {"description": "Bad Request"}, + }, + }, + } + actual = dereference_refs(schema) + assert actual == expected + + def test_dereference_refs_cyclical_refs() -> None: schema = { "type": "object",