KEMBAR78
Fix JSON serialization of team state by handling datetime objects in message dump by Copilot · Pull Request #6797 · microsoft/autogen · GitHub
Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jul 11, 2025

Problem

When saving team state to JSON, users encountered a serialization error due to datetime objects in messages:

# This was failing with "Object of type datetime is not JSON serializable"
team_state = await team.save_state()
with open(state_file, "w") as f:
    json.dump(team_state, f)  # TypeError: Object of type datetime is not JSON serializable

The issue occurred because BaseChatMessage and BaseAgentEvent classes both have a created_at field of type datetime, which is not JSON serializable by default.

Solution

Changed the BaseMessage.dump() method to use Pydantic's JSON-aware serialization mode:

# Before
return self.model_dump()

# After  
return self.model_dump(mode="json")

This leverages Pydantic's built-in capability to automatically convert datetime objects to ISO 8601 format strings during serialization.

Benefits

  • Minimal change: Only 1 line changed + documentation update
  • Surgical fix: Targets the exact source of the problem
  • Backward compatible: All existing functionality works unchanged
  • Standards compliant: Uses ISO 8601 datetime format
  • Round-trip safe: Load/dump operations preserve data correctly

Testing

Verified the fix with comprehensive tests covering:

  • Original user scenario now works without errors
  • All message types serialize/deserialize correctly
  • Team state saving/loading works end-to-end
  • Backward compatibility maintained for existing APIs
  • Round-trip load/dump operations preserve all data

Example of working code after the fix:

# Create team and run task
team = Swarm([project_agent], termination_condition=termination)
result = await team.run(task="What is a Montague?")

# Save state to JSON - now works without errors!
team_state = await team.save_state()
with open(state_file, "w") as f:
    json.dump(team_state, f)  # ✅ Success!

# Load state back
with open(state_file, "r") as f:
    loaded_state = json.load(f)

Fixes #6793.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Co-authored-by: ekzhu <320302+ekzhu@users.noreply.github.com>
Copilot AI changed the title [WIP] JSON dumping of save state on teams fails because of datateimes Fix JSON serialization of team state by handling datetime objects in message dump Jul 11, 2025
Copilot AI requested a review from ekzhu July 11, 2025 11:40
Copilot finished work on behalf of ekzhu July 11, 2025 11:40
@ekzhu
Copy link
Collaborator

ekzhu commented Jul 15, 2025

Add a unit test to validate the change.

@ekzhu ekzhu mentioned this pull request Jul 15, 2025
3 tasks
Co-authored-by: ekzhu <320302+ekzhu@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Jul 15, 2025

Add a unit test to validate the change.

Added comprehensive unit test test_datetime_serialization_in_messages() that validates the datetime serialization fix. The test covers both BaseChatMessage and BaseAgentEvent subclasses, verifies JSON serialization works without errors, and confirms round-trip serialization preserves datetime values correctly. Commit: a4dffb2

Warning

Firewall rules blocked me from connecting to one or more addresses

I tried to connect to the following addresses, but was blocked by firewall rules:

  • astral.sh
    • Triggering command: curl -LsSf REDACTED (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot finished work on behalf of ekzhu July 15, 2025 01:49
@ekzhu ekzhu marked this pull request as ready for review July 15, 2025 01:54
@codecov
Copy link

codecov bot commented Jul 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 80.40%. Comparing base (f45adde) to head (1eeb98d).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #6797   +/-   ##
=======================================
  Coverage   80.40%   80.40%           
=======================================
  Files         233      233           
  Lines       17904    17904           
=======================================
  Hits        14395    14395           
  Misses       3509     3509           
Flag Coverage Δ
unittests 80.40% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ekzhu ekzhu merged commit ca39adc into main Jul 15, 2025
63 checks passed
@ekzhu ekzhu deleted the copilot/fix-6793 branch July 15, 2025 02:05
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.

JSON dumping of save state on teams fails because of datateimes

2 participants