Fix datetime JSON serialization error in agentchat_fastapi samples #7075
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When running the
app_team.py
orapp_agent.py
examples from theagentchat_fastapi
sample directory with AutoGen 0.7.5, users encountered a JSON serialization error:This error occurred when the application attempted to send messages via WebSocket or save conversation history to JSON files.
Root Cause
The sample applications were using
model_dump()
to serialize message objects before passing them tojson.dumps()
orwebsocket.send_json()
. Themodel_dump()
method returns datetime fields (likecreated_at
) as Pythondatetime
objects, which are not JSON serializable by default.Example of the problematic code:
Solution
Replace
model_dump()
withdump()
method calls. Thedump()
method usesmodel_dump(mode="json")
internally, which automatically converts datetime objects to ISO 8601 format strings.Example of the fix:
Changes
Files modified:
python/samples/agentchat_fastapi/app_team.py
- Lines 124, 127python/samples/agentchat_fastapi/app_agent.py
- Lines 91, 92The changes are minimal (4 lines total) and use the recommended serialization method from the
BaseMessage
class, which is already tested intest_datetime_serialization_in_messages
.Testing
test_datetime_serialization_in_messages
passesThis issue did not occur in AutoGen 0.5.7 because the serialization behavior changed in later versions. This fix ensures the samples work correctly with AutoGen 0.7.5 and later.
Original prompt
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.