|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Time : 2025/1/2 |
| 3 | +# @Author : wenshao |
| 4 | +# @ProjectName: browser-use-webui |
| 5 | +# @FileName: custom_agent.py |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import os |
| 11 | +import time |
| 12 | +import uuid |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any, Optional, Type, TypeVar |
| 15 | + |
| 16 | +from dotenv import load_dotenv |
| 17 | +from langchain_core.language_models.chat_models import BaseChatModel |
| 18 | +from langchain_core.messages import ( |
| 19 | + BaseMessage, |
| 20 | + SystemMessage, |
| 21 | +) |
| 22 | +from openai import RateLimitError |
| 23 | +from pydantic import BaseModel, ValidationError |
| 24 | + |
| 25 | +from browser_use.agent.message_manager.service import MessageManager |
| 26 | +from browser_use.agent.prompts import AgentMessagePrompt, SystemPrompt |
| 27 | +from browser_use.agent.views import ( |
| 28 | + ActionResult, |
| 29 | + AgentError, |
| 30 | + AgentHistory, |
| 31 | + AgentHistoryList, |
| 32 | + AgentOutput, |
| 33 | + AgentStepInfo, |
| 34 | +) |
| 35 | +from browser_use.telemetry.views import ( |
| 36 | + AgentEndTelemetryEvent, |
| 37 | + AgentRunTelemetryEvent, |
| 38 | + AgentStepErrorTelemetryEvent, |
| 39 | +) |
| 40 | +from browser_use.agent.service import Agent |
| 41 | +from browser_use.utils import time_execution_async |
| 42 | + |
| 43 | +from .custom_views import CustomAgentOutput |
| 44 | + |
| 45 | +logger = logging.getLogger(__name__) |
| 46 | + |
| 47 | + |
| 48 | +class CustomAgent(Agent): |
| 49 | + |
| 50 | + def _setup_action_models(self) -> None: |
| 51 | + """Setup dynamic action models from controller's registry""" |
| 52 | + # Get the dynamic action model from controller's registry |
| 53 | + self.ActionModel = self.controller.registry.create_action_model() |
| 54 | + # Create output model with the dynamic actions |
| 55 | + self.AgentOutput = CustomAgentOutput.type_with_custom_actions(self.ActionModel) |
| 56 | + |
| 57 | + def _log_response(self, response: CustomAgentOutput) -> None: |
| 58 | + """Log the model's response""" |
| 59 | + if 'Success' in response.current_state.evaluation_previous_goal: |
| 60 | + emoji = '👍' |
| 61 | + elif 'Failed' in response.current_state.evaluation_previous_goal: |
| 62 | + emoji = '⚠' |
| 63 | + else: |
| 64 | + emoji = '🤷' |
| 65 | + |
| 66 | + logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}') |
| 67 | + logger.info(f'🧠 Memory: {response.current_state.memory}') |
| 68 | + logger.info(f'🎯 Next goal: {response.current_state.next_goal}') |
| 69 | + for i, action in enumerate(response.action): |
| 70 | + logger.info( |
| 71 | + f'🛠️ Action {i + 1}/{len(response.action)}: {action.model_dump_json(exclude_unset=True)}' |
| 72 | + ) |
| 73 | + |
| 74 | + @time_execution_async('--step') |
| 75 | + async def step(self, step_info: Optional[AgentStepInfo] = None) -> None: |
| 76 | + """Execute one step of the task""" |
| 77 | + logger.info(f'\n📍 Step {self.n_steps}') |
| 78 | + state = None |
| 79 | + model_output = None |
| 80 | + result: list[ActionResult] = [] |
| 81 | + |
| 82 | + try: |
| 83 | + state = await self.browser_context.get_state(use_vision=self.use_vision) |
| 84 | + self.message_manager.add_state_message(state, self._last_result, step_info) |
| 85 | + input_messages = self.message_manager.get_messages() |
| 86 | + model_output = await self.get_next_action(input_messages) |
| 87 | + self._save_conversation(input_messages, model_output) |
| 88 | + self.message_manager._remove_last_state_message() # we dont want the whole state in the chat history |
| 89 | + self.message_manager.add_model_output(model_output) |
| 90 | + |
| 91 | + result: list[ActionResult] = await self.controller.multi_act( |
| 92 | + model_output.action, self.browser_context |
| 93 | + ) |
| 94 | + self._last_result = result |
| 95 | + |
| 96 | + if len(result) > 0 and result[-1].is_done: |
| 97 | + logger.info(f'📄 Result: {result[-1].extracted_content}') |
| 98 | + |
| 99 | + self.consecutive_failures = 0 |
| 100 | + |
| 101 | + except Exception as e: |
| 102 | + result = self._handle_step_error(e) |
| 103 | + self._last_result = result |
| 104 | + |
| 105 | + finally: |
| 106 | + if not result: |
| 107 | + return |
| 108 | + for r in result: |
| 109 | + if r.error: |
| 110 | + self.telemetry.capture( |
| 111 | + AgentStepErrorTelemetryEvent( |
| 112 | + agent_id=self.agent_id, |
| 113 | + error=r.error, |
| 114 | + ) |
| 115 | + ) |
| 116 | + if state: |
| 117 | + self._make_history_item(model_output, state, result) |
0 commit comments