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/harness-safety-gate/stable/tool_dispatcher.py | .py | """稳定版本 1.0.0 的 Harness 工具调度器(教学简化版)。
注册了 read_file / write_file / delete_file / run_shell / git_push /
sql_query 六个工具,dispatch 不做任何风险分级,直接调用目标工具——
这正是本实验要修复的缺陷:删除文件、force push、DROP TABLE 等不可逆
操作在未经用户确认时也会被执行。
所有工具只作用于调用方传入的内存模拟环境 env(默认由 default_env()
构造),不触碰真实文件系统、Shell、Git 远端或数据库,因此失败回放与
候选验证都可以离线安全运行。
"""
import... | 126 | 4,455 |
ai-agent-book | chapter9/harness-safety-gate/validation/real_20260807T160109Z/candidates/deterministic/confirmation_gate.py | .py | """候选模块:高风险工具调用确认门禁。
由 Coding Agent 生成的独立新模块,不覆盖稳定代码。在工具调度前进行
风险分类:高风险调用先挂起,必须持有绑定具体操作与参数的一次性确认
token 才会放行执行。
"""
import hashlib
import hmac
import json
import re
VERSION = "1.1.0-candidate"
_DESTRUCTIVE_SQL = re.compile(r"\b(DROP\s+TABLE|TRUNCATE)\b", re.IGNORECASE)
_DELETE_FROM = re.compile(r"\bDELETE\s+FROM\b", ... | 75 | 3,194 |
ai-agent-book | chapter9/harness-safety-gate/validation/real_20260807T160109Z/candidates/real_llm/confirmation_gate.py | .py | import hashlib
import hmac
import json
import re
import secrets
import string
VERSION = "1.1.0-candidate"
# Store tokens for confirmation
confirmation_tokens = {}
# Define high-risk tool patterns
HIGH_RISK_TOOLS = {
"delete_file": lambda args: True,
"git_push": lambda args: args.get('force', False),
"sql... | 65 | 2,095 |
ai-agent-book | chapter9/harness-safety-gate/validation/real_20260807T160109Z/candidates/rejected_control/confirmation_gate.py | .py | """候选模块:高风险工具调用确认门禁。
由 Coding Agent 生成的独立新模块,不覆盖稳定代码。在工具调度前进行
风险分类:高风险调用先挂起,必须持有绑定具体操作与参数的一次性确认
token 才会放行执行。
"""
import hashlib
import hmac
import json
import re
VERSION = "1.0.1-rejected"
_DESTRUCTIVE_SQL = re.compile(r"\b(DROP\s+TABLE|TRUNCATE)\b", re.IGNORECASE)
_DELETE_FROM = re.compile(r"\bDELETE\s+FROM\b", r... | 76 | 3,212 |
ai-agent-book | chapter9/prompt-distillation/compare.py | .py | """
Prompt 蒸馏「蒸馏前 vs 蒸馏后」量化对比脚本。
本脚本回答实验 7-8 的核心问题:把「长提示 + 思考型教师」蒸馏成「无提示 + 直接
回答的学生」之后,到底省了多少、质量掉了多少?它在 **不加载任何大模型、不联网** 的
前提下,用真实数据算出一张 before/after 对比表:
1. 输入成本(token):教师每次调用都要带上完整的语言分类提示(约上千 token),
学生只需要原始待分类文本。二者的 token 差就是每次调用省下的输入开销。
2. 任务质量:直接读取 evaluate.py 产出的 evaluation_results.json,得到学生在
相同输入... | 356 | 13,908 |
ai-agent-book | chapter9/prompt-distillation/train_sft_trl.py | .py | """
Prompt Distillation Training using Hugging Face TRL
This script trains a student model using the TRL SFTTrainer instead of verl.
TRL is more widely used, better documented, and easier to work with.
Based on the same prompt distillation methodology but using standard HF tools.
"""
import argparse
import json
impo... | 491 | 16,635 |
ai-agent-book | chapter9/prompt-distillation/test_evaluate_empty_parse_rate.py | .py | """Regression: empty test set must not ZeroDivisionError on parse-rate summary."""
import sys
import types
def _stub_evaluate_deps() -> None:
for name in ["torch", "numpy", "transformers", "peft", "tqdm"]:
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules["transformers"].AutoTokenizer =... | 26 | 747 |
ai-agent-book | chapter9/prompt-distillation/test_compare_empty.py | .py | from compare import compare
def test_compare_empty_texts():
result = compare(
prompt_template="Classify: {text}",
texts=[],
teacher_labels={},
eval_results=None,
count_tokens=lambda s: max(1, len(s) // 4),
token_method="test",
num_examples=3,
)
asser... | 17 | 457 |
ai-agent-book | chapter9/prompt-distillation/run_experiment_7_8.py | .py | #!/usr/bin/env python3
"""Run the manuscript's Experiment 7-8 with canonical, leakage-free evidence.
The campaign deliberately uses a small student so that *real parameter training*
can run on Apple Silicon. It still preserves the experiment's causal contrast:
* teacher: long task prompt + a thinking model (Moonshot... | 753 | 32,967 |
ai-agent-book | chapter9/prompt-distillation/test_create_data_empty.py | .py | import asyncio
from create_data import generate_distillation_data
def test_generate_empty_input_file(tmp_path):
# 空输入文件(0 个句子):应干净地直接返回,不加载模型、不抛 IndexError/ZeroDivisionError
input_file = tmp_path / "empty.txt"
input_file.write_text("", encoding="utf-8")
output_file = tmp_path / "out.jsonl"
resul... | 38 | 1,108 |
ai-agent-book | chapter9/prompt-distillation/create_data.py | .py | """
Data generation script for prompt distillation using vLLM.
This script generates training data for prompt distillation by using a teacher model
to generate language classification labels with a detailed prompt, which will then be
used to train a student model that internalizes the prompt.
Based on the tinker cook... | 446 | 18,013 |
ai-agent-book | chapter9/prompt-distillation/test_experiment_7_8.py | .py | import importlib.util
import sys
from pathlib import Path
MODULE_PATH = Path(__file__).with_name("run_experiment_7_8.py")
SPEC = importlib.util.spec_from_file_location("experiment_7_8", MODULE_PATH)
exp = importlib.util.module_from_spec(SPEC)
assert SPEC and SPEC.loader
sys.modules[SPEC.name] = exp
SPEC.loader.exec_m... | 66 | 2,171 |
ai-agent-book | chapter9/prompt-distillation/evaluate.py | .py | """
Evaluation script for the distilled prompt model.
This script evaluates the student model's performance on language classification
without providing the detailed prompt.
The student model (Qwen3-30B-A3B-Instruct) has been distilled from the teacher
(Qwen3-30B-A3B-Thinking) which used a 2000+ token prompt. After d... | 540 | 20,489 |
ai-agent-book | chapter9/prompt-distillation/test_evaluate_none_pred_label.py | .py | """Regression: unparseable model output (pred_label None) must not crash progress prints."""
import sys
import types
import pytest
def _stub_evaluate_deps() -> None:
for name in ["torch", "numpy", "transformers", "peft", "tqdm"]:
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules["trans... | 39 | 1,204 |
ai-agent-book | chapter9/browser-use-rpa/quickstart.py | .py | """
Quick start script for the Learning Agent.
This script provides a simple example of how to use the learning agent
for common tasks.
"""
import asyncio
from dotenv import load_dotenv
from browser_use import ChatOpenAI, ChatGoogle
from learning_agent import LearningAgent
from llm_factory import make_llm
# Load env... | 158 | 4,671 |
ai-agent-book | chapter9/browser-use-rpa/demo_weather.py | .py | """
Demo: Weather checking with learning capability
This demo shows how the agent learns to check weather and reuses the learned workflow.
"""
import asyncio
import logging
from dotenv import load_dotenv
from browser_use import ChatOpenAI
from learning_agent import LearningAgent
from llm_factory import make_llm
# ... | 106 | 2,989 |
ai-agent-book | chapter9/browser-use-rpa/run_experiment_8_4.py | .py | #!/usr/bin/env python3
"""Run Experiment 8-4 with a real model, localhost HTTP, and Chromium."""
from __future__ import annotations
import argparse
import asyncio
from datetime import datetime, timezone
import hashlib
import json
import os
import platform
from pathlib import Path
import re
import shutil
import time
f... | 544 | 25,984 |
ai-agent-book | chapter9/browser-use-rpa/local_mail_sandbox.py | .py | """Resettable localhost mail UI used by the real Playwright Experiment 8-4.
The server is deliberately small, but it is not a mocked browser: Chromium
loads the page, JavaScript sends HTTP requests, and the final sent-list is
rendered from server-side state. All side effects remain inside this process.
"""
from __fu... | 157 | 6,954 |
ai-agent-book | chapter9/browser-use-rpa/test_state_predicates.py | .py | import tempfile
import unittest
from learning_agent import KnowledgeBase
from learning_agent.workflow import WorkflowStatus
from workflow_validation_demo import (
candidate_workflow,
changed_environment,
replay,
validate_candidate,
)
class StatePredicateTest(unittest.TestCase):
def test_candidate... | 46 | 1,714 |
ai-agent-book | chapter9/browser-use-rpa/demo_email.py | .py | """
Demo: Email sending with learning capability
This demo shows how the agent learns to send emails and reuses the learned workflow.
Uses Ethereal Email (ethereal.email) as a test email service.
"""
import argparse
import asyncio
import json
import logging
import time
from dotenv import load_dotenv
from browser_use... | 374 | 14,665 |
ai-agent-book | chapter9/browser-use-rpa/test_real_playwright_campaign.py | .py | import asyncio
import tempfile
import unittest
from learning_agent import KnowledgeBase
from learning_agent.workflow import WorkflowStatus
from local_mail_sandbox import mail_sandbox
from run_experiment_8_4 import FIRST, TRANSFER, compile_workflow, replay
CAPTURED = [
{"action": "input_text", "selector": "#recip... | 66 | 2,858 |
ai-agent-book | chapter9/browser-use-rpa/test_validation.py | .py | """
Comprehensive validation test for the Learning Agent system.
This script validates all components of the learning agent:
1. Workflow capture and storage
2. Intent matching
3. Workflow replay
4. Performance improvements
"""
import asyncio
import json
import logging
from pathlib import Path
import time
from typing ... | 369 | 12,951 |
ai-agent-book | chapter9/browser-use-rpa/llm_factory.py | .py | """包装层 LLM 工厂:为 browser-use 示例统一提供带 OpenRouter 兜底的模型客户端。
本文件位于 RPA 包装层,**不修改** 上游 browser-use fork。它按环境变量决定用哪家:
- gemini-* 模型 -> ChatGoogle(走 GOOGLE_API_KEY)
- 有 OPENAI_API_KEY -> 直连 OpenAI
- 否则有 OPENROUTER_API_KEY -> 走 OpenRouter,并把模型名映射到 OpenRouter 命名:
gpt-* -> openai/gpt-*
claude-* ... | 52 | 1,784 |
ai-agent-book | chapter9/browser-use-rpa/workflow_validation_demo.py | .py | """Offline state-machine demo for validated browser workflow learning.
It uses the same Workflow/StatePredicate schema as the Playwright replayer,
but replaces a real site with a deterministic page state. This makes the
candidate -> reset -> replay -> validated -> invalid lifecycle reproducible.
"""
from __future__ i... | 162 | 5,827 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/scripts/test_frame_hierarchy.py | .py | #!/usr/bin/env python3
"""Test frame hierarchy for any URL passed as argument."""
import asyncio
import sys
from browser_use.browser import BrowserSession
from browser_use.browser.events import BrowserStartEvent
from browser_use.browser.profile import BrowserProfile
async def analyze_frame_hierarchy(url):
"""Analy... | 259 | 8,271 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/scripts/debug_iframe_scrolling.py | .py | """
Debug test for iframe scrolling issue where DOM tree only shows top elements after scrolling.
This test verifies that after scrolling inside an iframe, the selector_map correctly
contains lower input elements like City, State, Zip Code, etc.
"""
import asyncio
import sys
from pathlib import Path
# Add parent dir... | 302 | 9,344 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py | .py | """Test full circle: download a file and then upload it back, verifying hash matches"""
import asyncio
import hashlib
import tempfile
from pathlib import Path
import pytest
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel
from browser_use.browser import BrowserSession
from bro... | 368 | 13,491 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_downloads.py | .py | """Test downloads watchdog functionality."""
import asyncio
import tempfile
from pathlib import Path
import pytest
from pytest_httpserver import HTTPServer
from browser_use.browser import BrowserSession
from browser_use.browser.events import (
BrowserConnectedEvent,
BrowserStartEvent,
BrowserStopEvent,
BrowserSt... | 266 | 8,789 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_GetDropdownOptionsEvent.py | .py | """Test GetDropdownOptionsEvent and SelectDropdownOptionEvent functionality.
This file consolidates all tests related to dropdown functionality including:
- Native <select> dropdowns
- ARIA role="menu" dropdowns
- Custom dropdown implementations
"""
import pytest
from pytest_httpserver import HTTPServer
from browser... | 671 | 24,424 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_registry_action_parameter_injection.py | .py | import asyncio
import base64
import socketserver
import pytest
from pytest_httpserver import HTTPServer
from browser_use.browser import BrowserProfile, BrowserSession
# Fix for httpserver hanging on shutdown - prevent blocking on socket close
socketserver.ThreadingMixIn.block_on_close = False
socketserver.ThreadingM... | 399 | 15,535 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_registry.py | .py | """
Comprehensive tests for the action registry system to ensure backward compatibility
and proper parameter handling for all existing patterns.
Tests cover:
1. Existing parameter patterns (individual params, pydantic models)
2. Special parameter injection (browser_session, page_extraction_llm, etc.)
3. Action-to-acti... | 1,067 | 41,182 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_output_paths.py | .py | """Test all recording and save functionality for Agent and BrowserSession."""
from pathlib import Path
import pytest
from browser_use import Agent, AgentHistoryList
from browser_use.browser import BrowserProfile, BrowserSession
from tests.ci.conftest import create_mock_llm
@pytest.fixture
def test_dir(tmp_path):
... | 220 | 6,631 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_GetDropdownOptionsEvent_aria_menus.py | .py | import pytest
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.tools.service import Tools
from browser_use.tools.views import GoToUrlAction
@pyt... | 351 | 12,834 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_llm_custom_structured_ouput.py | .py | import json
import os
import tiktoken
from browser_use.agent.views import AgentOutput
from browser_use.llm.schema import SchemaOptimizer
from browser_use.tools.service import Tools
def test_optimized_schema():
"""Test the optimized schema generation and save to file."""
# Create tools and get all registered acti... | 91 | 3,222 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_agent_sensitive_data.py | .py | import pytest
from pydantic import BaseModel, Field
from browser_use.agent.message_manager.service import MessageManager
from browser_use.agent.views import MessageManagerState
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm import SystemMessage, UserMessage
from browser_use.llm.messages... | 272 | 13,400 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_recent_events.py | .py | """
Test browser session recent events tracking functionality.
"""
import json
import time
import pytest
from pytest_httpserver import HTTPServer
from werkzeug.wrappers import Response
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.events import NavigateToUrlEvent, Screenshot... | 356 | 13,131 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_sync_client_auth.py | .py | """
Tests for OAuth2 device flow and cloud sync functionality.
"""
import json
import tempfile
from datetime import datetime
from pathlib import Path
import anyio
import httpx
import pytest
from dotenv import load_dotenv
from pytest_httpserver import HTTPServer
# Load environment variables before any imports
load_do... | 994 | 30,997 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_take_screenshot.py | .py | import pytest
from browser_use.browser.events import NavigateToUrlEvent
from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
@pytest.fixture(scope='function')
async def browser_session():
session = BrowserSession(browser_profile=BrowserProfile(headless=True))... | 34 | 1,109 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_element_cache.py | .py | """
Systematic debugging of the selector map issue.
Test each assumption step by step to isolate the problem.
"""
import pytest
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.tools.service import Tools
@pytest.fixture
def httpserver(make_httpse... | 243 | 8,792 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_via_cdp_tab_management.py | .py | """Test CDP session handling when creating new tabs."""
import asyncio
import pytest
from browser_use.browser.events import NavigateToUrlEvent, TabCreatedEvent
from browser_use.browser.profile import BrowserProfile, ViewportSize
from browser_use.browser.session import BrowserSession
@pytest.fixture
async def https... | 122 | 3,978 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_filesystem.py | .py | """Tests for the FileSystem class and related file operations."""
import asyncio
import tempfile
from pathlib import Path
import pytest
from browser_use.filesystem.file_system import (
DEFAULT_FILE_SYSTEM_PATH,
INVALID_FILENAME_ERROR_MESSAGE,
CsvFile,
FileSystem,
FileSystemState,
JsonFile,
MarkdownFile,
TxtF... | 938 | 31,581 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_start.py | .py | """
Test script for BrowserSession.start() method to ensure proper initialization,
concurrency handling, and error handling.
Tests cover:
- Calling .start() on a session that's already started
- Simultaneously calling .start() from two parallel coroutines
- Calling .start() on a session that's started but has a closed... | 435 | 15,294 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_proxy.py | .py | import asyncio
from typing import Any
import pytest
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.profile import ProxySettings
from browser_use.config import CONFIG
def test_chromium_args_include_proxy_flags():
profile = BrowserProfile(
headless=True,
user_data_dir=str... | 114 | 3,786 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_radio_buttons.py | .py | # @file purpose: Test radio button interactions and serialization in browser-use
"""
Test file for verifying radio button clicking functionality and DOM serialization.
This test creates a simple HTML page with radio buttons, sends an agent to click them,
and logs the final agent message to show how radio buttons are r... | 106 | 3,281 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_screenshots.py | .py | """
Test that screenshots work correctly in headless browser mode.
"""
import asyncio
import base64
import time
import pytest
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.events import NavigateToUrlEvent, ScreenshotEvent
class TestHeadlessScreenshots:
"""Test screenshot ... | 404 | 15,792 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_llm_gemini_type_field_fix.py | .py | """
Test to reproduce and verify fix for GitHub issue #2470:
"Python field with name 'type' handled differently between Gemini and OpenAI GPT"
"""
from browser_use.llm.google.chat import ChatGoogle
from browser_use.llm.schema import SchemaOptimizer
class TestGeminiTypeFieldHandling:
"""Test class for reproducing th... | 108 | 3,855 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_url_shortening.py | .py | """
Simplified tests for URL shortening functionality in Agent service.
Three focused tests:
1. Input message processing with URL shortening
2. Output processing with custom actions and URL restoration
3. End-to-end pipeline test
"""
import json
import pytest
from browser_use.agent.service import Agent
from browser... | 162 | 7,644 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_crash.py | .py | """Test CrashWatchdog functionality."""
import asyncio
from typing import cast
import pytest
from browser_use.browser.events import (
BrowserConnectedEvent,
BrowserErrorEvent,
BrowserStartEvent,
BrowserStopEvent,
BrowserStoppedEvent,
NavigateToUrlEvent,
)
from browser_use.browser.profile import BrowserProfile
... | 329 | 11,746 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_NavigateToUrlEvent2.py | .py | """Test navigation events are emitted properly in all cases."""
import asyncio
import time
from typing import cast
import pytest
from browser_use.browser.events import (
ClickElementEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
NavigationStartedEvent,
TabCreatedEvent,
)
from browser_use.browser.profile im... | 380 | 14,196 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_downloads_simple.py | .py | """Test simple download functionality."""
import pytest
# Skip Playwright imports - removed dependency
from pytest_httpserver import HTTPServer
async def test_simple_playwright_download():
"""Test basic Playwright download functionality without browser-use - this just validates the browser setup"""
# Skip Playwri... | 34 | 1,088 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_ClickElementEvent.py | .py | import asyncio
import tempfile
from pathlib import Path
import pytest
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionResult
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.tools.service import Tools
from browser... | 1,312 | 47,060 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_telemetry.py | .py | """Test telemetry functionality."""
from unittest.mock import MagicMock, patch
import pytest
from browser_use.config import CONFIG
from browser_use.telemetry import (
CLITelemetryEvent,
MCPClientTelemetryEvent,
MCPServerTelemetryEvent,
ProductTelemetry,
)
from browser_use.utils import get_browser_use_version
@... | 287 | 8,905 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_llm_anthropic_502_error.py | .py | """Test for handling Anthropic 502 errors"""
import pytest
from anthropic import APIStatusError
from browser_use.llm.anthropic.chat import ChatAnthropic
from browser_use.llm.exceptions import ModelProviderError
from browser_use.llm.messages import BaseMessage, UserMessage
@pytest.mark.asyncio
async def test_anthrop... | 75 | 2,724 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_tab_management.py | .py | import asyncio
import logging
import pytest
from dotenv import load_dotenv
from pytest_httpserver import HTTPServer
load_dotenv()
from browser_use.agent.views import ActionModel
from browser_use.browser.events import NavigateToUrlEvent
from browser_use.browser.profile import BrowserProfile
from browser_use.browser.s... | 317 | 12,128 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_session_viewport_and_proxy.py | .py | async def test_proxy_settings_pydantic_model():
"""
Test that ProxySettings as a Pydantic model is correctly converted to a dictionary when used.
"""
# Create ProxySettings with Pydantic model
proxy_settings = dict(server='http://example.proxy:4242', bypass='localhost', username='testuser', password='testpass')
... | 22 | 945 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_llm_schema_optimizer.py | .py | """
Tests for the SchemaOptimizer to ensure it correctly processes and
optimizes the schemas for agent actions without losing information.
"""
from pydantic import BaseModel
from browser_use.agent.views import AgentOutput
from browser_use.llm.schema import SchemaOptimizer
from browser_use.tools.service import Tools
... | 67 | 2,752 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_NavigateToUrlEvent.py | .py | import asyncio
import pytest
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.tools.service import Tools
from browser_use.tools.views import GoTo... | 407 | 14,952 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_event_ScrollEvent.py | .py | import asyncio
import pytest
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.tools.service import Tools
from browser_use.tools.views import (
G... | 410 | 14,284 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/evaluate_tasks.py | .py | """
Runs all agent tasks in parallel (up to 10 at a time) using separate subprocesses.
Each task gets its own Python process, preventing browser session interference.
Does not fail on partial failures (always exits 0).
"""
import argparse
import asyncio
import glob
import json
import logging
import os
import sys
impor... | 347 | 10,892 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_browser_watchdog_security2.py | .py | from browser_use.browser import BrowserProfile, BrowserSession
class TestUrlAllowlistSecurity:
"""Tests for URL allowlist security bypass prevention and URL allowlist glob pattern matching."""
def test_authentication_bypass_prevention(self):
"""Test that the URL allowlist cannot be bypassed using authentication ... | 436 | 20,546 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_tools.py | .py | import asyncio
import tempfile
import time
import pytest
from pydantic import BaseModel
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.filesyst... | 583 | 20,616 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/test_cloud_browser.py | .py | """Tests for cloud browser functionality."""
import tempfile
from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
from browser_use.browser.cloud import (
CloudBrowserAuthError,
CloudBrowserClient,
CloudBrowserError,
get_cloud_browser_cdp_url,
stop_cloud_browser_session,
)
from brows... | 334 | 10,919 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/tests/ci/conftest.py | .py | """
Pytest configuration for browser-use CI tests.
Sets up environment variables to ensure tests never connect to production services.
"""
import os
import socketserver
import tempfile
from unittest.mock import AsyncMock
import pytest
from dotenv import load_dotenv
from pytest_httpserver import HTTPServer
# Fix for... | 240 | 6,837 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/utils.py | .py | import asyncio
import logging
import os
import platform
import re
import signal
import time
from collections.abc import Callable, Coroutine
from fnmatch import fnmatch
from functools import cache, wraps
from pathlib import Path
from sys import stderr
from typing import Any, ParamSpec, TypeVar
from urllib.parse import u... | 671 | 22,953 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/__init__.py | .py | import os
from typing import TYPE_CHECKING
from browser_use.logging_config import setup_logging
# Only set up logging if not in MCP mode or if explicitly requested
if os.environ.get('BROWSER_USE_SETUP_LOGGING', 'true').lower() != 'false':
from browser_use.config import CONFIG
# Get log file paths from config/envir... | 139 | 4,829 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/observability.py | .py | # @file purpose: Observability module for browser-use that handles optional lmnr integration with debug mode support
"""
Observability module for browser-use
This module provides observability decorators that optionally integrate with lmnr (Laminar) for tracing.
If lmnr is not installed, it provides no-op wrappers tha... | 203 | 6,030 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/logging_config.py | .py | import logging
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
from browser_use.config import CONFIG
def addLoggingLevel(levelName, levelNum, methodName=None):
"""
Comprehensively adds a new logging level to the `logging` module and the
currently configured logging cla... | 331 | 10,743 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/cli.py | .py | # pyright: reportMissingImports=false
# Check for MCP mode early to prevent logging initialization
import sys
if '--mcp' in sys.argv:
import logging
import os
os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical'
os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false'
logging.disable(logging.CRITICAL)
import asyncio
... | 2,003 | 70,030 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/config.py | .py | """Configuration system for browser-use with automatic migration support."""
import json
import logging
import os
from datetime import datetime
from functools import cache
from pathlib import Path
from typing import Any
from uuid import uuid4
import psutil
from pydantic import BaseModel, ConfigDict, Field
from pydant... | 506 | 16,336 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/filesystem/file_system.py | .py | import asyncio
import re
import shutil
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
from pydantic import BaseModel, Field
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportl... | 505 | 16,241 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/exceptions.py | .py | class ModelError(Exception):
pass
class ModelProviderError(ModelError):
"""Exception raised when a model provider returns an error."""
def __init__(
self,
message: str,
status_code: int = 502,
model: str | None = None,
):
super().__init__(message, status_code)
self.model = model
class ModelRateLimi... | 28 | 568 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/models.py | .py | """
Convenient access to LLM models.
Usage:
from browser_use import llm
# Simple model access
model = llm.azure_gpt_4_1_mini
model = llm.openai_gpt_4o
model = llm.google_gemini_2_5_pro
"""
import os
from typing import TYPE_CHECKING
from browser_use.llm.azure.chat import ChatAzureOpenAI
from brow... | 172 | 4,826 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/__init__.py | .py | """
We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.
For easier transition we have
"""
from typing import TYPE_CHECKING
# Lightweight imports that are commonly used
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import (
AssistantMessa... | 147 | 4,423 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/views.py | .py | from typing import Generic, TypeVar, Union
from pydantic import BaseModel
T = TypeVar('T', bound=Union[BaseModel, str])
class ChatInvokeUsage(BaseModel):
"""
Usage information for a chat model invocation.
"""
prompt_tokens: int
"""The number of tokens in the prompt (this includes the cached tokens as well. Wh... | 46 | 1,187 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/messages.py | .py | """
This implementation is based on the OpenAI types, while removing all the parts that are not needed for Browser Use.
"""
# region - Content parts
from typing import Literal, Union
from openai import BaseModel
def _truncate(text: str, max_length: int = 50) -> str:
"""Truncate text to max_length characters, addin... | 239 | 6,575 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/schema.py | .py | """
Utilities for creating optimized Pydantic schemas for LLM usage.
"""
from typing import Any
from pydantic import BaseModel
class SchemaOptimizer:
@staticmethod
def create_optimized_json_schema(model: type[BaseModel]) -> dict[str, Any]:
"""
Create the most optimized schema by flattening all $ref/$defs whil... | 162 | 5,864 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/base.py | .py | """
We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.
For easier transition we have
"""
from typing import Any, Protocol, TypeVar, overload, runtime_checkable
from pydantic import BaseModel
from browser_use.llm.messages import BaseMessage
from browser_use.llm.views ... | 58 | 1,495 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/deepseek/chat.py | .py | 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 pydantic import BaseModel
from browser_use.llm.base imp... | 213 | 6,780 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/groq/chat.py | .py | import logging
from dataclasses import dataclass
from typing import Literal, TypeVar, overload
from groq import (
APIError,
APIResponseValidationError,
APIStatusError,
AsyncGroq,
NotGiven,
RateLimitError,
Timeout,
)
from groq.types.chat import ChatCompletion, ChatCompletionToolChoiceOptionParam, ChatCompletionT... | 230 | 7,455 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/aws/chat_anthropic.py | .py | import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, TypeVar, overload
from anthropic import (
NOT_GIVEN,
APIConnectionError,
APIStatusError,
AsyncAnthropicBedrock,
RateLimitError,
)
from anthropic.types import CacheControlEphemeralParam, Message... | 243 | 8,037 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/aws/chat_bedrock.py | .py | import json
from dataclasses import dataclass
from os import getenv
from typing import TYPE_CHECKING, Any, TypeVar, overload
from pydantic import BaseModel
from browser_use.llm.aws.serializer import AWSBedrockMessageSerializer
from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import Model... | 290 | 9,288 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/tests/test_chat_models.py | .py | import os
import pytest
from pydantic import BaseModel
from browser_use.llm import ChatAnthropic, ChatGoogle, ChatGroq, ChatOpenAI, ChatOpenRouter
from browser_use.llm.messages import ContentPartTextParam
class CapitalResponse(BaseModel):
"""Structured response for capital question"""
country: str
capital: str
... | 249 | 8,716 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/tests/test_gemini_image.py | .py | import asyncio
import base64
import io
import random
from PIL import Image, ImageDraw, ImageFont
from browser_use.llm.google.chat import ChatGoogle
from browser_use.llm.google.serializer import GoogleMessageSerializer
from browser_use.llm.messages import (
BaseMessage,
ContentPartImageParam,
ContentPartTextParam,
... | 92 | 2,678 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/tests/test_single_step.py | .py | import logging
import tempfile
import pytest
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.service import Agent
from browser_use.browser.views import BrowserStateSummary, TabInfo
from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType, SerializedDOMState, Simp... | 189 | 5,790 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/tests/test_anthropic_cache.py | .py | import logging
from typing import cast
from browser_use.agent.service import Agent
from browser_use.llm.anthropic.chat import ChatAnthropic
from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer, NonSystemMessage
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartI... | 291 | 12,013 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/openai/chat.py | .py | from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from typing import Any, Literal, TypeVar, overload
import httpx
from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError
from openai.types.chat import ChatCompletionContentPartTextParam
from openai.types.ch... | 274 | 8,896 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/anthropic/chat.py | .py | import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from anthropic import (
NOT_GIVEN,
APIConnectionError,
APIStatusError,
AsyncAnthropic,
NotGiven,
RateLimitError,
)
from anthropic.types import CacheControlEphemeralParam, Messa... | 237 | 7,615 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/anthropic/serializer.py | .py | import json
from typing import overload
from anthropic.types import (
Base64ImageSourceParam,
CacheControlEphemeralParam,
ImageBlockParam,
MessageParam,
TextBlockParam,
ToolUseBlockParam,
URLImageSourceParam,
)
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartImageParam,
Con... | 313 | 10,338 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/google/chat.py | .py | import asyncio
import json
import logging
import time
from dataclasses import dataclass
from typing import Any, Literal, TypeVar, overload
from google import genai
from google.auth.credentials import Credentials
from google.genai import types
from google.genai.types import MediaModality
from pydantic import BaseModel
... | 507 | 17,358 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/google/serializer.py | .py | import base64
from google.genai.types import Content, ContentListUnion, Part
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
SystemMessage,
UserMessage,
)
class GoogleMessageSerializer:
"""Serializer for converting messages to Google Gemini format."""
@staticmethod
def serialize_messag... | 121 | 4,138 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/openrouter/chat.py | .py | from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, 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_js... | 209 | 6,402 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/ollama/chat.py | .py | from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from ollama import AsyncClient as OllamaAsyncClient
from ollama import Options
from pydantic import BaseModel
from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions impo... | 98 | 2,750 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/ollama/serializer.py | .py | import base64
import json
from typing import Any, overload
from ollama._types import Image, Message
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
SystemMessage,
ToolCall,
UserMessage,
)
class OllamaMessageSerializer:
"""Serializer for converting between custom message types and Ollama ... | 144 | 4,051 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/llm/azure/chat.py | .py | import os
from dataclasses import dataclass
from typing import Any
import httpx
from openai import AsyncAzureOpenAI as AsyncAzureOpenAIClient
from openai.types.shared import ChatModel
from browser_use.llm.openai.like import ChatOpenAILike
@dataclass
class ChatAzureOpenAI(ChatOpenAILike):
"""
A class for to intera... | 92 | 2,735 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tools/views.py | .py | from typing import Generic, TypeVar
from pydantic import BaseModel, ConfigDict, Field
# Action Input Models
class SearchGoogleAction(BaseModel):
query: str
class GoToUrlAction(BaseModel):
url: str
new_tab: bool = False # True to open in new tab, False to navigate in current tab
class ClickElementAction(BaseM... | 94 | 2,599 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tools/service.py | .py | import asyncio
import enum
import json
import logging
import os
from typing import Any, Generic, TypeVar
try:
from lmnr import Laminar # type: ignore
except ImportError:
Laminar = None # type: ignore
from pydantic import BaseModel
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.brow... | 1,312 | 53,346 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tools/registry/views.py | .py | from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ConfigDict
from browser_use.browser import BrowserSession
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
if TYPE_CHECKING:
pass
class RegisteredActio... | 162 | 5,280 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tools/registry/service.py | .py | import asyncio
import functools
import inspect
import logging
import re
from collections.abc import Callable
from inspect import Parameter, iscoroutinefunction, signature
from types import UnionType
from typing import Any, Generic, Optional, TypeVar, Union, get_args, get_origin
import pyotp
from pydantic import BaseMo... | 575 | 22,796 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tokens/views.py | .py | from datetime import datetime
from typing import Any, TypeVar
from pydantic import BaseModel, Field
from browser_use.llm.views import ChatInvokeUsage
T = TypeVar('T', bound=BaseModel)
class TokenUsageEntry(BaseModel):
"""Single token usage entry"""
model: str
timestamp: datetime
usage: ChatInvokeUsage
class... | 109 | 2,306 |
ai-agent-book | chapter9/browser-use-rpa/browser-use/browser_use/tokens/service.py | .py | """
Token cost service that tracks LLM token usage and costs.
Fetches pricing data from LiteLLM repository and caches it for 1 day.
Automatically tracks token usage when LLMs are registered and invoked.
"""
import asyncio
import logging
import os
from datetime import datetime, timedelta
from pathlib import Path
from ... | 569 | 19,886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.