Skip to content

fix(tools): automatically serialize list and dictionary tool outputs to JSON strings#6377

Open
Hasnaathussain wants to merge 2 commits into
crewAIInc:mainfrom
Hasnaathussain:fix/6267-tool-nested-dict-serialization
Open

fix(tools): automatically serialize list and dictionary tool outputs to JSON strings#6377
Hasnaathussain wants to merge 2 commits into
crewAIInc:mainfrom
Hasnaathussain:fix/6267-tool-nested-dict-serialization

Conversation

@Hasnaathussain

@Hasnaathussain Hasnaathussain commented Jun 28, 2026

Copy link
Copy Markdown

Currently, when a custom tool returns a dictionary or a list, format_output_for_agent falls back to returning the Python string representation (e.g. str(raw_result) which outputs invalid JSON with single quotes like {'foo': 'bar'}). This can cause parsing/validation failures downstream when processed by LLMs or JSON output parsers.

This PR updates _format_tool_output_for_agent to automatically serialize dictionary and list outputs into valid JSON strings using json.dumps.

I've added unit tests verifying that both dictionary and list tool outputs are successfully serialized to JSON strings.

Closes #6267

Summary by CodeRabbit

  • Bug Fixes

    • Improved tool output formatting so structured results are more reliably returned as JSON when possible.
    • Added safer fallback handling for complex outputs, reducing the chance of unreadable agent responses.
  • Tests

    • Added coverage for structured outputs to confirm dictionaries and lists are serialized correctly, including nested values.

Copilot AI review requested due to automatic review settings June 28, 2026 09:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 303df22c-920e-4560-8e78-740e53ff19a4

📥 Commits

Reviewing files that changed from the base of the PR and between 2aa257e and 8ab8144.

📒 Files selected for processing (1)
  • lib/crewai/src/crewai/tools/structured_tool.py

📝 Walkthrough

Walkthrough

_format_tool_output_for_agent now JSON-serializes dict and list tool outputs in both fallback paths, and a new test checks that nested structures round-trip through json.loads.

Changes

JSON serialization fallback for dict/list tool outputs

Layer / File(s) Summary
json.dumps fallback in _format_tool_output_for_agent + tests
lib/crewai/src/crewai/tools/structured_tool.py, lib/crewai/tests/tools/test_structured_tool.py
Both the no-schema fallback and the exception-handling fallback now use json.dumps(raw_result, ensure_ascii=False) for dict/list outputs, with str(raw_result) as the last resort. The new test test_format_output_for_agent_with_dict_and_list verifies JSON round-tripping for nested dict and list inputs.

Suggested Reviewers

  • lucasgomide
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: auto-serializing tool outputs to JSON strings.
Linked Issues check ✅ Passed The change addresses #6267 by JSON-serializing dict/list tool outputs and adds coverage for nested structures.
Out of Scope Changes check ✅ Passed The edits stay focused on tool output formatting and a matching unit test, with no obvious unrelated changes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/crewai/src/crewai/tools/structured_tool.py`:
- Around line 88-92: The fallback warning in StructuredTool handling is now
misleading because the branch in structured_tool.py can return JSON for
dict/list results before ever using str(raw_result). Update the warning message
in the same raw_result handling path to describe the actual behavior and
distinguish the JSON serialization attempt from the str(raw_result) fallback.
Use the relevant structured result conversion logic around the
isinstance(raw_result, (dict, list)) branch so the log accurately reflects what
happens on validation failure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d0919d97-a286-4ad7-a566-d0499ee49a55

📥 Commits

Reviewing files that changed from the base of the PR and between 6491f5a and 2aa257e.

📒 Files selected for processing (2)
  • lib/crewai/src/crewai/tools/structured_tool.py
  • lib/crewai/tests/tools/test_structured_tool.py

Comment thread lib/crewai/src/crewai/tools/structured_tool.py Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]Agent execution loop crashes with TypeError when custom tool returns a nested dict

2 participants