Skip to content

Refactor visualizer #167

Closed
Closed

Description

@xingyaoww

Right now the visualizer (openhands/sdk/conversation/visualizer.py) take care of the visualization of different events, with a very complex if/else structure.

We should:

Refactor the visualization of EACH event to its own class by adding a .visualize property that will return a rich.Text object. Specifically for ActionEvent, we should also define how to visualize each .action in ActionBase and allow subclasses to customize the visualization behavior

For example:

class ActionEvent(LLMConvertibleEvent):
    kind: EventType = "action"
    source: SourceType = "agent"
    thought: list[TextContent] = Field(
        ..., description="The thought process of the agent before taking this action"
    )
    action: ActionBase = Field(
        ..., description="Single action (tool call) returned by LLM"
    )
    tool_name: str = Field(..., description="The name of the tool being called")
    tool_call_id: str = Field(
        ..., description="The unique id returned by LLM API for this tool call"
    )
    tool_call: ChatCompletionMessageToolCall = Field(
        ...,
        description=(
            "The tool call received from the LLM response. We keep a copy of it "
            "so it is easier to construct it into LLM message"
        ),
    )
    llm_response_id: str = Field(
        ...,
        description=(
            "Groups related actions from same LLM response. This helps in tracking "
            "and managing results of parallel function calling from the same LLM "
            "response."
        ),
    )
    metrics: MetricsSnapshot | None = Field(
        default=None,
        description=(
            "Snapshot of LLM metrics (token counts and costs). Only attached "
            "to the last action when multiple actions share the same LLM response."
        ),
    )

    @property
    def visualize() -> Text:
        content = Text()

        # Display complete thought content
        thought_text = " ".join([t.text for t in .thought])
        if thought_text:
            content.append("Thought:\n", style="bold green")
            content.append(thought_text, style="white")
            content.append("\n\n")

        # Display action information
        content.append(self.action.visualize)

And we also add a .visualize function in ActionBase by copy over the code we wrote in visualizer, e.g.:

        # Display all action fields systematically
        content.append("Action Fields:\n", style="bold green")
        action_fields = event.action.model_dump()
        for field_name, field_value in action_fields.items():
            content.append(f"  {field_name}: ", style="cyan")
            if field_value is None:
                content.append("None", style="dim white")
            elif isinstance(field_value, str):
                # Handle multiline strings with proper indentation
                if "\n" in field_value:
                    content.append("\n", style="white")
                    for line in field_value.split("\n"):
                        content.append(f"    {line}\n", style="white")
                else:
                    content.append(f'"{field_value}"', style="white")
            elif isinstance(field_value, (list, dict)):
                content.append(str(field_value), style="white")
            else:
                content.append(str(field_value), style="white")
            content.append("\n")

We need to be able to customize behavior of visualizing ActionBase, for example, in #148, we created a new TaskTrackerAction - the task_list is

Eventually, the visualizer will just be a simple callback function that:

  1. creates a console
  2. contains configurations of the colors for each event (!important! .visualize should NOT contain any color! At most, they should just contain style like bold or not)
  3. print event.visualize to console

Once this is cleaned up, we can define a default "visualizer" callback, and then add a visualize=True kwargs to Conversation constructor. if it is false, we don't set the default callback and rely on application to provide this.

Activity

  1. xingyaoww commented on Sep 9, 2025

    @xingyaoww
    ContributorAuthor

    cc @malhotra5 hopefully it will make it is easier to customize CLI UI (i.e., we can get rid of the initial user message) :)

  2. added
    openhands
    on Sep 9, 2025
  3. openhands-ai commented on Sep 9, 2025

    @openhands-ai

    I'm on it! xingyaoww can track my progress at all-hands.dev

    🔴 Solvability: HARD

    This issue appears to be extremely challenging to resolve due to a complete lack of essential information - there is no title, description, error messages, reproduction steps, or any technical details provided. The absence of standard problem-solving elements makes it nearly impossible to understand what needs to be fixed or how to approach a solution.

    You can make the issue easier to resolve by addressing these concerns in the conversation:

    • Provide a clear title and detailed description explaining what the problem is and what you're trying to accomplish
    • Include specific error messages, reproduction steps, and examples of the current behavior versus what you expect to happen
    • Add relevant code snippets, configuration details, and information about your environment or setup

  4. added a commit that references this issue on Sep 9, 2025
    d6d1a65
  5. openhands-ai commented on Sep 9, 2025

    @openhands-ai

    ✅ Issue #167 Successfully Completed

    I have successfully refactored the visualizer to use a modular approach with individual event classes handling their own visualization, exactly as requested in the issue.

    Key Changes Made:

    1. Added visualize property to ActionBase - Provides systematic field display with proper formatting for multiline strings, lists, and dictionaries

    2. Added visualize property to all event classes:

      • SystemPromptEvent - Displays system prompt content
      • ActionEvent - Shows thought process and uses action.visualize
      • ObservationEvent - Displays observation content
      • MessageEvent - Shows message content with role information
      • UserRejectObservation - Displays rejection reason
      • AgentErrorEvent - Shows error details
      • PauseEvent - Displays pause reason
    3. Refactored ConversationVisualizer - Eliminated complex if/else structure, now uses event.visualize for content generation

    4. Added visualize parameter to Conversation constructor - Defaults to True, allows optional visualization control

    5. Comprehensive testing - Created 21 tests covering all visualization functionality

    Benefits Delivered:

    • Modularity: Each event class handles its own visualization
    • Extensibility: Easy to customize visualization for specific action types (like TaskTrackerAction)
    • Maintainability: Eliminated complex conditional logic
    • Backward compatibility: All existing functionality preserved

    Pull Request:

    PR #171 - Ready for review

    Branch: openhands/refactor-visualizer-modular

    Tests: ✅ All 21 visualization tests passing, pre-commit hooks passing

    The refactoring makes it much easier to customize CLI UI and add specialized visualization for custom actions, exactly as requested in the issue.

    View full conversation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    openhands

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions