ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
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,
|
||||
)
|
||||
|
||||
# Lazy imports mapping
|
||||
_LAZY_IMPORTS = {
|
||||
'ProductTelemetry': ('browser_use.telemetry.service', 'ProductTelemetry'),
|
||||
'BaseTelemetryEvent': ('browser_use.telemetry.views', 'BaseTelemetryEvent'),
|
||||
'CLITelemetryEvent': ('browser_use.telemetry.views', 'CLITelemetryEvent'),
|
||||
'MCPClientTelemetryEvent': ('browser_use.telemetry.views', 'MCPClientTelemetryEvent'),
|
||||
'MCPServerTelemetryEvent': ('browser_use.telemetry.views', 'MCPServerTelemetryEvent'),
|
||||
}
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""Lazy import mechanism for telemetry components."""
|
||||
if name in _LAZY_IMPORTS:
|
||||
module_path, attr_name = _LAZY_IMPORTS[name]
|
||||
try:
|
||||
from importlib import import_module
|
||||
|
||||
module = import_module(module_path)
|
||||
attr = getattr(module, attr_name)
|
||||
# Cache the imported attribute in the module's globals
|
||||
globals()[name] = attr
|
||||
return attr
|
||||
except ImportError as e:
|
||||
raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e
|
||||
|
||||
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
|
||||
|
||||
|
||||
__all__ = [
|
||||
'BaseTelemetryEvent',
|
||||
'ProductTelemetry',
|
||||
'CLITelemetryEvent',
|
||||
'MCPClientTelemetryEvent',
|
||||
'MCPServerTelemetryEvent',
|
||||
]
|
||||
@@ -0,0 +1,112 @@
|
||||
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__)
|
||||
|
||||
|
||||
POSTHOG_EVENT_SETTINGS = {
|
||||
'process_person_profile': True,
|
||||
}
|
||||
|
||||
|
||||
@singleton
|
||||
class ProductTelemetry:
|
||||
"""
|
||||
Service for capturing anonymized telemetry data.
|
||||
|
||||
If the environment variable `ANONYMIZED_TELEMETRY=False`, anonymized telemetry will be disabled.
|
||||
"""
|
||||
|
||||
USER_ID_PATH = str(CONFIG.BROWSER_USE_CONFIG_DIR / 'device_id')
|
||||
PROJECT_API_KEY = 'phc_F8JMNjW1i2KbGUTaW1unnDdLSPCoyc52SGRU0JecaUh'
|
||||
HOST = 'https://eu.i.posthog.com'
|
||||
UNKNOWN_USER_ID = 'UNKNOWN'
|
||||
|
||||
_curr_user_id = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
telemetry_disabled = not CONFIG.ANONYMIZED_TELEMETRY
|
||||
self.debug_logging = CONFIG.BROWSER_USE_LOGGING_LEVEL == 'debug'
|
||||
|
||||
if telemetry_disabled:
|
||||
self._posthog_client = None
|
||||
else:
|
||||
logger.info('Using anonymized telemetry, see https://docs.browser-use.com/development/telemetry.')
|
||||
self._posthog_client = Posthog(
|
||||
project_api_key=self.PROJECT_API_KEY,
|
||||
host=self.HOST,
|
||||
disable_geoip=False,
|
||||
enable_exception_autocapture=True,
|
||||
)
|
||||
|
||||
# Silence posthog's logging
|
||||
if not self.debug_logging:
|
||||
posthog_logger = logging.getLogger('posthog')
|
||||
posthog_logger.disabled = True
|
||||
|
||||
if self._posthog_client is None:
|
||||
logger.debug('Telemetry disabled')
|
||||
|
||||
def capture(self, event: BaseTelemetryEvent) -> None:
|
||||
if self._posthog_client is None:
|
||||
return
|
||||
|
||||
self._direct_capture(event)
|
||||
|
||||
def _direct_capture(self, event: BaseTelemetryEvent) -> None:
|
||||
"""
|
||||
Should not be thread blocking because posthog magically handles it
|
||||
"""
|
||||
if self._posthog_client is None:
|
||||
return
|
||||
|
||||
try:
|
||||
self._posthog_client.capture(
|
||||
distinct_id=self.user_id,
|
||||
event=event.name,
|
||||
properties={**event.properties, **POSTHOG_EVENT_SETTINGS},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to send telemetry event {event.name}: {e}')
|
||||
|
||||
def flush(self) -> None:
|
||||
if self._posthog_client:
|
||||
try:
|
||||
self._posthog_client.flush()
|
||||
logger.debug('PostHog client telemetry queue flushed.')
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to flush PostHog client: {e}')
|
||||
else:
|
||||
logger.debug('PostHog client not available, skipping flush.')
|
||||
|
||||
@property
|
||||
def user_id(self) -> str:
|
||||
if self._curr_user_id:
|
||||
return self._curr_user_id
|
||||
|
||||
# File access may fail due to permissions or other reasons. We don't want to
|
||||
# crash so we catch all exceptions.
|
||||
try:
|
||||
if not os.path.exists(self.USER_ID_PATH):
|
||||
os.makedirs(os.path.dirname(self.USER_ID_PATH), exist_ok=True)
|
||||
with open(self.USER_ID_PATH, 'w') as f:
|
||||
new_user_id = uuid7str()
|
||||
f.write(new_user_id)
|
||||
self._curr_user_id = new_user_id
|
||||
else:
|
||||
with open(self.USER_ID_PATH) as f:
|
||||
self._curr_user_id = f.read()
|
||||
except Exception:
|
||||
self._curr_user_id = 'UNKNOWN_USER_ID'
|
||||
return self._curr_user_id
|
||||
@@ -0,0 +1,93 @@
|
||||
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 properties(self) -> dict[str, Any]:
|
||||
props = {k: v for k, v in asdict(self).items() if k != 'name'}
|
||||
# Add Docker context if running in Docker
|
||||
props['is_docker'] = is_running_in_docker()
|
||||
return props
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentTelemetryEvent(BaseTelemetryEvent):
|
||||
# start details
|
||||
task: str
|
||||
model: str
|
||||
model_provider: str
|
||||
max_steps: int
|
||||
max_actions_per_step: int
|
||||
use_vision: bool
|
||||
version: str
|
||||
source: str
|
||||
cdp_url: str | None
|
||||
# step details
|
||||
action_errors: Sequence[str | None]
|
||||
action_history: Sequence[list[dict] | None]
|
||||
urls_visited: Sequence[str | None]
|
||||
# end details
|
||||
steps: int
|
||||
total_input_tokens: int
|
||||
total_duration_seconds: float
|
||||
success: bool | None
|
||||
final_result_response: str | None
|
||||
error_message: str | None
|
||||
|
||||
name: str = 'agent_event'
|
||||
|
||||
|
||||
@dataclass
|
||||
class MCPClientTelemetryEvent(BaseTelemetryEvent):
|
||||
"""Telemetry event for MCP client usage"""
|
||||
|
||||
server_name: str
|
||||
command: str
|
||||
tools_discovered: int
|
||||
version: str
|
||||
action: str # 'connect', 'disconnect', 'tool_call'
|
||||
tool_name: str | None = None
|
||||
duration_seconds: float | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
name: str = 'mcp_client_event'
|
||||
|
||||
|
||||
@dataclass
|
||||
class MCPServerTelemetryEvent(BaseTelemetryEvent):
|
||||
"""Telemetry event for MCP server usage"""
|
||||
|
||||
version: str
|
||||
action: str # 'start', 'stop', 'tool_call'
|
||||
tool_name: str | None = None
|
||||
duration_seconds: float | None = None
|
||||
error_message: str | None = None
|
||||
parent_process_cmdline: str | None = None
|
||||
|
||||
name: str = 'mcp_server_event'
|
||||
|
||||
|
||||
@dataclass
|
||||
class CLITelemetryEvent(BaseTelemetryEvent):
|
||||
"""Telemetry event for CLI usage"""
|
||||
|
||||
version: str
|
||||
action: str # 'start', 'message_sent', 'task_completed', 'error'
|
||||
mode: str # 'interactive', 'oneshot', 'mcp_server'
|
||||
model: str | None = None
|
||||
model_provider: str | None = None
|
||||
duration_seconds: float | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
name: str = 'cli_event'
|
||||
Reference in New Issue
Block a user