Skip to content

Commit 07a2256

Browse files
committed
genai: Fix handling of optional arrays in tool input
1 parent 7382d23 commit 07a2256

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

libs/genai/langchain_google_genai/_function_utils.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,16 @@ def _get_properties_from_schema(schema: Dict) -> Dict[str, Any]:
314314

315315
if properties_item.get("type_") == glm.Type.ARRAY and v.get("items"):
316316
properties_item["items"] = _get_items_from_schema_any(v.get("items"))
317+
elif properties_item.get("type_") == glm.Type.ARRAY and v.get("anyOf"):
318+
types_with_items = [t for t in v.get("anyOf") if t.get("items")]
319+
if len(types_with_items) > 1:
320+
len_types = len(types_with_items)
321+
logger.warning(
322+
"Only first value for 'anyOf' key is supported in array types."
323+
f"Got {len_types} types, using first one: {types_with_items[0]}"
324+
)
325+
items = types_with_items[0]['items']
326+
properties_item["items"] = _get_items_from_schema_any(items)
317327

318328
if properties_item.get("type_") == glm.Type.OBJECT and v.get("properties"):
319329
properties_item["properties"] = _get_properties_from_schema_any(

libs/genai/tests/unit_tests/test_function_utils.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
from typing import Any, Generator, Optional, Union
1+
from typing import Any, Generator, List, Optional, Union
22
from unittest.mock import MagicMock, patch
33

44
import google.ai.generativelanguage as glm
55
import pytest
66
from langchain_core.documents import Document
77
from langchain_core.tools import InjectedToolArg, tool
88
from langchain_core.utils.function_calling import convert_to_openai_tool
9-
from pydantic import BaseModel
9+
from pydantic import BaseModel, Field
1010
from typing_extensions import Annotated
1111

1212
from langchain_google_genai._function_utils import (
@@ -309,3 +309,13 @@ class MyModel(BaseModel):
309309
gapic_tool = convert_to_genai_function_declarations([MyModel])
310310
tool_dict = tool_to_dict(gapic_tool)
311311
assert gapic_tool == convert_to_genai_function_declarations([tool_dict])
312+
313+
314+
def test_tool_input_can_have_optional_arrays() -> None:
315+
class ExampleToolInput(BaseModel):
316+
numbers: Optional[List[str]] = Field()
317+
318+
gapic_tool = convert_to_genai_function_declarations([ExampleToolInput])
319+
properties = gapic_tool.function_declarations[0].parameters.properties
320+
assert properties.get('numbers').items.type_ == 1
321+

0 commit comments

Comments
 (0)