repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tokens/tests/test_cost.py | .py | """
Simple test for token cost tracking with real LLM calls.
Tests ChatOpenAI and ChatGoogle by iteratively generating countries.
"""
import asyncio
import logging
from browser_use.llm import ChatOpenAI
from browser_use.llm.messages import AssistantMessage, SystemMessage, UserMessage
from browser_use.tokens.service ... | 103 | 3,191 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/telemetry/__init__.py | .py | """
Telemetry for Browser Use.
"""
from typing import TYPE_CHECKING
# Type stubs for lazy imports
if TYPE_CHECKING:
from browser_use.telemetry.service import ProductTelemetry
from browser_use.telemetry.views import (
BaseTelemetryEvent,
CLITelemetryEvent,
MCPClientTelemetryEvent,
MCPServerTelemetryEvent,
)... | 52 | 1,470 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/telemetry/views.py | .py | from abc import ABC, abstractmethod
from collections.abc import Sequence
from dataclasses import asdict, dataclass
from typing import Any
from browser_use.config import is_running_in_docker
@dataclass
class BaseTelemetryEvent(ABC):
@property
@abstractmethod
def name(self) -> str:
pass
@property
def propertie... | 94 | 2,180 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/telemetry/service.py | .py | import logging
import os
from dotenv import load_dotenv
from posthog import Posthog
from uuid_extensions import uuid7str
from browser_use.telemetry.views import BaseTelemetryEvent
from browser_use.utils import singleton
load_dotenv()
from browser_use.config import CONFIG
logger = logging.getLogger(__name__)
POST... | 113 | 3,030 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/mcp/server.py | .py | """MCP Server for browser-use - exposes browser automation capabilities via Model Context Protocol.
This server provides tools for:
- Running autonomous browser tasks with an AI agent
- Direct browser control (navigation, clicking, typing, etc.)
- Content extraction from web pages
- File system operations
Usage:
... | 1,092 | 34,388 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/mcp/client.py | .py | """MCP (Model Context Protocol) client integration for browser-use.
This module provides integration between external MCP servers and browser-use's action registry.
MCP tools are dynamically discovered and registered as browser-use actions.
Example usage:
from browser_use import Tools
from browser_use.mcp.cli... | 545 | 17,051 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdog_base.py | .py | """Base watchdog class for browser monitoring components."""
import inspect
import time
from collections.abc import Iterable
from typing import Any, ClassVar
from bubus import BaseEvent, EventBus
from pydantic import BaseModel, ConfigDict, Field
from browser_use.browser.session import BrowserSession
class BaseWatc... | 269 | 11,682 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/video_recorder.py | .py | """Video Recording Service for Browser Use Sessions."""
import base64
import logging
import math
import subprocess
from pathlib import Path
from typing import Optional
from browser_use.browser.profile import ViewportSize
try:
import imageio.v2 as iio # type: ignore[import-not-found]
import imageio_ffmpeg # type:... | 163 | 5,360 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/cloud.py | .py | """Cloud browser service integration for browser-use.
This module provides integration with the browser-use cloud browser service.
When cloud_browser=True, it automatically creates a cloud browser instance
and returns the CDP URL for connection.
"""
import logging
import os
import httpx
from pydantic import BaseMode... | 288 | 9,134 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/python_highlights.py | .py | """Python-based highlighting system for drawing bounding boxes on screenshots.
This module replaces JavaScript-based highlighting with fast Python image processing
to draw bounding boxes around interactive elements directly on screenshots.
"""
import asyncio
import base64
import io
import logging
import os
from PIL ... | 549 | 18,137 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/views.py | .py | from dataclasses import dataclass, field
from typing import Any
from bubus import BaseEvent
from cdp_use.cdp.target import TargetID
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_serializer
from browser_use.dom.views import DOMInteractedElement, SerializedDOMState
# Known placeholder image da... | 177 | 5,263 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/session.py | .py | """Event-driven browser session with backwards compatibility."""
import asyncio
import logging
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Self, Union, cast
import httpx
from bubus import EventBus
from cdp_use import CDPClient
from cdp_use.cdp.fetch i... | 2,507 | 99,985 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/profile.py | .py | import sys
import tempfile
from collections.abc import Iterable
from enum import Enum
from functools import cache
from pathlib import Path
from typing import Annotated, Any, Literal, Self
from urllib.parse import urlparse
from pydantic import AfterValidator, AliasChoices, BaseModel, ConfigDict, Field, field_validator,... | 1,111 | 44,657 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/events.py | .py | """Event definitions for browser communication."""
import inspect
import os
from typing import Any, Literal
from bubus import BaseEvent
from bubus.models import T_EventResultType
from cdp_use.cdp.target import TargetID
from pydantic import BaseModel, Field, field_validator
from browser_use.browser.views import Brows... | 585 | 18,366 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/screenshot_watchdog.py | .py | """Screenshot watchdog for handling screenshot requests using CDP."""
from typing import TYPE_CHECKING, Any, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.page import CaptureScreenshotParameters
from browser_use.browser.events import ScreenshotEvent
from browser_use.browser.views import BrowserError
from bro... | 63 | 2,177 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/crash_watchdog.py | .py | """Browser watchdog for monitoring crashes and network timeouts using CDP."""
import asyncio
import time
from typing import TYPE_CHECKING, ClassVar
import psutil
from bubus import BaseEvent
from cdp_use.cdp.target import SessionID, TargetID
from cdp_use.cdp.target.events import TargetCrashedEvent
from pydantic import... | 363 | 14,720 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/downloads_watchdog.py | .py | """Downloads watchdog for monitoring and handling file downloads."""
import asyncio
import json
import os
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
from urllib.parse import urlparse
import anyio
from bubus import BaseEvent
from cdp_use.cdp.browser import DownloadProgress... | 934 | 35,705 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/default_action_watchdog.py | .py | """Default browser action handlers using CDP."""
import asyncio
import json
import platform
from browser_use.browser.events import (
ClickElementEvent,
GetDropdownOptionsEvent,
GoBackEvent,
GoForwardEvent,
RefreshEvent,
ScrollEvent,
ScrollToTextEvent,
SelectDropdownOptionEvent,
SendKeysEvent,
TypeTextEvent,... | 2,345 | 81,334 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/storage_state_watchdog.py | .py | """Storage state watchdog for managing browser cookies and storage persistence."""
import asyncio
import json
import os
from pathlib import Path
from typing import Any, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.network import Cookie
from pydantic import Field, PrivateAttr
from browser_use.browser.events ... | 336 | 12,043 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/aboutblank_watchdog.py | .py | """About:blank watchdog for managing about:blank tabs with DVD screensaver."""
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.target import TargetID
from pydantic import PrivateAttr
from browser_use.browser.events import (
AboutBlankDVDScreensaverShownEvent,
BrowserStopEven... | 254 | 9,167 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/popups_watchdog.py | .py | """Watchdog for handling JavaScript dialogs (alert, confirm, prompt) automatically."""
import asyncio
from typing import ClassVar
from bubus import BaseEvent
from pydantic import PrivateAttr
from browser_use.browser.events import TabCreatedEvent
from browser_use.browser.watchdog_base import BaseWatchdog
class Popu... | 113 | 4,674 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/recording_watchdog.py | .py | """Recording Watchdog for Browser Use Sessions."""
import asyncio
from pathlib import Path
from typing import ClassVar
from bubus import BaseEvent
from cdp_use.cdp.page.events import ScreencastFrameEvent
from uuid_extensions import uuid7str
from browser_use.browser.events import BrowserConnectedEvent, BrowserStopEve... | 127 | 4,432 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/local_browser_watchdog.py | .py | """Local browser watchdog for managing browser subprocess lifecycle."""
import asyncio
import os
import shutil
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import psutil
from bubus import BaseEvent
from pydantic import PrivateAttr
from browser_use.browser.events import (
... | 457 | 15,884 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/security_watchdog.py | .py | """Security watchdog for enforcing URL access policies."""
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
from browser_use.browser.events import (
BrowserErrorEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
TabCreatedEvent,
)
from browser_use.browser.watchdog_base import BaseWatchdog
... | 220 | 6,886 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/browser/watchdogs/dom_watchdog.py | .py | """DOM watchdog for browser DOM tree management using CDP."""
import asyncio
import time
from typing import TYPE_CHECKING
from browser_use.browser.events import (
BrowserErrorEvent,
BrowserStateRequestEvent,
ScreenshotEvent,
TabCreatedEvent,
)
from browser_use.browser.watchdog_base import BaseWatchdog
from browse... | 583 | 23,280 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/sync/service.py | .py | """
Cloud sync service for sending events to the Browser Use cloud.
"""
import asyncio
import logging
import shutil
import httpx
from bubus import BaseEvent
from browser_use.config import CONFIG
from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
logger = logging.getLogger(__name__)
class CloudSync:
... | 216 | 8,623 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/actor/mouse.py | .py | """Mouse class for mouse operations."""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cdp_use.cdp.input.commands import DispatchMouseEventParameters, SynthesizeScrollGestureParameters
from cdp_use.cdp.input.types import MouseButton
from browser_use.browser.session import BrowserSession
class Mouse:
"... | 142 | 4,455 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/actor/__init__.py | .py | """CDP-Use High-Level Library
A Playwright-like library built on top of CDP (Chrome DevTools Protocol).
"""
from .element import Element
from .mouse import Mouse
from .page import Page
__all__ = ['Page', 'Element', 'Mouse']
| 11 | 227 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/actor/page.py | .py | """Page class for page-level operations."""
from typing import TYPE_CHECKING, TypeVar
from pydantic import BaseModel
from browser_use.dom.serializer.serializer import DOMTreeSerializer
from browser_use.dom.service import DomService
from browser_use.llm.messages import SystemMessage, UserMessage
T = TypeVar('T', bou... | 555 | 18,659 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/actor/element.py | .py | """Element class for element operations."""
import asyncio
from typing import TYPE_CHECKING, Literal, Union
from cdp_use.client import logger
from typing_extensions import TypedDict
if TYPE_CHECKING:
from cdp_use.cdp.dom.commands import (
DescribeNodeParameters,
FocusParameters,
GetAttributesParameters,
Get... | 1,045 | 31,966 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/enhanced_snapshot.py | .py | """
Enhanced snapshot processing for browser-use DOM tree extraction.
This module provides stateless functions for parsing Chrome DevTools Protocol (CDP) DOMSnapshot data
to extract visibility, clickability, cursor styles, and other layout information.
"""
from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotR... | 162 | 6,173 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/utils.py | .py | def cap_text_length(text: str, max_length: int) -> str:
"""Cap text length for display."""
if len(text) <= max_length:
return text
return text[:max_length] + '...'
| 6 | 169 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/views.py | .py | import hashlib
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXPropertyName
from cdp_use.cdp.dom.commands import GetDocumentReturns
from cdp_use.cdp.dom.types ... | 874 | 26,977 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/test_enhanced_snapshot_null_layout.py | .py | """
Test suite locking out TypeError in _build_dom_tree
when layout dictionary contains None values for array properties.
"""
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
def test_layout_index_map_handles_null_layout_arrays():
"""
Ensure layout array checks tolerate No... | 39 | 1,066 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/service.py | .py | import asyncio
import logging
import time
from typing import TYPE_CHECKING
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXNode
from cdp_use.cdp.dom.types import Node
from cdp_use.cdp.target import TargetID
from browser_use.dom.enhanced_snapshot import... | 742 | 28,432 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/playground/multi_act.py | .py | from browser_use import Agent
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.types import ViewportSize
from browser_use.llm import ChatAzureOpenAI
# Initialize the Azure OpenAI client
llm = ChatAzureOpenAI(
model='gpt-4.1-mini',
)
TASK = """
Go to https://browser-use.github.... | 33 | 732 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/serializer/serializer.py | .py | # @file purpose: Serializes enhanced DOM trees to string format for LLM consumption
from typing import Any
from browser_use.dom.serializer.clickable_elements import ClickableElementDetector
from browser_use.dom.serializer.paint_order import PaintOrderRemover
from browser_use.dom.utils import cap_text_length
from brow... | 955 | 36,525 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/serializer/clickable_elements.py | .py | from browser_use.dom.views import EnhancedDOMTreeNode, NodeType
class ClickableElementDetector:
@staticmethod
def is_interactive(node: EnhancedDOMTreeNode) -> bool:
"""Check if this node is clickable/interactive using enhanced scoring."""
# Skip non-element nodes
if node.node_type != NodeType.ELEMENT_NODE:
... | 200 | 6,495 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/dom/serializer/paint_order.py | .py | from collections import defaultdict
from dataclasses import dataclass
from browser_use.dom.views import SimplifiedNode
"""
Helper class for maintaining a union of rectangles (used for order of elements calculation)
"""
@dataclass(frozen=True, slots=True)
class Rect:
"""Closed axis-aligned rectangle with (x1,y1) bo... | 198 | 5,542 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/integrations/gmail/service.py | .py | """
Gmail API Service for Browser Use
Handles Gmail API authentication, email reading, and 2FA code extraction.
This service provides a clean interface for agents to interact with Gmail.
"""
import base64
import logging
import os
from pathlib import Path
from typing import Any
import aiofiles
from google.auth.transpo... | 227 | 7,708 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/gif.py | .py | from __future__ import annotations
import base64
import io
import logging
import os
import platform
from typing import TYPE_CHECKING
from browser_use.agent.views import AgentHistoryList
from browser_use.browser.views import PLACEHOLDER_4PX_SCREENSHOT
from browser_use.config import CONFIG
if TYPE_CHECKING:
from PIL ... | 425 | 12,302 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/views.py | .py | from __future__ import annotations
import json
import logging
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Generic, Literal
from openai import RateLimitError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model, model_validator
from ty... | 659 | 23,429 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/cloud_events.py | .py | import base64
import os
from datetime import datetime, timezone
from pathlib import Path
import anyio
from bubus import BaseEvent
from pydantic import Field, field_validator
from uuid_extensions import uuid7str
MAX_STRING_LENGTH = 100000 # 100K chars ~ 25k tokens should be enough
MAX_URL_LENGTH = 100000
MAX_TASK_LEN... | 283 | 11,316 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/service.py | .py | import asyncio
import gc
import inspect
import json
import logging
import re
import tempfile
import time
from collections.abc import Awaitable, Callable
from datetime import datetime
from pathlib import Path
from typing import Any, Generic, Literal, TypeVar
from urllib.parse import urlparse
from dotenv import load_dot... | 2,184 | 85,863 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/prompts.py | .py | import importlib.resources
from datetime import datetime
from typing import TYPE_CHECKING, Literal, Optional
from browser_use.dom.views import NodeType, SimplifiedNode
from browser_use.llm.messages import ContentPartImageParam, ContentPartTextParam, ImageURL, SystemMessage, UserMessage
from browser_use.observability i... | 379 | 14,446 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/message_manager/utils.py | .py | from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any
import anyio
from browser_use.llm.messages import BaseMessage
logger = logging.getLogger(__name__)
async def save_conversation(
input_messages: list[BaseMessage],
response: Any,
target: str | Path,
en... | 53 | 1,372 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/message_manager/views.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import BaseModel, ConfigDict, Field
from browser_use.llm.messages import (
BaseMessage,
)
if TYPE_CHECKING:
pass
class HistoryItem(BaseModel):
"""Represents a single agent history item with its data and string representation"""
... | 99 | 2,737 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/agent/message_manager/service.py | .py | from __future__ import annotations
import logging
from typing import Literal
from browser_use.agent.message_manager.views import (
HistoryItem,
)
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.views import (
ActionResult,
AgentOutput,
AgentStepInfo,
MessageManagerState,
)
from br... | 423 | 16,081 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/simple.py | .py | from dotenv import load_dotenv
from browser_use import Agent, ChatGoogle
load_dotenv()
agent = Agent(
task='Find the number of stars of the browser-use repo',
llm=ChatGoogle(model='gemini-2.5-flash'),
# browser=Browser(use_cloud=True), # Uses Browser-Use cloud for the browser
)
agent.run_sync()
| 13 | 303 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/apps/ad-use/ad_generator.py | .py | import argparse
import asyncio
import logging
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
def setup_environment(debug: bool):
if not debug:
os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false'
os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical'
logging.getLogger(... | 414 | 14,599 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/file_system/file_system.py | .py | import asyncio
import os
import pathlib
import shutil
from dotenv import load_dotenv
from browser_use import Agent, ChatOpenAI
load_dotenv()
SCRIPT_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
agent_dir = SCRIPT_DIR / 'file_system'
agent_dir.mkdir(exist_ok=True)
conversation_dir = agent_dir / 'co... | 51 | 1,240 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/getting_started/03_data_extraction.py | .py | """
Getting Started Example 3: Data Extraction
This example demonstrates how to:
- Navigate to a website with structured data
- Extract specific information from the page
- Process and organize the extracted data
- Return structured results
This builds on previous examples by showing how to get valuable data from web... | 51 | 1,314 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/getting_started/02_form_filling.py | .py | """
Getting Started Example 2: Form Filling
This example demonstrates how to:
- Navigate to a website with forms
- Fill out input fields
- Submit forms
- Handle basic form interactions
This builds on the basic search example by showing more complex interactions.
"""
import asyncio
import os
import sys
# Add the par... | 52 | 1,176 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/getting_started/04_multi_step_task.py | .py | """
Getting Started Example 4: Multi-Step Task
This example demonstrates how to:
- Perform a complex workflow with multiple steps
- Navigate between different pages
- Combine search, form filling, and data extraction
- Handle a realistic end-to-end scenario
This is the most advanced getting started example, combining... | 55 | 1,504 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/getting_started/05_fast_agent.py | .py | import asyncio
import os
import sys
# Add the parent directory to the path so we can import browser_use
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, BrowserProfile
# Speed optimization inst... | 65 | 1,692 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/getting_started/01_basic_search.py | .py | import asyncio
import os
import sys
# Add the parent directory to the path so we can import browser_use
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, ChatOpenAI
async def main():
llm = Chat... | 24 | 540 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/custom-functions/file_upload.py | .py | """
Example of implementing file upload functionality.
This shows how to upload files to file input elements on web pages.
"""
import asyncio
import logging
import os
import sys
import aiofiles
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dot... | 115 | 3,246 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/custom-functions/cua.py | .py | """
OpenAI Computer Use Assistant (CUA) Integration
This example demonstrates how to integrate OpenAI's Computer Use Assistant as a fallback
action when standard browser actions are insufficient to achieve the desired goal.
The CUA can perform complex computer interactions that might be difficult to achieve
through re... | 342 | 10,593 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/custom-functions/advanced_search.py | .py | import asyncio
import http.client
import json
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
import logging
from pydantic import BaseModel
from browser_use import ActionResult, Agent, ChatOpenAI, Tools... | 113 | 2,939 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/use-cases/find_influencer_profiles.py | .py | """
Show how to use custom outputs.
@dev You need to add OPENAI_API_KEY to your environment variables.
"""
import asyncio
import json
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
import httpx
from py... | 90 | 2,450 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/use-cases/find_and_apply_to_jobs.py | .py | """
Goal: Searches for job listings, evaluates relevance based on a CV, and applies
@dev You need to add OPENAI_API_KEY to your environment variables.
Also you have to install PyPDF2 to read pdf files: pip install PyPDF2
"""
import asyncio
import csv
import logging
import os
import sys
from pathlib import Path
sys.p... | 158 | 4,834 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/cloud/02_fast_mode_gemini.py | .py | """
Cloud Example 2: Ultra-Fast Mode with Gemini Flash ⚡
====================================================
This example demonstrates the fastest and most cost-effective configuration:
- Gemini 2.5 Flash model ($0.01 per step)
- No proxy (faster execution, but no captcha solving)
- No element highlighting (better pe... | 272 | 8,563 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/cloud/05_search_api.py | .py | """
Cloud Example 5: Search API (Beta) 🔍
=====================================
This example demonstrates the Browser Use Search API (BETA):
- Simple search: Search Google and extract from multiple results
- URL search: Extract specific content from a target URL
- Deep navigation through websites (depth parameter)
- R... | 362 | 11,135 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/cloud/04_proxy_usage.py | .py | """
Cloud Example 4: Proxy Usage 🌍
===============================
This example demonstrates reliable proxy usage scenarios:
- Different country proxies for geo-restrictions
- IP address and location verification
- Region-specific content access (streaming, news)
- Search result localization by country
- Mobile/resid... | 338 | 10,031 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/cloud/03_structured_output.py | .py | """
Cloud Example 3: Structured JSON Output 📋
==========================================
This example demonstrates how to get structured, validated JSON output:
- Define Pydantic schemas for type safety
- Extract structured data from websites
- Validate and parse JSON responses
- Handle different data types and neste... | 369 | 11,795 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/cloud/01_basic_task.py | .py | """
Cloud Example 1: Your First Browser Use Cloud Task
==================================================
This example demonstrates the most basic Browser Use Cloud functionality:
- Create a simple automation task
- Get the task ID
- Monitor completion
- Retrieve results
Perfect for first-time cloud users to understa... | 195 | 5,658 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/api/search/search_url.py | .py | """
Search URL API Example
This example shows how to use the Browser Use API to extract specific
content from a given URL based on your query.
Usage:
# Copy this function and customize the parameters
result = await search_url("https://example.com", "what to find", depth=2)
"""
import asyncio
import os
impor... | 73 | 2,124 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/api/search/simple_search.py | .py | """
Simple Search API Example
This example shows how to use the Browser Use API to search and extract
content from multiple websites based on a query.
Usage:
# Copy this function and customize the parameters
result = await simple_search("your search query", max_websites=5, depth=2)
"""
import asyncio
import ... | 75 | 2,215 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/mcp/advanced_server.py | .py | """
Advanced example of building an AI assistant that uses browser-use MCP server.
This example shows how to build a more sophisticated MCP client that:
- Connects to multiple MCP servers (browser-use + filesystem)
- Orchestrates complex multi-step workflows
- Handles errors and retries
- Provides a conversational int... | 325 | 10,388 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/mcp/simple_client.py | .py | """
Simple example of using MCP client with browser-use.
This example shows how to connect to an MCP server and use its tools with an agent.
"""
import asyncio
import os
from browser_use import Agent, Tools
from browser_use.llm.openai.chat import ChatOpenAI
from browser_use.mcp.client import MCPClient
async def ma... | 45 | 1,111 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/mcp/advanced_client.py | .py | """
Advanced example: Using multiple MCP servers together.
This example demonstrates how to:
1. Connect multiple MCP servers (Gmail + Filesystem) to browser-use
2. Sign up for a new account on a website
3. Save registration details to a file
4. Retrieve the verification link from Gmail
5. Complete the verification pro... | 112 | 3,944 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/mcp/simple_server.py | .py | """
Simple example of connecting to browser-use MCP server as a client.
This example demonstrates how to use the MCP client library to connect to
a running browser-use MCP server and call its browser automation tools.
Prerequisites:
1. Install required packages:
pip install 'browser-use[cli]'
2. Start the browser... | 139 | 4,564 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/features/initial_actions.py | .py | import asyncio
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, ChatOpenAI
llm = ChatOpenAI(model='gpt-4.1-mini')
initial_actions = [
{'go_to_url': {'url': 'https://www.go... | 32 | 650 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/features/rerun_history.py | .py | """
Example: Rerunning saved agent history
This example shows how to:
1. Run an agent and save its history (including initial URL navigation)
2. Load and rerun the history with a new agent instance
Useful for:
- Debugging agent behavior
- Testing changes with consistent scenarios
- Replaying successful workflows
Not... | 42 | 1,194 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/features/add_image_context.py | .py | """
Show how to use sample_images to add image context for your task
"""
import asyncio
import base64
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
from browser_use import Agent
from browser_use.llm import ChatOpenAI
from browser_use.llm.messages import ContentPartImageParam, Content... | 114 | 2,828 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/browser/using_cdp.py | .py | """
Simple demonstration of the CDP feature.
To test this locally, follow these steps:
1. Find the chrome executable file.
2. On mac by default, the chrome is in `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`
3. Add the following argument to the shortcut:
`--remote-debugging-port=9222`
4. Open a web... | 52 | 1,458 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/browser/cloud_browser.py | .py | """
Simple example of using Browser-Use cloud browser service.
Prerequisites:
1. Set BROWSER_USE_API_KEY environment variable
2. Active subscription at https://cloud.browser-use.com
"""
import asyncio
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
from browser_use import Agent, Browser, ... | 44 | 1,027 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/browser/real_browser.py | .py | import asyncio
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, Browser, ChatOpenAI
# Connect to your existing Chrome browser
browser = Browser(
executable_path='/Applicati... | 33 | 780 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/models/qwen.py | .py | import os
from dotenv import load_dotenv
from browser_use import Agent, ChatOpenAI
load_dotenv()
import asyncio
# get an api key from https://modelstudio.console.alibabacloud.com/?tab=playground#/api-key
api_key = os.getenv('ALIBABA_CLOUD')
base_url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
# so f... | 28 | 979 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/models/gemini.py | .py | import asyncio
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
from browser_use import Agent, ChatGoogle
load_dotenv()
api_key = os.getenv('GOOGLE_API_KEY')
if not api_key:
raise ValueError('GOOGLE_API_KEY is not set... | 31 | 593 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/models/azure_openai.py | .py | """
Simple try of the agent.
@dev You need to add AZURE_OPENAI_KEY and AZURE_OPENAI_ENDPOINT to your environment variables.
"""
import asyncio
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from brows... | 45 | 877 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/models/aws.py | .py | """
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 environ... | 101 | 2,617 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/models/openrouter.py | .py | """
Simple try of the agent.
@dev You need to add OPENAI_API_KEY to your environment variables.
"""
import asyncio
import os
from dotenv import load_dotenv
from browser_use import Agent, ChatOpenAI
load_dotenv()
# All the models are type safe from OpenAI in case you need a list of supported models
llm = ChatOpenA... | 34 | 655 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/ui/gradio_demo.py | .py | # pyright: reportMissingImports=false
import asyncio
import os
import sys
from dataclasses import dataclass
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
# Third-party imports
import gradio as gr # type: ignore
from rich.c... | 112 | 2,694 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/integrations/gmail_2fa_integration.py | .py | """
Gmail 2FA Integration Example with Grant Mechanism
This example demonstrates how to use the Gmail integration for handling 2FA codes
during web automation with a robust credential grant and re-authentication system.
Features:
- Automatic credential validation and setup
- Interactive OAuth grant flow when credentia... | 332 | 11,549 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/examples/integrations/agentmail/2fa.py | .py | import asyncio
import os
import sys
from agentmail import AsyncAgentMail # type: ignore
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, Browser, models
from examples.integrations.agentmail.emai... | 43 | 1,227 |
ai-agent-book | chapter9/browser-use-rpa/learning_agent/workflow.py | .py | """
Workflow data structures for capturing and storing browser action sequences.
This module defines the structures used to represent learned workflows,
including individual steps and complete action sequences.
"""
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, Li... | 265 | 10,183 |
ai-agent-book | chapter9/browser-use-rpa/learning_agent/__init__.py | .py | """
Learning Agent for Browser-Use RPA
A wrapper system that adds learning and experience-replay capabilities to browser-use.
This agent can learn from successful task executions and replay learned workflows efficiently.
"""
from .knowledge_base import KnowledgeBase
from .workflow import Workflow, WorkflowStep, State... | 23 | 731 |
ai-agent-book | chapter9/browser-use-rpa/learning_agent/knowledge_base.py | .py | """
Knowledge Base for storing and retrieving learned workflows.
This module provides persistent storage and intelligent retrieval of workflows,
including intent matching and workflow selection.
"""
import json
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from datetime import date... | 337 | 13,001 |
ai-agent-book | chapter9/browser-use-rpa/learning_agent/replay.py | .py | """
Workflow replay functionality using Playwright.
This module provides reliable replay of learned workflows by directly
controlling the browser through Playwright, bypassing the need for LLM calls.
"""
import asyncio
import logging
from typing import Any, Dict, Optional
from playwright.async_api import Page, Browse... | 402 | 16,584 |
ai-agent-book | chapter9/browser-use-rpa/learning_agent/agent.py | .py | """
Learning Agent that extends browser-use with experience-based learning.
This agent wraps the browser-use Agent to capture successful workflows
and replay them efficiently without LLM calls.
"""
import asyncio
import logging
from typing import Any, Dict, List, Optional
import time
from pathlib import Path
import s... | 610 | 25,022 |
ai-agent-book | chapter9/gaia-experience/test_experience_similar.py | .py | """Unit-test _is_similar without importing the full AWorld agent stack."""
import ast
from pathlib import Path
def _load_is_similar():
src = Path(__file__).with_name("experience_agent.py").read_text()
tree = ast.parse(src)
method = None
for node in tree.body:
if isinstance(node, ast.ClassDef)... | 42 | 1,307 |
ai-agent-book | chapter9/gaia-experience/experience_documents.py | .py | """Cross-trajectory Markdown experience documents for Experiment 8-2.
This module is intentionally independent of AWorld so that the learning
method can be inspected and tested offline. AWorld trajectories only need to
be converted to the small evaluated record schema used here.
"""
from __future__ import annotations... | 211 | 8,245 |
ai-agent-book | chapter9/gaia-experience/test_kb_topk_zero.py | .py | import pickle
from pathlib import Path
from unittest.mock import MagicMock
class FakeEncoder:
def __init__(self, _model_name):
self.encoded_queries = []
def get_sentence_embedding_dimension(self):
return 3
def encode(self, queries):
import numpy as np
self.encoded_querie... | 155 | 4,986 |
ai-agent-book | chapter9/gaia-experience/real_gaia_campaign.py | .py | #!/usr/bin/env python3
"""Real GAIA learning/transfer campaign for manuscript Experiment 8-2.
This runner uses actual GAIA validation questions, externally scores answers
against the published references, extracts cross-run experience with a real
LLM, and reruns a disjoint transfer split under all three manuscript con... | 484 | 24,579 |
ai-agent-book | chapter9/gaia-experience/demo_documents.py | .py | """Offline demonstration of Experiment 8-2."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from experience_documents import build_documents, evaluate_retrieval_baselines, write_documents
ROOT = Path(__file__).parent
def main() -> None:
parser = argparse.ArgumentPar... | 39 | 1,644 |
ai-agent-book | chapter9/gaia-experience/test_experience_documents.py | .py | import json
import tempfile
import unittest
from pathlib import Path
from experience_documents import build_documents, evaluate_retrieval_baselines, outcome_label, write_documents
class ExperienceDocumentTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
dataset = json.loads(Path(__file__).wi... | 65 | 2,802 |
ai-agent-book | chapter9/gaia-experience/llm_env.py | .py | """包装层 LLM 环境解析:为 GAIA 经验学习示例提供带 OpenRouter 兜底的配置。
本文件位于 gaia-experience 包装层,**不修改** 上游 AWorld fork。它把散落在各处的
`os.getenv("LLM_API_KEY"/"LLM_BASE_URL"/"LLM_MODEL_NAME")` 读取集中起来,并加入统一兜底:
- 有 LLM_API_KEY / OPENAI_API_KEY -> 直连(沿用 LLM_BASE_URL,可为空即 OpenAI 官方)
- 否则有 OPENROUTER_API_KEY -> 走 OpenRouter(https://openrou... | 56 | 2,072 |
ai-agent-book | chapter9/gaia-experience/llm_extractor.py | .py | """Real LLM extraction of candidate experience fields from evaluated runs."""
from __future__ import annotations
import json
import os
import re
from typing import Any, Dict, Iterable, List
def _parse(text: str) -> Dict[str, Any]:
cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.IGNORECA... | 97 | 4,220 |
ai-agent-book | chapter9/gaia-experience/test_analyze_action_types_null.py | .py | """Unit-test _analyze_action_types / _format_trajectory with null tool_name,
without importing the full AWorld agent stack (same ast-extraction trick as
test_experience_similar.py)."""
import ast
from pathlib import Path
from typing import Any, Dict, List
def _load_methods(*method_names):
src = Path(__file__).wit... | 63 | 2,357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.