Python: fix(python): add __str__ to ChatMessage to prevent repr in display output#2565
Closed
The-Obstacle-Is-The-Way wants to merge 1 commit intomicrosoft:mainfrom
Closed
Conversation
…tput When a ChatMessage contains only tool calls (no TextContent), code like `str(message)` would return Python's default repr: "<agent_framework._types.ChatMessage object at 0x...>" This bug manifests in MagenticAgentExecutor._invoke_agent() at line 1730 where `text = last.text or str(last)` uses str(last) as fallback when .text is empty (which happens for tool-call-only messages). Changes: - Add __str__ method to ChatMessage that returns text content or formatted tool call summary, never repr - Add __repr__ method to ChatMessage for better debugging - Add comprehensive tests for both methods The buggy line 1730 now works correctly without modification because str(ChatMessage) returns meaningful content. Fixes microsoft#2562
Author
|
@microsoft-github-policy-service agree |
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
When a
ChatMessagecontains only tool calls (no text),str(message)returns Python's default repr (<agent_framework._types.ChatMessage object at 0x...>) instead of meaningful content.This PR adds
__str__and__repr__methods toChatMessage:__str__returns text content when present, or a formatted summary of tool calls__repr__returns debug-friendly output with role, text preview, and content countThe Bug
In
MagenticAgentExecutor._invoke_agent()line 1730:When the message has only
FunctionCallContent(noTextContent),.textreturns empty string, triggering thestr(last)fallback—which produced the repr garbage.The Fix
By adding
__str__toChatMessage, the existing code works correctly without modification. This also future-proofs any other code that callsstr()on aChatMessage.Test Plan
Fixes #2562