|
| 1 | +"""Browser Session Recording Example |
| 2 | +
|
| 3 | +This example demonstrates how to use the browser session recording feature |
| 4 | +to capture and save a recording of the agent's browser interactions using rrweb. |
| 5 | +
|
| 6 | +The recording can be replayed later using rrweb-player to visualize the agent's |
| 7 | +browsing session. |
| 8 | +
|
| 9 | +The recording will be automatically saved to the persistence directory when |
| 10 | +browser_stop_recording is called. You can replay it with: |
| 11 | + - rrweb-player: https://github.com/rrweb-io/rrweb/tree/master/packages/rrweb-player |
| 12 | + - Online viewer: https://www.rrweb.io/demo/ |
| 13 | +""" |
| 14 | + |
| 15 | +import json |
| 16 | +import os |
| 17 | + |
| 18 | +from pydantic import SecretStr |
| 19 | + |
| 20 | +from openhands.sdk import ( |
| 21 | + LLM, |
| 22 | + Agent, |
| 23 | + Conversation, |
| 24 | + Event, |
| 25 | + LLMConvertibleEvent, |
| 26 | + get_logger, |
| 27 | +) |
| 28 | +from openhands.sdk.tool import Tool |
| 29 | +from openhands.tools.browser_use import BrowserToolSet |
| 30 | +from openhands.tools.browser_use.definition import BROWSER_RECORDING_OUTPUT_DIR |
| 31 | + |
| 32 | + |
| 33 | +logger = get_logger(__name__) |
| 34 | + |
| 35 | +# Configure LLM |
| 36 | +api_key = os.getenv("LLM_API_KEY") |
| 37 | +assert api_key is not None, "LLM_API_KEY environment variable is not set." |
| 38 | +model = os.getenv("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250929") |
| 39 | +base_url = os.getenv("LLM_BASE_URL") |
| 40 | +llm = LLM( |
| 41 | + usage_id="agent", |
| 42 | + model=model, |
| 43 | + base_url=base_url, |
| 44 | + api_key=SecretStr(api_key), |
| 45 | +) |
| 46 | + |
| 47 | +# Tools - including browser tools with recording capability |
| 48 | +cwd = os.getcwd() |
| 49 | +tools = [ |
| 50 | + Tool(name=BrowserToolSet.name), |
| 51 | +] |
| 52 | + |
| 53 | +# Agent |
| 54 | +agent = Agent(llm=llm, tools=tools) |
| 55 | + |
| 56 | +llm_messages = [] # collect raw LLM messages |
| 57 | + |
| 58 | + |
| 59 | +def conversation_callback(event: Event): |
| 60 | + if isinstance(event, LLMConvertibleEvent): |
| 61 | + llm_messages.append(event.to_llm_message()) |
| 62 | + |
| 63 | + |
| 64 | +# Create conversation with persistence_dir set to save browser recordings |
| 65 | +conversation = Conversation( |
| 66 | + agent=agent, |
| 67 | + callbacks=[conversation_callback], |
| 68 | + workspace=cwd, |
| 69 | + persistence_dir="./.conversations", |
| 70 | +) |
| 71 | + |
| 72 | +# The prompt instructs the agent to: |
| 73 | +# 1. Start recording the browser session |
| 74 | +# 2. Browse to a website and perform some actions |
| 75 | +# 3. Stop recording (auto-saves to file) |
| 76 | +PROMPT = """ |
| 77 | +Please complete the following task to demonstrate browser session recording: |
| 78 | +
|
| 79 | +1. First, use `browser_start_recording` to begin recording the browser session. |
| 80 | +
|
| 81 | +2. Then navigate to https://docs.openhands.dev/ and: |
| 82 | + - Get the page content |
| 83 | + - Scroll down the page |
| 84 | + - Get the browser state to see interactive elements |
| 85 | +
|
| 86 | +3. Next, navigate to https://docs.openhands.dev/openhands/usage/cli/installation and: |
| 87 | + - Get the page content |
| 88 | + - Scroll down to see more content |
| 89 | +
|
| 90 | +4. Finally, use `browser_stop_recording` to stop the recording. |
| 91 | + Events are automatically saved. |
| 92 | +""" |
| 93 | + |
| 94 | +print("=" * 80) |
| 95 | +print("Browser Session Recording Example") |
| 96 | +print("=" * 80) |
| 97 | +print("\nTask: Record an agent's browser session and save it for replay") |
| 98 | +print("\nStarting conversation with agent...\n") |
| 99 | + |
| 100 | +conversation.send_message(PROMPT) |
| 101 | +conversation.run() |
| 102 | + |
| 103 | +print("\n" + "=" * 80) |
| 104 | +print("Conversation finished!") |
| 105 | +print("=" * 80) |
| 106 | + |
| 107 | +# Check if the recording files were created |
| 108 | +# Recordings are saved in BROWSER_RECORDING_OUTPUT_DIR/recording-{timestamp}/ |
| 109 | +if os.path.exists(BROWSER_RECORDING_OUTPUT_DIR): |
| 110 | + # Find recording subdirectories (they start with "recording-") |
| 111 | + recording_dirs = sorted( |
| 112 | + [ |
| 113 | + d |
| 114 | + for d in os.listdir(BROWSER_RECORDING_OUTPUT_DIR) |
| 115 | + if d.startswith("recording-") |
| 116 | + and os.path.isdir(os.path.join(BROWSER_RECORDING_OUTPUT_DIR, d)) |
| 117 | + ] |
| 118 | + ) |
| 119 | + |
| 120 | + if recording_dirs: |
| 121 | + # Process the most recent recording directory |
| 122 | + latest_recording = recording_dirs[-1] |
| 123 | + recording_path = os.path.join(BROWSER_RECORDING_OUTPUT_DIR, latest_recording) |
| 124 | + json_files = sorted( |
| 125 | + [f for f in os.listdir(recording_path) if f.endswith(".json")] |
| 126 | + ) |
| 127 | + |
| 128 | + print(f"\n✓ Recording saved to: {recording_path}") |
| 129 | + print(f"✓ Number of files: {len(json_files)}") |
| 130 | + |
| 131 | + # Count total events across all files |
| 132 | + total_events = 0 |
| 133 | + all_event_types: dict[int | str, int] = {} |
| 134 | + total_size = 0 |
| 135 | + |
| 136 | + for json_file in json_files: |
| 137 | + filepath = os.path.join(recording_path, json_file) |
| 138 | + file_size = os.path.getsize(filepath) |
| 139 | + total_size += file_size |
| 140 | + |
| 141 | + with open(filepath) as f: |
| 142 | + events = json.load(f) |
| 143 | + |
| 144 | + # Events are stored as a list in each file |
| 145 | + if isinstance(events, list): |
| 146 | + total_events += len(events) |
| 147 | + for event in events: |
| 148 | + event_type = event.get("type", "unknown") |
| 149 | + all_event_types[event_type] = all_event_types.get(event_type, 0) + 1 |
| 150 | + |
| 151 | + print(f" - {json_file}: {len(events)} events, {file_size} bytes") |
| 152 | + |
| 153 | + print(f"✓ Total events: {total_events}") |
| 154 | + print(f"✓ Total size: {total_size} bytes") |
| 155 | + if all_event_types: |
| 156 | + print(f"✓ Event types: {all_event_types}") |
| 157 | + |
| 158 | + print("\nTo replay this recording, you can use:") |
| 159 | + print( |
| 160 | + " - rrweb-player: " |
| 161 | + "https://github.com/rrweb-io/rrweb/tree/master/packages/rrweb-player" |
| 162 | + ) |
| 163 | + else: |
| 164 | + print(f"\n✗ No recording directories found in: {BROWSER_RECORDING_OUTPUT_DIR}") |
| 165 | + print(" The agent may not have completed the recording task.") |
| 166 | +else: |
| 167 | + print(f"\n✗ Observations directory not found: {BROWSER_RECORDING_OUTPUT_DIR}") |
| 168 | + print(" The agent may not have completed the recording task.") |
| 169 | + |
| 170 | +print("\n" + "=" * 100) |
| 171 | +print("Conversation finished.") |
| 172 | +print(f"Total LLM messages: {len(llm_messages)}") |
| 173 | +print("=" * 100) |
| 174 | + |
| 175 | +# Report cost |
| 176 | +cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost |
| 177 | +print(f"Conversation ID: {conversation.id}") |
| 178 | +print(f"EXAMPLE_COST: {cost}") |
0 commit comments