Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

outsource state

Gregor Žuničded606a233f2
diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.py
index 7f002e6da..c78926909 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -21,13 +21,16 @@ class ManagedMessage(BaseModel):
message: BaseMessage
metadata: MessageMetadata = Field(default_factory=MessageMetadata)
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
-class MessageHistory:
+class MessageHistory(BaseModel):
"""History of messages with metadata"""
- def __init__(self):
- self.messages: list[ManagedMessage] = []
- self.total_tokens: int = 0
+ messages: list[ManagedMessage] = Field(default_factory=list)
+ total_tokens: int = 0
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
def add_message(self, message: BaseMessage, metadata: MessageMetadata, position: int = -1) -> None:
"""Add message with metadata to history"""
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 4ef3a6389..8bd59e40d 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -67,7 +67,7 @@ class AgentState(BaseModel):
agent_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
n_steps: int = 1
consecutive_failures: int = 0
- last_result: Optional[List[ActionResult]] = None
+ last_result: Optional[List['ActionResult']] = None
history: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[]))
last_plan: Optional[str] = None
paused: bool = False
diff --git a/examples/features/outsource_state.py b/examples/features/outsource_state.py
index 4b02c8f3a..946f896f5 100644
--- a/examples/features/outsource_state.py
+++ b/examples/features/outsource_state.py
@@ -8,7 +8,7 @@ import os
import sys
from browser_use.agent.views import AgentState
-from browser_use.browser.browser import Browser
+from browser_use.browser.browser import Browser, BrowserConfig
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -25,11 +25,15 @@ load_dotenv()
async def main():
task = 'Go to hackernews show hn and give me the first 5 posts'
- agent_state = AgentState()
-
- browser = Browser()
+ browser = Browser(
+ config=BrowserConfig(
+ headless=True,
+ )
+ )
browser_context = await browser.new_context()
+ agent_state = AgentState()
+
for i in range(10):
agent = Agent(
task=task,
@@ -46,6 +50,20 @@ async def main():
if done and valid:
break
+ agent_state.history.history = []
+
+ # Save state to file
+ with open('agent_state.json', 'w') as f:
+ serialized = agent_state.model_dump_json(exclude={'history'})
+ f.write(serialized)
+
+ # Load state back from file
+ with open('agent_state.json', 'r') as f:
+ loaded_json = f.read()
+ agent_state = AgentState.model_validate_json(loaded_json)
+
+ break
+
if __name__ == '__main__':
asyncio.run(main())