Skip to content

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

Deepseek r1 working draft

magmuellerbc029639b19d
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 1302f8895..c10284e6b 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -1,7 +1,7 @@
from __future__ import annotations
-import logging
import json
+import logging
from datetime import datetime
from typing import List, Optional, Type
@@ -11,6 +11,7 @@ from langchain_core.messages import (
AIMessage,
BaseMessage,
HumanMessage,
+ SystemMessage,
ToolMessage,
)
from langchain_openai import ChatOpenAI
@@ -257,3 +258,56 @@ class MessageManager:
logger.debug(
f'Added message with {last_msg.metadata.input_tokens} tokens - total tokens now: {self.history.total_tokens}/{self.max_input_tokens} - total messages: {len(self.history.messages)}'
)
+
+ def convert_messages_for_non_function_calling_models(self, input_messages: list[BaseMessage]) -> list[BaseMessage]:
+ """Convert messages for non-function-calling models"""
+ output_messages = []
+ for message in input_messages:
+ if isinstance(message, HumanMessage):
+ output_messages.append(message)
+ elif isinstance(message, SystemMessage):
+ output_messages.append(message)
+ elif isinstance(message, ToolMessage):
+ output_messages.append(HumanMessage(content=message.content))
+ elif isinstance(message, AIMessage):
+ # check if tool_calls is a valid JSON object
+ if message.tool_calls:
+ tool_calls = json.dumps(message.tool_calls)
+ output_messages.append(AIMessage(content=tool_calls))
+ else:
+ output_messages.append(message)
+ else:
+ raise ValueError(f'Unknown message type: {type(message)}')
+ return output_messages
+
+ def merge_successive_human_messages(self, messages: list[BaseMessage]) -> list[BaseMessage]:
+ """Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one."""
+ merged_messages = []
+ streak = 0
+ for message in messages:
+ if isinstance(message, HumanMessage):
+ streak += 1
+ if streak > 1:
+ merged_messages[-1].content += message.content
+ else:
+ merged_messages.append(message)
+ else:
+ merged_messages.append(message)
+ streak = 0
+ return merged_messages
+
+ def extract_json_from_model_output(self, content: str) -> dict:
+ """Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""
+ try:
+ # If content is wrapped in code blocks, extract just the JSON part
+ if content.startswith('```'):
+ # Find the JSON content between code blocks
+ content = content.split('```')[1]
+ # Remove language identifier if present (e.g., 'json\n')
+ if '\n' in content:
+ content = content.split('\n', 1)[1]
+ # Parse the cleaned content
+ return json.loads(content)
+ except json.JSONDecodeError as e:
+ logger.warning(f'Failed to parse model output: {str(e)}')
+ raise ValueError('Could not parse response.')
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 2a4c3b8cf..c7b89c434 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -347,14 +347,31 @@ class Agent:
@time_execution_async('--get_next_action')
async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:
"""Get next action from LLM based on current state"""
- if self.tool_calling_method is None:
- structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)
+
+ if self.model_name == 'deepseek-reasoner':
+ converted_input_messages = self.message_manager.convert_messages_for_non_function_calling_models(input_messages)
+ merged_input_messages = self.message_manager.merge_successive_human_messages(converted_input_messages)
+ output = self.llm.invoke(merged_input_messages)
+ # TODO: currently invoke does not return reasoning_content, we should override it
+ # print(f'reasoning_content: {output.reasoning_content}')
+ print(f'content: {output.content}')
+ try:
+ parsed_json = self.message_manager.extract_json_from_model_output(output.content)
+ parsed = self.AgentOutput(**parsed_json)
+ except (ValueError, ValidationError) as e:
+ logger.warning(f'Failed to parse model output: {str(e)}')
+ raise ValueError('Could not parse response.')
else:
- structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True, method=self.tool_calling_method)
+ if self.tool_calling_method is None:
+ structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)
+ else:
+ structured_llm = self.llm.with_structured_output(
+ self.AgentOutput, include_raw=True, method=self.tool_calling_method
+ )
- response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore
+ response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore
- parsed: AgentOutput | None = response['parsed']
+ parsed: AgentOutput | None = response['parsed']
if parsed is None:
raise ValueError('Could not parse response.')
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 9af625241..644400b69 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -124,6 +124,8 @@ def setup_logging():
'charset_normalizer',
'anthropic._base_client',
'PIL.PngImagePlugin',
+ 'trafilatura.htmlprocessing',
+ 'trafilatura',
]:
third_party = logging.getLogger(logger)
third_party.setLevel(logging.ERROR)
diff --git a/examples/models/deepseek-r1.py b/examples/models/deepseek-r1.py
new file mode 100644
index 000000000..1a8808a38
--- /dev/null
+++ b/examples/models/deepseek-r1.py
@@ -0,0 +1,35 @@
+import asyncio
+import os
+
+from dotenv import load_dotenv
+from langchain_openai import ChatOpenAI
+from pydantic import SecretStr
+
+from browser_use import Agent
+
+# dotenv
+load_dotenv()
+
+api_key = os.getenv('DEEPSEEK_API_KEY', '')
+if not api_key:
+ raise ValueError('DEEPSEEK_API_KEY is not set')
+
+
+async def run_search():
+ agent = Agent(
+ task=('go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result'),
+ llm=ChatOpenAI(
+ base_url='https://api.deepseek.com/v1',
+ model='deepseek-reasoner',
+ api_key=SecretStr(api_key),
+ ),
+ use_vision=False,
+ max_failures=2,
+ max_actions_per_step=1,
+ )
+
+ await agent.run()
+
+
+if __name__ == '__main__':
+ asyncio.run(run_search())