Skip to content

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

create cerebras project

kevint-cerebrasf9d06a4852df
diff --git a/browser_use/llm/README.md b/browser_use/llm/README.md
index fedce4fe6..b53663c97 100644
--- a/browser_use/llm/README.md
+++ b/browser_use/llm/README.md
@@ -8,6 +8,7 @@ We officially support the following LLMs:
- Groq
- Ollama
- DeepSeek
+- Cerebras
## Migrating from LangChain
diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.py
index badaef2eb..9fbb197c0 100644
--- a/browser_use/llm/__init__.py
+++ b/browser_use/llm/__init__.py
@@ -30,6 +30,7 @@ if TYPE_CHECKING:
from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock
from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock
from browser_use.llm.azure.chat import ChatAzureOpenAI
+ from browser_use.llm.cerebras.chat import ChatCerebras
from browser_use.llm.deepseek.chat import ChatDeepSeek
from browser_use.llm.google.chat import ChatGoogle
from browser_use.llm.groq.chat import ChatGroq
@@ -78,6 +79,7 @@ _LAZY_IMPORTS = {
'ChatAnthropicBedrock': ('browser_use.llm.aws.chat_anthropic', 'ChatAnthropicBedrock'),
'ChatAWSBedrock': ('browser_use.llm.aws.chat_bedrock', 'ChatAWSBedrock'),
'ChatAzureOpenAI': ('browser_use.llm.azure.chat', 'ChatAzureOpenAI'),
+ 'ChatCerebras': ('browser_use.llm.cerebras.chat', 'ChatCerebras'),
'ChatDeepSeek': ('browser_use.llm.deepseek.chat', 'ChatDeepSeek'),
'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'),
'ChatGroq': ('browser_use.llm.groq.chat', 'ChatGroq'),
@@ -143,4 +145,5 @@ __all__ = [
'ChatAzureOpenAI',
'ChatOllama',
'ChatOpenRouter',
+ 'ChatCerebras',
]
diff --git a/browser_use/llm/cerebras/chat.py b/browser_use/llm/cerebras/chat.py
new file mode 100644
index 000000000..2084a4926
--- /dev/null
+++ b/browser_use/llm/cerebras/chat.py
@@ -0,0 +1,198 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from typing import Any, TypeVar, overload
+
+import httpx
+from openai import (
+ APIConnectionError,
+ APIError,
+ APIStatusError,
+ APITimeoutError,
+ AsyncOpenAI,
+ RateLimitError,
+)
+from openai.types.chat import ChatCompletion
+from openai.types.shared_params.response_format_json_schema import JSONSchema, ResponseFormatJSONSchema
+from pydantic import BaseModel
+
+from browser_use.llm.base import BaseChatModel
+from browser_use.llm.cerebras.serializer import CerebrasMessageSerializer
+from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
+from browser_use.llm.messages import BaseMessage
+from browser_use.llm.schema import SchemaOptimizer
+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage
+
+T = TypeVar('T', bound=BaseModel)
+
+
+@dataclass
+class ChatCerebras(BaseChatModel):
+ """Cerebras inference wrapper (OpenAI-compatible)."""
+
+ model: str = 'llama3.1-8b'
+
+ # Generation parameters
+ max_tokens: int | None = 4096
+ temperature: float | None = 0.2
+ top_p: float | None = None
+ seed: int | None = None
+
+ # Connection parameters
+ api_key: str | None = None
+ base_url: str | httpx.URL | None = 'https://api.cerebras.ai/v1'
+ timeout: float | httpx.Timeout | None = None
+ client_params: dict[str, Any] | None = None
+
+ @property
+ def provider(self) -> str:
+ return 'cerebras'
+
+ def _client(self) -> AsyncOpenAI:
+ return AsyncOpenAI(
+ api_key=self.api_key,
+ base_url=self.base_url,
+ timeout=self.timeout,
+ **(self.client_params or {}),
+ )
+
+ @property
+ def name(self) -> str:
+ return self.model
+
+ def _get_usage(self, response: ChatCompletion) -> ChatInvokeUsage | None:
+ if response.usage is not None:
+ usage = ChatInvokeUsage(
+ prompt_tokens=response.usage.prompt_tokens,
+ prompt_cached_tokens=None,
+ prompt_cache_creation_tokens=None,
+ prompt_image_tokens=None,
+ completion_tokens=response.usage.completion_tokens,
+ total_tokens=response.usage.total_tokens,
+ )
+ else:
+ usage = 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]:
+ """
+ Cerebras ainvoke supports:
+ 1. Regular text/multi-turn conversation
+ 2. JSON Output (response_format)
+ """
+ client = self._client()
+ cerebras_messages = CerebrasMessageSerializer.serialize_messages(messages)
+ common: dict[str, Any] = {}
+
+ if self.temperature is not None:
+ common['temperature'] = self.temperature
+ if self.max_tokens is not None:
+ common['max_tokens'] = self.max_tokens
+ if self.top_p is not None:
+ common['top_p'] = self.top_p
+ if self.seed is not None:
+ common['seed'] = self.seed
+
+ # ① Regular multi-turn conversation/text output
+ if output_format is None:
+ try:
+ resp = await client.chat.completions.create( # type: ignore
+ model=self.model,
+ messages=cerebras_messages, # type: ignore
+ **common,
+ )
+ usage = self._get_usage(resp)
+ return ChatInvokeCompletion(
+ completion=resp.choices[0].message.content or '',
+ usage=usage,
+ )
+ except RateLimitError as e:
+ raise ModelRateLimitError(str(e), model=self.name) from e
+ except (APIError, APIConnectionError, APITimeoutError, APIStatusError) as e:
+ raise ModelProviderError(str(e), model=self.name) from e
+ except Exception as e:
+ raise ModelProviderError(str(e), model=self.name) from e
+
+ # ② JSON Output path (response_format)
+ if output_format is not None and hasattr(output_format, 'model_json_schema'):
+ try:
+ # For Cerebras, we'll use a simpler approach without response_format
+ # Instead, we'll ask the model to return JSON and parse it
+ import json
+
+ # Get the schema to guide the model
+ schema = output_format.model_json_schema()
+ schema_str = json.dumps(schema, indent=2)
+
+ # Create a prompt that asks for the specific JSON structure
+ json_prompt = f"""
+Please respond with a JSON object that follows this exact schema:
+{schema_str}
+
+Your response must be valid JSON only, no other text.
+"""
+
+ # Add or modify the last user message to include the JSON prompt
+ if cerebras_messages and cerebras_messages[-1]['role'] == 'user':
+ if isinstance(cerebras_messages[-1]['content'], str):
+ cerebras_messages[-1]['content'] += json_prompt
+ elif isinstance(cerebras_messages[-1]['content'], list):
+ cerebras_messages[-1]['content'].append({'type': 'text', 'text': json_prompt})
+ else:
+ # Add as a new user message
+ cerebras_messages.append({
+ 'role': 'user',
+ 'content': json_prompt
+ })
+
+ resp = await client.chat.completions.create( # type: ignore
+ model=self.model,
+ messages=cerebras_messages, # type: ignore
+ **common,
+ )
+ content = resp.choices[0].message.content
+ if not content:
+ raise ModelProviderError('Empty JSON content in Cerebras response', model=self.name)
+
+ usage = self._get_usage(resp)
+
+ # Try to extract JSON from the response
+ import re
+ json_match = re.search(r'\{.*\}', content, re.DOTALL)
+ if json_match:
+ json_str = json_match.group(0)
+ else:
+ json_str = content
+
+ parsed = output_format.model_validate_json(json_str)
+ return ChatInvokeCompletion(
+ completion=parsed,
+ usage=usage,
+ )
+ except RateLimitError as e:
+ raise ModelRateLimitError(str(e), model=self.name) from e
+ except (APIError, APIConnectionError, APITimeoutError, APIStatusError) as e:
+ raise ModelProviderError(str(e), model=self.name) from e
+ except Exception as e:
+ raise ModelProviderError(str(e), model=self.name) from e
+
+ raise ModelProviderError('No valid ainvoke execution path for Cerebras LLM', model=self.name)
diff --git a/browser_use/llm/cerebras/serializer.py b/browser_use/llm/cerebras/serializer.py
new file mode 100644
index 000000000..d8e470f26
--- /dev/null
+++ b/browser_use/llm/cerebras/serializer.py
@@ -0,0 +1,109 @@
+from __future__ import annotations
+
+import json
+from typing import Any, overload
+
+from browser_use.llm.messages import (
+ AssistantMessage,
+ BaseMessage,
+ ContentPartImageParam,
+ ContentPartTextParam,
+ SystemMessage,
+ ToolCall,
+ UserMessage,
+)
+
+MessageDict = dict[str, Any]
+
+
+class CerebrasMessageSerializer:
+ """Serializer for converting browser-use messages to Cerebras messages."""
+
+ # -------- content 处理 --------------------------------------------------
+ @staticmethod
+ def _serialize_text_part(part: ContentPartTextParam) -> str:
+ return part.text
+
+ @staticmethod
+ def _serialize_image_part(part: ContentPartImageParam) -> dict[str, Any]:
+ url = part.image_url.url
+ if url.startswith('data:'):
+ return {'type': 'image_url', 'image_url': {'url': url}}
+ return {'type': 'image_url', 'image_url': {'url': url}}
+
+ @staticmethod
+ def _serialize_content(content: Any) -> str | list[dict[str, Any]]:
+ if content is None:
+ return ''
+ if isinstance(content, str):
+ return content
+ serialized: list[dict[str, Any]] = []
+ for part in content:
+ if part.type == 'text':
+ serialized.append({'type': 'text', 'text': CerebrasMessageSerializer._serialize_text_part(part)})
+ elif part.type == 'image_url':
+ serialized.append(CerebrasMessageSerializer._serialize_image_part(part))
+ elif part.type == 'refusal':
+ serialized.append({'type': 'text', 'text': f'[Refusal] {part.refusal}'})
+ return serialized
+
+ # -------- Tool-call 处理 -------------------------------------------------
+ @staticmethod
+ def _serialize_tool_calls(tool_calls: list[ToolCall]) -> list[dict[str, Any]]:
+ cerebras_tool_calls: list[dict[str, Any]] = []
+ for tc in tool_calls:
+ try:
+ arguments = json.loads(tc.function.arguments)
+ except json.JSONDecodeError:
+ arguments = {'arguments': tc.function.arguments}
+ cerebras_tool_calls.append(
+ {
+ 'id': tc.id,
+ 'type': 'function',
+ 'function': {
+ 'name': tc.function.name,
+ 'arguments': arguments,
+ },
+ }
+ )
+ return cerebras_tool_calls
+
+ # -------- 单条消息序列化 -------------------------------------------------
+ @overload
+ @staticmethod
+ def serialize(message: UserMessage) -> MessageDict: ...
+
+ @overload
+ @staticmethod
+ def serialize(message: SystemMessage) -> MessageDict: ...
+
+ @overload
+ @staticmethod
+ def serialize(message: AssistantMessage) -> MessageDict: ...
+
+ @staticmethod
+ def serialize(message: BaseMessage) -> MessageDict:
+ if isinstance(message, UserMessage):
+ return {
+ 'role': 'user',
+ 'content': CerebrasMessageSerializer._serialize_content(message.content),
+ }
+ if isinstance(message, SystemMessage):
+ return {
+ 'role': 'system',
+ 'content': CerebrasMessageSerializer._serialize_content(message.content),
+ }
+ if isinstance(message, AssistantMessage):
+ msg: MessageDict = {
+ 'role': 'assistant',
+ 'content': CerebrasMessageSerializer._serialize_content(message.content),
+ }
+ if message.tool_calls:
+ msg['tool_calls'] = CerebrasMessageSerializer._serialize_tool_calls(message.tool_calls)
+ return msg
+ raise ValueError(f'Unknown message type: {type(message)}')
+
+ # -------- 列表序列化 -----------------------------------------------------
+ @staticmethod
+ def serialize_messages(messages: list[BaseMessage]) -> list[MessageDict]:
+ return [CerebrasMessageSerializer.serialize(m) for m in messages]
diff --git a/browser_use/llm/models.py b/browser_use/llm/models.py
index d09cd4c36..0e30200bc 100644
--- a/browser_use/llm/models.py
+++ b/browser_use/llm/models.py
@@ -14,6 +14,7 @@ import os
from typing import TYPE_CHECKING
from browser_use.llm.azure.chat import ChatAzureOpenAI
+from browser_use.llm.cerebras.chat import ChatCerebras
from browser_use.llm.google.chat import ChatGoogle
from browser_use.llm.openai.chat import ChatOpenAI
@@ -53,6 +54,16 @@ google_gemini_2_5_pro: 'BaseChatModel'
google_gemini_2_5_flash: 'BaseChatModel'
google_gemini_2_5_flash_lite: 'BaseChatModel'
+cerebras_llama3_1_8b: 'BaseChatModel'
+cerebras_llama3_3_70b: 'BaseChatModel'
+cerebras_gpt_oss_120b: 'BaseChatModel'
+cerebras_llama_4_scout_17b_16e_instruct: 'BaseChatModel'
+cerebras_llama_4_maverick_17b_128e_instruct: 'BaseChatModel'
+cerebras_qwen_3_32b: 'BaseChatModel'
+cerebras_qwen_3_235b_a22b_instruct_2507: 'BaseChatModel'
+cerebras_qwen_3_235b_a22b_thinking_2507: 'BaseChatModel'
+cerebras_qwen_3_coder_480b: 'BaseChatModel'
+
def get_llm_by_name(model_name: str):
"""
@@ -89,6 +100,30 @@ def get_llm_by_name(model_name: str):
model = model_part.replace('gemini_2_0', 'gemini-2.0').replace('_', '-')
elif 'gemini_2_5' in model_part:
model = model_part.replace('gemini_2_5', 'gemini-2.5').replace('_', '-')
+ elif 'llama3_1' in model_part:
+ model = model_part.replace('llama3_1', 'llama3.1').replace('_', '-')
+ elif 'llama3_3' in model_part:
+ model = model_part.replace('llama3_3', 'llama-3.3').replace('_', '-')
+ elif 'llama_4_scout' in model_part:
+ model = model_part.replace('llama_4_scout', 'llama-4-scout').replace('_', '-')
+ elif 'llama_4_maverick' in model_part:
+ model = model_part.replace('llama_4_maverick', 'llama-4-maverick').replace('_', '-')
+ elif 'gpt_oss_120b' in model_part:
+ model = model_part.replace('gpt_oss_120b', 'gpt-oss-120b')
+ elif 'qwen_3_32b' in model_part:
+ model = model_part.replace('qwen_3_32b', 'qwen-3-32b')
+ elif 'qwen_3_235b_a22b_instruct' in model_part:
+ if model_part.endswith('_2507'):
+ model = model_part.replace('qwen_3_235b_a22b_instruct_2507', 'qwen-3-235b-a22b-instruct-2507')
+ else:
+ model = model_part.replace('qwen_3_235b_a22b_instruct', 'qwen-3-235b-a22b-instruct-2507')
+ elif 'qwen_3_235b_a22b_thinking' in model_part:
+ if model_part.endswith('_2507'):
+ model = model_part.replace('qwen_3_235b_a22b_thinking_2507', 'qwen-3-235b-a22b-thinking-2507')
+ else:
+ model = model_part.replace('qwen_3_235b_a22b_thinking', 'qwen-3-235b-a22b-thinking-2507')
+ elif 'qwen_3_coder_480b' in model_part:
+ model = model_part.replace('qwen_3_coder_480b', 'qwen-3-coder-480b')
else:
model = model_part.replace('_', '-')
@@ -108,8 +143,13 @@ def get_llm_by_name(model_name: str):
api_key = os.getenv('GOOGLE_API_KEY')
return ChatGoogle(model=model, api_key=api_key)
+ # Cerebras Models
+ elif provider == 'cerebras':
+ api_key = os.getenv('CEREBRAS_API_KEY')
+ return ChatCerebras(model=model, api_key=api_key)
+
else:
- available_providers = ['openai', 'azure', 'google']
+ available_providers = ['openai', 'azure', 'google', 'cerebras']
raise ValueError(f"Unknown provider: '{provider}'. Available providers: {', '.join(available_providers)}")
@@ -123,6 +163,8 @@ def __getattr__(name: str) -> 'BaseChatModel':
return ChatAzureOpenAI # type: ignore
elif name == 'ChatGoogle':
return ChatGoogle # type: ignore
+ elif name == 'ChatCerebras':
+ return ChatCerebras # type: ignore
# Handle model instances - these are the main use case
try:
@@ -135,6 +177,7 @@ __all__ = [
'ChatOpenAI',
'ChatAzureOpenAI',
'ChatGoogle',
+ 'ChatCerebras',
'get_llm_by_name',
# OpenAI instances - created on demand
'openai_gpt_4o',
@@ -168,4 +211,14 @@ __all__ = [
'google_gemini_2_5_pro',
'google_gemini_2_5_flash',
'google_gemini_2_5_flash_lite',
+ # Cerebras instances - created on demand
+ 'cerebras_llama3_1_8b',
+ 'cerebras_llama3_3_70b',
+ 'cerebras_gpt_oss_120b',
+ 'cerebras_llama_4_scout_17b_16e_instruct',
+ 'cerebras_llama_4_maverick_17b_128e_instruct',
+ 'cerebras_qwen_3_32b',
+ 'cerebras_qwen_3_235b_a22b_instruct_2507',
+ 'cerebras_qwen_3_235b_a22b_thinking_2507',
+ 'cerebras_qwen_3_coder_480b',
]
diff --git a/examples/models/cerebras_example.py b/examples/models/cerebras_example.py
new file mode 100644
index 000000000..77eb1bc98
--- /dev/null
+++ b/examples/models/cerebras_example.py
@@ -0,0 +1,77 @@
+"""
+Example of using Cerebras with browser-use.
+
+To use this example:
+1. Set your CEREBRAS_API_KEY environment variable
+2. Run this script
+
+Cerebras integration is working great for:
+- Direct text generation
+- Simple tasks without complex structured output
+- Fast inference for web automation
+
+Available Cerebras models (9 total):
+Small/Fast models (8B-32B):
+- cerebras_llama3_1_8b (8B parameters, fast)
+- cerebras_llama_4_scout_17b_16e_instruct (17B, instruction-tuned)
+- cerebras_llama_4_maverick_17b_128e_instruct (17B, extended context)
+- cerebras_qwen_3_32b (32B parameters)
+
+Large/Capable models (70B-480B):
+- cerebras_llama3_3_70b (70B parameters, latest version)
+- cerebras_gpt_oss_120b (120B parameters, OpenAI's model)
+- cerebras_qwen_3_235b_a22b_instruct_2507 (235B, instruction-tuned)
+- cerebras_qwen_3_235b_a22b_thinking_2507 (235B, complex reasoning)
+- cerebras_qwen_3_coder_480b (480B, code generation)
+
+Note: Cerebras has some limitations with complex structured output due to JSON schema compatibility.
+"""
+
+import os
+import asyncio
+from browser_use import Agent
+from browser_use.llm import ChatCerebras
+
+async def main():
+ # Set your API key (recommended to use environment variable)
+ api_key = os.getenv("CEREBRAS_API_KEY")
+ if not api_key:
+ raise ValueError("Please set CEREBRAS_API_KEY environment variable")
+
+ # Option 1: Use the pre-configured model instance (recommended)
+ from browser_use import llm
+
+ # Choose your model:
+ # Small/Fast models:
+ # model = llm.cerebras_llama3_1_8b # 8B, fast
+ # model = llm.cerebras_llama_4_scout_17b_16e_instruct # 17B, instruction-tuned
+ # model = llm.cerebras_llama_4_maverick_17b_128e_instruct # 17B, extended context
+ # model = llm.cerebras_qwen_3_32b # 32B
+
+ # Large/Capable models:
+ # model = llm.cerebras_llama3_3_70b # 70B, latest
+ # model = llm.cerebras_gpt_oss_120b # 120B, OpenAI's model
+ # model = llm.cerebras_qwen_3_235b_a22b_instruct_2507 # 235B, instruction-tuned
+ model = llm.cerebras_qwen_3_235b_a22b_thinking_2507 # 235B, complex reasoning
+ # model = llm.cerebras_qwen_3_coder_480b # 480B, code generation
+
+ # Option 2: Create the model instance directly
+ # model = ChatCerebras(
+ # model="qwen-3-coder-480b", # or any other model ID
+ # api_key=os.getenv("CEREBRAS_API_KEY"),
+ # temperature=0.2,
+ # max_tokens=4096,
+ # )
+
+ # Create and run the agent with a simple task
+ task = "Explain the concept of quantum entanglement in simple terms."
+ agent = Agent(task=task, llm=model)
+
+ print(f"Running task with Cerebras {model.name} (ID: {model.model}): {task}")
+ history = await agent.run(max_steps=3)
+ result = history.final_result()
+
+ print(f"Result: {result}")
+
+if __name__ == "__main__":
+ asyncio.run(main())