Skip to content

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

add gemma support

Goldener Stefancbc951995b90
diff --git a/browser_use/llm/google/chat.py b/browser_use/llm/google/chat.py
index 95423f584..f0fc8ff0f 100644
--- a/browser_use/llm/google/chat.py
+++ b/browser_use/llm/google/chat.py
@@ -59,6 +59,8 @@ class ChatGoogle(BaseChatModel):
project: Google Cloud project ID
location: Google Cloud location
http_options: HTTP options for the client
+ include_system_in_user: If True, system messages are included in the first user message
+ supports_structured_output: If True, uses native JSON mode; if False, uses prompt-based fallback
Example:
from google.genai import types
@@ -78,6 +80,8 @@ class ChatGoogle(BaseChatModel):
seed: int | None = None
thinking_budget: int | None = None
config: types.GenerateContentConfigDict | None = None
+ include_system_in_user: bool = False
+ supports_structured_output: bool = True # New flag
# Client initialization parameters
api_key: str | None = None
@@ -167,8 +171,10 @@ class ChatGoogle(BaseChatModel):
Either a string response or an instance of output_format
"""
- # Serialize messages to Google format
- contents, system_instruction = GoogleMessageSerializer.serialize_messages(messages)
+ # Serialize messages to Google format with the include_system_in_user flag
+ contents, system_instruction = GoogleMessageSerializer.serialize_messages(
+ messages, include_system_in_user=self.include_system_in_user
+ )
# Build config dictionary starting with user-provided config
config: types.GenerateContentConfigDict = {}
@@ -213,36 +219,101 @@ class ChatGoogle(BaseChatModel):
)
else:
- # Return structured response
- config['response_mime_type'] = 'application/json'
- # Convert Pydantic model to Gemini-compatible schema
- optimized_schema = SchemaOptimizer.create_optimized_json_schema(output_format)
+ # Handle structured output
+ if self.supports_structured_output:
+ # Use native JSON mode
+ config['response_mime_type'] = 'application/json'
+ # Convert Pydantic model to Gemini-compatible schema
+ optimized_schema = SchemaOptimizer.create_optimized_json_schema(output_format)
+
+ gemini_schema = self._fix_gemini_schema(optimized_schema)
+ config['response_schema'] = gemini_schema
+
+ response = await self.get_client().aio.models.generate_content(
+ model=self.model,
+ contents=contents,
+ config=config,
+ )
- gemini_schema = self._fix_gemini_schema(optimized_schema)
- config['response_schema'] = gemini_schema
+ usage = self._get_usage(response)
+
+ # Handle case where response.parsed might be None
+ if response.parsed is None:
+ # When using response_schema, Gemini returns JSON as text
+ if response.text:
+ try:
+ # Parse the JSON text and validate with the Pydantic model
+ parsed_data = json.loads(response.text)
+ return ChatInvokeCompletion(
+ completion=output_format.model_validate(parsed_data),
+ usage=usage,
+ )
+ except (json.JSONDecodeError, ValueError) as e:
+ raise ModelProviderError(
+ message=f'Failed to parse or validate response: {str(e)}',
+ status_code=500,
+ model=self.model,
+ ) from e
+ else:
+ raise ModelProviderError(
+ message='No response from model',
+ status_code=500,
+ model=self.model,
+ )
- response = await self.get_client().aio.models.generate_content(
- model=self.model,
- contents=contents,
- config=config,
- )
+ # Ensure we return the correct type
+ if isinstance(response.parsed, output_format):
+ return ChatInvokeCompletion(
+ completion=response.parsed,
+ usage=usage,
+ )
+ else:
+ # If it's not the expected type, try to validate it
+ return ChatInvokeCompletion(
+ completion=output_format.model_validate(response.parsed),
+ usage=usage,
+ )
+ else:
+ # Fallback: Request JSON in the prompt for models without native JSON mode
+ # Add JSON instruction to the last message
+ if messages and isinstance(messages[-1].content, str):
+ json_instruction = f"\n\nPlease respond with a valid JSON object that matches this schema: {SchemaOptimizer.create_optimized_json_schema(output_format)}"
+ messages[-1].content += json_instruction
+
+ # Re-serialize with modified messages
+ contents, _ = GoogleMessageSerializer.serialize_messages(
+ messages, include_system_in_user=self.include_system_in_user
+ )
- usage = self._get_usage(response)
+ response = await self.get_client().aio.models.generate_content(
+ model=self.model,
+ contents=contents, # type: ignore
+ config=config,
+ )
+
+ usage = self._get_usage(response)
- # Handle case where response.parsed might be None
- if response.parsed is None:
- # When using response_schema, Gemini returns JSON as text
+ # Try to extract JSON from the text response
if response.text:
try:
- # Parse the JSON text and validate with the Pydantic model
- parsed_data = json.loads(response.text)
+ # Try to find JSON in the response
+ text = response.text.strip()
+
+ # Common patterns: JSON wrapped in markdown code blocks
+ if text.startswith('```json') and text.endswith('```'):
+ text = text[7:-3].strip()
+ elif text.startswith('```') and text.endswith('```'):
+ text = text[3:-3].strip()
+
+ # Parse and validate
+ parsed_data = json.loads(text)
return ChatInvokeCompletion(
completion=output_format.model_validate(parsed_data),
usage=usage,
)
except (json.JSONDecodeError, ValueError) as e:
raise ModelProviderError(
- message=f'Failed to parse or validate response: {str(e)}',
+ message=f'Model does not support JSON mode and failed to parse JSON from text response: {str(e)}',
status_code=500,
model=self.model,
) from e
@@ -253,19 +324,6 @@ class ChatGoogle(BaseChatModel):
model=self.model,
)
- # Ensure we return the correct type
- if isinstance(response.parsed, output_format):
- return ChatInvokeCompletion(
- completion=response.parsed,
- usage=usage,
- )
- else:
- # If it's not the expected type, try to validate it
- return ChatInvokeCompletion(
- completion=output_format.model_validate(response.parsed),
- usage=usage,
- )
-
try:
# Use manual retry loop for Google API calls
last_exception = None
diff --git a/browser_use/llm/google/serializer.py b/browser_use/llm/google/serializer.py
index 560de2544..5cf46ca96 100644
--- a/browser_use/llm/google/serializer.py
+++ b/browser_use/llm/google/serializer.py
@@ -14,16 +14,17 @@ class GoogleMessageSerializer:
"""Serializer for converting messages to Google Gemini format."""
@staticmethod
- def serialize_messages(messages: list[BaseMessage]) -> tuple[ContentListUnion, str | None]:
+ def serialize_messages(messages: list[BaseMessage], include_system_in_user: bool = False) -> tuple[ContentListUnion, str | None]:
"""
Convert a list of BaseMessages to Google format, extracting system message.
Google handles system instructions separately from the conversation, so we need to:
- 1. Extract any system messages and return them separately as a string
+ 1. Extract any system messages and return them separately as a string (or include in first user message if flag is set)
2. Convert the remaining messages to Content objects
Args:
messages: List of messages to convert
+ include_system_in_user: If True, system/developer messages are prepended to the first user message
Returns:
A tuple of (formatted_messages, system_message) where:
@@ -35,22 +36,30 @@ class GoogleMessageSerializer:
formatted_messages: ContentListUnion = []
system_message: str | None = None
+ system_parts: list[str] = []
- for message in messages:
+ for i, message in enumerate(messages):
role = message.role if hasattr(message, 'role') else None
# Handle system/developer messages
if isinstance(message, SystemMessage) or role in ['system', 'developer']:
# Extract system message content as string
if isinstance(message.content, str):
- system_message = message.content
+ if include_system_in_user:
+ system_parts.append(message.content)
+ else:
+ system_message = 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)
- system_message = '\n'.join(parts)
+ combined_text = '\n'.join(parts)
+ if include_system_in_user:
+ system_parts.append(combined_text)
+ else:
+ system_message = combined_text
continue
# Determine the role for non-system messages
@@ -65,30 +74,40 @@ class GoogleMessageSerializer:
# Initialize message parts
message_parts: list[Part] = []
- # Extract content and create parts
- if isinstance(message.content, str):
- # Regular text content
- message_parts = [Part.from_text(text=message.content)]
- elif message.content is not None:
- # Handle Iterable of content parts
- for part in message.content:
- if part.type == 'text':
- message_parts.append(Part.from_text(text=part.text))
- elif part.type == 'refusal':
- message_parts.append(Part.from_text(text=f'[Refusal] {part.refusal}'))
- elif part.type == 'image_url':
- # Handle images
- url = part.image_url.url
-
- # Format: data:image/png;base64,<data>
- header, data = url.split(',', 1)
- # Decode base64 to bytes
- image_bytes = base64.b64decode(data)
-
- # Add image part
- image_part = Part.from_bytes(data=image_bytes, mime_type='image/png')
-
- message_parts.append(image_part)
+ # If this is the first user message and we have system parts, prepend them
+ if include_system_in_user and system_parts and role == 'user' and not formatted_messages:
+ system_text = '\n\n'.join(system_parts)
+ if isinstance(message.content, str):
+ message_parts.append(Part.from_text(text=f"{system_text}\n\n{message.content}"))
+ else:
+ # Add system text as the first part
+ message_parts.append(Part.from_text(text=system_text))
+ system_parts = [] # Clear after using
+ else:
+ # Extract content and create parts normally
+ if isinstance(message.content, str):
+ # Regular text content
+ message_parts = [Part.from_text(text=message.content)]
+ elif message.content is not None:
+ # Handle Iterable of content parts
+ for part in message.content:
+ if part.type == 'text':
+ message_parts.append(Part.from_text(text=part.text))
+ elif part.type == 'refusal':
+ message_parts.append(Part.from_text(text=f'[Refusal] {part.refusal}'))
+ elif part.type == 'image_url':
+ # Handle images
+ url = part.image_url.url
+
+ # Format: data:image/png;base64,<data>
+ header, data = url.split(',', 1)
+ # Decode base64 to bytes
+ image_bytes = base64.b64decode(data)
+
+ # Add image part
+ image_part = Part.from_bytes(data=image_bytes, mime_type='image/png')
+
+ message_parts.append(image_part)
# Create the Content object
if message_parts: