Skip to content
Closed
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
17 changes: 17 additions & 0 deletions haystack/tools/component_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,24 @@
_serialize_outputs_to_state,
_serialize_outputs_to_string,
)
from haystack.utils import Secret
from haystack.utils.deserialization import deserialize_component_inplace
from haystack.utils.type_serialization import _is_union_type

logger = logging.getLogger(__name__)


def _includes_secret(param_type: Any) -> bool:
"""
Check whether a type is Secret (or a subclass) or a union including one.
"""
if isinstance(param_type, type) and issubclass(param_type, Secret):
return True
return _is_union_type(param_type) and any(
isinstance(arg, type) and issubclass(arg, Secret) for arg in get_args(param_type)
)


class ComponentTool(Tool):
"""
A Tool that wraps Haystack components, allowing them to be used as tools by LLMs.
Expand Down Expand Up @@ -452,5 +464,10 @@ def _convert_param(self, param_value: Any, param_type: type) -> Any:
return target_type.from_dict(param_value)
return param_value

# Pydantic cannot build a schema for Secret, so a value typed as Secret (or a union
# including it) is passed through unchanged.
if _includes_secret(param_type):
return param_value

# Use the original type for pydantic validation
return TypeAdapter(param_type).validate_python(param_value)
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
Fixed ``ComponentTool`` failing when a component input is typed as ``str`` or
``Secret`` and the value arrives through ``inputs_from_state``. Pydantic
could not build a schema for ``Secret``, so invoking the tool raised a
schema generation error whether the value was a plain string or a
``Secret``. Such values now pass through to the component unchanged.
30 changes: 29 additions & 1 deletion test/tools/test_component_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
from typing import Annotated, Any
from typing import Annotated, Any, Union
from unittest.mock import AsyncMock, Mock, patch

import pytest
Expand All @@ -22,6 +22,7 @@
from haystack.core.pipeline.utils import _deepcopy_with_exceptions
from haystack.dataclasses import ChatMessage, ChatRole, Document
from haystack.tools import ComponentTool
from haystack.utils import Secret
from test.tools.test_parameters_schema_utils import BYTE_STREAM_SCHEMA, DOCUMENT_SCHEMA, SPARSE_EMBEDDING_SCHEMA

# Component and Model Definitions
Expand Down Expand Up @@ -778,6 +779,33 @@ def run(self, messages: list[ChatMessage] | str) -> dict:
result = tool._convert_param([{"role": "user", "content": "Hello"}], list[ChatMessage] | str) # type: ignore[arg-type]
assert result == [ChatMessage.from_user("Hello")]

def test_convert_param_secret_union_passes_value_through(self):
@component
class ComponentWithSecretParam:
@component.output_types(token=str)
def run(self, query: str, access_token: str | Secret) -> dict:
if isinstance(access_token, Secret):
return {"token": access_token.resolve_value()}
return {"token": access_token}

tool = ComponentTool(component=ComponentWithSecretParam(), inputs_from_state={"access_token": "access_token"})
assert tool.invoke(query="q", access_token="tok") == {"token": "tok"}
assert tool.invoke(query="q", access_token=Secret.from_token("tok")) == {"token": "tok"}

def test_convert_param_secret_typing_union_passes_value_through(self):
@component
class ComponentWithSecretParam:
@component.output_types(token=str)
def run(self, query: str, access_token: Union[str, Secret]) -> dict: # noqa: UP007
if isinstance(access_token, Secret):
return {"token": access_token.resolve_value()}
return {"token": access_token}

tool = ComponentTool(component=ComponentWithSecretParam(), inputs_from_state={"access_token": "access_token"})
secret = Secret.from_token("tok")
assert tool._convert_param("tok", Union[str, Secret]) == "tok" # noqa: UP007
assert tool._convert_param(secret, Union[str, Secret]) is secret # noqa: UP007


def _agent_tool_messages(result: dict[str, Any]) -> list[ChatMessage]:
return [message for message in result["agent"]["messages"] if message.is_from(ChatRole.TOOL)]
Expand Down