sakthai-kaggle-notebooks / scripts /web-agent-job.py
Nanthasit's picture
Upload scripts/web-agent-job.py with huggingface_hub
5bfd895 verified
Raw History Blame
5.55 kB
#!/usr/bin/env python3
# /// script
# dependencies = ["smolagents", "transformers>=4.44", "torch>=2.0", "playwright>=1.40", "accelerate", "bitsandbytes", "pillow"]
# ///
"""SakThai Web Agent — headless browser automation via HF Jobs.
Root cause analysis of previous failures:
- Jobs 1-2: docstring format wrong (needs Google-style multi-line) — fixed
- Jobs 3-4: `type` tool name conflicts with Python builtin (shadows in BASE_PYTHON_TOOLS) — fix: inject into executor state
- Job 5: Playwright "cannot switch thread" error — fix: threading.local for per-thread pages
- All jobs wasted ~$3 due to launching before verifying locally — NEVER again
Usage: uv run python web-agent-job.py <url> <task>"""
import sys, os, subprocess, json, threading
subprocess.run(["playwright", "install", "chromium", "--with-deps"], capture_output=True)
from smolagents import CodeAgent, TransformersModel, tool
from playwright.sync_api import sync_playwright
# threading.local keeps a separate Playwright page per thread
# smolagents spawns a new thread per step via ThreadPoolExecutor timeout
_tls = threading.local()
def _ensure_page():
if not hasattr(_tls, "page") or _tls.page is None:
pw = sync_playwright().start()
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
_tls.page = browser.new_page()
_tls.pw = pw
_tls.browser = browser
return _tls.page
@tool
def navigate(url: str) -> str:
"""Navigate to a webpage.
Args:
url: The full URL to visit
"""
_ensure_page().goto(url, wait_until="domcontentloaded")
return f"Navigated to {url}"
@tool
def click(target: str) -> str:
"""Click an element by selector or text.
Args:
target: CSS selector, text label, or coordinate
"""
_ensure_page().click(target)
return f"Clicked {target}"
# NOTE: Cannot name this function 'type' because Python's builtin type() shadows it.
# The agent's code executor checks state dict first, then static_tools (which includes
# BASE_PYTHON_TOOLS['type'] = builtin type). By injecting into state after agent creation,
# our tool takes precedence. See below in main().
@tool
def type_into(selector: str, text: str) -> str:
"""Type text into a field.
Args:
selector: CSS selector for the input field
text: The text to type
"""
_ensure_page().fill(selector, text)
return f"Typed into {selector}"
@tool
def select(selector: str, value: str) -> str:
"""Select from dropdown.
Args:
selector: CSS selector for the select element
value: The option value to select
"""
_ensure_page().select_option(selector, value)
return f"Selected {value}"
@tool
def extract(selector: str = "body") -> str:
"""Extract text content.
Args:
selector: CSS selector to extract text from
"""
return _ensure_page().inner_text(selector)[:2000]
@tool
def scroll(direction: str = "down") -> str:
"""Scroll the page.
Args:
direction: up, down, top, or bottom
"""
cmds = {"up": "window.scrollBy(0,-500)", "down": "window.scrollBy(0,500)",
"top": "window.scrollTo(0,0)", "bottom": "window.scrollTo(0,document.body.scrollHeight)"}
_ensure_page().evaluate(cmds.get(direction, cmds["down"]))
return f"Scrolled {direction}"
@tool
def wait(ms: int = 1000) -> str:
"""Wait for milliseconds.
Args:
ms: Time to wait in milliseconds
"""
_ensure_page().wait_for_timeout(ms)
return f"Waited {ms}ms"
@tool
def press_key(key: str) -> str:
"""Press a keyboard key.
Args:
key: Key to press (e.g. Enter, Tab, Escape)
"""
_ensure_page().keyboard.press(key)
return f"Pressed {key}"
@tool
def screenshot() -> str:
"""Take screenshot."""
_ensure_page().screenshot()
return "Screenshot taken"
@tool
def go_back() -> str:
"""Go back to previous page."""
_ensure_page().go_back()
return "Went back"
@tool
def done(answer: str = "") -> str:
"""Mark task as complete.
Args:
answer: The final answer or summary
"""
return f"DONE: {answer}"
tools = [navigate, click, type_into, select, extract, scroll, wait, press_key, screenshot, go_back, done]
url = sys.argv[1] if len(sys.argv) > 1 else "https://www.google.com"
task = sys.argv[2] if len(sys.argv) > 2 else "search for sakthai coder browser"
prompt = (f"Go to {url} and {task}. Use navigate(), click(), type_into(), "
f"select(), extract(), scroll(), wait(), press_key(), go_back(), screenshot(), "
f"and done() as needed. When finished, call done() with a summary.")
print(f"URL: {url}", flush=True)
print(f"Task: {task}", flush=True)
print("Loading model Nanthasit/sakthai-coder-browser...", flush=True)
from transformers import BitsAndBytesConfig
import torch
quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
model = TransformersModel(
model_id="Nanthasit/sakthai-coder-browser",
device_map="auto", torch_dtype="auto", max_new_tokens=512,
model_kwargs={"quantization_config": quant},
)
agent = CodeAgent(tools=tools, model=model, max_steps=10, verbosity_level=2)
# Inject type_into as 'type' into executor state so it takes precedence over
# BASE_PYTHON_TOOLS['type'] (builtin). evaluate_name checks state FIRST, then static_tools.
agent.python_executor.state["type"] = agent.tools["type_into"]
result = agent.run(prompt)
print(f"\nResult: {result}", flush=True)