From a0027c820dafaddb1af4c0e536c8018c9940b794 Mon Sep 17 00:00:00 2001 From: RazCrimson Date: Tue, 4 Feb 2025 20:35:36 +0530 Subject: [PATCH] genai: fix function_utils to parse object/array json schemas properly (#715) --- libs/genai/langchain_google_genai/_function_utils.py | 10 +++++++++- libs/genai/tests/unit_tests/test_function_utils.py | 5 ----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/libs/genai/langchain_google_genai/_function_utils.py b/libs/genai/langchain_google_genai/_function_utils.py index 829f9549..e6e983dd 100644 --- a/libs/genai/langchain_google_genai/_function_utils.py +++ b/libs/genai/langchain_google_genai/_function_utils.py @@ -301,10 +301,18 @@ def _get_properties_from_schema(schema: Dict) -> Dict[str, Any]: continue properties_item: Dict[str, Union[str, int, Dict, List]] = {} if v.get("type") or v.get("anyOf") or v.get("type_"): - properties_item["type_"] = _get_type_from_schema(v) + item_type_ = _get_type_from_schema(v) + properties_item["type_"] = item_type_ if _is_nullable_schema(v): properties_item["nullable"] = True + # Replace `v` with chosen definition for array / object json types + any_of_types = v.get("anyOf") + if any_of_types and item_type_ in [glm.Type.ARRAY, glm.Type.OBJECT]: + json_type_ = "array" if item_type_ == glm.Type.ARRAY else "object" + # Use Index -1 for consistency with `_get_nullable_type_from_schema` + v = [val for val in any_of_types if val.get("type") == json_type_][-1] + if v.get("enum"): properties_item["enum"] = v["enum"] diff --git a/libs/genai/tests/unit_tests/test_function_utils.py b/libs/genai/tests/unit_tests/test_function_utils.py index 482248e9..2faf03fa 100644 --- a/libs/genai/tests/unit_tests/test_function_utils.py +++ b/libs/genai/tests/unit_tests/test_function_utils.py @@ -84,11 +84,6 @@ def possibly_none_list( # Convert to OpenAI tool oai_tool = convert_to_openai_tool(possibly_none_list) - # Manually assign the 'items' type in the parameters - oai_tool["function"]["parameters"]["properties"]["items"]["items"] = { - "type": "string" - } - # Convert to GenAI, then to dict genai_tool = convert_to_genai_function_declarations([oai_tool]) genai_tool_dict = tool_to_dict(genai_tool)