Skip to content

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

Add Vercel AI Gateway integration with ChatVercel model support

kalil03219096011c4dae
diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.py
index 9007559a5..e8b372097 100644
--- a/browser_use/llm/__init__.py
+++ b/browser_use/llm/__init__.py
@@ -39,6 +39,7 @@ if TYPE_CHECKING:
from browser_use.llm.ollama.chat import ChatOllama
from browser_use.llm.openai.chat import ChatOpenAI
from browser_use.llm.openrouter.chat import ChatOpenRouter
+ from browser_use.llm.vercel.chat import ChatVercel
# Type stubs for model instances - enables IDE autocomplete
openai_gpt_4o: ChatOpenAI
@@ -90,6 +91,7 @@ _LAZY_IMPORTS = {
'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'),
'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'),
'ChatOpenRouter': ('browser_use.llm.openrouter.chat', 'ChatOpenRouter'),
+ 'ChatVercel': ('browser_use.llm.vercel.chat', 'ChatVercel'),
}
# Cache for model instances - only created when accessed
@@ -151,5 +153,6 @@ __all__ = [
'ChatOCIRaw',
'ChatOllama',
'ChatOpenRouter',
+ 'ChatVercel',
'ChatCerebras',
]
diff --git a/browser_use/llm/vercel/__init__.py b/browser_use/llm/vercel/__init__.py
new file mode 100644
index 000000000..76df66d6e
--- /dev/null
+++ b/browser_use/llm/vercel/__init__.py
@@ -0,0 +1,3 @@
+from browser_use.llm.vercel.chat import ChatVercel
+
+__all__ = ['ChatVercel']
diff --git a/browser_use/llm/vercel/chat.py b/browser_use/llm/vercel/chat.py
new file mode 100644
index 000000000..6952abf27
--- /dev/null
+++ b/browser_use/llm/vercel/chat.py
@@ -0,0 +1,356 @@
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any, Literal, TypeAlias, TypeVar, overload
+
+import httpx
+from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError
+from openai.types.chat.chat_completion 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.exceptions import ModelProviderError, ModelRateLimitError
+from browser_use.llm.messages import BaseMessage
+from browser_use.llm.schema import SchemaOptimizer
+from browser_use.llm.vercel.serializer import VercelMessageSerializer
+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage
+
+T = TypeVar('T', bound=BaseModel)
+
+ChatVercelModel: TypeAlias = Literal[
+ 'alibaba/qwen-3-14b',
+ 'alibaba/qwen-3-235b',
+ 'alibaba/qwen-3-30b',
+ 'alibaba/qwen-3-32b',
+ 'alibaba/qwen3-coder',
+ 'alibaba/qwen3-coder-30b-a3b',
+ 'alibaba/qwen3-coder-plus',
+ 'alibaba/qwen3-max',
+ 'alibaba/qwen3-max-preview',
+ 'alibaba/qwen3-next-80b-a3b-instruct',
+ 'alibaba/qwen3-next-80b-a3b-thinking',
+ 'alibaba/qwen3-vl-instruct',
+ 'alibaba/qwen3-vl-thinking',
+ 'amazon/nova-lite',
+ 'amazon/nova-micro',
+ 'amazon/nova-pro',
+ 'amazon/titan-embed-text-v2',
+ 'anthropic/claude-3-haiku',
+ 'anthropic/claude-3-opus',
+ 'anthropic/claude-3.5-haiku',
+ 'anthropic/claude-3.5-sonnet',
+ 'anthropic/claude-3.5-sonnet-20240620',
+ 'anthropic/claude-3.7-sonnet',
+ 'anthropic/claude-haiku-4.5',
+ 'anthropic/claude-opus-4',
+ 'anthropic/claude-opus-4.1',
+ 'anthropic/claude-sonnet-4',
+ 'anthropic/claude-sonnet-4.5',
+ 'cohere/command-a',
+ 'cohere/command-r',
+ 'cohere/command-r-plus',
+ 'cohere/embed-v4.0',
+ 'deepseek/deepseek-r1',
+ 'deepseek/deepseek-r1-distill-llama-70b',
+ 'deepseek/deepseek-v3',
+ 'deepseek/deepseek-v3.1',
+ 'deepseek/deepseek-v3.1-base',
+ 'deepseek/deepseek-v3.1-terminus',
+ 'deepseek/deepseek-v3.2-exp',
+ 'deepseek/deepseek-v3.2-exp-thinking',
+ 'google/gemini-2.0-flash',
+ 'google/gemini-2.0-flash-lite',
+ 'google/gemini-2.5-flash',
+ 'google/gemini-2.5-flash-image',
+ 'google/gemini-2.5-flash-image-preview',
+ 'google/gemini-2.5-flash-lite',
+ 'google/gemini-2.5-flash-lite-preview-09-2025',
+ 'google/gemini-2.5-flash-preview-09-2025',
+ 'google/gemini-2.5-pro',
+ 'google/gemini-embedding-001',
+ 'google/gemma-2-9b',
+ 'google/text-embedding-005',
+ 'google/text-multilingual-embedding-002',
+ 'inception/mercury-coder-small',
+ 'meituan/longcat-flash-chat',
+ 'meituan/longcat-flash-thinking',
+ 'meta/llama-3-70b',
+ 'meta/llama-3-8b',
+ 'meta/llama-3.1-70b',
+ 'meta/llama-3.1-8b',
+ 'meta/llama-3.2-11b',
+ 'meta/llama-3.2-1b',
+ 'meta/llama-3.2-3b',
+ 'meta/llama-3.2-90b',
+ 'meta/llama-3.3-70b',
+ 'meta/llama-4-maverick',
+ 'meta/llama-4-scout',
+ 'mistral/codestral',
+ 'mistral/codestral-embed',
+ 'mistral/devstral-small',
+ 'mistral/magistral-medium',
+ 'mistral/magistral-medium-2506',
+ 'mistral/magistral-small',
+ 'mistral/magistral-small-2506',
+ 'mistral/ministral-3b',
+ 'mistral/ministral-8b',
+ 'mistral/mistral-embed',
+ 'mistral/mistral-large',
+ 'mistral/mistral-medium',
+ 'mistral/mistral-small',
+ 'mistral/mixtral-8x22b-instruct',
+ 'mistral/pixtral-12b',
+ 'mistral/pixtral-large',
+ 'moonshotai/kimi-k2',
+ 'moonshotai/kimi-k2-0905',
+ 'moonshotai/kimi-k2-turbo',
+ 'morph/morph-v3-fast',
+ 'morph/morph-v3-large',
+ 'openai/gpt-3.5-turbo',
+ 'openai/gpt-3.5-turbo-instruct',
+ 'openai/gpt-4-turbo',
+ 'openai/gpt-4.1',
+ 'openai/gpt-4.1-mini',
+ 'openai/gpt-4.1-nano',
+ 'openai/gpt-4o',
+ 'openai/gpt-4o-mini',
+ 'openai/gpt-5',
+ 'openai/gpt-5-codex',
+ 'openai/gpt-5-mini',
+ 'openai/gpt-5-nano',
+ 'openai/gpt-5-pro',
+ 'openai/gpt-oss-120b',
+ 'openai/gpt-oss-20b',
+ 'openai/o1',
+ 'openai/o3',
+ 'openai/o3-mini',
+ 'openai/o4-mini',
+ 'openai/text-embedding-3-large',
+ 'openai/text-embedding-3-small',
+ 'openai/text-embedding-ada-002',
+ 'perplexity/sonar',
+ 'perplexity/sonar-pro',
+ 'perplexity/sonar-reasoning',
+ 'perplexity/sonar-reasoning-pro',
+ 'stealth/sonoma-dusk-alpha',
+ 'stealth/sonoma-sky-alpha',
+ 'vercel/v0-1.0-md',
+ 'vercel/v0-1.5-md',
+ 'voyage/voyage-3-large',
+ 'voyage/voyage-3.5',
+ 'voyage/voyage-3.5-lite',
+ 'voyage/voyage-code-2',
+ 'voyage/voyage-code-3',
+ 'voyage/voyage-finance-2',
+ 'voyage/voyage-law-2',
+ 'xai/grok-2',
+ 'xai/grok-2-vision',
+ 'xai/grok-3',
+ 'xai/grok-3-fast',
+ 'xai/grok-3-mini',
+ 'xai/grok-3-mini-fast',
+ 'xai/grok-4',
+ 'xai/grok-4-fast-non-reasoning',
+ 'xai/grok-4-fast-reasoning',
+ 'xai/grok-code-fast-1',
+ 'zai/glm-4.5',
+ 'zai/glm-4.5-air',
+ 'zai/glm-4.5v',
+ 'zai/glm-4.6',
+]
+
+
+@dataclass
+class ChatVercel(BaseChatModel):
+ """
+ A wrapper around Vercel AI Gateway's API, which provides OpenAI-compatible access
+ to various LLM models with features like rate limiting, caching, and monitoring.
+
+ Examples:
+ ```python
+ from browser_use import Agent, ChatVercel
+
+ llm = ChatVercel(model='openai/gpt-4o', api_key='your_vercel_api_key')
+
+ agent = Agent(task='Your task here', llm=llm)
+ ```
+
+ Args:
+ model: The model identifier
+ api_key: Your Vercel API key
+ base_url: The Vercel AI Gateway endpoint (defaults to https://ai-gateway.vercel.sh/v1)
+ temperature: Sampling temperature (0-2)
+ max_tokens: Maximum tokens to generate
+ timeout: Request timeout in seconds
+ max_retries: Maximum number of retries for failed requests
+ """
+
+ # Model configuration
+ model: ChatVercelModel | str
+
+ # Model params
+ temperature: float | None = None
+ max_tokens: int | None = None
+ top_p: float | None = None
+
+ # Client initialization parameters
+ api_key: str | None = None
+ base_url: str | httpx.URL = 'https://ai-gateway.vercel.sh/v1'
+ timeout: float | httpx.Timeout | None = None
+ max_retries: int = 5
+ default_headers: Mapping[str, str] | None = None
+ default_query: Mapping[str, object] | None = None
+ http_client: httpx.AsyncClient | None = None
+ _strict_response_validation: bool = False
+
+ # Static
+ @property
+ def provider(self) -> str:
+ return 'vercel'
+
+ def _get_client_params(self) -> dict[str, Any]:
+ """Prepare client parameters dictionary."""
+ base_params = {
+ 'api_key': self.api_key,
+ 'base_url': self.base_url,
+ 'timeout': self.timeout,
+ 'max_retries': self.max_retries,
+ 'default_headers': self.default_headers,
+ 'default_query': self.default_query,
+ '_strict_response_validation': self._strict_response_validation,
+ }
+
+ client_params = {k: v for k, v in base_params.items() if v is not None}
+
+ if self.http_client is not None:
+ client_params['http_client'] = self.http_client
+
+ return client_params
+
+ def get_client(self) -> AsyncOpenAI:
+ """
+ Returns an AsyncOpenAI client configured for Vercel AI Gateway.
+
+ Returns:
+ AsyncOpenAI: An instance of the AsyncOpenAI client with Vercel base URL.
+ """
+ if not hasattr(self, '_client'):
+ client_params = self._get_client_params()
+ self._client = AsyncOpenAI(**client_params)
+ return self._client
+
+ @property
+ def name(self) -> str:
+ return str(self.model)
+
+ def _get_usage(self, response: ChatCompletion) -> ChatInvokeUsage | None:
+ """Extract usage information from the Vercel response."""
+ if response.usage is None:
+ return None
+
+ prompt_details = getattr(response.usage, 'prompt_tokens_details', None)
+ cached_tokens = prompt_details.cached_tokens if prompt_details else None
+
+ return ChatInvokeUsage(
+ prompt_tokens=response.usage.prompt_tokens,
+ prompt_cached_tokens=cached_tokens,
+ prompt_cache_creation_tokens=None,
+ prompt_image_tokens=None,
+ completion_tokens=response.usage.completion_tokens,
+ total_tokens=response.usage.total_tokens,
+ )
+
+ @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 model with the given messages through Vercel AI Gateway.
+
+ 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
+ """
+ vercel_messages = VercelMessageSerializer.serialize_messages(messages)
+
+ try:
+ model_params: dict[str, Any] = {}
+ if self.temperature is not None:
+ model_params['temperature'] = self.temperature
+ if self.max_tokens is not None:
+ model_params['max_tokens'] = self.max_tokens
+ if self.top_p is not None:
+ model_params['top_p'] = self.top_p
+
+ if output_format is None:
+ # Return string response
+ response = await self.get_client().chat.completions.create(
+ model=self.model,
+ messages=vercel_messages,
+ **model_params,
+ )
+
+ usage = self._get_usage(response)
+ return ChatInvokeCompletion(
+ completion=response.choices[0].message.content or '',
+ usage=usage,
+ )
+
+ else:
+ # Create a JSON schema for structured output
+ schema = SchemaOptimizer.create_optimized_json_schema(output_format)
+
+ response_format_schema: JSONSchema = {
+ 'name': 'agent_output',
+ 'strict': True,
+ 'schema': schema,
+ }
+
+ # Return structured response
+ response = await self.get_client().chat.completions.create(
+ model=self.model,
+ messages=vercel_messages,
+ response_format=ResponseFormatJSONSchema(
+ json_schema=response_format_schema,
+ type='json_schema',
+ ),
+ **model_params,
+ )
+
+ if response.choices[0].message.content is None:
+ raise ModelProviderError(
+ message='Failed to parse structured output from model response',
+ status_code=500,
+ model=self.name,
+ )
+
+ usage = self._get_usage(response)
+ parsed = output_format.model_validate_json(response.choices[0].message.content)
+
+ return ChatInvokeCompletion(
+ completion=parsed,
+ usage=usage,
+ )
+
+ except RateLimitError as e:
+ raise ModelRateLimitError(message=e.message, model=self.name) from e
+
+ except APIConnectionError as e:
+ raise ModelProviderError(message=str(e), 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 e
diff --git a/browser_use/llm/vercel/serializer.py b/browser_use/llm/vercel/serializer.py
new file mode 100644
index 000000000..d89596fb6
--- /dev/null
+++ b/browser_use/llm/vercel/serializer.py
@@ -0,0 +1,26 @@
+from openai.types.chat import ChatCompletionMessageParam
+
+from browser_use.llm.messages import BaseMessage
+from browser_use.llm.openai.serializer import OpenAIMessageSerializer
+
+
+class VercelMessageSerializer:
+ """
+ Serializer for converting between custom message types and Vercel AI Gateway message formats.
+
+ Vercel AI Gateway uses the OpenAI-compatible API, so we can reuse the OpenAI serializer.
+ """
+
+ @staticmethod
+ def serialize_messages(messages: list[BaseMessage]) -> list[ChatCompletionMessageParam]:
+ """
+ Serialize a list of browser_use messages to Vercel AI Gateway-compatible messages.
+
+ Args:
+ messages: List of browser_use messages
+
+ Returns:
+ List of Vercel AI Gateway-compatible messages (identical to OpenAI format)
+ """
+ # Vercel AI Gateway uses the same message format as OpenAI
+ return OpenAIMessageSerializer.serialize_messages(messages)
diff --git a/docs/supported-models.mdx b/docs/supported-models.mdx
index d2161e714..5481e58e1 100644
--- a/docs/supported-models.mdx
+++ b/docs/supported-models.mdx
@@ -329,6 +329,42 @@ Required environment variables:
MODELSCOPE_API_KEY=
```
+### Vercel AI Gateway [example](https://github.com/browser-use/browser-use/blob/main/examples/models/vercel_ai_gateway.py)
+
+Vercel AI Gateway provides an OpenAI-compatible API endpoint that acts as a proxy to various AI providers, with features like rate limiting, caching, and monitoring.
+
+To see all available models, visit: https://ai-gateway.vercel.sh/v1/models
+
+```python
+from browser_use import Agent, ChatVercel
+from dotenv import load_dotenv
+import os
+
+load_dotenv()
+
+# Get API key (https://vercel.com/ai-gateway)
+api_key = os.getenv('VERCEL_API_KEY')
+if not api_key:
+ raise ValueError('VERCEL_API_KEY is not set')
+
+# Use Vercel AI Gateway
+llm = ChatVercel(
+ model='openai/gpt-4o',
+ api_key=api_key,
+)
+
+agent = Agent(
+ task="Your task here",
+ llm=llm
+)
+```
+
+Required environment variables:
+
+```bash .env
+VERCEL_API_KEY=
+```
+
## Other models (DeepSeek, Novita, X...)
We support all other models that can be called via OpenAI compatible API. We are open to PRs for more providers.
diff --git a/examples/models/vercel_ai_gateway.py b/examples/models/vercel_ai_gateway.py
new file mode 100644
index 000000000..977539a6c
--- /dev/null
+++ b/examples/models/vercel_ai_gateway.py
@@ -0,0 +1,43 @@
+"""
+Example using Vercel AI Gateway with browser-use.
+
+Vercel AI Gateway provides an OpenAI-compatible API endpoint that can proxy
+requests to various AI providers. This allows you to use Vercel's infrastructure
+for rate limiting, caching, and monitoring.
+
+Prerequisites:
+1. Set VERCEL_API_KEY in your environment variables
+
+To see all available models, visit: https://ai-gateway.vercel.sh/v1/models
+"""
+
+import asyncio
+import os
+
+from dotenv import load_dotenv
+
+from browser_use import Agent, ChatVercel
+
+load_dotenv()
+
+api_key = os.getenv('VERCEL_API_KEY')
+if not api_key:
+ raise ValueError('VERCEL_API_KEY is not set')
+
+llm = ChatVercel(
+ model='openai/gpt-4o',
+ api_key=api_key,
+)
+
+agent = Agent(
+ task='Go to example.com and summarize the main content',
+ llm=llm,
+)
+
+
+async def main():
+ await agent.run(max_steps=10)
+
+
+if __name__ == '__main__':
+ asyncio.run(main())