Skip to content

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

Add optional parameter to control tool call examples in Agent

Cursor Agentc72b9ddabd98
diff --git a/IMPLEMENTATION_SUMMARY.md b/IMPLEMENTATION_SUMMARY.md
new file mode 100644
index 000000000..995ca6d69
--- /dev/null
+++ b/IMPLEMENTATION_SUMMARY.md
@@ -0,0 +1,76 @@
+# Implementation Summary: `include_tool_call_examples` Parameter
+
+## ✅ Complete Implementation
+
+This PR successfully adds the `include_tool_call_examples` parameter to the Agent class, allowing users to control whether tool call examples are included in the message history.
+
+## 🔧 Files Modified
+
+### 1. `browser_use/agent/service.py`
+- ✅ Added `include_tool_call_examples: bool = True` parameter to `Agent.__init__()`
+- ✅ Added parameter to `AgentSettings` initialization
+- ✅ Passed parameter to `MessageManager` constructor
+
+### 2. `browser_use/agent/views.py`
+- ✅ Added `include_tool_call_examples: bool = True` field to `AgentSettings` model
+
+### 3. `browser_use/agent/message_manager/service.py`
+- ✅ Added `include_tool_call_examples: bool = True` parameter to `MessageManager.__init__()`
+- ✅ Stored parameter as instance variable `self.include_tool_call_examples`
+- ✅ Modified `_init_messages()` to conditionally include the 3 example messages
+
+## 📋 Parameter Details
+
+**Parameter**: `include_tool_call_examples`
+**Type**: `bool`
+**Default**: `True`
+**Location**: Agent initialization
+
+## 🎯 Behavior
+
+### When `include_tool_call_examples=True` (default)
+- System prompt + 3 example messages are added
+- **Total messages**: 4 (1 system + 3 examples)
+- **Backward compatible**: Existing behavior is preserved
+
+### When `include_tool_call_examples=False`
+- Only system prompt is added
+- **Total messages**: 1 (system only)
+- **Cleaner history**: No example clutter
+
+## 🔍 The 3 Example Messages
+
+1. **UserMessage**: `"<example_1>\nHere is an example output..."`
+2. **AssistantMessage**: JSON example with thinking and actions
+3. **UserMessage**: `"Data written to todo.md.\nData written to github.md..."`
+
+## 📖 Usage Examples
+
+```python
+# Default behavior (with examples)
+agent = Agent(
+ task="Your task",
+ llm=your_llm_model
+)
+
+# Without examples
+agent = Agent(
+ task="Your task",
+ llm=your_llm_model,
+ include_tool_call_examples=False
+)
+```
+
+## ✅ Validation
+
+- [x] All modified files pass syntax validation
+- [x] Parameter properly flows through: Agent → AgentSettings → MessageManager
+- [x] Backward compatibility maintained (default=True)
+- [x] Clean implementation with conditional logic in `_init_messages()`
+
+## 🎉 Ready for Review
+
+The implementation is complete and ready for PR submission. The feature allows users to:
+- Reduce token usage by skipping examples
+- Have cleaner message histories
+- Maintain full backward compatibility
\ No newline at end of file
diff --git a/PR_CHANGES.md b/PR_CHANGES.md
new file mode 100644
index 000000000..ae28bf14d
--- /dev/null
+++ b/PR_CHANGES.md
@@ -0,0 +1,63 @@
+# PR: Add `include_tool_call_examples` Parameter to Agent
+
+## Summary
+Added a new optional parameter `include_tool_call_examples` to the Agent class initialization that controls whether the tool call examples (3 messages after the system prompt) are included in the message history.
+
+## Changes Made
+
+### 1. Added parameter to Agent class (`browser_use/agent/service.py`)
+- Added `include_tool_call_examples: bool = True` parameter to the `Agent.__init__()` method
+- Parameter defaults to `True` to maintain backward compatibility
+
+### 2. Updated AgentSettings class (`browser_use/agent/views.py`)
+- Added `include_tool_call_examples: bool = True` field to the `AgentSettings` model
+
+### 3. Updated MessageManager class (`browser_use/agent/message_manager/service.py`)
+- Added `include_tool_call_examples: bool = True` parameter to the `MessageManager.__init__()` method
+- Stored the parameter as an instance variable `self.include_tool_call_examples`
+- Modified `_init_messages()` method to conditionally include the 3 example messages based on this parameter
+
+### 4. Updated Agent-MessageManager integration (`browser_use/agent/service.py`)
+- Passed `include_tool_call_examples=self.settings.include_tool_call_examples` to the MessageManager constructor
+
+## Usage
+
+### Default behavior (backward compatible)
+```python
+# Tool call examples are included by default
+agent = Agent(
+ task="Your task",
+ llm=your_llm_model
+)
+```
+
+### Disable tool call examples
+```python
+# Tool call examples are excluded
+agent = Agent(
+ task="Your task",
+ llm=your_llm_model,
+ include_tool_call_examples=False
+)
+```
+
+## Technical Details
+
+The tool call examples consist of 3 messages that are normally added after the system prompt:
+
+1. **UserMessage**: Example introduction message
+2. **AssistantMessage**: Example response with thinking and actions
+3. **UserMessage**: Example result message
+
+When `include_tool_call_examples=False`, these messages are skipped, resulting in:
+- **With examples**: 4 messages (1 system + 3 example messages)
+- **Without examples**: 1 message (system only)
+
+This allows for:
+- Cleaner message history for users who don't need examples
+- Reduced token usage when examples are not needed
+- More flexibility in prompt engineering
+
+## Backward Compatibility
+- Default value is `True`, so existing code continues to work unchanged
+- No breaking changes to existing functionality
\ No newline at end of file
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index b48dbdb62..ee92d1d2b 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -103,6 +103,7 @@ class MessageManager:
available_file_paths: list[str] | None = None,
state: MessageManagerState = MessageManagerState(),
use_thinking: bool = True,
+ include_tool_call_examples: bool = True,
include_attributes: list[str] | None = None,
message_context: str | None = None,
sensitive_data: dict[str, str | dict[str, str]] | None = None,
@@ -116,6 +117,7 @@ class MessageManager:
self.sensitive_data_description = ''
self.available_file_paths = available_file_paths
self.use_thinking = use_thinking
+ self.include_tool_call_examples = include_tool_call_examples
self.max_history_items = max_history_items
self.images_per_step = images_per_step
@@ -163,60 +165,61 @@ class MessageManager:
"""Initialize the message history with system message, context, task, and other initial messages"""
self._add_message_with_type(self.system_prompt)
- placeholder_message = UserMessage(
- content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.',
- cache=True,
- )
- # placeholder_message = HumanMessage(content='Example output:')
- self._add_message_with_type(placeholder_message)
+ if self.include_tool_call_examples:
+ placeholder_message = UserMessage(
+ content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.',
+ cache=True,
+ )
+ # placeholder_message = HumanMessage(content='Example output:')
+ self._add_message_with_type(placeholder_message)
- example_content = dict()
+ example_content = dict()
- # Add thinking field only if use_thinking is True
- if self.use_thinking:
- example_content[
- 'thinking'
- ] = """I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop (index [4]) and ray-project/kuberay (index [5]). The user's request is to explore GitHub repositories and collect information about them such as descriptions, stars, or other metadata. So far, I haven't collected any information.
+ # Add thinking field only if use_thinking is True
+ if self.use_thinking:
+ example_content[
+ 'thinking'
+ ] = """I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop (index [4]) and ray-project/kuberay (index [5]). The user's request is to explore GitHub repositories and collect information about them such as descriptions, stars, or other metadata. So far, I haven't collected any information.
My navigation to the GitHub explore page was successful. The page loaded correctly and I can see the expected content.
I need to capture the key repositories I've identified so far into my memory and into a file.
Since this appears to be a multi-step task involving visiting multiple repositories and collecting their information, I need to create a structured plan in todo.md.
After writing todo.md, I can also initialize a github.md file to accumulate the information I've collected.
The file system actions do not change the browser state, so I can also click on the bytedance/UI-TARS-desktop (index [4]) to start collecting information."""
- # Create base example content
- example_content['evaluation_previous_goal'] = 'Navigated to GitHub explore page. Verdict: Success'
- example_content['memory'] = 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.'
- example_content['next_goal'] = (
- 'Create todo.md checklist to track progress, initialize github.md for collecting information, and click on bytedance/UI-TARS-desktop.'
- )
- example_content['action'] = [
- {
- 'write_file': {
- 'path': 'todo.md',
- 'content': '# Interesting Github Repositories in Explore Section\n\n## Tasks\n- [ ] Initialize a tracking file for GitHub repositories called github.md\n- [ ] Visit each Github repository and find their description\n- [ ] Visit bytedance/UI-TARS-desktop\n- [ ] Visit ray-project/kuberay\n- [ ] Check for additional Github repositories by scrolling down\n- [ ] Compile all results in the requested format\n- [ ] Validate that I have not missed anything in the page\n- [ ] Report final results to user',
- }
- },
- {
- 'write_file': {
- 'path': 'github.md',
- 'content': '# Github Repositories:\n',
- }
- },
- {
- 'click_element_by_index': {
- 'index': 4,
- }
- },
- ]
-
- example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)
- self._add_message_with_type(example_tool_call_1)
- self._add_message_with_type(
- UserMessage(
- content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',
- cache=True,
- ),
- )
+ # Create base example content
+ example_content['evaluation_previous_goal'] = 'Navigated to GitHub explore page. Verdict: Success'
+ example_content['memory'] = 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.'
+ example_content['next_goal'] = (
+ 'Create todo.md checklist to track progress, initialize github.md for collecting information, and click on bytedance/UI-TARS-desktop.'
+ )
+ example_content['action'] = [
+ {
+ 'write_file': {
+ 'path': 'todo.md',
+ 'content': '# Interesting Github Repositories in Explore Section\n\n## Tasks\n- [ ] Initialize a tracking file for GitHub repositories called github.md\n- [ ] Visit each Github repository and find their description\n- [ ] Visit bytedance/UI-TARS-desktop\n- [ ] Visit ray-project/kuberay\n- [ ] Check for additional Github repositories by scrolling down\n- [ ] Compile all results in the requested format\n- [ ] Validate that I have not missed anything in the page\n- [ ] Report final results to user',
+ }
+ },
+ {
+ 'write_file': {
+ 'path': 'github.md',
+ 'content': '# Github Repositories:\n',
+ }
+ },
+ {
+ 'click_element_by_index': {
+ 'index': 4,
+ }
+ },
+ ]
+
+ example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)
+ self._add_message_with_type(example_tool_call_1)
+ self._add_message_with_type(
+ UserMessage(
+ content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',
+ cache=True,
+ ),
+ )
def add_new_task(self, new_task: str) -> None:
self.task = new_task
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index cc5afa68d..fe1d5f852 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -171,6 +171,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
cloud_sync: CloudSync | None = None,
calculate_cost: bool = False,
display_files_in_done_text: bool = True,
+ include_tool_call_examples: bool = True,
**kwargs,
):
# Check for deprecated memory parameters
@@ -233,6 +234,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
is_planner_reasoning=is_planner_reasoning,
extend_planner_system_message=extend_planner_system_message,
calculate_cost=calculate_cost,
+ include_tool_call_examples=include_tool_call_examples,
)
# Token cost service
@@ -305,6 +307,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
available_file_paths=self.settings.available_file_paths,
state=self.state.message_manager_state,
use_thinking=self.settings.use_thinking,
+ include_tool_call_examples=self.settings.include_tool_call_examples,
# Settings that were previously in MessageManagerSettings
include_attributes=self.settings.include_attributes,
message_context=self.settings.message_context,
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 31e9ef0c6..c54a05c9c 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -63,6 +63,7 @@ class AgentSettings(BaseModel):
is_planner_reasoning: bool = False # type: ignore
extend_planner_system_message: str | None = None
calculate_cost: bool = False
+ include_tool_call_examples: bool = True
class AgentState(BaseModel):