Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
bedrock and anthropic example
Gregor Žuničec4a10ae57a4
diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.pyindex 477629104..4366f199e 100644--- a/browser_use/llm/__init__.py+++ b/browser_use/llm/__init__.py@@ -5,6 +5,8 @@ For easier transition we have"""from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock+from browser_use.llm.aws.chat_bedrock import ChatAWSBedrockfrom browser_use.llm.azure.chat import ChatAzureOpenAIfrom browser_use.llm.base import BaseChatModelfrom browser_use.llm.google.chat import ChatGoogle@@ -44,6 +46,8 @@ __all__ = ['ChatOpenAI','ChatGoogle','ChatAnthropic',+ 'ChatAnthropicBedrock',+ 'ChatAWSBedrock','ChatGroq','ChatAzureOpenAI','ChatOllama',diff --git a/browser_use/llm/aws/__init__.py b/browser_use/llm/aws/__init__.pynew file mode 100644index 000000000..69afb3a95--- /dev/null+++ b/browser_use/llm/aws/__init__.py@@ -0,0 +1,7 @@+from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock+from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock++__all__ = [+ 'ChatAWSBedrock',+ 'ChatAnthropicBedrock',+]diff --git a/browser_use/llm/aws/chat_anthropic.py b/browser_use/llm/aws/chat_anthropic.pynew file mode 100644index 000000000..fdcbcfc1e--- /dev/null+++ b/browser_use/llm/aws/chat_anthropic.py@@ -0,0 +1,239 @@+import json+from collections.abc import Mapping+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, TypeVar, overload++from anthropic import (+ NOT_GIVEN,+ APIConnectionError,+ APIStatusError,+ AsyncAnthropicBedrock,+ RateLimitError,+)+from anthropic.types import CacheControlEphemeralParam, Message, ToolParam+from anthropic.types.text_block import TextBlock+from anthropic.types.tool_choice_tool_param import ToolChoiceToolParam+from pydantic import BaseModel++from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer+from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock+from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError+from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage++if TYPE_CHECKING:+ from boto3.session import Session+++T = TypeVar('T', bound=BaseModel)+++@dataclass+class ChatAnthropicBedrock(ChatAWSBedrock):+ """+ AWS Bedrock Anthropic Claude chat model.++ This is a convenience class that provides Claude-specific defaults+ for the AWS Bedrock service. It inherits all functionality from+ ChatAWSBedrock but sets Anthropic Claude as the default model.+ """++ # Anthropic Claude specific defaults+ model: str = 'anthropic.claude-3-5-sonnet-20240620-v1:0'+ max_tokens: int = 8192+ temperature: float | None = None+ top_p: float | None = None+ top_k: int | None = None+ stop_sequences: list[str] | None = None++ # AWS credentials and configuration+ aws_access_key: str | None = None+ aws_secret_key: str | None = None+ aws_session_token: str | None = None+ aws_region: str | None = None+ session: 'Session | None' = None++ # Client initialization parameters+ max_retries: int = 10+ default_headers: Mapping[str, str] | None = None+ default_query: Mapping[str, object] | None = None++ @property+ def provider(self) -> str:+ return 'anthropic_bedrock'++ def _get_client_params(self) -> dict[str, Any]:+ """Prepare client parameters dictionary for Bedrock."""+ client_params: dict[str, Any] = {}++ if self.session:+ credentials = self.session.get_credentials()+ client_params.update(+ {+ 'aws_access_key': credentials.access_key,+ 'aws_secret_key': credentials.secret_key,+ 'aws_session_token': credentials.token,+ 'aws_region': self.session.region_name,+ }+ )+ else:+ # Use individual credentials+ if self.aws_access_key:+ client_params['aws_access_key'] = self.aws_access_key+ if self.aws_secret_key:+ client_params['aws_secret_key'] = self.aws_secret_key+ if self.aws_region:+ client_params['aws_region'] = self.aws_region+ if self.aws_session_token:+ client_params['aws_session_token'] = self.aws_session_token++ # Add optional parameters+ if self.max_retries:+ client_params['max_retries'] = self.max_retries+ if self.default_headers:+ client_params['default_headers'] = self.default_headers+ if self.default_query:+ client_params['default_query'] = self.default_query++ return client_params++ def _get_client_params_for_invoke(self) -> dict[str, Any]:+ """Prepare client parameters dictionary for invoke."""+ client_params = {}++ if self.temperature is not None:+ client_params['temperature'] = self.temperature+ if self.max_tokens is not None:+ client_params['max_tokens'] = self.max_tokens+ if self.top_p is not None:+ client_params['top_p'] = self.top_p+ if self.top_k is not None:+ client_params['top_k'] = self.top_k+ if self.stop_sequences is not None:+ client_params['stop_sequences'] = self.stop_sequences++ return client_params++ def get_client(self) -> AsyncAnthropicBedrock:+ """+ Returns an AsyncAnthropicBedrock client.++ Returns:+ AsyncAnthropicBedrock: An instance of the AsyncAnthropicBedrock client.+ """+ client_params = self._get_client_params()+ return AsyncAnthropicBedrock(**client_params)++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_usage(self, response: Message) -> ChatInvokeUsage | None:+ """Extract usage information from the response."""+ usage = ChatInvokeUsage(+ prompt_tokens=response.usage.input_tokens+ + (+ response.usage.cache_read_input_tokens or 0+ ), # Total tokens in Anthropic are a bit fucked, you have to add cached tokens to the prompt tokens+ completion_tokens=response.usage.output_tokens,+ total_tokens=response.usage.input_tokens + response.usage.output_tokens,+ prompt_cached_tokens=response.usage.cache_read_input_tokens,+ prompt_cache_creation_tokens=response.usage.cache_creation_input_tokens,+ prompt_image_tokens=None,+ )+ return usage++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ anthropic_messages, system_prompt = AnthropicMessageSerializer.serialize_messages(messages)++ try:+ if output_format is None:+ # Normal completion without structured output+ response = await self.get_client().messages.create(+ model=self.model,+ messages=anthropic_messages,+ system=system_prompt or NOT_GIVEN,+ **self._get_client_params_for_invoke(),+ )++ usage = self._get_usage(response)++ # Extract text from the first content block+ first_content = response.content[0]+ if isinstance(first_content, TextBlock):+ response_text = first_content.text+ else:+ # If it's not a text block, convert to string+ response_text = str(first_content)++ return ChatInvokeCompletion(+ completion=response_text,+ usage=usage,+ )++ else:+ # Use tool calling for structured output+ # Create a tool that represents the output format+ tool_name = output_format.__name__+ schema = output_format.model_json_schema()++ # Remove title from schema if present (Anthropic doesn't like it in parameters)+ if 'title' in schema:+ del schema['title']++ tool = ToolParam(+ name=tool_name,+ description=f'Extract information in the format of {tool_name}',+ input_schema=schema,+ cache_control=CacheControlEphemeralParam(type='ephemeral'),+ )++ # Force the model to use this tool+ tool_choice = ToolChoiceToolParam(type='tool', name=tool_name)++ response = await self.get_client().messages.create(+ model=self.model,+ messages=anthropic_messages,+ tools=[tool],+ system=system_prompt or NOT_GIVEN,+ tool_choice=tool_choice,+ **self._get_client_params_for_invoke(),+ )++ usage = self._get_usage(response)++ # Extract the tool use block+ for content_block in response.content:+ if hasattr(content_block, 'type') and content_block.type == 'tool_use':+ # Parse the tool input as the structured output+ try:+ return ChatInvokeCompletion(completion=output_format.model_validate(content_block.input), usage=usage)+ except Exception as e:+ # If validation fails, try to parse it as JSON first+ if isinstance(content_block.input, str):+ data = json.loads(content_block.input)+ return ChatInvokeCompletion(+ completion=output_format.model_validate(data),+ usage=usage,+ )+ raise e++ # If no tool use block found, raise an error+ raise ValueError('Expected tool use in response but none found')++ except APIConnectionError as e:+ raise ModelProviderError(message=e.message, model=self.name) from e+ except RateLimitError as e:+ raise ModelRateLimitError(message=e.message, model=self.name) from e+ except APIStatusError as e:+ raise ModelProviderError(message=e.message, status_code=e.status_code, model=self.name) from e+ except Exception as e:+ raise ModelProviderError(message=str(e), model=self.name) from ediff --git a/browser_use/llm/aws/chat_bedrock.py b/browser_use/llm/aws/chat_bedrock.pynew file mode 100644index 000000000..1a2298ac4--- /dev/null+++ b/browser_use/llm/aws/chat_bedrock.py@@ -0,0 +1,273 @@+import json+from dataclasses import dataclass+from os import getenv+from typing import Any, TypeVar, overload++from pydantic import BaseModel++from browser_use.llm.aws.serializer import AWSBedrockMessageSerializer+from browser_use.llm.base import BaseChatModel+from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError+from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage++try:+ from boto3 import client as AwsClient+ from boto3.session import Session+ from botocore.exceptions import ClientError+except ImportError:+ raise ImportError(+ '`boto3` not installed. Please install using `pip install browser-use[aws] or pip install browser-use[all]`'+ )++T = TypeVar('T', bound=BaseModel)+++@dataclass+class ChatAWSBedrock(BaseChatModel):+ """+ AWS Bedrock chat model supporting multiple providers (Anthropic, Meta, etc.).++ This class provides access to various models via AWS Bedrock,+ supporting both text generation and structured output via tool calling.++ To use this model, you need to either:+ 1. Set the following environment variables:+ - AWS_ACCESS_KEY_ID+ - AWS_SECRET_ACCESS_KEY+ - AWS_REGION+ 2. Or provide a boto3 Session object+ 3. Or use AWS SSO authentication+ """++ # Model configuration+ model: str = 'anthropic.claude-3-5-sonnet-20240620-v1:0'+ max_tokens: int | None = 4096+ temperature: float | None = None+ top_p: float | None = None+ stop_sequences: list[str] | None = None++ # AWS credentials and configuration+ aws_access_key_id: str | None = None+ aws_secret_access_key: str | None = None+ aws_region: str | None = None+ aws_sso_auth: bool = False+ session: Session | None = None++ # Request parameters+ request_params: dict[str, Any] | None = None++ # Static+ @property+ def provider(self) -> str:+ return 'aws_bedrock'++ def _get_client(self) -> AwsClient: # type: ignore[reportUnknownReturnType]+ """Get the AWS Bedrock client."""+ if self.session:+ return self.session.client('bedrock-runtime')++ # Get credentials from environment or instance parameters+ access_key = self.aws_access_key_id or getenv('AWS_ACCESS_KEY_ID')+ secret_key = self.aws_secret_access_key or getenv('AWS_SECRET_ACCESS_KEY')+ region = self.aws_region or getenv('AWS_REGION') or getenv('AWS_DEFAULT_REGION')++ if self.aws_sso_auth:+ return AwsClient(service_name='bedrock-runtime', region_name=region)+ else:+ if not access_key or not secret_key:+ raise ModelProviderError(+ message='AWS credentials not found. Please set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables or provide a boto3 session.',+ model=self.name,+ )++ return AwsClient(+ service_name='bedrock-runtime',+ region_name=region,+ aws_access_key_id=access_key,+ aws_secret_access_key=secret_key,+ )++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_inference_config(self) -> dict[str, Any]:+ """Get the inference configuration for the request."""+ config = {}+ if self.max_tokens is not None:+ config['maxTokens'] = self.max_tokens+ if self.temperature is not None:+ config['temperature'] = self.temperature+ if self.top_p is not None:+ config['topP'] = self.top_p+ if self.stop_sequences is not None:+ config['stopSequences'] = self.stop_sequences+ return config++ def _format_tools_for_request(self, output_format: type[BaseModel]) -> list[dict[str, Any]]:+ """Format a Pydantic model as a tool for structured output."""+ schema = output_format.model_json_schema()++ # Convert Pydantic schema to Bedrock tool format+ properties = {}+ required = []++ for prop_name, prop_info in schema.get('properties', {}).items():+ properties[prop_name] = {+ 'type': prop_info.get('type', 'string'),+ 'description': prop_info.get('description', ''),+ }++ # Add required fields+ required = schema.get('required', [])++ return [+ {+ 'toolSpec': {+ 'name': f'extract_{output_format.__name__.lower()}',+ 'description': f'Extract information in the format of {output_format.__name__}',+ 'inputSchema': {'json': {'type': 'object', 'properties': properties, 'required': required}},+ }+ }+ ]++ def _get_usage(self, response: dict[str, Any]) -> ChatInvokeUsage | None:+ """Extract usage information from the response."""+ if 'usage' not in response:+ return None++ usage_data = response['usage']+ return ChatInvokeUsage(+ prompt_tokens=usage_data.get('inputTokens', 0),+ completion_tokens=usage_data.get('outputTokens', 0),+ total_tokens=usage_data.get('totalTokens', 0),+ prompt_cached_tokens=None, # Bedrock doesn't provide this+ prompt_cache_creation_tokens=None,+ prompt_image_tokens=None,+ )++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ """+ Invoke the AWS Bedrock model with the given messages.++ Args:+ messages: List of chat messages+ output_format: Optional Pydantic model class for structured output++ Returns:+ Either a string response or an instance of output_format+ """+ bedrock_messages, system_message = AWSBedrockMessageSerializer.serialize_messages(messages)++ try:+ # Prepare the request body+ body: dict[str, Any] = {}++ if system_message:+ body['system'] = system_message++ inference_config = self._get_inference_config()+ if inference_config:+ body['inferenceConfig'] = inference_config++ # Handle structured output via tool calling+ if output_format is not None:+ tools = self._format_tools_for_request(output_format)+ body['toolConfig'] = {'tools': tools}++ # Add any additional request parameters+ if self.request_params:+ body.update(self.request_params)++ # Filter out None values+ body = {k: v for k, v in body.items() if v is not None}++ # Make the API call+ client = self._get_client()+ response = client.converse(modelId=self.model, messages=bedrock_messages, **body)++ usage = self._get_usage(response)++ # Extract the response content+ if 'output' in response and 'message' in response['output']:+ message = response['output']['message']+ content = message.get('content', [])++ if output_format is None:+ # Return text response+ text_content = []+ for item in content:+ if 'text' in item:+ text_content.append(item['text'])++ response_text = '\n'.join(text_content) if text_content else ''+ return ChatInvokeCompletion(+ completion=response_text,+ usage=usage,+ )+ else:+ # Handle structured output from tool calls+ for item in content:+ if 'toolUse' in item:+ tool_use = item['toolUse']+ tool_input = tool_use.get('input', {})++ try:+ # Validate and return the structured output+ return ChatInvokeCompletion(+ completion=output_format.model_validate(tool_input),+ usage=usage,+ )+ except Exception as e:+ # If validation fails, try to parse as JSON first+ if isinstance(tool_input, str):+ try:+ data = json.loads(tool_input)+ return ChatInvokeCompletion(+ completion=output_format.model_validate(data),+ usage=usage,+ )+ except json.JSONDecodeError:+ pass+ raise ModelProviderError(+ message=f'Failed to validate structured output: {str(e)}',+ model=self.name,+ ) from e++ # If no tool use found but output_format was requested+ raise ModelProviderError(+ message='Expected structured output but no tool use found in response',+ model=self.name,+ )++ # If no valid content found+ if output_format is None:+ return ChatInvokeCompletion(+ completion='',+ usage=usage,+ )+ else:+ raise ModelProviderError(+ message='No valid content found in response',+ model=self.name,+ )++ except ClientError as e:+ error_code = e.response.get('Error', {}).get('Code', 'Unknown')+ error_message = e.response.get('Error', {}).get('Message', str(e))++ if error_code in ['ThrottlingException', 'TooManyRequestsException']:+ raise ModelRateLimitError(message=error_message, model=self.name) from e+ else:+ raise ModelProviderError(message=error_message, model=self.name) from e+ except Exception as e:+ raise ModelProviderError(message=str(e), model=self.name) from ediff --git a/browser_use/llm/aws/serializer.py b/browser_use/llm/aws/serializer.pynew file mode 100644index 000000000..e0a21ffc1--- /dev/null+++ b/browser_use/llm/aws/serializer.py@@ -0,0 +1,257 @@+import base64+import json+import re+from typing import Any, overload++from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ ContentPartImageParam,+ ContentPartRefusalParam,+ ContentPartTextParam,+ SystemMessage,+ ToolCall,+ UserMessage,+)+++class AWSBedrockMessageSerializer:+ """Serializer for converting between custom message types and AWS Bedrock message format."""++ @staticmethod+ def _is_base64_image(url: str) -> bool:+ """Check if the URL is a base64 encoded image."""+ return url.startswith('data:image/')++ @staticmethod+ def _is_url_image(url: str) -> bool:+ """Check if the URL is a regular HTTP/HTTPS image URL."""+ return url.startswith(('http://', 'https://')) and any(+ url.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']+ )++ @staticmethod+ def _parse_base64_url(url: str) -> tuple[str, bytes]:+ """Parse a base64 data URL to extract format and raw bytes."""+ # Format: data:image/jpeg;base64,<data>+ if not url.startswith('data:'):+ raise ValueError(f'Invalid base64 URL: {url}')++ header, data = url.split(',', 1)++ # Extract format from mime type+ mime_match = re.search(r'image/(\w+)', header)+ if mime_match:+ format_name = mime_match.group(1).lower()+ # Map common formats+ format_mapping = {'jpg': 'jpeg', 'jpeg': 'jpeg', 'png': 'png', 'gif': 'gif', 'webp': 'webp'}+ image_format = format_mapping.get(format_name, 'jpeg')+ else:+ image_format = 'jpeg' # Default format++ # Decode base64 data+ try:+ image_bytes = base64.b64decode(data)+ except Exception as e:+ raise ValueError(f'Failed to decode base64 image data: {e}')++ return image_format, image_bytes++ @staticmethod+ def _download_and_convert_image(url: str) -> tuple[str, bytes]:+ """Download an image from URL and convert to base64 bytes."""+ try:+ import httpx+ except ImportError:+ raise ImportError('httpx not available. Please install it to use URL images with AWS Bedrock.')++ try:+ response = httpx.get(url, timeout=30)+ response.raise_for_status()++ # Detect format from content type or URL+ content_type = response.headers.get('content-type', '').lower()+ if 'jpeg' in content_type or url.lower().endswith(('.jpg', '.jpeg')):+ image_format = 'jpeg'+ elif 'png' in content_type or url.lower().endswith('.png'):+ image_format = 'png'+ elif 'gif' in content_type or url.lower().endswith('.gif'):+ image_format = 'gif'+ elif 'webp' in content_type or url.lower().endswith('.webp'):+ image_format = 'webp'+ else:+ image_format = 'jpeg' # Default format++ return image_format, response.content++ except Exception as e:+ raise ValueError(f'Failed to download image from {url}: {e}')++ @staticmethod+ def _serialize_content_part_text(part: ContentPartTextParam) -> dict[str, Any]:+ """Convert a text content part to AWS Bedrock format."""+ return {'text': part.text}++ @staticmethod+ def _serialize_content_part_image(part: ContentPartImageParam) -> dict[str, Any]:+ """Convert an image content part to AWS Bedrock format."""+ url = part.image_url.url++ if AWSBedrockMessageSerializer._is_base64_image(url):+ # Handle base64 encoded images+ image_format, image_bytes = AWSBedrockMessageSerializer._parse_base64_url(url)+ elif AWSBedrockMessageSerializer._is_url_image(url):+ # Download and convert URL images+ image_format, image_bytes = AWSBedrockMessageSerializer._download_and_convert_image(url)+ else:+ raise ValueError(f'Unsupported image URL format: {url}')++ return {+ 'image': {+ 'format': image_format,+ 'source': {+ 'bytes': image_bytes,+ },+ }+ }++ @staticmethod+ def _serialize_user_content(+ content: str | list[ContentPartTextParam | ContentPartImageParam],+ ) -> list[dict[str, Any]]:+ """Serialize content for user messages."""+ if isinstance(content, str):+ return [{'text': content}]++ content_blocks: list[dict[str, Any]] = []+ for part in content:+ if part.type == 'text':+ content_blocks.append(AWSBedrockMessageSerializer._serialize_content_part_text(part))+ elif part.type == 'image_url':+ content_blocks.append(AWSBedrockMessageSerializer._serialize_content_part_image(part))++ return content_blocks++ @staticmethod+ def _serialize_system_content(+ content: str | list[ContentPartTextParam],+ ) -> list[dict[str, Any]]:+ """Serialize content for system messages."""+ if isinstance(content, str):+ return [{'text': content}]++ content_blocks: list[dict[str, Any]] = []+ for part in content:+ if part.type == 'text':+ content_blocks.append(AWSBedrockMessageSerializer._serialize_content_part_text(part))++ return content_blocks++ @staticmethod+ def _serialize_assistant_content(+ content: str | list[ContentPartTextParam | ContentPartRefusalParam] | None,+ ) -> list[dict[str, Any]]:+ """Serialize content for assistant messages."""+ if content is None:+ return []+ if isinstance(content, str):+ return [{'text': content}]++ content_blocks: list[dict[str, Any]] = []+ for part in content:+ if part.type == 'text':+ content_blocks.append(AWSBedrockMessageSerializer._serialize_content_part_text(part))+ # Skip refusal content parts - AWS Bedrock doesn't need them++ return content_blocks++ @staticmethod+ def _serialize_tool_call(tool_call: ToolCall) -> dict[str, Any]:+ """Convert a tool call to AWS Bedrock format."""+ try:+ arguments = json.loads(tool_call.function.arguments)+ except json.JSONDecodeError:+ # If arguments aren't valid JSON, wrap them+ arguments = {'arguments': tool_call.function.arguments}++ return {+ 'toolUse': {+ 'toolUseId': tool_call.id,+ 'name': tool_call.function.name,+ 'input': arguments,+ }+ }++ # region - Serialize overloads+ @overload+ @staticmethod+ def serialize(message: UserMessage) -> dict[str, Any]: ...++ @overload+ @staticmethod+ def serialize(message: SystemMessage) -> SystemMessage: ...++ @overload+ @staticmethod+ def serialize(message: AssistantMessage) -> dict[str, Any]: ...++ @staticmethod+ def serialize(message: BaseMessage) -> dict[str, Any] | SystemMessage:+ """Serialize a custom message to AWS Bedrock format."""++ if isinstance(message, UserMessage):+ return {+ 'role': 'user',+ 'content': AWSBedrockMessageSerializer._serialize_user_content(message.content),+ }++ elif isinstance(message, SystemMessage):+ # System messages are handled separately in AWS Bedrock+ return message++ elif isinstance(message, AssistantMessage):+ content_blocks: list[dict[str, Any]] = []++ # Add content blocks if present+ if message.content is not None:+ content_blocks.extend(AWSBedrockMessageSerializer._serialize_assistant_content(message.content))++ # Add tool use blocks if present+ if message.tool_calls:+ for tool_call in message.tool_calls:+ content_blocks.append(AWSBedrockMessageSerializer._serialize_tool_call(tool_call))++ # AWS Bedrock requires at least one content block+ if not content_blocks:+ content_blocks = [{'text': ''}]++ return {+ 'role': 'assistant',+ 'content': content_blocks,+ }++ else:+ raise ValueError(f'Unknown message type: {type(message)}')++ @staticmethod+ def serialize_messages(messages: list[BaseMessage]) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:+ """+ Serialize a list of messages, extracting any system message.++ Returns:+ Tuple of (bedrock_messages, system_message) where system_message is extracted+ from any SystemMessage in the list.+ """+ bedrock_messages: list[dict[str, Any]] = []+ system_message: list[dict[str, Any]] | None = None++ for message in messages:+ if isinstance(message, SystemMessage):+ # Extract system message content+ system_message = AWSBedrockMessageSerializer._serialize_system_content(message.content)+ else:+ # Serialize and add to regular messages+ serialized = AWSBedrockMessageSerializer.serialize(message)+ bedrock_messages.append(serialized)++ return bedrock_messages, system_messagediff --git a/docs/customize/supported-models.mdx b/docs/customize/supported-models.mdxindex 309434a65..b2e257004 100644--- a/docs/customize/supported-models.mdx+++ b/docs/customize/supported-models.mdx@@ -24,6 +24,7 @@ Our library natively supports the following models:- OpenAI- Anthropic+- AWS Bedrock (multiple providers)- Azure OpenAI- Gemini- Groq@@ -66,7 +67,7 @@ from browser_use import Agent# Initialize the modelllm = ChatAnthropic(- model_name="claude-3-5-sonnet-20240620",+ model="claude-3-5-sonnet-20240620",)# Create agent with the model@@ -137,6 +138,66 @@ Required environment variables:GOOGLE_API_KEY=```+### AWS Bedrock++AWS Bedrock provides access to multiple model providers through a single API. We support both a general AWS Bedrock client and provider-specific convenience classes.++#### General AWS Bedrock (supports all providers)++```python+from browser_use.llm import ChatAWSBedrock+from browser_use import Agent++# Works with any Bedrock model (Anthropic, Meta, AI21, etc.)+llm = ChatAWSBedrock(+ model="anthropic.claude-3-5-sonnet-20240620-v1:0", # or any Bedrock model+ aws_region="us-east-1",+)++# Create agent with the model+agent = Agent(+ task="Your task here",+ llm=llm+)+```++#### Anthropic Claude via AWS Bedrock (convenience class)++```python+from browser_use.llm import ChatAnthropicBedrock+from browser_use import Agent++# Anthropic-specific class with Claude defaults+llm = ChatAnthropicBedrock(+ model="anthropic.claude-3-5-sonnet-20240620-v1:0",+ aws_region="us-east-1",+)++# Create agent with the model+agent = Agent(+ task="Your task here",+ llm=llm+)+```++#### AWS Authentication++Required environment variables:++```bash .env+AWS_ACCESS_KEY_ID=+AWS_SECRET_ACCESS_KEY=+AWS_DEFAULT_REGION=us-east-1+```++You can also use AWS profiles or IAM roles instead of environment variables. The implementation supports:++- Environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`)+- AWS profiles and credential files+- IAM roles (when running on EC2)+- Session tokens for temporary credentials+- AWS SSO authentication (`aws_sso_auth=True`)+## Groq```python@@ -156,3 +217,12 @@ Required environment variables:```bash .envGROQ_API_KEY=```++## Ollama++```python+from browser_use.llm import ChatOllama+from browser_use import Agent++llm = ChatOllama(model="llama3.1:8b")+```diff --git a/examples/models/aws.py b/examples/models/aws.pynew file mode 100644index 000000000..e1fe3ea0f--- /dev/null+++ b/examples/models/aws.py@@ -0,0 +1,104 @@+"""+AWS Bedrock Examples++This file demonstrates how to use AWS Bedrock models with browser-use.+We provide two classes:+1. ChatAnthropicBedrock - Convenience class for Anthropic Claude models+2. ChatAWSBedrock - General AWS Bedrock client supporting all providers++Requirements:+- AWS credentials configured via environment variables+- boto3 installed: pip install boto3+- Access to AWS Bedrock models in your region+"""++import asyncio++from lmnr import Laminar++from browser_use import Agent+from browser_use.llm import ChatAnthropicBedrock, ChatAWSBedrock++Laminar.initialize()+++async def example_anthropic_bedrock():+ """Example using ChatAnthropicBedrock - convenience class for Claude models."""+ print('🔹 ChatAnthropicBedrock Example')++ # Initialize with Anthropic Claude via AWS Bedrock+ llm = ChatAnthropicBedrock(+ model='us.anthropic.claude-sonnet-4-20250514-v1:0',+ aws_region='us-east-1',+ temperature=0.7,+ )++ print(f'Model: {llm.name}')+ print(f'Provider: {llm.provider}')++ # Create agent+ agent = Agent(+ task="Navigate to google.com and search for 'AWS Bedrock pricing'",+ llm=llm,+ )++ print("Task: Navigate to google.com and search for 'AWS Bedrock pricing'")++ # Run the agent+ result = await agent.run(max_steps=2)+ print(f'Result: {result}')+++async def example_aws_bedrock():+ """Example using ChatAWSBedrock - general client for any Bedrock model."""+ print('\n🔹 ChatAWSBedrock Example')++ # Initialize with any AWS Bedrock model (using Meta Llama as example)+ llm = ChatAWSBedrock(+ model='us.meta.llama4-maverick-17b-instruct-v1:0',+ aws_region='us-east-1',+ temperature=0.5,+ )++ print(f'Model: {llm.name}')+ print(f'Provider: {llm.provider}')++ # Create agent+ agent = Agent(+ task='Go to github.com and find the most popular Python repository',+ llm=llm,+ )++ print('Task: Go to github.com and find the most popular Python repository')++ # Run the agent+ result = await agent.run(max_steps=2)+ print(f'Result: {result}')+++async def main():+ """Run AWS Bedrock examples."""+ print('🚀 AWS Bedrock Examples')+ print('=' * 40)++ print('Make sure you have AWS credentials configured:')+ print('export AWS_ACCESS_KEY_ID=your_key')+ print('export AWS_SECRET_ACCESS_KEY=your_secret')+ print('export AWS_DEFAULT_REGION=us-east-1')+ print('=' * 40)++ try:+ # Run both examples+ await example_aws_bedrock()+ await example_anthropic_bedrock()++ except Exception as e:+ print(f'❌ Error: {e}')+ print('Make sure you have:')+ print('- Valid AWS credentials configured')+ print('- Access to AWS Bedrock in your region')+ print('- boto3 installed: pip install boto3')+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/models/langchain/__init__.py b/examples/models/langchain/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/examples/models/langchain/chat.py b/examples/models/langchain/chat.pyindex 9207856d6..c4b7ad693 100644--- a/examples/models/langchain/chat.py+++ b/examples/models/langchain/chat.py@@ -1,8 +1,6 @@from dataclasses import dataclass-from typing import TypeVar, overload+from typing import TYPE_CHECKING, TypeVar, overload-from langchain_core.language_models.chat_models import BaseChatModel as LangChainBaseChatModel-from langchain_core.messages import AIMessage as LangChainAIMessagefrom pydantic import BaseModelfrom browser_use.llm.base import BaseChatModel@@ -11,6 +9,10 @@ from browser_use.llm.messages import BaseMessagefrom browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsagefrom examples.models.langchain.serializer import LangChainMessageSerializer+if TYPE_CHECKING:+ from langchain_core.language_models.chat_models import BaseChatModel as LangChainBaseChatModel # type: ignore+ from langchain_core.messages import AIMessage as LangChainAIMessage # type: ignore+T = TypeVar('T', bound=BaseModel)@@ -23,7 +25,7 @@ class ChatLangchain(BaseChatModel):"""# The LangChain model to wrap- chat: LangChainBaseChatModel+ chat: 'LangChainBaseChatModel'@propertydef model(self) -> str:@@ -62,7 +64,7 @@ class ChatLangchain(BaseChatModel):return self.chat.__class__.__name__- def _get_usage(self, response: LangChainAIMessage) -> ChatInvokeUsage | None:+ def _get_usage(self, response: 'LangChainAIMessage') -> ChatInvokeUsage | None:usage = response.usage_metadataif usage is None:return None@@ -115,7 +117,10 @@ class ChatLangchain(BaseChatModel):try:if output_format is None:# Return string response- response: LangChainAIMessage = await self.chat.ainvoke(langchain_messages) # type: ignore+ response = await self.chat.ainvoke(langchain_messages) # type: ignore++ # Import at runtime for isinstance check+ from langchain_core.messages import AIMessage as LangChainAIMessage # type: ignoreif not isinstance(response, LangChainAIMessage):raise ModelProviderError(@@ -149,7 +154,7 @@ class ChatLangchain(BaseChatModel):)except AttributeError:# Fall back to manual parsing if with_structured_output is not available- response: LangChainAIMessage = await self.chat.ainvoke(langchain_messages) # type: ignore+ response = await self.chat.ainvoke(langchain_messages) # type: ignorecontent = response.content if hasattr(response, 'content') else str(response)try:diff --git a/pyproject.toml b/pyproject.tomlindex 395c04005..d77abfe25 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -59,12 +59,17 @@ cli = ["click>=8.1.8","textual>=3.2.0",]+aws = [+ "boto3>=1.38.45"+]examples = [# botocore: only needed for Bedrock Claude boto3 examples/models/bedrock_claude.py"botocore>=1.37.23","imgcat>=0.6.0","stagehand-py>=0.3.6","browserbase>=0.4.0",+ "langchain-openai>=0.3.26",+ "langchain-core>=0.3.0",]eval = ["lmnr[all]>=0.6.11",@@ -73,7 +78,7 @@ eval = ["psutil>=7.0.0",]all = [- "browser-use[memory,cli,examples]",+ "browser-use[memory,cli,examples,aws]",]# will prefer to use local source code checked out in ../../browser-use (if present) instead of pypi browser-use package@@ -117,6 +122,8 @@ skip-magic-trailing-comma = false[tool.pyright]typeCheckingMode = "basic"exclude = ["tests/old/", ".venv/", ".git/", "__pycache__/"]+reportMissingModuleSource = false+reportOptionalMemberAccess = "warning"[tool.hatch.build]