Skip to content

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

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

Open
sjrl opened this issue Apr 23, 2025 · 0 comments
Labels
P2 Medium priority, add to the next sprint if no P1 available

Comments

@sjrl
Copy link
Contributor

sjrl commented Apr 23, 2025

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.

@julian-risch julian-risch added the P2 Medium priority, add to the next sprint if no P1 available label Apr 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
P2 Medium priority, add to the next sprint if no P1 available
Projects
None yet
Development

No branches or pull requests

2 participants