Skip to content

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

Solved all the comments raised

Sandeep2cf9a7dbd5dc
diff --git a/browser_use/llm/models.py b/browser_use/llm/models.py
index fbc4a0bfc..bb46e6211 100644
--- a/browser_use/llm/models.py
+++ b/browser_use/llm/models.py
@@ -15,9 +15,16 @@ from typing import TYPE_CHECKING
from browser_use.llm.azure.chat import ChatAzureOpenAI
from browser_use.llm.google.chat import ChatGoogle
-from browser_use.llm.oci_raw.chat import ChatOCIRaw
from browser_use.llm.openai.chat import ChatOpenAI
+# Optional OCI import
+try:
+ from browser_use.llm.oci_raw.chat import ChatOCIRaw
+ OCI_AVAILABLE = True
+except ImportError:
+ ChatOCIRaw = None
+ OCI_AVAILABLE = False
+
if TYPE_CHECKING:
from browser_use.llm.base import BaseChatModel
@@ -131,6 +138,8 @@ def __getattr__(name: str) -> 'BaseChatModel':
elif name == 'ChatGoogle':
return ChatGoogle # type: ignore
elif name == 'ChatOCIRaw':
+ if not OCI_AVAILABLE:
+ raise ImportError('OCI integration not available. Install with: pip install "browser-use[oci]"')
return ChatOCIRaw # type: ignore
# Handle model instances - these are the main use case
@@ -140,11 +149,10 @@ def __getattr__(name: str) -> 'BaseChatModel':
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
-__all__ = [
+_base_all = [
'ChatOpenAI',
'ChatAzureOpenAI',
'ChatGoogle',
- 'ChatOCIRaw',
'get_llm_by_name',
# OpenAI instances - created on demand
'openai_gpt_4o',
@@ -179,3 +187,9 @@ __all__ = [
'google_gemini_2_5_flash',
'google_gemini_2_5_flash_lite',
]
+
+# Add ChatOCIRaw to __all__ if available
+if OCI_AVAILABLE:
+ _base_all.insert(3, 'ChatOCIRaw') # Insert after ChatGoogle
+
+__all__ = _base_all
diff --git a/browser_use/llm/oci_raw/README.md b/browser_use/llm/oci_raw/README.md
index 79a9be176..50a8152d5 100644
--- a/browser_use/llm/oci_raw/README.md
+++ b/browser_use/llm/oci_raw/README.md
@@ -45,7 +45,9 @@ agent = Agent(
llm=model
)
-history = await agent.run()
+# Run with asyncio
+import asyncio
+history = asyncio.run(agent.run())
```
### Provider-Specific Configuration Examples
diff --git a/browser_use/llm/oci_raw/serializer.py b/browser_use/llm/oci_raw/serializer.py
index caf438cad..3cf50c51d 100644
--- a/browser_use/llm/oci_raw/serializer.py
+++ b/browser_use/llm/oci_raw/serializer.py
@@ -134,6 +134,7 @@ class OCIRawMessageSerializer:
contents.append(text_content)
elif part.type == 'image_url':
# Assistant messages can have images in responses
+ # Note: This is currently unreachable in browser-use but kept for completeness
image_content = OCIRawMessageSerializer._create_image_content(part)
contents.append(image_content)
elif part.type == 'refusal':
@@ -149,7 +150,9 @@ class OCIRawMessageSerializer:
text_content.text = str(message)
oci_message.content = [text_content]
- oci_messages.append(oci_message)
+ # Only append messages that have content
+ if hasattr(oci_message, 'content') and oci_message.content:
+ oci_messages.append(oci_message)
return oci_messages
@@ -182,8 +185,12 @@ class OCIRawMessageSerializer:
if part.type == 'text':
text_parts.append(part.text)
elif part.type == 'image_url':
- # Cohere may not support images in all models, but include a placeholder
- text_parts.append(f'[Image: {part.image_url.url}]')
+ # Cohere may not support images in all models, use a short placeholder
+ # to avoid massive token usage from base64 data URIs
+ if part.image_url.url.startswith('data:image/'):
+ text_parts.append('[Image: base64_data]')
+ else:
+ text_parts.append('[Image: external_url]')
content = ' '.join(text_parts)
conversation_parts.append(f'User: {content}')
diff --git a/browser_use/llm/tests/test_chat_models.py b/browser_use/llm/tests/test_chat_models.py
index e2a4d65d6..ed7c60989 100644
--- a/browser_use/llm/tests/test_chat_models.py
+++ b/browser_use/llm/tests/test_chat_models.py
@@ -5,7 +5,13 @@ from pydantic import BaseModel
from browser_use.llm import ChatAnthropic, ChatGoogle, ChatGroq, ChatOpenAI, ChatOpenRouter
from browser_use.llm.messages import ContentPartTextParam
-from examples.models.oci_models import xai_llm
+# Optional OCI import
+try:
+ from examples.models.oci_models import xai_llm
+ OCI_MODELS_AVAILABLE = True
+except ImportError:
+ xai_llm = None
+ OCI_MODELS_AVAILABLE = False
class CapitalResponse(BaseModel):
@@ -252,6 +258,10 @@ class TestChatModels:
@pytest.fixture
def oci_raw_chat(self):
"""Provides an initialized ChatOCIRaw client for tests."""
+ # Skip if OCI models not available
+ if not OCI_MODELS_AVAILABLE:
+ pytest.skip('OCI models not available - install with pip install "browser-use[oci]"')
+
# Skip if OCI credentials not available - check for config file existence
try:
import oci
@@ -260,6 +270,10 @@ class TestChatModels:
except Exception:
pytest.skip('OCI credentials not available')
+ # Skip if using placeholder config
+ if xai_llm and hasattr(xai_llm, 'compartment_id') and 'example' in xai_llm.compartment_id.lower():
+ pytest.skip('OCI model using placeholder configuration - set real credentials')
+
return xai_llm # xai or cohere
@pytest.mark.asyncio
diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.py
index 271326dd9..b042f4a29 100644
--- a/browser_use/llm/tests/test_single_step.py
+++ b/browser_use/llm/tests/test_single_step.py
@@ -1,4 +1,5 @@
import logging
+import os
import tempfile
import pytest
@@ -13,7 +14,13 @@ from browser_use.llm.azure.chat import ChatAzureOpenAI
from browser_use.llm.base import BaseChatModel
from browser_use.llm.google.chat import ChatGoogle
from browser_use.llm.groq.chat import ChatGroq
-from browser_use.llm.oci_raw.chat import ChatOCIRaw
+# Optional OCI import
+try:
+ from browser_use.llm.oci_raw.chat import ChatOCIRaw
+ OCI_AVAILABLE = True
+except ImportError:
+ ChatOCIRaw = None
+ OCI_AVAILABLE = False
from browser_use.llm.openai.chat import ChatOpenAI
# Set logging level to INFO for this module
@@ -23,6 +30,8 @@ logger.setLevel(logging.INFO)
def _check_oci_credentials() -> bool:
"""Check if OCI credentials are available."""
+ if not OCI_AVAILABLE:
+ return False
try:
import oci
@@ -127,9 +136,9 @@ def create_mock_state_message(temp_dir: str):
pytest.param(
ChatOCIRaw,
{
- 'model_id': 'ocid1.generativeaimodel.oc1.us-chicago-1.amaaaaaask7dceyarojgfh6msa452vziycwfymle5gxdvpwwxzara53topmq',
- 'service_endpoint': 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com',
- 'compartment_id': 'ocid1.tenancy.oc1..aaaaaaaayeiis5uk2nuubznrekd6xsm56k3m4i7tyvkxmr2ftojqfkpx2ura',
+ 'model_id': os.getenv('OCI_MODEL_ID', 'placeholder'),
+ 'service_endpoint': os.getenv('OCI_SERVICE_ENDPOINT', 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com'),
+ 'compartment_id': os.getenv('OCI_COMPARTMENT_ID', 'placeholder'),
'provider': 'meta',
'temperature': 0.7,
'max_tokens': 800,
@@ -139,7 +148,12 @@ def create_mock_state_message(temp_dir: str):
'auth_type': 'API_KEY',
'auth_profile': 'DEFAULT',
},
- marks=pytest.mark.skipif(not _check_oci_credentials(), reason='OCI credentials not available'),
+ marks=pytest.mark.skipif(
+ not _check_oci_credentials() or
+ not os.getenv('OCI_MODEL_ID') or
+ not os.getenv('OCI_COMPARTMENT_ID'),
+ reason='OCI credentials or environment variables not available'
+ ),
),
],
)
@@ -166,7 +180,7 @@ async def test_single_step_parametrized(llm_class, model_name):
response = await llm.ainvoke(messages, agent.AgentOutput)
# Additional validation for OCI Raw
- if isinstance(llm, ChatOCIRaw):
+ if ChatOCIRaw is not None and isinstance(llm, ChatOCIRaw):
# Verify OCI Raw generates proper Agent actions
assert response.completion.action is not None
assert len(response.completion.action) > 0
diff --git a/browser_use/tokens/tests/test_cost.py b/browser_use/tokens/tests/test_cost.py
index dc9c403e4..47e9f14be 100644
--- a/browser_use/tokens/tests/test_cost.py
+++ b/browser_use/tokens/tests/test_cost.py
@@ -7,19 +7,18 @@ Tests ChatOpenAI and ChatGoogle by iteratively generating countries.
import asyncio
import logging
-from browser_use import ChatGoogle
-from browser_use.llm import ChatOpenAI
+from browser_use.llm import ChatGoogle, ChatOpenAI
from browser_use.llm.messages import AssistantMessage, SystemMessage, UserMessage
from browser_use.tokens.service import TokenCost
-from examples.models.oci_models import meta_llm
-# Optional OCI import for testing
+# Optional OCI import
try:
- import importlib.util
-
- OCI_AVAILABLE = importlib.util.find_spec('browser_use.llm.oci_raw.chat') is not None
+ from examples.models.oci_models import meta_llm
+ OCI_MODELS_AVAILABLE = True
except ImportError:
- OCI_AVAILABLE = False
+ meta_llm = None
+ OCI_MODELS_AVAILABLE = False
+
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@@ -27,7 +26,7 @@ logger.setLevel(logging.INFO)
def get_oci_model_if_available():
"""Create OCI model for testing if credentials are available."""
- if not OCI_AVAILABLE:
+ if not OCI_MODELS_AVAILABLE:
return None
# Try to create OCI model with mock/test configuration