Skip to content

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

fix(llm): stop dropping system messages in the Gemini request

Mohil-Ahuja01f32db445be
diff --git a/browser_use/llm/google/serializer.py b/browser_use/llm/google/serializer.py
index 09eef9bdb..1f6a55c13 100644
--- a/browser_use/llm/google/serializer.py
+++ b/browser_use/llm/google/serializer.py
@@ -37,7 +37,6 @@ class GoogleMessageSerializer:
messages = [m.model_copy(deep=True) for m in messages]
formatted_messages: ContentListUnion = []
- system_message: str | None = None
system_parts: list[str] = []
for i, message in enumerate(messages):
@@ -45,23 +44,16 @@ class GoogleMessageSerializer:
# Handle system/developer messages
if isinstance(message, SystemMessage) or role in ['system', 'developer']:
- # Extract system message content as string
+ # Collect the text of every system message; the last one must not overwrite the earlier ones
if isinstance(message.content, str):
- if include_system_in_user:
- system_parts.append(message.content)
- else:
- system_message = message.content
+ system_parts.append(message.content)
elif message.content is not None:
# Handle Iterable of content parts
parts = []
for part in message.content:
if part.type == 'text':
parts.append(part.text)
- combined_text = '\n'.join(parts)
- if include_system_in_user:
- system_parts.append(combined_text)
- else:
- system_message = combined_text
+ system_parts.append('\n'.join(parts))
continue
# Determine the role for non-system messages
@@ -78,7 +70,8 @@ class GoogleMessageSerializer:
# If this is the first user message and we have system parts, prepend them
system_text = None
- if include_system_in_user and system_parts and role == 'user' and not formatted_messages:
+ # An earlier assistant turn must not disqualify the first user message
+ if include_system_in_user and system_parts and role == 'user':
system_text = '\n\n'.join(system_parts)
system_parts = [] # Clear after using
@@ -121,4 +114,9 @@ class GoogleMessageSerializer:
# for some reason, the type checker is not able to infer the type of formatted_messages
formatted_messages.append(final_message) # type: ignore
+ # Whatever is left was never merged into a user message, so it becomes the separate system
+ # instruction. With include_system_in_user=False that is every system message; with it set,
+ # this only happens when there is no user message to prepend to.
+ system_message = '\n\n'.join(system_parts) if system_parts else None
+
return formatted_messages, system_message
diff --git a/tests/ci/models/test_google_serializer.py b/tests/ci/models/test_google_serializer.py
new file mode 100644
index 000000000..9418ddac0
--- /dev/null
+++ b/tests/ci/models/test_google_serializer.py
@@ -0,0 +1,55 @@
+"""Regression tests for GoogleMessageSerializer's handling of system messages."""
+
+from browser_use.llm.google.serializer import GoogleMessageSerializer
+from browser_use.llm.messages import AssistantMessage, SystemMessage, UserMessage
+
+
+def test_single_system_message_becomes_the_system_instruction():
+ """The common case must keep returning the system text verbatim."""
+ contents, system_instruction = GoogleMessageSerializer.serialize_messages(
+ [SystemMessage(content='Follow the base system rule.'), UserMessage(content='Continue the task.')]
+ )
+
+ assert system_instruction == 'Follow the base system rule.'
+ assert len(contents) == 1
+
+
+def test_all_system_messages_reach_the_system_instruction():
+ """Every SystemMessage must survive, in order, instead of the last one winning."""
+ contents, system_instruction = GoogleMessageSerializer.serialize_messages(
+ [
+ SystemMessage(content='Follow the base system rule.'),
+ SystemMessage(content='Also follow the additional system rule.'),
+ UserMessage(content='Continue the task.'),
+ ]
+ )
+
+ assert system_instruction == 'Follow the base system rule.\n\nAlso follow the additional system rule.'
+ assert len(contents) == 1
+ assert contents[0].parts[0].text == 'Continue the task.' # type: ignore[union-attr]
+
+
+def test_system_text_is_prepended_even_when_an_assistant_message_comes_first():
+ """include_system_in_user must target the first *user* message, not the first message."""
+ contents, system_instruction = GoogleMessageSerializer.serialize_messages(
+ [
+ SystemMessage(content='Follow the system rule.'),
+ AssistantMessage(content='Earlier assistant turn.'),
+ UserMessage(content='Continue the task.'),
+ ],
+ include_system_in_user=True,
+ )
+
+ assert system_instruction is None
+ assert [content.role for content in contents] == ['model', 'user'] # type: ignore[union-attr]
+ assert contents[1].parts[0].text == 'Follow the system rule.\n\nContinue the task.' # type: ignore[union-attr]
+
+
+def test_system_text_falls_back_to_the_instruction_when_there_is_no_user_message():
+ """With nothing to merge into, the system text must not be silently dropped."""
+ _, system_instruction = GoogleMessageSerializer.serialize_messages(
+ [SystemMessage(content='Follow the system rule.'), AssistantMessage(content='Earlier assistant turn.')],
+ include_system_in_user=True,
+ )
+
+ assert system_instruction == 'Follow the system rule.'