Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

genai: Fix handling of optional arrays in tool input #661

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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

Loading