|
| 1 | +--- |
| 2 | +title: Custom Visualizer |
| 3 | +description: Customize conversation visualization by creating custom visualizers or configuring the default visualizer. |
| 4 | +--- |
| 5 | + |
| 6 | +<Note> |
| 7 | +This example is available on GitHub: [examples/01_standalone_sdk/26_custom_visualizer.py](https://github.com/OpenHands/software-agent-sdk/blob/main/examples/01_standalone_sdk/26_custom_visualizer.py) |
| 8 | +</Note> |
| 9 | + |
| 10 | +The SDK provides flexible visualization options. You can use the default rich-formatted visualizer, customize it with highlighting patterns, or build completely custom visualizers by subclassing `ConversationVisualizerBase`. |
| 11 | + |
| 12 | +## Basic Example |
| 13 | + |
| 14 | +```python icon="python" expandable examples/01_standalone_sdk/26_custom_visualizer.py |
| 15 | +"""Custom Visualizer Example |
| 16 | +
|
| 17 | +This example demonstrates how to create and use a custom visualizer by subclassing |
| 18 | +ConversationVisualizer. This approach provides: |
| 19 | +- Clean, testable code with class-based state management |
| 20 | +- Direct configuration (just pass the visualizer instance to visualizer parameter) |
| 21 | +- Reusable visualizer that can be shared across conversations |
| 22 | +- Better separation of concerns compared to callback functions |
| 23 | +- Event handler registration to avoid long if/elif chains |
| 24 | +
|
| 25 | +This demonstrates how you can pass a ConversationVisualizer instance directly |
| 26 | +to the visualizer parameter for clean, reusable visualization logic. |
| 27 | +""" |
| 28 | + |
| 29 | +import logging |
| 30 | +import os |
| 31 | + |
| 32 | +from pydantic import SecretStr |
| 33 | + |
| 34 | +from openhands.sdk import LLM, Conversation |
| 35 | +from openhands.sdk.conversation.visualizer import ConversationVisualizerBase |
| 36 | +from openhands.sdk.event import ( |
| 37 | + Event, |
| 38 | +) |
| 39 | +from openhands.tools.preset.default import get_default_agent |
| 40 | + |
| 41 | + |
| 42 | +class MinimalVisualizer(ConversationVisualizerBase): |
| 43 | + """A minimal visualizer that print the raw events as they occur.""" |
| 44 | + |
| 45 | + def __init__(self, name: str | None = None): |
| 46 | + """Initialize the minimal progress visualizer. |
| 47 | +
|
| 48 | + Args: |
| 49 | + name: Optional name to identify the agent/conversation. |
| 50 | + Note: This simple visualizer doesn't use it in output, |
| 51 | + but accepts it for compatibility with the base class. |
| 52 | + """ |
| 53 | + # Initialize parent - state will be set later via initialize() |
| 54 | + super().__init__(name=name) |
| 55 | + |
| 56 | + def on_event(self, event: Event) -> None: |
| 57 | + """Handle events for minimal progress visualization.""" |
| 58 | + print(f"\n\n[EVENT] {type(event).__name__}: {event.model_dump_json()[:200]}...") |
| 59 | + |
| 60 | + |
| 61 | +api_key = os.getenv("LLM_API_KEY") |
| 62 | +assert api_key is not None, "LLM_API_KEY environment variable is not set." |
| 63 | +model = os.getenv("LLM_MODEL", "openhands/claude-sonnet-4-5-20250929") |
| 64 | +base_url = os.getenv("LLM_BASE_URL") |
| 65 | +llm = LLM( |
| 66 | + model=model, |
| 67 | + api_key=SecretStr(api_key), |
| 68 | + base_url=base_url, |
| 69 | + usage_id="agent", |
| 70 | +) |
| 71 | +agent = get_default_agent(llm=llm, cli_mode=True) |
| 72 | + |
| 73 | +# ============================================================================ |
| 74 | +# Configure Visualization |
| 75 | +# ============================================================================ |
| 76 | +# Set logging level to reduce verbosity |
| 77 | +logging.getLogger().setLevel(logging.WARNING) |
| 78 | + |
| 79 | +# Start a conversation with custom visualizer |
| 80 | +cwd = os.getcwd() |
| 81 | +conversation = Conversation( |
| 82 | + agent=agent, |
| 83 | + workspace=cwd, |
| 84 | + visualizer=MinimalVisualizer(), |
| 85 | +) |
| 86 | + |
| 87 | +# Send a message and let the agent run |
| 88 | +print("Sending task to agent...") |
| 89 | +conversation.send_message("Write 3 facts about the current project into FACTS.txt.") |
| 90 | +conversation.run() |
| 91 | +print("Task completed!") |
| 92 | + |
| 93 | +# Report cost |
| 94 | +cost = llm.metrics.accumulated_cost |
| 95 | +print(f"EXAMPLE_COST: ${cost:.4f}") |
| 96 | +``` |
| 97 | + |
| 98 | +```bash Running the Example |
| 99 | +export LLM_API_KEY="your-api-key" |
| 100 | +cd agent-sdk |
| 101 | +uv run python examples/01_standalone_sdk/26_custom_visualizer.py |
| 102 | +``` |
| 103 | + |
| 104 | +## Visualizer Configuration Options |
| 105 | + |
| 106 | +The `visualizer` parameter in `Conversation` controls how events are displayed: |
| 107 | + |
| 108 | +```python |
| 109 | +from openhands.sdk import Conversation |
| 110 | +from openhands.sdk.conversation import DefaultConversationVisualizer, ConversationVisualizerBase |
| 111 | + |
| 112 | +# Option 1: Use default visualizer (enabled by default) |
| 113 | +conversation = Conversation(agent=agent, workspace=workspace) |
| 114 | + |
| 115 | +# Option 2: Disable visualization |
| 116 | +conversation = Conversation(agent=agent, workspace=workspace, visualizer=None) |
| 117 | + |
| 118 | +# Option 3: Pass a visualizer class (will be instantiated automatically) |
| 119 | +conversation = Conversation(agent=agent, workspace=workspace, visualizer=DefaultConversationVisualizer) |
| 120 | + |
| 121 | +# Option 4: Pass a configured visualizer instance |
| 122 | +custom_viz = DefaultConversationVisualizer( |
| 123 | + name="MyAgent", |
| 124 | + highlight_regex={r"^Reasoning:": "bold cyan"} |
| 125 | +) |
| 126 | +conversation = Conversation(agent=agent, workspace=workspace, visualizer=custom_viz) |
| 127 | + |
| 128 | +# Option 5: Use custom visualizer class |
| 129 | +class MyVisualizer(ConversationVisualizerBase): |
| 130 | + def on_event(self, event): |
| 131 | + print(f"Event: {event}") |
| 132 | + |
| 133 | +conversation = Conversation(agent=agent, workspace=workspace, visualizer=MyVisualizer()) |
| 134 | +``` |
| 135 | + |
| 136 | +## Customizing the Default Visualizer |
| 137 | + |
| 138 | +`DefaultConversationVisualizer` uses Rich panels and supports customization through configuration: |
| 139 | + |
| 140 | +```python |
| 141 | +from openhands.sdk.conversation import DefaultConversationVisualizer |
| 142 | + |
| 143 | +# Configure highlighting patterns using regex |
| 144 | +custom_visualizer = DefaultConversationVisualizer( |
| 145 | + name="MyAgent", # Prefix panel titles with agent name |
| 146 | + highlight_regex={ |
| 147 | + r"^Reasoning:": "bold cyan", # Lines starting with "Reasoning:" |
| 148 | + r"^Thought:": "bold green", # Lines starting with "Thought:" |
| 149 | + r"^Action:": "bold yellow", # Lines starting with "Action:" |
| 150 | + r"\[ERROR\]": "bold red", # Error markers anywhere |
| 151 | + r"\*\*(.*?)\*\*": "bold", # Markdown bold **text** |
| 152 | + }, |
| 153 | + skip_user_messages=False, # Show user messages |
| 154 | +) |
| 155 | + |
| 156 | +conversation = Conversation( |
| 157 | + agent=agent, |
| 158 | + workspace=workspace, |
| 159 | + visualizer=custom_visualizer |
| 160 | +) |
| 161 | +``` |
| 162 | + |
| 163 | +**When to use**: Perfect for customizing colors and highlighting without changing the panel-based layout. |
| 164 | + |
| 165 | +## Creating Custom Visualizers |
| 166 | + |
| 167 | +For complete control over visualization, subclass `ConversationVisualizerBase`: |
| 168 | + |
| 169 | +```python |
| 170 | +from openhands.sdk.conversation import ConversationVisualizerBase |
| 171 | +from openhands.sdk.event import ActionEvent, ObservationEvent, AgentErrorEvent, Event |
| 172 | + |
| 173 | +class MinimalVisualizer(ConversationVisualizerBase): |
| 174 | + """A minimal visualizer that prints raw event information.""" |
| 175 | + |
| 176 | + def __init__(self, name: str | None = None): |
| 177 | + super().__init__(name=name) |
| 178 | + self.step_count = 0 |
| 179 | + |
| 180 | + def on_event(self, event: Event) -> None: |
| 181 | + """Handle each event.""" |
| 182 | + if isinstance(event, ActionEvent): |
| 183 | + self.step_count += 1 |
| 184 | + tool_name = event.tool_name or "unknown" |
| 185 | + print(f"Step {self.step_count}: {tool_name}") |
| 186 | + |
| 187 | + elif isinstance(event, ObservationEvent): |
| 188 | + print(f" → Result received") |
| 189 | + |
| 190 | + elif isinstance(event, AgentErrorEvent): |
| 191 | + print(f"❌ Error: {event.error}") |
| 192 | + |
| 193 | +# Use your custom visualizer |
| 194 | +conversation = Conversation( |
| 195 | + agent=agent, |
| 196 | + workspace=workspace, |
| 197 | + visualizer=MinimalVisualizer(name="Agent") |
| 198 | +) |
| 199 | +``` |
| 200 | + |
| 201 | +### Key Methods |
| 202 | + |
| 203 | +**`__init__(self, name: str | None = None)`** |
| 204 | +- Initialize your visualizer with optional configuration |
| 205 | +- `name` parameter is available from the base class for agent identification |
| 206 | +- Call `super().__init__(name=name)` to initialize the base class |
| 207 | + |
| 208 | +**`initialize(self, state: ConversationStateProtocol)`** |
| 209 | +- Called automatically by `Conversation` after state is created |
| 210 | +- Provides access to conversation state and statistics via `self._state` |
| 211 | +- Override if you need custom initialization, but call `super().initialize(state)` |
| 212 | + |
| 213 | +**`on_event(self, event: Event)`** *(required)* |
| 214 | +- Called for each conversation event |
| 215 | +- Implement your visualization logic here |
| 216 | +- Access conversation stats via `self.conversation_stats` property |
| 217 | + |
| 218 | +**When to use**: When you need a completely different output format, custom state tracking, or integration with external systems. |
| 219 | + |
| 220 | +## Next Steps |
| 221 | + |
| 222 | +Now that you understand custom visualizers, explore these related topics: |
| 223 | + |
| 224 | +- **[Events](/sdk/arch/events)** - Learn more about different event types |
| 225 | +- **[Conversation Metrics](/sdk/guides/metrics)** - Track LLM usage, costs, and performance data |
| 226 | +- **[Send Messages While Running](/sdk/guides/convo-send-message-while-running)** - Interactive conversations with real-time updates |
| 227 | +- **[Pause and Resume](/sdk/guides/convo-pause-and-resume)** - Control agent execution flow with custom logic |
0 commit comments