1
1
import json
2
- from typing import Any , Callable , ClassVar , Dict , List , Optional , Tuple
2
+ from typing import Any , Callable , ClassVar , Dict , List , Optional , Tuple , Union
3
3
4
4
from haystack import component , default_from_dict , default_to_dict , logging
5
5
from haystack .dataclasses import (
12
12
ToolCallResult ,
13
13
select_streaming_callback ,
14
14
)
15
- from haystack .tools import Tool , _check_duplicate_tool_names
15
+ from haystack .tools import (
16
+ Tool ,
17
+ Toolset ,
18
+ _check_duplicate_tool_names ,
19
+ deserialize_tools_or_toolset_inplace ,
20
+ serialize_tools_or_toolset ,
21
+ )
16
22
from haystack .utils import Secret , deserialize_callable , deserialize_secrets_inplace , serialize_callable
17
23
18
- # Compatibility with Haystack 2.12.0 and 2.13.0 - remove after 2.13.0 is released
19
- try :
20
- from haystack .tools import deserialize_tools_or_toolset_inplace
21
- except ImportError :
22
- from haystack .tools import deserialize_tools_inplace as deserialize_tools_or_toolset_inplace
23
-
24
24
from anthropic import Anthropic , AsyncAnthropic
25
25
26
26
logger = logging .getLogger (__name__ )
@@ -186,7 +186,7 @@ def __init__(
186
186
streaming_callback : Optional [StreamingCallbackT ] = None ,
187
187
generation_kwargs : Optional [Dict [str , Any ]] = None ,
188
188
ignore_tools_thinking_messages : bool = True ,
189
- tools : Optional [List [Tool ]] = None ,
189
+ tools : Optional [Union [ List [Tool ], Toolset ]] = None ,
190
190
):
191
191
"""
192
192
Creates an instance of AnthropicChatGenerator.
@@ -213,10 +213,10 @@ def __init__(
213
213
`ignore_tools_thinking_messages` is `True`, the generator will drop so-called thinking messages when tool
214
214
use is detected. See the Anthropic [tools](https://docs.anthropic.com/en/docs/tool-use#chain-of-thought-tool-use)
215
215
for more details.
216
- :param tools: A list of Tool objects that the model can use. Each tool should have a unique name.
216
+ :param tools: A list of Tool objects or a Toolset that the model can use. Each tool should have a unique name.
217
217
218
218
"""
219
- _check_duplicate_tool_names (tools )
219
+ _check_duplicate_tool_names (list ( tools or [])) # handles Toolset as well
220
220
221
221
self .api_key = api_key
222
222
self .model = model
@@ -241,15 +241,14 @@ def to_dict(self) -> Dict[str, Any]:
241
241
The serialized component as a dictionary.
242
242
"""
243
243
callback_name = serialize_callable (self .streaming_callback ) if self .streaming_callback else None
244
- serialized_tools = [tool .to_dict () for tool in self .tools ] if self .tools else None
245
244
return default_to_dict (
246
245
self ,
247
246
model = self .model ,
248
247
streaming_callback = callback_name ,
249
248
generation_kwargs = self .generation_kwargs ,
250
249
api_key = self .api_key .to_dict (),
251
250
ignore_tools_thinking_messages = self .ignore_tools_thinking_messages ,
252
- tools = serialized_tools ,
251
+ tools = serialize_tools_or_toolset ( self . tools ) ,
253
252
)
254
253
255
254
@classmethod
@@ -402,14 +401,15 @@ def _prepare_request_params(
402
401
self ,
403
402
messages : List [ChatMessage ],
404
403
generation_kwargs : Optional [Dict [str , Any ]] = None ,
405
- tools : Optional [List [Tool ]] = None ,
404
+ tools : Optional [Union [ List [Tool ], Toolset ]] = None ,
406
405
) -> Tuple [List [Dict [str , Any ]], List [Dict [str , Any ]], Dict [str , Any ], List [Dict [str , Any ]]]:
407
406
"""
408
407
Prepare the parameters for the Anthropic API request.
409
408
410
409
:param messages: A list of ChatMessage instances representing the input messages.
411
410
:param generation_kwargs: Optional arguments to pass to the Anthropic generation endpoint.
412
- :param tools: A list of tools for which the model can prepare calls.
411
+ :param tools: A list of Tool objects or a Toolset that the model can use. Each tool should
412
+ have a unique name.
413
413
:returns: A tuple containing:
414
414
- system_messages: List of system messages in Anthropic format
415
415
- non_system_messages: List of non-system messages in Anthropic format
@@ -448,7 +448,8 @@ def _prepare_request_params(
448
448
449
449
# tools management
450
450
tools = tools or self .tools
451
- _check_duplicate_tool_names (tools )
451
+ tools = list (tools ) if isinstance (tools , Toolset ) else tools
452
+ _check_duplicate_tool_names (tools ) # handles Toolset as well
452
453
anthropic_tools = (
453
454
[
454
455
{
@@ -550,16 +551,16 @@ def run(
550
551
messages : List [ChatMessage ],
551
552
streaming_callback : Optional [StreamingCallbackT ] = None ,
552
553
generation_kwargs : Optional [Dict [str , Any ]] = None ,
553
- tools : Optional [List [Tool ]] = None ,
554
+ tools : Optional [Union [ List [Tool ], Toolset ]] = None ,
554
555
):
555
556
"""
556
557
Invokes the Anthropic API with the given messages and generation kwargs.
557
558
558
559
:param messages: A list of ChatMessage instances representing the input messages.
559
560
:param streaming_callback: A callback function that is called when a new token is received from the stream.
560
561
:param generation_kwargs: Optional arguments to pass to the Anthropic generation endpoint.
561
- :param tools: A list of tools for which the model can prepare calls. If set, it will override
562
- the `tools` parameter set during component initialization.
562
+ :param tools: A list of Tool objects or a Toolset that the model can use. Each tool should
563
+ have a unique name. If set, it will override the `tools` parameter set during component initialization.
563
564
:returns: A dictionary with the following keys:
564
565
- `replies`: The responses from the model
565
566
"""
@@ -591,16 +592,16 @@ async def run_async(
591
592
messages : List [ChatMessage ],
592
593
streaming_callback : Optional [StreamingCallbackT ] = None ,
593
594
generation_kwargs : Optional [Dict [str , Any ]] = None ,
594
- tools : Optional [List [Tool ]] = None ,
595
+ tools : Optional [Union [ List [Tool ], Toolset ]] = None ,
595
596
):
596
597
"""
597
598
Async version of the run method. Invokes the Anthropic API with the given messages and generation kwargs.
598
599
599
600
:param messages: A list of ChatMessage instances representing the input messages.
600
601
:param streaming_callback: A callback function that is called when a new token is received from the stream.
601
602
:param generation_kwargs: Optional arguments to pass to the Anthropic generation endpoint.
602
- :param tools: A list of tools for which the model can prepare calls. If set, it will override
603
- the `tools` parameter set during component initialization.
603
+ :param tools: A list of Tool objects or a Toolset that the model can use. Each tool should
604
+ have a unique name. If set, it will override the `tools` parameter set during component initialization.
604
605
:returns: A dictionary with the following keys:
605
606
- `replies`: The responses from the model
606
607
"""
0 commit comments