Skip to content

Update default output to string handler in ToolInvoker to serialize before using json.dumps #9293

@sjrl

Description

@sjrl

In the ToolInvoker we have an option called convert_result_to_json_string which does this currently

def _default_output_to_string_handler(self, result: Any) -> str:
"""
Default handler for converting a tool result to a string.
:param result: The tool result to convert to a string.
:returns: The converted tool result as a string.
"""
if self.convert_result_to_json_string:
# We disable ensure_ascii so special chars like emojis are not converted
tool_result_str = json.dumps(result, ensure_ascii=False)
else:
tool_result_str = str(result)
return tool_result_str

I believe it would be better if we followed the implementation of coerce_tag_value

try:
# do that with-in try-except because who knows what kind of objects are being passed
serializable = _serializable_value(value)
return json.dumps(serializable)
except Exception as error:
logger.debug("Failed to coerce tag value to string: {error}", error=error)
# Our last resort is to convert the value to a string
return str(value)
which first calls _serializable_value which iteratively goes through result and tries to serialize the value using to_dict if it's available.

This way Haystack native items like ChatMessage and Documents are better represented in a JSON format than by directly calling json.dumps on them.

Metadata

Metadata

Assignees

Labels

P2Medium priority, add to the next sprint if no P1 available

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions