mirror of
https://github.com/j93es/browser-use-oauth.git
synced 2026-06-04 03:31:51 +09:00
67 lines
2.7 KiB
Python
67 lines
2.7 KiB
Python
import json
|
|
from typing import Any
|
|
from pydantic import BaseModel
|
|
from browser_use import (
|
|
Agent,
|
|
Controller,
|
|
BrowserSession
|
|
)
|
|
from patchright.async_api import async_playwright as async_patchright
|
|
from lib.utils.logger import logger
|
|
from lib.prompt.get_sso_list import get_sso_list_task
|
|
from lib.browser_use_utils.create_google_ai import create_google_ai
|
|
from lib.browser_use_utils.get_profile import get_profile
|
|
from lib.browser_use_utils.clean_resources import clean_session_resources, clean_agent_resources
|
|
from lib.config import GOOGLE_MODEL
|
|
|
|
|
|
async def run_task(target_url: str, ReturnModel: type[BaseModel], task: str) -> tuple[bool, str | Any | None]:
|
|
session = BrowserSession(
|
|
playwright=(await async_patchright().start()),
|
|
browser_profile=await get_profile(),
|
|
)
|
|
|
|
initial_actions = [{"open_tab": {"url": target_url}}]
|
|
|
|
controller = Controller(output_model=ReturnModel, exclude_actions=['search_google'])
|
|
agent = Agent(
|
|
browser_session=session,
|
|
initial_actions=initial_actions,
|
|
task=task,
|
|
llm=create_google_ai(GOOGLE_MODEL),
|
|
controller=controller,
|
|
)
|
|
|
|
try:
|
|
response = await agent.run()
|
|
final_result = response.final_result()
|
|
|
|
if final_result is None:
|
|
logger(f"⚠️ 최종 결과가 없습니다. 에이전트 실행 실패: {target_url}")
|
|
print(f"⚠️ 최종 결과가 없습니다. 에이전트 실행 실패: {target_url}")
|
|
return False, "최종 결과가 없습니다. 에이전트 실행 실패"
|
|
except Exception as e:
|
|
# API 쿼터 문제인지 확인
|
|
if "ResourceExhausted" in str(e) or "429" in str(e):
|
|
logger(f"⚠️ API 쿼터 에러로 인한 실패: {target_url} | {e}")
|
|
print(f"⚠️ API 쿼터 에러로 인한 실패: {target_url} | {e}")
|
|
return False, "API 쿼터 에러로 인한 실패"
|
|
# 일반 에러 처리
|
|
else:
|
|
logger(f"⚠️ 일반 에러로 인한 실패: {target_url} | {e}")
|
|
print(f"⚠️ 일반 에러로 인한 실패: {target_url} | {e}")
|
|
return False, "일반 에러로 인한 실패"
|
|
finally:
|
|
await clean_agent_resources(agent)
|
|
|
|
try:
|
|
data = json.loads(final_result)
|
|
resp = ReturnModel(**data)
|
|
return True, resp
|
|
except Exception as e:
|
|
logger(f"⚠️ LLM 응답 결과 파싱 실패: {target_url} | {e}\n원본 결과: {data.msg}")
|
|
print(f"⚠️ LLM 응답 결과 파싱 실패: {target_url} | {e}\n원본 결과: {data.msg}")
|
|
return False, "LLM 응답 결과 파싱 실패"
|
|
finally:
|
|
await clean_session_resources(session)
|
|
|