Skip to content

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

Add flexible system prompt customization options

Magnus Müller2a6416f2722b
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 69a5a8a4b..b78cfe5bc 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -11,10 +11,26 @@ if TYPE_CHECKING:
class SystemPrompt:
- def __init__(self, action_description: str, max_actions_per_step: int = 10):
+ def __init__(
+ self,
+ action_description: str,
+ max_actions_per_step: int = 10,
+ override_system_message: Optional[str] = None,
+ extend_system_message: Optional[str] = None,
+ ):
self.default_action_description = action_description
self.max_actions_per_step = max_actions_per_step
- self._load_prompt_template()
+ prompt = ''
+ if override_system_message:
+ prompt = override_system_message
+ else:
+ self._load_prompt_template()
+ prompt = self.prompt_template.format(max_actions=self.max_actions_per_step)
+
+ if extend_system_message:
+ prompt += f'\n{extend_system_message}'
+
+ self.system_message = SystemMessage(content=prompt)
def _load_prompt_template(self) -> None:
"""Load the prompt template from the markdown file."""
@@ -32,8 +48,7 @@ class SystemPrompt:
Returns:
SystemMessage: Formatted system prompt
"""
- prompt = self.prompt_template.format(max_actions=self.max_actions_per_step)
- return SystemMessage(content=prompt)
+ return self.system_message
# Functions:
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 71c04fb63..d23df8c6c 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -6,7 +6,7 @@ import logging
import re
import time
from pathlib import Path
-from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, Type, TypeVar
+from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, TypeVar
from dotenv import load_dotenv
from langchain_core.language_models.chat_models import BaseChatModel
@@ -100,7 +100,8 @@ class Agent(Generic[Context]):
save_conversation_path_encoding: Optional[str] = 'utf-8',
max_failures: int = 3,
retry_delay: int = 10,
- system_prompt_class: Type[SystemPrompt] = SystemPrompt,
+ override_system_message: Optional[str] = None,
+ extend_system_message: Optional[str] = None,
max_input_tokens: int = 128000,
validate_output: bool = False,
message_context: Optional[str] = None,
@@ -144,7 +145,8 @@ class Agent(Generic[Context]):
save_conversation_path_encoding=save_conversation_path_encoding,
max_failures=max_failures,
retry_delay=retry_delay,
- system_prompt_class=system_prompt_class,
+ override_system_message=override_system_message,
+ extend_system_message=extend_system_message,
max_input_tokens=max_input_tokens,
validate_output=validate_output,
message_context=message_context,
@@ -178,9 +180,11 @@ class Agent(Generic[Context]):
# Initialize message manager with state
self._message_manager = MessageManager(
task=task,
- system_message=self.settings.system_prompt_class(
- self.available_actions,
+ system_message=SystemPrompt(
+ action_description=self.available_actions,
max_actions_per_step=self.settings.max_actions_per_step,
+ override_system_message=override_system_message,
+ extend_system_message=extend_system_message,
).get_system_message(),
settings=MessageManagerSettings(
max_input_tokens=self.settings.max_input_tokens,
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 5897ae6fd..a8d490de8 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -12,7 +12,6 @@ from openai import RateLimitError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model
from browser_use.agent.message_manager.views import MessageManagerState
-from browser_use.agent.prompts import SystemPrompt
from browser_use.browser.views import BrowserStateHistory
from browser_use.controller.registry.views import ActionModel
from browser_use.dom.history_tree_processor.service import (
@@ -34,12 +33,13 @@ class AgentSettings(BaseModel):
save_conversation_path_encoding: Optional[str] = 'utf-8'
max_failures: int = 3
retry_delay: int = 10
- system_prompt_class: Type[SystemPrompt] = SystemPrompt
max_input_tokens: int = 128000
validate_output: bool = False
message_context: Optional[str] = None
generate_gif: bool | str = False
available_file_paths: Optional[list[str]] = None
+ override_system_message: Optional[str] = None
+ extend_system_message: Optional[str] = None
include_attributes: list[str] = [
'title',
'type',
diff --git a/docs/customize/system-prompt.mdx b/docs/customize/system-prompt.mdx
index f501205cf..9180a8d63 100644
--- a/docs/customize/system-prompt.mdx
+++ b/docs/customize/system-prompt.mdx
@@ -6,7 +6,9 @@ icon: "message"
## Overview
-You can customize the system prompt by extending the `SystemPrompt` class. Internally, this adds extra instructions to the default system prompt.
+You can customize the system prompt in two ways:
+1. Extend the default system prompt with additional instructions
+2. Override the default system prompt entirely
<Note>
Custom system prompts allow you to modify the agent's behavior at a
@@ -14,42 +16,46 @@ You can customize the system prompt by extending the `SystemPrompt` class. Inter
the agent's performance and reliability.
</Note>
-## Basic Customization
+## Basic Usage
-Create a custom system prompt by inheriting from the base class.
+### Extend System Prompt
-```python
-from browser_use import Agent, SystemPrompt
+To add additional instructions to the default system prompt:
-class MySystemPrompt(SystemPrompt):
- def important_rules(self) -> str:
- # Get existing rules from parent class
- existing_rules = super().important_rules()
+```python
+from browser_use import Agent
+from langchain_openai import ChatOpenAI
- # Add your custom rules
- new_rules = """
-9. MOST IMPORTANT RULE:
-- ALWAYS open first a new tab and go to wikipedia.com no matter the task!!!
+# Add your custom instructions
+extend_system_message = """
+REMEMBER the most important RULE:
+ALWAYS open first a new tab and go first to url wikipedia.com no matter the task!!!
"""
- # Make sure to use this pattern otherwise the exiting rules will be lost
- return f'{existing_rules}\n{new_rules}'
+# Create agent with extended system prompt
+agent = Agent(
+ task="Your task here",
+ llm=ChatOpenAI(model='gpt-4'),
+ extend_system_message=extend_system_message
+)
```
-## Using Custom System Prompt
+### Override System Prompt
-Apply your custom system prompt when creating an agent:
+To completely replace the default system prompt with your own:
```python
-from langchain_openai import ChatOpenAI
+# Define your complete custom prompt
+override_system_message = """
+You are an AI agent that helps users with web browsing tasks.
-# Initialize the model
-model = ChatOpenAI(model='gpt-4o')
+[Your complete custom instructions here...]
+"""
# Create agent with custom system prompt
agent = Agent(
task="Your task here",
- llm=model,
- system_prompt_class=MySystemPrompt
+ llm=ChatOpenAI(model='gpt-4'),
+ override_system_message=override_system_message
)
```
diff --git a/examples/features/custom_system_prompt.py b/examples/features/custom_system_prompt.py
index 83ab8c0bb..e873631bd 100644
--- a/examples/features/custom_system_prompt.py
+++ b/examples/features/custom_system_prompt.py
@@ -8,22 +8,19 @@ import asyncio
from langchain_openai import ChatOpenAI
-from browser_use import Agent, SystemPrompt
+from browser_use import Agent
+extend_system_message = (
+ 'REMEMBER the most important RULE: ALWAYS open first a new tab and go first to url wikipedia.com no matter the task!!!'
+)
-class MySystemPrompt(SystemPrompt):
- def important_rules(self) -> str:
- existing_rules = super().important_rules()
- new_rules = 'REMEMBER the most important RULE: ALWAYS open first a new tab and go first to url wikipedia.com no matter the task!!!'
- return f'{existing_rules}\n{new_rules}'
-
- # other methods can be overridden as well (not recommended)
+# or use override_system_message to completely override the system prompt
async def main():
task = "do google search to find images of Elon Musk's wife"
model = ChatOpenAI(model='gpt-4o')
- agent = Agent(task=task, llm=model, system_prompt_class=MySystemPrompt)
+ agent = Agent(task=task, llm=model, extend_system_message=extend_system_message)
print(
json.dumps(