Skip to content

Commit

Permalink
genai: Fix handling of optional arrays in tool input
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-rudnik committed Jan 13, 2025
1 parent 2314c92 commit 2e06e4b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 10 additions & 0 deletions libs/genai/langchain_google_genai/_function_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,16 @@ def _get_properties_from_schema(schema: Dict) -> Dict[str, Any]:

if properties_item.get("type_") == glm.Type.ARRAY and v.get("items"):
properties_item["items"] = _get_items_from_schema_any(v.get("items"))
elif properties_item.get("type_") == glm.Type.ARRAY and v.get("anyOf"):
types_with_items = [t for t in v.get("anyOf") if t.get("items")]
if len(types_with_items) > 1:
len_types = len(types_with_items)
logger.warning(
"Only first value for 'anyOf' key is supported in array types."
f"Got {len_types} types, using first one: {types_with_items[0]}"
)
items = types_with_items[0]['items']
properties_item["items"] = _get_items_from_schema_any(items)

if properties_item.get("type_") == glm.Type.OBJECT:
if (
Expand Down
12 changes: 11 additions & 1 deletion libs/genai/tests/unit_tests/test_function_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from langchain_core.documents import Document
from langchain_core.tools import InjectedToolArg, tool
from langchain_core.utils.function_calling import convert_to_openai_tool
from pydantic import BaseModel
from pydantic import BaseModel, Field
from typing_extensions import Annotated

from langchain_google_genai._function_utils import (
Expand Down Expand Up @@ -525,3 +525,13 @@ class MyModel(BaseModel):
gapic_tool = convert_to_genai_function_declarations([MyModel])
tool_dict = tool_to_dict(gapic_tool)
assert gapic_tool == convert_to_genai_function_declarations([tool_dict])


def test_tool_input_can_have_optional_arrays() -> None:
class ExampleToolInput(BaseModel):
numbers: Optional[List[str]] = Field()

gapic_tool = convert_to_genai_function_declarations([ExampleToolInput])
properties = gapic_tool.function_declarations[0].parameters.properties
assert properties.get('numbers').items.type_ == 1

0 comments on commit 2e06e4b

Please sign in to comment.