Skip to content

Commit 2e06e4b

Browse files
committed
genai: Fix handling of optional arrays in tool input
1 parent 2314c92 commit 2e06e4b

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
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:
319329
if (

libs/genai/tests/unit_tests/test_function_utils.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
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 (
@@ -525,3 +525,13 @@ class MyModel(BaseModel):
525525
gapic_tool = convert_to_genai_function_declarations([MyModel])
526526
tool_dict = tool_to_dict(gapic_tool)
527527
assert gapic_tool == convert_to_genai_function_declarations([tool_dict])
528+
529+
530+
def test_tool_input_can_have_optional_arrays() -> None:
531+
class ExampleToolInput(BaseModel):
532+
numbers: Optional[List[str]] = Field()
533+
534+
gapic_tool = convert_to_genai_function_declarations([ExampleToolInput])
535+
properties = gapic_tool.function_declarations[0].parameters.properties
536+
assert properties.get('numbers').items.type_ == 1
537+

0 commit comments

Comments
 (0)