Skip to content

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

Add support for procedural memory

Deshraj Yadav55e5e2168ed2
diff --git a/browser_use/agent/memory/__init__.py b/browser_use/agent/memory/__init__.py
new file mode 100644
index 000000000..50f06c1f0
--- /dev/null
+++ b/browser_use/agent/memory/__init__.py
@@ -0,0 +1,3 @@
+from browser_use.agent.memory.service import Memory, MemorySettings
+
+__all__ = ['Memory', 'MemorySettings']
diff --git a/browser_use/agent/memory/service.py b/browser_use/agent/memory/service.py
new file mode 100644
index 000000000..cc3c1f023
--- /dev/null
+++ b/browser_use/agent/memory/service.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import logging
+from typing import List, Optional
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ BaseMessage,
+ HumanMessage,
+)
+from langchain_core.messages.utils import convert_to_openai_messages
+from mem0 import Memory as Mem0Memory
+from pydantic import BaseModel
+
+from browser_use.agent.message_manager.service import MessageManager
+from browser_use.agent.message_manager.views import ManagedMessage, MessageMetadata
+from browser_use.utils import time_execution_sync
+
+logger = logging.getLogger(__name__)
+
+
+class MemorySettings(BaseModel):
+ """Settings for procedural memory."""
+
+ agent_id: str
+ enabled: bool = True
+ interval: int = 10
+ config: Optional[dict] | None = None
+
+
+class Memory:
+ """
+ Manages procedural memory for agents.
+
+ This class implements a procedural memory management system using Mem0 that transforms agent interaction history
+ into concise, structured representations at specified intervals. It serves to optimize context window
+ utilization during extended task execution by converting verbose historical information into compact,
+ yet comprehensive memory constructs that preserve essential operational knowledge.
+ """
+
+ def __init__(
+ self,
+ message_manager: MessageManager,
+ llm: BaseChatModel,
+ settings: MemorySettings,
+ ):
+ self.message_manager = message_manager
+ self.llm = llm
+ self.settings = settings
+ self._memory_config = self.settings.config or {'vector_store': {'provider': 'chroma', 'config': {'path': '/tmp/mem0'}}}
+ self.mem0 = Mem0Memory.from_config(config_dict=self._memory_config)
+
+ @time_execution_sync('--create_procedural_memory')
+ def create_procedural_memory(self, current_step: int) -> None:
+ """
+ Create a procedural memory if needed based on the current step.
+
+ Args:
+ current_step: The current step number of the agent
+ """
+ if not self.settings.enabled:
+ return
+
+ logger.info(f'Creating procedural memory at step {current_step}')
+
+ # Get all messages
+ all_messages = self.message_manager.state.history.messages
+
+ # Filter out messages that are marked as memory in metadata
+ messages_to_process = []
+ new_messages = []
+ for msg in all_messages:
+ # Exclude system message and initial messages
+ if isinstance(msg, ManagedMessage) and msg.metadata.message_type in set(['init', 'memory']):
+ new_messages.append(msg)
+ else:
+ messages_to_process.append(msg)
+
+ if len(messages_to_process) <= 1:
+ logger.info('Not enough non-memory messages to summarize')
+ return
+
+ # Create a summary
+ summary = self._create([m.message for m in messages_to_process], current_step)
+
+ if not summary:
+ logger.warning('Failed to create summary')
+ return
+
+ # Replace the summarized messages with the summary
+ summary_message = HumanMessage(content=summary)
+ summary_tokens = self.message_manager._count_tokens(summary_message)
+ summary_metadata = MessageMetadata(tokens=summary_tokens, message_type='memory')
+
+ # Calculate the total tokens being removed
+ removed_tokens = sum(m.metadata.tokens for m in messages_to_process)
+
+ # Add the summary message
+ new_messages.append(ManagedMessage(message=summary_message, metadata=summary_metadata))
+
+ # Update the history
+ self.message_manager.state.history.messages = new_messages
+ self.message_manager.state.history.current_tokens -= removed_tokens
+ self.message_manager.state.history.current_tokens += summary_tokens
+
+ logger.info(f'Memories summarized: {len(messages_to_process)} messages converted to procedural memory')
+ logger.info(f'Token reduction: {removed_tokens - summary_tokens} tokens')
+
+ def _create(self, messages: List[BaseMessage], current_step: int) -> Optional[str]:
+ parsed_messages = convert_to_openai_messages(messages)
+ try:
+ if current_step == 10:
+ import pdb
+
+ pdb.set_trace()
+ results = self.mem0.add(
+ messages=parsed_messages,
+ agent_id=self.settings.agent_id,
+ memory_type='procedural_memory',
+ metadata={'step': current_step},
+ )
+ if len(results.get('results', [])):
+ return results.get('results', [])[0].get('memory')
+ return None
+ except Exception as e:
+ logger.error(f'Error creating procedural memory: {e}')
+ return None
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 73b3cf787..b75ea7d9d 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -50,25 +50,25 @@ class MessageManager:
def _init_messages(self) -> None:
"""Initialize the message history with system message, context, task, and other initial messages"""
- self._add_message_with_tokens(self.system_prompt)
+ self._add_message_with_tokens(self.system_prompt, message_type='init')
if self.settings.message_context:
context_message = HumanMessage(content='Context for the task' + self.settings.message_context)
- self._add_message_with_tokens(context_message)
+ self._add_message_with_tokens(context_message, message_type='init')
task_message = HumanMessage(
content=f'Your ultimate task is: """{self.task}""". If you achieved your ultimate task, stop everything and use the done action in the next step to complete the task. If not, continue as usual.'
)
- self._add_message_with_tokens(task_message)
+ self._add_message_with_tokens(task_message, message_type='init')
if self.settings.sensitive_data:
info = f'Here are placeholders for sensitve data: {list(self.settings.sensitive_data.keys())}'
info += 'To use them, write <secret>the placeholder name</secret>'
info_message = HumanMessage(content=info)
- self._add_message_with_tokens(info_message)
+ self._add_message_with_tokens(info_message, message_type='init')
placeholder_message = HumanMessage(content='Example output:')
- self._add_message_with_tokens(placeholder_message)
+ self._add_message_with_tokens(placeholder_message, message_type='init')
tool_calls = [
{
@@ -90,15 +90,15 @@ class MessageManager:
content='',
tool_calls=tool_calls,
)
- self._add_message_with_tokens(example_tool_call)
- self.add_tool_message(content='Browser started')
+ self._add_message_with_tokens(example_tool_call, message_type='init')
+ self.add_tool_message(content='Browser started', message_type='init')
placeholder_message = HumanMessage(content='[Your task history memory starts here]')
self._add_message_with_tokens(placeholder_message)
if self.settings.available_file_paths:
filepaths_msg = HumanMessage(content=f'Here are file paths you can use: {self.settings.available_file_paths}')
- self._add_message_with_tokens(filepaths_msg)
+ self._add_message_with_tokens(filepaths_msg, message_type='init')
def add_new_task(self, new_task: str) -> None:
content = f'Your new ultimate task is: """{new_task}""". Take the previous context into account and finish your new ultimate task. '
@@ -182,7 +182,9 @@ class MessageManager:
return msg
- def _add_message_with_tokens(self, message: BaseMessage, position: int | None = None) -> None:
+ def _add_message_with_tokens(
+ self, message: BaseMessage, position: int | None = None, message_type: str | None = None
+ ) -> None:
"""Add message with token count metadata
position: None for last, -1 for second last, etc.
"""
@@ -192,7 +194,7 @@ class MessageManager:
message = self._filter_sensitive_data(message)
token_count = self._count_tokens(message)
- metadata = MessageMetadata(tokens=token_count)
+ metadata = MessageMetadata(tokens=token_count, message_type=message_type)
self.state.history.add_message(message, metadata, position)
@time_execution_sync('--filter_sensitive_data')
@@ -299,8 +301,8 @@ class MessageManager:
"""Remove last state message from history"""
self.state.history.remove_last_state_message()
- def add_tool_message(self, content: str) -> None:
+ def add_tool_message(self, content: str, message_type: str | None = None) -> None:
"""Add tool message to history"""
msg = ToolMessage(content=content, tool_call_id=str(self.state.tool_id))
self.state.tool_id += 1
- self._add_message_with_tokens(msg)
+ self._add_message_with_tokens(msg, message_type=message_type)
diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.py
index b16438ef6..45addd18e 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -18,6 +18,7 @@ class MessageMetadata(BaseModel):
"""Metadata for a message"""
tokens: int = 0
+ message_type: str | None = None
class ManagedMessage(BaseModel):
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index da04052a4..633812755 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -23,6 +23,7 @@ from langchain_core.messages import (
from pydantic import BaseModel, ValidationError
from browser_use.agent.gif import create_history_gif
+from browser_use.agent.memory.service import Memory, MemorySettings
from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings
from browser_use.agent.message_manager.utils import convert_input_messages, extract_json_from_model_output, save_conversation
from browser_use.agent.prompts import AgentMessagePrompt, PlannerPrompt, SystemPrompt
@@ -146,6 +147,9 @@ class Agent(Generic[Context]):
injected_agent_state: Optional[AgentState] = None,
#
context: Context | None = None,
+ # Procedural memory settings
+ enable_memory: bool = True,
+ memory_interval: int = 10,
):
if page_extraction_llm is None:
page_extraction_llm = llm
@@ -177,6 +181,8 @@ class Agent(Generic[Context]):
planner_llm=planner_llm,
planner_interval=planner_interval,
is_planner_reasoning=is_planner_reasoning,
+ enable_memory=enable_memory,
+ memory_interval=memory_interval,
)
# Initialize state
@@ -226,6 +232,19 @@ class Agent(Generic[Context]):
state=self.state.message_manager_state,
)
+ memory_settings = MemorySettings(
+ agent_id=self.state.agent_id,
+ enabled=self.settings.enable_memory,
+ interval=self.settings.memory_interval,
+ )
+
+ # Initialize procedural memory
+ self.memory = Memory(
+ message_manager=self._message_manager,
+ llm=self.llm,
+ settings=memory_settings,
+ )
+
# Browser setup
self.injected_browser = browser is not None
self.injected_browser_context = browser_context is not None
@@ -365,6 +384,10 @@ class Agent(Generic[Context]):
state = await self.browser_context.get_state()
active_page = await self.browser_context.get_current_page()
+ # summarize memories if needed
+ if self.state.n_steps % self.settings.memory_interval == 0:
+ self.memory.create_procedural_memory(self.state.n_steps)
+
await self._raise_if_stopped_or_paused()
# Update action models with page-specific actions
diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.md
index 15ced6501..0de6eab90 100644
--- a/browser_use/agent/system_prompt.md
+++ b/browser_use/agent/system_prompt.md
@@ -63,6 +63,7 @@ Common action sequences:
8. Long tasks:
- Keep track of the status and subresults in the memory.
+- You are provided with procedural memory summaries that condense previous task history (every N steps). Use these summaries to maintain context about completed actions, current progress, and next steps. The summaries appear in chronological order and contain key information about navigation history, findings, errors encountered, and current state. Refer to these summaries to avoid repeating actions and to ensure consistent progress toward the task goal.
9. Extraction:
- If your task is to find information - call extract_content on the specific pages to get and store the information.
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 172e080e2..56b723e54 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -67,6 +67,10 @@ class AgentSettings(BaseModel):
planner_interval: int = 1 # Run planner every N steps
is_planner_reasoning: bool = False # type: ignore
+ # Procedural memory settings
+ enable_memory: bool = True
+ memory_interval: int = 10
+
class AgentState(BaseModel):
"""Holds all state information for an Agent"""
diff --git a/example.py b/example.py
new file mode 100644
index 000000000..da2775b4b
--- /dev/null
+++ b/example.py
@@ -0,0 +1,162 @@
+"""
+Example command:
+
+uv run python example.py --session_name mem-docs-agent --session_id 28032025_001 --memory_interval 10
+"""
+
+import argparse
+import asyncio
+import json
+import os
+from typing import List
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+
+from langchain_openai import ChatOpenAI
+from pydantic import BaseModel
+
+from browser_use import Agent, Browser, BrowserConfig, Controller
+
+links = [
+ 'https://docs.mem0.ai/components/llms/models/litellm',
+ 'https://docs.mem0.ai/components/llms/models/mistral_AI',
+ 'https://docs.mem0.ai/components/llms/models/ollama',
+ 'https://docs.mem0.ai/components/llms/models/openai',
+ 'https://docs.mem0.ai/components/llms/models/together',
+ 'https://docs.mem0.ai/components/llms/models/xAI',
+ 'https://docs.mem0.ai/components/llms/overview',
+ 'https://docs.mem0.ai/components/vectordbs/config',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/azure_ai_search',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/chroma',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/milvus',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/opensearch',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/pgvector',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/pinecone',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/qdrant',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/redis',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/supabase',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai_vector_search',
+ 'https://docs.mem0.ai/components/vectordbs/dbs/weaviate',
+ 'https://docs.mem0.ai/components/vectordbs/overview',
+ 'https://docs.mem0.ai/contributing/development',
+ 'https://docs.mem0.ai/contributing/documentation',
+ 'https://docs.mem0.ai/core-concepts/memory-operations',
+ 'https://docs.mem0.ai/core-concepts/memory-types',
+ 'https://docs.mem0.ai/examples/ai_companion_js',
+ 'https://docs.mem0.ai/examples/chrome-extension',
+ 'https://docs.mem0.ai/examples/customer-support-agent',
+ 'https://docs.mem0.ai/examples/document-writing',
+ 'https://docs.mem0.ai/examples/llama-index-mem0',
+ 'https://docs.mem0.ai/examples/mem0-agentic-tool',
+ 'https://docs.mem0.ai/examples/mem0-demo',
+ 'https://docs.mem0.ai/examples/mem0-openai-voice-demo',
+ 'https://docs.mem0.ai/examples/mem0-with-ollama',
+ 'https://docs.mem0.ai/examples/multimodal-demo',
+ 'https://docs.mem0.ai/examples/openai-inbuilt-tools',
+ 'https://docs.mem0.ai/examples/overview',
+ 'https://docs.mem0.ai/examples/personal-ai-tutor',
+ 'https://docs.mem0.ai/examples/personal-travel-assistant',
+ 'https://docs.mem0.ai/examples/personalized-deep-research',
+ 'https://docs.mem0.ai/faqs',
+ 'https://docs.mem0.ai/features/advanced-retrieval',
+ 'https://docs.mem0.ai/features/async-client',
+ 'https://docs.mem0.ai/features/contextual-add',
+ 'https://docs.mem0.ai/features/custom-categories',
+ 'https://docs.mem0.ai/features/custom-fact-extraction-prompt',
+ 'https://docs.mem0.ai/features/custom-instructions',
+ 'https://docs.mem0.ai/features/custom-update-memory-prompt',
+ 'https://docs.mem0.ai/features/direct-import',
+ 'https://docs.mem0.ai/features/feedback-mechanism',
+]
+
+print('-' * 100)
+print(f'Total links: {len(links)}')
+print('-' * 100)
+
+
+class Link(BaseModel):
+ url: str
+ title: str
+ summary: str
+
+
+class Links(BaseModel):
+ links: List[Link]
+
+
+initial_actions = [
+ {'open_tab': {'url': 'https://docs.mem0.ai/'}},
+]
+controller = Controller(output_model=Links)
+
+
+async def main(session_name, session_id, max_steps, memory_interval):
+ config = BrowserConfig(headless=True)
+ browser = Browser(config=config)
+
+ agent = Agent(
+ task=f"""Visit all the links provided in {links} and summarize the content of each page with url and title. There are {len(links)} links to visit. The summary should be SEO friendly based on the title and content of the page. The pages you are visiting are the documentation of Mem0. Return a json with the following format: [{{url: <url>, title: <title>, summary: <summary>}}].
+
+ Guidelines:
+ 1. Strictly stay on the domain https://docs.mem0.ai
+ 2. Do not visit any other websites
+ 3. Ignore the links that are hashed (#) or javascript (:), or mailto, or tel, or other protocols
+ 4. Capture the unique urls which are not already visited.
+ 5. If you visit any page that doesn't have host name docs.mem0.ai, then do not visit it and come back to the page with host name docs.mem0.ai.
+ """,
+ llm=ChatOpenAI(
+ model='gpt-4o-mini',
+ model_kwargs={
+ 'extra_headers': {
+ 'Helicone-Auth': f'Bearer {os.environ["HELICONE_API_KEY"]}',
+ 'Helicone-Session-Id': session_id,
+ 'Helicone-Session-Name': session_name,
+ },
+ },
+ base_url='https://oai.helicone.ai/v1',
+ ),
+ controller=controller,
+ initial_actions=initial_actions,
+ enable_memory=True if memory_interval > 0 else False,
+ memory_interval=memory_interval,
+ browser=browser,
+ )
+ history = await agent.run(max_steps=max_steps)
+ result = history.final_result()
+ parsed_result = []
+ if result:
+ parsed: Links = Links.model_validate_json(result)
+ print('-- RESULTS --')
+ print(f'Total links: {len(parsed.links)}')
+ for link in parsed.links:
+ parsed_result.append({'title': link.title, 'url': link.url, 'summary': link.summary})
+ else:
+ print('No result')
+
+ # Write to a file
+ with open(f'result_{session_name}_{session_id}.json', 'w+') as f:
+ f.write(json.dumps(parsed_result, indent=4))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--session_name', type=str, required=True)
+ parser.add_argument('--session_id', type=str, required=True)
+ parser.add_argument('--max_steps', type=int, default=500)
+ parser.add_argument('--memory_interval', type=int, default=-1)
+ args = parser.parse_args()
+ session_name = args.session_name
+ session_id = args.session_id
+ max_steps = args.max_steps
+ memory_interval = args.memory_interval
+ print('--- Arguments Start ---')
+ print(f'Session Name: {session_name}')
+ print(f'Session ID: {session_id}')
+ print(f'Max Steps: {max_steps}')
+ print(f'Memory Interval: {memory_interval}')
+ print('--- Arguments End ---')
+ asyncio.run(main(session_name, session_id, max_steps, memory_interval))
diff --git a/pyproject.toml b/pyproject.toml
index 0c2aa0197..8c8e5ee1f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -31,6 +31,8 @@ dependencies = [
"screeninfo>=0.8.1; platform_system != 'darwin'",
"typing-extensions>=4.12.2",
"psutil>=7.0.0",
+ "mem0ai==0.1.78",
+ "chromadb==0.6.3",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste