Skip to content

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

primitive skills impl (with cookies)

Gregor Žuničb1e4d6e6868f
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 99034c2a3..7e7af5591 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -298,6 +298,7 @@ class MessageManager:
page_filtered_actions: str | None = None,
sensitive_data=None,
available_file_paths: list[str] | None = None, # Always pass current available_file_paths
+ unavailable_skills_info: str | None = None, # Information about skills that cannot be used yet
) -> None:
"""Create single state message with all content"""
@@ -364,6 +365,7 @@ class MessageManager:
sample_images=self.sample_images,
read_state_images=self.state.read_state_images,
llm_screenshot_size=self.llm_screenshot_size,
+ unavailable_skills_info=unavailable_skills_info,
).get_user_message(effective_use_vision)
# Store state message text for history
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 0c8c8e63b..f201a58a1 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -90,6 +90,7 @@ class AgentMessagePrompt:
sample_images: list[ContentPartTextParam | ContentPartImageParam] | None = None,
read_state_images: list[dict] | None = None,
llm_screenshot_size: tuple[int, int] | None = None,
+ unavailable_skills_info: str | None = None,
):
self.browser_state: 'BrowserStateSummary' = browser_state_summary
self.file_system: 'FileSystem | None' = file_system
@@ -107,6 +108,7 @@ class AgentMessagePrompt:
self.include_recent_events = include_recent_events
self.sample_images = sample_images or []
self.read_state_images = read_state_images or []
+ self.unavailable_skills_info: str | None = unavailable_skills_info
self.llm_screenshot_size = llm_screenshot_size
assert self.browser_state
@@ -377,6 +379,10 @@ Available tabs:
state_description += self.page_filtered_actions + '\n'
state_description += '</page_specific_actions>\n'
+ # Add unavailable skills information if any
+ if self.unavailable_skills_info:
+ state_description += '\n' + self.unavailable_skills_info + '\n'
+
# Sanitize surrogates from all text content
state_description = sanitize_surrogates(state_description)
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 7a95d5a57..dbdfeb960 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -8,9 +8,12 @@ import tempfile
import time
from collections.abc import Awaitable, Callable
from pathlib import Path
-from typing import Any, Generic, Literal, TypeVar
+from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
from urllib.parse import urlparse
+if TYPE_CHECKING:
+ from browser_use.skills.views import Skill
+
from dotenv import load_dotenv
from browser_use.agent.cloud_events import (
@@ -135,7 +138,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
tools: Tools[Context] | None = None,
controller: Tools[Context] | None = None, # Alias for tools
# Skills integration
- skill_ids: list[str] | None = None,
+ skill_ids: list[str | Literal['*']] | None = None,
# Initial agent run parameters
sensitive_data: dict[str, str | dict[str, str]] | None = None,
initial_actions: list[dict[str, dict[str, Any]]] | None = None,
@@ -705,12 +708,31 @@ class Agent(Generic[Context, AgentStructuredOutput]):
else:
self.DoneAgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.DoneActionModel)
+ def _get_skill_display_name(self, skill: 'Skill', all_skills: list['Skill']) -> str:
+ """Get display name for a skill, adding UUID suffix if there are duplicates
+
+ Args:
+ skill: The skill to get display name for
+ all_skills: List of all skills to check for duplicates
+
+ Returns:
+ Display name with UUID[:4] suffix if title is duplicated
+ """
+ # Count how many skills have the same title
+ same_title_count = sum(1 for s in all_skills if s.title == skill.title)
+
+ if same_title_count > 1:
+ # Add UUID suffix for disambiguation
+ return f'{skill.title} [{skill.id[:4]}]'
+ else:
+ return skill.title
+
async def _register_skills_as_actions(self) -> None:
- """Register all skills from SkillService as actions in the tools registry"""
+ """Register a single 'skill' action that can execute any loaded skill"""
if not self.skill_service or self._skills_registered:
return
- self.logger.info('🔧 Registering skills as actions...')
+ self.logger.info('🔧 Registering unified skill action...')
# Fetch all skills (auto-initializes if needed)
skills = await self.skill_service.get_all_skills()
@@ -719,56 +741,183 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.logger.warning('No skills loaded from SkillService')
return
- # Register each skill as an action
+ # Build a description that lists all available skills with disambiguated names and parameters
+ skill_entries = []
for skill in skills:
- # Create a unique action name from skill title (lowercase, replace spaces with underscores)
- action_name = skill.title.lower().replace(' ', '_').replace('-', '_')
- # Remove any non-alphanumeric characters except underscores
- action_name = ''.join(c for c in action_name if c.isalnum() or c == '_')
-
- # Get the skill's pydantic parameter model
- param_model = skill.parameters_pydantic
-
- # Create the skill handler function
- # We need to capture skill.id in the closure
- def create_skill_handler(skill_id: str, skill_title: str):
- async def skill_handler(params: BaseModel) -> ActionResult:
- """Execute skill and return result"""
- assert self.skill_service is not None, 'SkillService not initialized'
-
- try:
- result = await self.skill_service.execute_skill(skill_id=skill_id, parameters=params)
-
- if result.success:
- return ActionResult(
- extracted_content=str(result.result) if result.result else None,
- error=None,
- )
- else:
- return ActionResult(extracted_content=None, error=result.error or 'Skill execution failed')
- except Exception as e:
- return ActionResult(extracted_content=None, error=f'Skill execution error: {type(e).__name__}: {e}')
+ display_name = self._get_skill_display_name(skill, skills)
+ # Get non-cookie parameters
+ non_cookie_params = [p for p in skill.parameters if p.type != 'cookie']
+ if non_cookie_params:
+ params_desc = ', '.join(
+ [
+ f'{p.name} ({p.type}, {"required" if p.required else "optional"}): {p.description}'
+ for p in non_cookie_params
+ ]
+ )
+ skill_entries.append(f' - {display_name}: {skill.description}\n Parameters: {params_desc}')
+ else:
+ skill_entries.append(f' - {display_name}: {skill.description}')
+
+ skill_list = '\n'.join(skill_entries)
+ skill_action_description = f'Execute a skill from the Browser Use skill library.\n\nAvailable skills:\n{skill_list}'
+
+ # Create parameter model for the unified skill action
+ from pydantic import Field, create_model
+
+ # Create the skill data model (no outer wrapper needed - action registry wraps it)
+ # Use string type for parameters to avoid OpenAI strict mode constraints - LLM outputs JSON as string
+ SkillData = create_model(
+ 'SkillData',
+ name=(str, Field(..., description='The name of the skill to execute (as shown in the available skills list)')),
+ parameters=(
+ str,
+ Field(
+ ...,
+ description='The parameters for the skill as a JSON string (e.g., "{\\"repo\\": \\"browser-use/browser-use\\"}")',
+ ),
+ ),
+ __base__=BaseModel,
+ )
+
+ # Create the skill handler function
+ async def skill_handler(params: BaseModel) -> ActionResult:
+ """Execute any skill based on skill name"""
+ assert self.skill_service is not None, 'SkillService not initialized'
+
+ # Extract skill data directly (action registry already wraps with 'skill' key)
+ skill_name = getattr(params, 'name')
+ skill_params_str = getattr(params, 'parameters')
- return skill_handler
+ # Parse parameters from JSON string
+ import json
- # Register the skill as an action
- handler = create_skill_handler(skill.id, skill.title)
+ try:
+ skill_params = json.loads(skill_params_str) if isinstance(skill_params_str, str) else skill_params_str
+ except json.JSONDecodeError as e:
+ return ActionResult(extracted_content=None, error=f'Invalid JSON in parameters: {e}')
+
+ # Look up skill by display name
+ all_skills = await self.skill_service.get_all_skills()
+ matching_skill = None
+ for skill in all_skills:
+ if self._get_skill_display_name(skill, all_skills) == skill_name:
+ matching_skill = skill
+ break
- # Set the function name to the unique action name
- handler.__name__ = action_name
+ if matching_skill is None:
+ available_names = [self._get_skill_display_name(s, all_skills) for s in all_skills]
+ return ActionResult(
+ extracted_content=None,
+ error=f'Skill "{skill_name}" not found. Available skills: {", ".join(available_names)}',
+ )
- # Use the registry's action decorator
- self.tools.registry.action(description=skill.description, param_model=param_model)(handler)
+ _cookies = await self.browser_session.cookies()
- self.logger.info(f' ✓ Registered skill: {skill.title} (action: {action_name})')
+ try:
+ result = await self.skill_service.execute_skill(
+ skill_id=matching_skill.id, parameters=skill_params, cookies=_cookies
+ )
+
+ if result.success:
+ return ActionResult(
+ extracted_content=str(result.result) if result.result else None,
+ error=None,
+ )
+ else:
+ return ActionResult(extracted_content=None, error=result.error or 'Skill execution failed')
+ except Exception as e:
+ # Check if it's a MissingCookieException
+ if type(e).__name__ == 'MissingCookieException':
+ # Format: "Missing cookies (name): description"
+ cookie_name = getattr(e, 'cookie_name', 'unknown')
+ cookie_description = getattr(e, 'cookie_description', str(e))
+ error_msg = f'Missing cookies ({cookie_name}): {cookie_description}'
+ return ActionResult(extracted_content=None, error=error_msg)
+ return ActionResult(extracted_content=None, error=f'Skill execution error: {type(e).__name__}: {e}')
+
+ # Register the unified skill action
+ skill_handler.__name__ = 'skill'
+ self.tools.registry.action(description=skill_action_description, param_model=SkillData)(skill_handler)
# Mark as registered
self._skills_registered = True
- # Rebuild action models to include the new skills
+ # Rebuild action models to include the new skill action
self._setup_action_models()
- self.logger.info(f'✓ Registered {len(skills)} skills as actions')
+ self.logger.info(f'✓ Registered unified skill action with {len(skills)} available skills')
+
+ async def _get_unavailable_skills_info(self) -> str:
+ """Get information about skills that are unavailable due to missing cookies
+
+ Returns:
+ Formatted string describing unavailable skills and how to make them available
+ """
+ if not self.skill_service:
+ return ''
+
+ try:
+ # Get all skills
+ skills = await self.skill_service.get_all_skills()
+ if not skills:
+ return ''
+
+ # Get current cookies
+ current_cookies = await self.browser_session.cookies()
+ cookie_dict = {cookie['name']: cookie['value'] for cookie in current_cookies}
+
+ # Check each skill for missing required cookies
+ unavailable_skills: list[dict[str, Any]] = []
+
+ for skill in skills:
+ # Get cookie parameters for this skill
+ cookie_params = [p for p in skill.parameters if p.type == 'cookie']
+
+ if not cookie_params:
+ # No cookies needed, skip
+ continue
+
+ # Check for missing required cookies
+ missing_cookies: list[dict[str, str]] = []
+ for cookie_param in cookie_params:
+ is_required = cookie_param.required if cookie_param.required is not None else True
+
+ if is_required and cookie_param.name not in cookie_dict:
+ missing_cookies.append(
+ {'name': cookie_param.name, 'description': cookie_param.description or 'No description provided'}
+ )
+
+ if missing_cookies:
+ unavailable_skills.append(
+ {
+ 'id': skill.id,
+ 'title': skill.title,
+ 'description': skill.description,
+ 'missing_cookies': missing_cookies,
+ }
+ )
+
+ if not unavailable_skills:
+ return ''
+
+ # Format the unavailable skills info with disambiguated names
+ lines = ['Unavailable Skills (missing required cookies):']
+ for skill_info in unavailable_skills:
+ # Get the full skill object to use the display name helper
+ skill_obj = next((s for s in skills if s.id == skill_info['id']), None)
+ display_name = self._get_skill_display_name(skill_obj, skills) if skill_obj else skill_info['title']
+
+ lines.append(f'\n • {display_name}')
+ lines.append(f' Description: {skill_info["description"]}')
+ lines.append(' Missing cookies:')
+ for cookie in skill_info['missing_cookies']:
+ lines.append(f' - {cookie["name"]}: {cookie["description"]}')
+
+ return '\n'.join(lines)
+
+ except Exception as e:
+ self.logger.error(f'Error getting unavailable skills info: {type(e).__name__}: {e}')
+ return ''
def add_new_task(self, new_task: str) -> None:
"""Add a new task to the agent, keeping the same task_id as tasks are continuous"""
@@ -868,6 +1017,11 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Page-specific actions will be included directly in the browser_state message
self.logger.debug(f'💬 Step {self.state.n_steps}: Creating state messages for context...')
+ # Get unavailable skills info if skills service is enabled
+ unavailable_skills_info = None
+ if self.skill_service is not None:
+ unavailable_skills_info = await self._get_unavailable_skills_info()
+
self._message_manager.create_state_messages(
browser_state_summary=browser_state_summary,
model_output=self.state.last_model_output,
@@ -877,6 +1031,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
page_filtered_actions=page_filtered_actions if page_filtered_actions else None,
sensitive_data=self.sensitive_data,
available_file_paths=self.available_file_paths, # Always pass current available_file_paths
+ unavailable_skills_info=unavailable_skills_info,
)
await self._force_done_after_last_step(step_info)
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index b8b8d4419..381da90cb 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1154,15 +1154,10 @@ class BrowserSession(BaseModel):
params: CloseTargetParameters = {'targetId': target_id}
await self.cdp_client.send.Target.closeTarget(params)
- async def cookies(self, urls: list[str] | None = None) -> list['Cookie']:
+ async def cookies(self) -> list['Cookie']:
"""Get cookies, optionally filtered by URLs."""
- from cdp_use.cdp.network.library import GetCookiesParameters
- params: GetCookiesParameters = {}
- if urls:
- params['urls'] = urls
-
- result = await self.cdp_client.send.Network.getCookies(params)
+ result = await self.cdp_client.send.Storage.getCookies()
return result['cookies']
async def clear_cookies(self) -> None:
diff --git a/browser_use/skills/__init__.py b/browser_use/skills/__init__.py
index 3983a21cc..92bab595c 100644
--- a/browser_use/skills/__init__.py
+++ b/browser_use/skills/__init__.py
@@ -1,3 +1,4 @@
from browser_use.skills.service import SkillService
+from browser_use.skills.views import MissingCookieException
-__all__ = ['SkillService']
+__all__ = ['SkillService', 'MissingCookieException']
diff --git a/browser_use/skills/service.py b/browser_use/skills/service.py
index 8c50cd6c3..cda920dd8 100644
--- a/browser_use/skills/service.py
+++ b/browser_use/skills/service.py
@@ -1,14 +1,19 @@
"""Skills service for fetching and executing skills from the Browser Use API"""
-import asyncio
import logging
import os
-from typing import Any
+from typing import Any, Literal
from browser_use_sdk import AsyncBrowserUse
+from browser_use_sdk.types.execute_skill_response import ExecuteSkillResponse
+from browser_use_sdk.types.skill_list_response import SkillListResponse
+from cdp_use.cdp.network import Cookie
from pydantic import BaseModel, ValidationError
-from browser_use.skills.views import ExecuteSkillResponse, Skill, SkillResponse
+from browser_use.skills.views import (
+ MissingCookieException,
+ Skill,
+)
logger = logging.getLogger(__name__)
@@ -16,11 +21,11 @@ logger = logging.getLogger(__name__)
class SkillService:
"""Service for managing and executing skills from the Browser Use API"""
- def __init__(self, skill_ids: list[str], api_key: str | None = None):
+ def __init__(self, skill_ids: list[str | Literal['*']], api_key: str | None = None):
"""Initialize the skills service
Args:
- skill_ids: List of skill IDs to fetch and cache
+ skill_ids: List of skill IDs to fetch and cache, or ['*'] to fetch all available skills
api_key: Browser Use API key (optional, will use env var if not provided)
"""
self.skill_ids = skill_ids
@@ -34,9 +39,10 @@ class SkillService:
self._initialized = False
async def async_init(self) -> None:
- """Async initialization to fetch all skills concurrently
+ """Async initialization to fetch all skills at once
This should be called after __init__ to fetch and cache all skills.
+ Fetches all available skills in one API call and filters based on skill_ids.
"""
if self._initialized:
logger.debug('SkillService already initialized')
@@ -45,55 +51,52 @@ class SkillService:
# Create the SDK client
self._client = AsyncBrowserUse(api_key=self.api_key)
- # Fetch all skills concurrently
- logger.info(f'Fetching {len(self.skill_ids)} skills from Browser Use API...')
-
- fetch_tasks = [self._fetch_skill(skill_id) for skill_id in self.skill_ids]
- results = await asyncio.gather(*fetch_tasks, return_exceptions=True)
-
- # Process results
- for skill_id, result in zip(self.skill_ids, results):
- if isinstance(result, Exception):
- logger.error(f'Failed to fetch skill {skill_id}: {result}')
- elif isinstance(result, Skill):
- self._skills[skill_id] = result
- logger.debug(f'Cached skill: {result.title} ({skill_id})')
-
- logger.info(f'Successfully loaded {len(self._skills)}/{len(self.skill_ids)} skills')
- self._initialized = True
-
- async def _fetch_skill(self, skill_id: str) -> Skill | None:
- """Fetch a single skill from the API and convert to Skill model
-
- Args:
- skill_id: The UUID of the skill to fetch
-
- Returns:
- Skill model or None if fetch failed
- """
- assert self._client is not None, 'Client not initialized - call async_init() first'
-
try:
- # Fetch skill details from API (returns SkillResponse from SDK)
- skill_response: SkillResponse = await self._client.skills.get_skill(skill_id=skill_id)
+ # Fetch all skills from API in one call
+ logger.info('Fetching all available skills from Browser Use API...')
+ skills_response: SkillListResponse = await self._client.skills.list_skills(
+ page_size=100
+ ) # max size is 100, assuming users have less than 100 skills
- # Check if skill is finished and enabled
- if skill_response.status != 'finished':
- logger.warning(f'Skill {skill_id} is not finished (status: {skill_response.status})')
- return None
+ # Filter to only enabled and finished skills
+ all_available_skills = [skill for skill in skills_response.items if skill.is_enabled and skill.status == 'finished']
- if not skill_response.is_enabled:
- logger.warning(f'Skill {skill_id} is not enabled')
- return None
+ logger.info(f'Found {len(all_available_skills)} available skills from API')
- # Convert SDK SkillResponse to our Skill model with helper properties
- skill = Skill.from_skill_response(skill_response)
+ # Determine which skills to load
+ use_wildcard = '*' in self.skill_ids
- return skill
+ if use_wildcard:
+ logger.info('Wildcard "*" detected, loading all available skills')
+ # Load all available skills
+ skills_to_load = all_available_skills
+ else:
+ # Load only the requested skill IDs
+ requested_ids = set(self.skill_ids)
+ skills_to_load = [skill for skill in all_available_skills if skill.id in requested_ids]
+
+ # Warn about any requested skills that weren't found
+ found_ids = {skill.id for skill in skills_to_load}
+ missing_ids = requested_ids - found_ids
+ if missing_ids:
+ logger.warning(f'Requested skills not found or not available: {missing_ids}')
+
+ # Convert SDK SkillResponse objects to our Skill models and cache them
+ for skill_response in skills_to_load:
+ try:
+ skill = Skill.from_skill_response(skill_response)
+ self._skills[skill.id] = skill
+ logger.debug(f'Cached skill: {skill.title} ({skill.id})')
+ except Exception as e:
+ logger.error(f'Failed to convert skill {skill_response.id}: {type(e).__name__}: {e}')
+
+ logger.info(f'Successfully loaded {len(self._skills)} skills')
+ self._initialized = True
except Exception as e:
- logger.error(f'Error fetching skill {skill_id}: {type(e).__name__}: {e}')
- return None
+ logger.error(f'Error during skill initialization: {type(e).__name__}: {e}')
+ self._initialized = True # Mark as initialized even on failure to avoid retry loops
+ raise
async def get_skill(self, skill_id: str) -> Skill | None:
"""Get a cached skill by ID. Auto-initializes if not already initialized.
@@ -120,7 +123,9 @@ class SkillService:
return list(self._skills.values())
- async def execute_skill(self, skill_id: str, parameters: dict[str, Any] | BaseModel) -> ExecuteSkillResponse:
+ async def execute_skill(
+ self, skill_id: str, parameters: dict[str, Any] | BaseModel, cookies: list[Cookie]
+ ) -> ExecuteSkillResponse:
"""Execute a skill with the provided parameters. Auto-initializes if not already initialized.
Parameters are validated against the skill's Pydantic schema before execution.
@@ -147,8 +152,40 @@ class SkillService:
if skill is None:
raise ValueError(f'Skill {skill_id} not found in cache. Available skills: {list(self._skills.keys())}')
+ # Extract cookie parameters from the skill
+ cookie_params = [p for p in skill.parameters if p.type == 'cookie']
+
+ # Build a dict of cookies from the provided cookie list
+ cookie_dict: dict[str, str] = {cookie['name']: cookie['value'] for cookie in cookies}
+
+ # Check for missing required cookies and fill cookie values
+ if cookie_params:
+ for cookie_param in cookie_params:
+ is_required = cookie_param.required if cookie_param.required is not None else True
+
+ if is_required and cookie_param.name not in cookie_dict:
+ # Required cookie is missing - raise exception with description
+ raise MissingCookieException(
+ cookie_name=cookie_param.name, cookie_description=cookie_param.description or 'No description provided'
+ )
+
+ # Fill in cookie values into parameters
+ # Convert parameters to dict first if it's a BaseModel
+ if isinstance(parameters, BaseModel):
+ params_dict = parameters.model_dump()
+ else:
+ params_dict = dict(parameters)
+
+ # Add cookie values to parameters
+ for cookie_param in cookie_params:
+ if cookie_param.name in cookie_dict:
+ params_dict[cookie_param.name] = cookie_dict[cookie_param.name]
+
+ # Replace parameters with the updated dict
+ parameters = params_dict
+
# Get the skill's pydantic model for parameter validation
- ParameterModel = skill.parameters_pydantic
+ ParameterModel = skill.parameters_pydantic(exclude_cookies=False)
# Validate and convert parameters to dict
validated_params_dict: dict[str, Any]
diff --git a/browser_use/skills/views.py b/browser_use/skills/views.py
index 604d499db..9c44376bf 100644
--- a/browser_use/skills/views.py
+++ b/browser_use/skills/views.py
@@ -2,25 +2,23 @@
from typing import Any
-from browser_use_sdk.types import (
- app_api_v2skills_views_parameter_schema as parameter_schema_module,
-)
-from browser_use_sdk.types import (
- app_api_v2skills_views_parameter_type as parameter_type_module,
-)
-from browser_use_sdk.types import (
- execute_skill_response,
- skill_response,
- skills_generation_status,
-)
+from browser_use_sdk.types.parameter_schema import ParameterSchema
+from browser_use_sdk.types.skill_response import SkillResponse
from pydantic import BaseModel, ConfigDict, Field
-# Re-export SDK types for convenience
-SkillsGenerationStatus = skills_generation_status.SkillsGenerationStatus
-ParameterType = parameter_type_module.AppApiV2SkillsViewsParameterType
-ParameterSchema = parameter_schema_module.AppApiV2SkillsViewsParameterSchema
-SkillResponse = skill_response.SkillResponse
-ExecuteSkillResponse = execute_skill_response.ExecuteSkillResponse
+
+class MissingCookieException(Exception):
+ """Raised when a required cookie is missing for skill execution
+
+ Attributes:
+ cookie_name: The name of the missing cookie parameter
+ cookie_description: Description of how to obtain the cookie
+ """
+
+ def __init__(self, cookie_name: str, cookie_description: str):
+ self.cookie_name = cookie_name
+ self.cookie_description = cookie_description
+ super().__init__(f"Missing required cookie '{cookie_name}': {cookie_description}")
class Skill(BaseModel):
@@ -49,12 +47,19 @@ class Skill(BaseModel):
output_schema=response.output_schema,
)
- @property
- def parameters_pydantic(self) -> type[BaseModel]:
- """Convert parameter schemas to a pydantic model for structured output"""
+ def parameters_pydantic(self, exclude_cookies: bool = False) -> type[BaseModel]:
+ """Convert parameter schemas to a pydantic model for structured output
+
+ exclude_cookies is very useful when dealing with LLMs that are not aware of cookies.
+ """
from browser_use.skills.utils import convert_parameters_to_pydantic
- return convert_parameters_to_pydantic(self.parameters, model_name=f'{self.title}Parameters')
+ parameters = list[ParameterSchema](self.parameters)
+
+ if exclude_cookies:
+ parameters = [param for param in parameters if param.type != 'cookie']
+
+ return convert_parameters_to_pydantic(parameters, model_name=f'{self.title}Parameters')
@property
def output_type_pydantic(self) -> type[BaseModel] | None:
diff --git a/pyproject.toml b/pyproject.toml
index b2ffa1754..8bd3082f6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,7 +47,7 @@ dependencies = [
"cloudpickle>=3.1.1",
"markdownify>=1.2.0",
"python-docx>=1.2.0",
- "browser-use-sdk>=2.0.11",
+ "browser-use-sdk>=2.0.12",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste