code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
async def input_text(self, text: str) -> None: """Input text. Args: text: Text to input """ await self._adb.shell(self._serial, f"input text {text}")
Input text. Args: text: Text to input
input_text
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def press_key(self, keycode: int) -> None: """Press a key. Args: keycode: Android keycode to press """ await self._adb.shell(self._serial, f"input keyevent {keycode}")
Press a key. Args: keycode: Android keycode to press
press_key
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def start_activity( self, package: str, activity: str = ".MainActivity", extras: Optional[Dict[str, str]] = None ) -> None: """Start an app activity. Args: package: Package name activity: Activity name extras: Intent extras """ cmd = f"am start -n {package}/{activity}" if extras: for key, value in extras.items(): cmd += f" -e {key} {value}" await self._adb.shell(self._serial, cmd)
Start an app activity. Args: package: Package name activity: Activity name extras: Intent extras
start_activity
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def start_app(self, package: str, activity: str = "") -> str: """Start an app on the device. Args: package: Package name activity: Optional activity name (if empty, launches default activity) Returns: Result message """ if activity: if not activity.startswith(".") and "." not in activity: activity = f".{activity}" if not activity.startswith(".") and "." in activity and not activity.startswith(package): # Fully qualified activity name component = activity.split("/", 1) return await self.start_activity(component[0], component[1] if len(component) > 1 else activity) # Relative activity name return await self.start_activity(package, activity) # Start main activity using monkey cmd = f"monkey -p {package} -c android.intent.category.LAUNCHER 1" result = await self._adb.shell(self._serial, cmd) return f"Started {package}"
Start an app on the device. Args: package: Package name activity: Optional activity name (if empty, launches default activity) Returns: Result message
start_app
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def install_app(self, apk_path: str, reinstall: bool = False, grant_permissions: bool = True) -> str: """Install an APK on the device. Args: apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all requested permissions Returns: Installation result """ if not os.path.exists(apk_path): return f"Error: APK file not found: {apk_path}" # Build install command args install_args = ["install"] if reinstall: install_args.append("-r") if grant_permissions: install_args.append("-g") install_args.append(apk_path) try: stdout, stderr = await self._adb._run_device_command( self._serial, install_args, timeout=120 # Longer timeout for installation ) if "success" in stdout.lower(): return f"Successfully installed {os.path.basename(apk_path)}" return f"Installation failed: {stdout or stderr}" except Exception as e: return f"Installation failed: {str(e)}"
Install an APK on the device. Args: apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all requested permissions Returns: Installation result
install_app
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def uninstall_app(self, package: str, keep_data: bool = False) -> str: """Uninstall an app from the device. Args: package: Package name to uninstall keep_data: Whether to keep app data and cache directories Returns: Uninstallation result """ cmd = ["pm", "uninstall"] if keep_data: cmd.append("-k") cmd.append(package) result = await self._adb.shell(self._serial, " ".join(cmd)) return result.strip()
Uninstall an app from the device. Args: package: Package name to uninstall keep_data: Whether to keep app data and cache directories Returns: Uninstallation result
uninstall_app
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
async def list_packages(self, include_system_apps: bool = False) -> List[Dict[str, str]]: """List installed packages on the device. Args: include_system_apps: Whether to include system apps Returns: List of package dictionaries with 'package' and 'path' keys """ cmd = ["pm", "list", "packages", "-f"] if not include_system_apps: cmd.append("-3") output = await self._adb.shell(self._serial, " ".join(cmd)) packages = [] for line in output.splitlines(): if line.startswith("package:"): parts = line[8:].split("=") if len(parts) == 2: path, package = parts packages.append({ "package": package, "path": path }) return packages
List installed packages on the device. Args: include_system_apps: Whether to include system apps Returns: List of package dictionaries with 'package' and 'path' keys
list_packages
python
droidrun/droidrun
droidrun/adb/device.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py
MIT
def __init__(self, adb_path: Optional[str] = None): """Initialize device manager. Args: adb_path: Path to ADB binary """ self._adb = ADBWrapper(adb_path) self._devices: Dict[str, Device] = {}
Initialize device manager. Args: adb_path: Path to ADB binary
__init__
python
droidrun/droidrun
droidrun/adb/manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/manager.py
MIT
async def list_devices(self) -> List[Device]: """List connected devices. Returns: List of connected devices """ devices_info = await self._adb.get_devices() # Update device cache current_serials = set() for device_info in devices_info: serial = device_info["serial"] current_serials.add(serial) if serial not in self._devices: self._devices[serial] = Device(serial, self._adb) # Remove disconnected devices for serial in list(self._devices.keys()): if serial not in current_serials: del self._devices[serial] return list(self._devices.values())
List connected devices. Returns: List of connected devices
list_devices
python
droidrun/droidrun
droidrun/adb/manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/manager.py
MIT
async def get_device(self, serial: str) -> Optional[Device]: """Get a specific device. Args: serial: Device serial number Returns: Device instance if found, None otherwise """ if serial in self._devices: return self._devices[serial] # Try to find the device devices = await self.list_devices() for device in devices: if device.serial == serial: return device return None
Get a specific device. Args: serial: Device serial number Returns: Device instance if found, None otherwise
get_device
python
droidrun/droidrun
droidrun/adb/manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/manager.py
MIT
async def connect(self, host: str, port: int = 5555) -> Optional[Device]: """Connect to a device over TCP/IP. Args: host: Device IP address port: Device port Returns: Connected device instance """ try: serial = await self._adb.connect(host, port) return await self.get_device(serial) except Exception: return None
Connect to a device over TCP/IP. Args: host: Device IP address port: Device port Returns: Connected device instance
connect
python
droidrun/droidrun
droidrun/adb/manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/manager.py
MIT
async def disconnect(self, serial: str) -> bool: """Disconnect from a device. Args: serial: Device serial number Returns: True if disconnected successfully """ success = await self._adb.disconnect(serial) if success and serial in self._devices: del self._devices[serial] return success
Disconnect from a device. Args: serial: Device serial number Returns: True if disconnected successfully
disconnect
python
droidrun/droidrun
droidrun/adb/manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/manager.py
MIT
def __init__(self, adb_path: Optional[str] = None): """Initialize ADB wrapper. Args: adb_path: Path to ADB binary (defaults to 'adb' in PATH) """ self.adb_path = adb_path or "adb" self._devices_cache: List[Dict[str, str]] = []
Initialize ADB wrapper. Args: adb_path: Path to ADB binary (defaults to 'adb' in PATH)
__init__
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def _run_command( self, args: List[str], timeout: Optional[float] = None, check: bool = True ) -> Tuple[str, str]: """Run an ADB command. Args: args: Command arguments timeout: Command timeout in seconds check: Whether to check return code Returns: Tuple of (stdout, stderr) """ cmd = [self.adb_path, *args] try: process = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) if timeout is not None: stdout_bytes, stderr_bytes = await asyncio.wait_for( process.communicate(), timeout ) else: stdout_bytes, stderr_bytes = await process.communicate() stdout = stdout_bytes.decode("utf-8", errors="replace").strip() stderr = stderr_bytes.decode("utf-8", errors="replace").strip() if check and process.returncode != 0: raise RuntimeError(f"ADB command failed: {stderr or stdout}") return stdout, stderr except asyncio.TimeoutError: raise TimeoutError(f"ADB command timed out: {' '.join(cmd)}") except FileNotFoundError: raise FileNotFoundError(f"ADB not found at {self.adb_path}")
Run an ADB command. Args: args: Command arguments timeout: Command timeout in seconds check: Whether to check return code Returns: Tuple of (stdout, stderr)
_run_command
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def _run_device_command( self, serial: str, args: List[str], timeout: Optional[float] = None, check: bool = True ) -> Tuple[str, str]: """Run an ADB command for a specific device.""" return await self._run_command(["-s", serial, *args], timeout, check)
Run an ADB command for a specific device.
_run_device_command
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def get_devices(self) -> List[Dict[str, str]]: """Get list of connected devices. Returns: List of device info dictionaries with 'serial' and 'status' keys """ stdout, _ = await self._run_command(["devices", "-l"]) devices = [] for line in stdout.splitlines()[1:]: # Skip first line (header) if not line.strip(): continue parts = line.split() if not parts: continue serial = parts[0] status = parts[1] if len(parts) > 1 else "unknown" devices.append({ "serial": serial, "status": status }) self._devices_cache = devices return devices
Get list of connected devices. Returns: List of device info dictionaries with 'serial' and 'status' keys
get_devices
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def connect(self, host: str, port: int = 5555) -> str: """Connect to a device over TCP/IP. Args: host: Device IP address port: Device port Returns: Device serial number (host:port) """ serial = f"{host}:{port}" # Check if already connected devices = await self.get_devices() if any(d["serial"] == serial for d in devices): return serial stdout, _ = await self._run_command(["connect", serial], timeout=10.0) if "connected" not in stdout.lower(): raise RuntimeError(f"Failed to connect: {stdout}") return serial
Connect to a device over TCP/IP. Args: host: Device IP address port: Device port Returns: Device serial number (host:port)
connect
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def disconnect(self, serial: str) -> bool: """Disconnect from a device. Args: serial: Device serial number Returns: True if disconnected successfully """ try: stdout, _ = await self._run_command(["disconnect", serial]) return "disconnected" in stdout.lower() except Exception: return False
Disconnect from a device. Args: serial: Device serial number Returns: True if disconnected successfully
disconnect
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def shell(self, serial: str, command: str, timeout: Optional[float] = None) -> str: """Run a shell command on the device. Args: serial: Device serial number command: Shell command to run timeout: Command timeout in seconds Returns: Command output """ stdout, _ = await self._run_device_command(serial, ["shell", command], timeout=timeout) return stdout
Run a shell command on the device. Args: serial: Device serial number command: Shell command to run timeout: Command timeout in seconds Returns: Command output
shell
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def get_properties(self, serial: str) -> Dict[str, str]: """Get device properties. Args: serial: Device serial number Returns: Dictionary of device properties """ output = await self.shell(serial, "getprop") properties = {} for line in output.splitlines(): if not line or "[" not in line or "]" not in line: continue try: key = line.split("[")[1].split("]")[0] value = line.split("[")[2].split("]")[0] properties[key] = value except IndexError: continue return properties
Get device properties. Args: serial: Device serial number Returns: Dictionary of device properties
get_properties
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def install_app( self, serial: str, apk_path: str, reinstall: bool = False, grant_permissions: bool = True ) -> Tuple[str, str]: """Install an APK on the device. Args: serial: Device serial number apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all permissions Returns: Tuple of (stdout, stderr) """ args = ["install"] if reinstall: args.append("-r") if grant_permissions: args.append("-g") args.append(apk_path) return await self._run_device_command(serial, args, timeout=120.0)
Install an APK on the device. Args: serial: Device serial number apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all permissions Returns: Tuple of (stdout, stderr)
install_app
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
async def pull_file(self, serial: str, device_path: str, local_path: str) -> Tuple[str, str]: """Pull a file from the device. Args: serial: Device serial number device_path: Path on the device local_path: Path on the local machine Returns: Tuple of (stdout, stderr) """ # Create directory if it doesn't exist local_dir = os.path.dirname(local_path) if local_dir and not os.path.exists(local_dir): os.makedirs(local_dir) return await self._run_device_command(serial, ["pull", device_path, local_path], timeout=60.0)
Pull a file from the device. Args: serial: Device serial number device_path: Path on the device local_path: Path on the local machine Returns: Tuple of (stdout, stderr)
pull_file
python
droidrun/droidrun
droidrun/adb/wrapper.py
https://github.com/droidrun/droidrun/blob/master/droidrun/adb/wrapper.py
MIT
def async_to_sync(func): """ Convert an async function to a sync function. Args: func: Async function to convert Returns: Callable: Synchronous version of the async function """ def wrapper(*args, **kwargs): return asyncio.run(func(*args, **kwargs)) return wrapper
Convert an async function to a sync function. Args: func: Async function to convert Returns: Callable: Synchronous version of the async function
async_to_sync
python
droidrun/droidrun
droidrun/agent/utils/async_utils.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/async_utils.py
MIT
async def add_ui_text_block(ui_state: str, chat_history: List[ChatMessage], copy = True) -> List[ChatMessage]: """Add UI elements to the chat history without modifying the original.""" if ui_state: ui_block = TextBlock(text="\nCurrent Clickable UI elements from the device using the custom TopViewService:\n```json\n" + json.dumps(ui_state) + "\n```\n") if copy: chat_history = chat_history.copy() chat_history[-1] = message_copy(chat_history[-1]) chat_history[-1].blocks.append(ui_block) return chat_history
Add UI elements to the chat history without modifying the original.
add_ui_text_block
python
droidrun/droidrun
droidrun/agent/utils/chat_utils.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/chat_utils.py
MIT
def __init__(self, loop: AbstractEventLoop, locals: Dict[str, Any] = {}, globals: Dict[str, Any] = {}, tools = {}, use_same_scope: bool = True): """ Initialize the code executor. Args: locals: Local variables to use in the execution context globals: Global variables to use in the execution context tools: List of tools available for execution """ # loop throught tools and add them to globals, but before that check if tool value is async, if so convert it to sync. tools is a dictionary of tool name: function # e.g. tools = {'tool_name': tool_function} # check if tools is a dictionary if isinstance(tools, dict): for tool_name, tool_function in tools.items(): if asyncio.iscoroutinefunction(tool_function): # If the function is async, convert it to sync tool_function = async_to_sync(tool_function) # Add the tool to globals globals[tool_name] = tool_function elif isinstance(tools, list): # If tools is a list, convert it to a dictionary with tool name as key and function as value for tool in tools: if asyncio.iscoroutinefunction(tool): # If the function is async, convert it to sync tool = async_to_sync(tool) # Add the tool to globals globals[tool.__name__] = tool else: raise ValueError("Tools must be a dictionary or a list of functions.") import time globals['time'] = time self.globals = globals self.locals = locals self.loop = loop self.use_same_scope = use_same_scope if self.use_same_scope: # If using the same scope, set the globals and locals to the same dictionary self.globals = self.locals = {**self.locals, **{k: v for k, v in self.globals.items() if k not in self.locals}}
Initialize the code executor. Args: locals: Local variables to use in the execution context globals: Global variables to use in the execution context tools: List of tools available for execution
__init__
python
droidrun/droidrun
droidrun/agent/utils/executer.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/executer.py
MIT
async def execute(self, ctx: Context, code: str) -> str: """ Execute Python code and capture output and return values. Args: code: Python code to execute Returns: str: Output from the execution, including print statements. """ # Update UI elements before execution self.globals['ui_elements'] = await ctx.get("ui_state") # Capture stdout and stderr stdout = io.StringIO() stderr = io.StringIO() output = "" try: # Execute with captured output with contextlib.redirect_stdout( stdout ), contextlib.redirect_stderr(stderr): def execute_code(): exec(code, self.globals, self.locals) t = threading.Thread(target=execute_code) t.start() t.join() # Get output output = stdout.getvalue() if stderr.getvalue(): output += "\n" + stderr.getvalue() except Exception as e: # Capture exception information output = f"Error: {type(e).__name__}: {str(e)}\n" output += traceback.format_exc() return output
Execute Python code and capture output and return values. Args: code: Python code to execute Returns: str: Output from the execution, including print statements.
execute
python
droidrun/droidrun
droidrun/agent/utils/executer.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/executer.py
MIT
def load_llm(provider_name: str, **kwargs: Any) -> LLM: """ Dynamically loads and initializes a LlamaIndex LLM. Imports `llama_index.llms.<provider_name_lower>`, finds the class named `provider_name` within that module, verifies it's an LLM subclass, and initializes it with kwargs. Args: provider_name: The case-sensitive name of the provider and the class (e.g., "OpenAI", "Ollama", "HuggingFaceLLM"). **kwargs: Keyword arguments for the LLM class constructor. Returns: An initialized LLM instance. Raises: ModuleNotFoundError: If the provider's module cannot be found. AttributeError: If the class `provider_name` is not found in the module. TypeError: If the found class is not a subclass of LLM or if kwargs are invalid. RuntimeError: For other initialization errors. """ if not provider_name: raise ValueError("provider_name cannot be empty.") if provider_name == "OpenAILike": module_provider_part = "openai_like" elif provider_name == "GoogleGenAI": module_provider_part = "google_genai" else: # Use lowercase for module path, handle hyphens for package name suggestion lower_provider_name = provider_name.lower() # Special case common variations like HuggingFaceLLM -> huggingface module if lower_provider_name.endswith("llm"): module_provider_part = lower_provider_name[:-3].replace("-", "_") else: module_provider_part = lower_provider_name.replace("-", "_") module_path = f"llama_index.llms.{module_provider_part}" install_package_name = f"llama-index-llms-{module_provider_part.replace('_', '-')}" try: logger.info(f"Attempting to import module: {module_path}") llm_module = importlib.import_module(module_path) logger.info(f"Successfully imported module: {module_path}") except ModuleNotFoundError: logger.error(f"Module '{module_path}' not found. Try: pip install {install_package_name}") raise ModuleNotFoundError( f"Could not import '{module_path}'. Is '{install_package_name}' installed?" ) from None try: logger.info(f"Attempting to get class '{provider_name}' from module {module_path}") llm_class = getattr(llm_module, provider_name) logger.info(f"Found class: {llm_class.__name__}") # Verify the class is a subclass of LLM if not isinstance(llm_class, type) or not issubclass(llm_class, LLM): raise TypeError(f"Class '{provider_name}' found in '{module_path}' is not a valid LLM subclass.") # Filter out None values from kwargs filtered_kwargs = {k: v for k, v in kwargs.items() if v is not None} # Initialize logger.info(f"Initializing {llm_class.__name__} with kwargs: {list(filtered_kwargs.keys())}") llm_instance = llm_class(**filtered_kwargs) logger.info(f"Successfully loaded and initialized LLM: {provider_name}") if not llm_instance: raise RuntimeError(f"Failed to initialize LLM instance for {provider_name}.") return llm_instance except AttributeError: logger.error(f"Class '{provider_name}' not found in module '{module_path}'.") raise AttributeError( f"Could not find class '{provider_name}' in module '{module_path}'. Check spelling and capitalization." ) from None except TypeError as e: logger.error(f"Error initializing {provider_name}: {e}") raise # Re-raise TypeError (could be from issubclass check or __init__) except Exception as e: logger.error(f"An unexpected error occurred initializing {provider_name}: {e}") raise e
Dynamically loads and initializes a LlamaIndex LLM. Imports `llama_index.llms.<provider_name_lower>`, finds the class named `provider_name` within that module, verifies it's an LLM subclass, and initializes it with kwargs. Args: provider_name: The case-sensitive name of the provider and the class (e.g., "OpenAI", "Ollama", "HuggingFaceLLM"). **kwargs: Keyword arguments for the LLM class constructor. Returns: An initialized LLM instance. Raises: ModuleNotFoundError: If the provider's module cannot be found. AttributeError: If the class `provider_name` is not found in the module. TypeError: If the found class is not a subclass of LLM or if kwargs are invalid. RuntimeError: For other initialization errors.
load_llm
python
droidrun/droidrun
droidrun/agent/utils/llm_picker.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/llm_picker.py
MIT
def set_tasks(self, tasks: List[str], task_contexts: Optional[List[Dict[str, Any]]] = None): """ Clears the current task list and sets new tasks from a list. Each task should be a string. Args: tasks: A list of strings, each representing a task. task_contexts: Optional list of context dictionaries for each task. """ try: # Save any completed or failed tasks before clearing the list for task in self.tasks: if task["status"] == self.STATUS_COMPLETED and task not in self.persistent_completed_tasks: # Store a copy to prevent modifications self.persistent_completed_tasks.append(task.copy()) elif task["status"] == self.STATUS_FAILED and task not in self.persistent_failed_tasks: # Store a copy to prevent modifications self.persistent_failed_tasks.append(task.copy()) # Now clear the task list and add new tasks self.tasks = [] for i, task in enumerate(tasks): if not isinstance(task, str) or not task.strip(): raise ValueError("Each task must be a non-empty string.") task_dict = { "description": task.strip(), "status": self.STATUS_PENDING } # Add context if provided if task_contexts and i < len(task_contexts): task_dict["context"] = task_contexts[i] self.tasks.append(task_dict) print(f"Tasks set: {len(self.tasks)} tasks added.") self.save_to_file() except Exception as e: print(f"Error setting tasks: {e}")
Clears the current task list and sets new tasks from a list. Each task should be a string. Args: tasks: A list of strings, each representing a task. task_contexts: Optional list of context dictionaries for each task.
set_tasks
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def add_task(self, task_description: str, task_context: Optional[Dict[str, Any]] = None): """ Adds a new task to the list with a 'pending' status. Args: task_description: The string describing the task. task_context: Optional dictionary with context for the task. Returns: int: The index of the newly added task. Raises: ValueError: If the task_description is empty or not a string. """ if not isinstance(task_description, str) or not task_description.strip(): raise ValueError("Task description must be a non-empty string.") task = { "description": task_description.strip(), "status": self.STATUS_PENDING } # Add context if provided if task_context: task["context"] = task_context self.tasks.append(task) self.save_to_file() print(f"Task added: {task_description} (Status: {self.STATUS_PENDING})") return len(self.tasks) - 1 # Return the index of the new task
Adds a new task to the list with a 'pending' status. Args: task_description: The string describing the task. task_context: Optional dictionary with context for the task. Returns: int: The index of the newly added task. Raises: ValueError: If the task_description is empty or not a string.
add_task
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def get_task(self, index: int): """ Retrieves a specific task by its index. Args: index: The integer index of the task. Returns: dict: The task dictionary {'description': str, 'status': str}. Raises: IndexError: If the index is out of bounds. """ if 0 <= index < len(self.tasks): return self.tasks[index] else: raise IndexError(f"Task index {index} out of bounds.")
Retrieves a specific task by its index. Args: index: The integer index of the task. Returns: dict: The task dictionary {'description': str, 'status': str}. Raises: IndexError: If the index is out of bounds.
get_task
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def update_status(self, index: int, new_status: str, result_info: Optional[Dict[str, Any]] = None): """ Updates the status of a specific task. Args: index: The index of the task to update. new_status: The new status string (must be one of VALID_STATUSES). result_info: Optional dictionary with additional information about the task result. Raises: IndexError: If the index is out of bounds. ValueError: If the new_status is not a valid status. """ if new_status not in self.VALID_STATUSES: raise ValueError(f"Invalid status '{new_status}'. Valid statuses are: {', '.join(self.VALID_STATUSES)}") # get_task will raise IndexError if index is invalid task = self.get_task(index) old_status = task["status"] task["status"] = new_status # Add result information if provided if result_info: for key, value in result_info.items(): task[key] = value # Store task history when status changes if old_status != new_status: history_entry = { "index": index, "description": task["description"], "old_status": old_status, "new_status": new_status, "result_info": result_info } self.task_history.append(history_entry) # If the task is now completed or failed, add it to our persistent lists if new_status == self.STATUS_COMPLETED: # Make a copy to ensure it doesn't change if the original task is modified task_copy = task.copy() if task_copy not in self.persistent_completed_tasks: self.persistent_completed_tasks.append(task_copy) elif new_status == self.STATUS_FAILED: # Make a copy to ensure it doesn't change if the original task is modified task_copy = task.copy() if task_copy not in self.persistent_failed_tasks: self.persistent_failed_tasks.append(task_copy) self.save_to_file() # No need to re-assign task to self.tasks[index] as dictionaries are mutable
Updates the status of a specific task. Args: index: The index of the task to update. new_status: The new status string (must be one of VALID_STATUSES). result_info: Optional dictionary with additional information about the task result. Raises: IndexError: If the index is out of bounds. ValueError: If the new_status is not a valid status.
update_status
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def delete_task(self, index: int): """ Deletes a task by its index. Args: index: The index of the task to delete. Raises: IndexError: If the index is out of bounds. """ if 0 <= index < len(self.tasks): del self.tasks[index] self.save_to_file() else: raise IndexError(f"Task index {index} out of bounds.")
Deletes a task by its index. Args: index: The index of the task to delete. Raises: IndexError: If the index is out of bounds.
delete_task
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def clear_tasks(self): """Removes all tasks from the list.""" self.tasks = [] print("All tasks cleared.") self.save_to_file()
Removes all tasks from the list.
clear_tasks
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def get_tasks_by_status(self, status: str): """ Filters and returns tasks matching a specific status. Args: status: The status string to filter by. Returns: list[dict]: A list of tasks matching the status. Raises: ValueError: If the status is not a valid status. """ if status not in self.VALID_STATUSES: raise ValueError(f"Invalid status '{status}'. Valid statuses are: {', '.join(self.VALID_STATUSES)}") return [task for task in self.tasks if task["status"] == status]
Filters and returns tasks matching a specific status. Args: status: The status string to filter by. Returns: list[dict]: A list of tasks matching the status. Raises: ValueError: If the status is not a valid status.
get_tasks_by_status
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def __str__(self): """Provides a user-friendly string representation of the task list.""" if not self.tasks: return "Task List (empty)" output = "Task List:\n" output += "----------\n" for i, task in enumerate(self.tasks): output += f"{i}: [{task['status'].upper():<10}] {task['description']}\n" output += "----------" return output
Provides a user-friendly string representation of the task list.
__str__
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def save_to_file(self, filename=file_path): """Saves the current task list to a Markdown file.""" try: with open(filename, 'w', encoding='utf-8') as f: f.write(str(self)) #print(f"Tasks saved to {filename}.") except Exception as e: print(f"Error saving tasks to file: {e}")
Saves the current task list to a Markdown file.
save_to_file
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def complete_goal(self, message: str): """ Marks the goal as completed, use this whether the task completion was successful or on failure. This method should be called when the task is finished, regardless of the outcome. Args: message: The message to be logged. """ self.task_completed = True self.message = message print(f"Goal completed: {message}")
Marks the goal as completed, use this whether the task completion was successful or on failure. This method should be called when the task is finished, regardless of the outcome. Args: message: The message to be logged.
complete_goal
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def start_agent(self): """Starts the sub-agent to perform the tasks if there are any tasks to perform. Use this function after setting the tasks. Args: None""" if len(self.tasks) == 0: print("No tasks to perform.") return self.start_execution = True
Starts the sub-agent to perform the tasks if there are any tasks to perform. Use this function after setting the tasks. Args: None
start_agent
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def get_all_completed_tasks(self) -> List[Dict]: """ Returns all completed tasks, including those from previous planning cycles. Returns: List of completed task dictionaries """ # Get currently active completed tasks current_completed = self.get_completed_tasks() # Create a combined list, ensuring no duplicates all_completed = [] # Add current completed tasks for task in current_completed: if task not in all_completed: all_completed.append(task) # Add historical completed tasks for task in self.persistent_completed_tasks: # Check if task is already in the list based on description if not any(t["description"] == task["description"] for t in all_completed): all_completed.append(task) return all_completed
Returns all completed tasks, including those from previous planning cycles. Returns: List of completed task dictionaries
get_all_completed_tasks
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def get_all_failed_tasks(self) -> List[Dict]: """ Returns all failed tasks, including those from previous planning cycles. Returns: List of failed task dictionaries """ # Get currently active failed tasks current_failed = self.get_tasks_by_status(self.STATUS_FAILED) # Create a combined list, ensuring no duplicates all_failed = [] # Add current failed tasks for task in current_failed: if task not in all_failed: all_failed.append(task) # Add historical failed tasks for task in self.persistent_failed_tasks: # Check if task is already in the list based on description if not any(t["description"] == task["description"] for t in all_failed): all_failed.append(task) return all_failed
Returns all failed tasks, including those from previous planning cycles. Returns: List of failed task dictionaries
get_all_failed_tasks
python
droidrun/droidrun
droidrun/agent/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/task_manager.py
MIT
def create_screenshot_gif(self, output_path: str, duration: int = 1000) -> str: """ Create a GIF from a list of screenshots. Args: output_path: Base path for the GIF (without extension) duration: Duration for each frame in milliseconds Returns: Path to the created GIF file """ if len(self.screenshots) == 0: return None images = [] for screenshot in self.screenshots: img_data = screenshot img = Image.open(io.BytesIO(img_data)) images.append(img) # Save as GIF gif_path = f"{output_path}.gif" images[0].save( gif_path, save_all=True, append_images=images[1:], duration=duration, loop=0 ) return gif_path
Create a GIF from a list of screenshots. Args: output_path: Base path for the GIF (without extension) duration: Duration for each frame in milliseconds Returns: Path to the created GIF file
create_screenshot_gif
python
droidrun/droidrun
droidrun/agent/utils/trajectory.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/trajectory.py
MIT
def save_trajectory( self, directory: str = "trajectories", ) -> str: """ Save trajectory steps to a JSON file and create a GIF of screenshots if available. Args: directory: Directory to save the trajectory files Returns: Path to the saved trajectory file """ os.makedirs(directory, exist_ok=True) timestamp = time.strftime("%Y%m%d_%H%M%S") base_path = os.path.join(directory, f"trajectory_{timestamp}") def make_serializable(obj): """Recursively make objects JSON serializable.""" if hasattr(obj, "__class__") and obj.__class__.__name__ == "ChatMessage": # Extract the text content from the ChatMessage if hasattr(obj, "content") and obj.content is not None: return {"role": obj.role.value, "content": obj.content} # If content is not available, try extracting from blocks elif hasattr(obj, "blocks") and obj.blocks: text_content = "" for block in obj.blocks: if hasattr(block, "text"): text_content += block.text return {"role": obj.role.value, "content": text_content} else: return str(obj) elif isinstance(obj, dict): return {k: make_serializable(v) for k, v in obj.items()} elif isinstance(obj, list): return [make_serializable(item) for item in obj] elif hasattr(obj, "__dict__"): # Handle other custom objects by converting to dict return {k: make_serializable(v) for k, v in obj.__dict__.items() if not k.startswith('_')} else: return obj serializable_events = [] for event in self.events: event_dict = { "type": event.__class__.__name__, **{k: make_serializable(v) for k, v in event.__dict__.items() if not k.startswith('_')} } serializable_events.append(event_dict) json_path = f"{base_path}.json" with open(json_path, "w") as f: json.dump(serializable_events, f, indent=2) self.create_screenshot_gif(base_path) return json_path
Save trajectory steps to a JSON file and create a GIF of screenshots if available. Args: directory: Directory to save the trajectory files Returns: Path to the saved trajectory file
save_trajectory
python
droidrun/droidrun
droidrun/agent/utils/trajectory.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/trajectory.py
MIT
def get_trajectory_statistics(trajectory_data: Dict[str, Any]) -> Dict[str, Any]: """ Get statistics about a trajectory. Args: trajectory_data: The trajectory data dictionary Returns: Dictionary with statistics about the trajectory """ trajectory_steps = trajectory_data.get("trajectory_steps", []) # Count different types of steps step_types = {} for step in trajectory_steps: step_type = step.get("type", "unknown") step_types[step_type] = step_types.get(step_type, 0) + 1 # Count planning vs execution steps planning_steps = sum(count for step_type, count in step_types.items() if step_type.startswith("planner_")) execution_steps = sum(count for step_type, count in step_types.items() if step_type.startswith("codeact_")) # Count successful vs failed executions successful_executions = sum(1 for step in trajectory_steps if step.get("type") == "codeact_execution" and step.get("success", False)) failed_executions = sum(1 for step in trajectory_steps if step.get("type") == "codeact_execution" and not step.get("success", True)) # Return statistics return { "total_steps": len(trajectory_steps), "step_types": step_types, "planning_steps": planning_steps, "execution_steps": execution_steps, "successful_executions": successful_executions, "failed_executions": failed_executions, "goal_achieved": trajectory_data.get("success", False) }
Get statistics about a trajectory. Args: trajectory_data: The trajectory data dictionary Returns: Dictionary with statistics about the trajectory
get_trajectory_statistics
python
droidrun/droidrun
droidrun/agent/utils/trajectory.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/trajectory.py
MIT
def print_trajectory_summary(self, trajectory_data: Dict[str, Any]) -> None: """ Print a summary of a trajectory. Args: trajectory_data: The trajectory data dictionary """ stats = self.get_trajectory_statistics(trajectory_data) print("=== Trajectory Summary ===") print(f"Goal: {trajectory_data.get('goal', 'Unknown')}") print(f"Success: {trajectory_data.get('success', False)}") print(f"Reason: {trajectory_data.get('reason', 'Unknown')}") print(f"Total steps: {stats['total_steps']}") print("Step breakdown:") for step_type, count in stats['step_types'].items(): print(f" - {step_type}: {count}") print(f"Planning steps: {stats['planning_steps']}") print(f"Execution steps: {stats['execution_steps']}") print(f"Successful executions: {stats['successful_executions']}") print(f"Failed executions: {stats['failed_executions']}") print("==========================")
Print a summary of a trajectory. Args: trajectory_data: The trajectory data dictionary
print_trajectory_summary
python
droidrun/droidrun
droidrun/agent/utils/trajectory.py
https://github.com/droidrun/droidrun/blob/master/droidrun/agent/utils/trajectory.py
MIT
def __init__(self, logs: List[str], debug: bool = False): """ Initialize the event handler. Args: logs: List to append log messages to update_display_callback: Callback function to update the display """ self.logs = logs self.debug = debug self.current_step = "Initializing..." self.is_completed = False self.is_success = None
Initialize the event handler. Args: logs: List to append log messages to update_display_callback: Callback function to update the display
__init__
python
droidrun/droidrun
droidrun/cli/event_handler.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/event_handler.py
MIT
def create_layout(): """Create a layout with logs at top and status at bottom""" layout = Layout() layout.split( Layout(name="logs"), Layout(name="goal", size=3), Layout(name="status", size=3) ) return layout
Create a layout with logs at top and status at bottom
create_layout
python
droidrun/droidrun
droidrun/cli/main.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/main.py
MIT
def configure_logging(debug: bool): """Configure logging verbosity based on debug flag.""" warnings.filterwarnings("ignore") logging.getLogger().setLevel(logging.CRITICAL + 1) logging.getLogger().disabled = True for logger_name in list(logging.Logger.manager.loggerDict.keys()): logger = logging.getLogger(logger_name) logger.disabled = True logger.handlers = [] logger.propagate = False logger.setLevel(logging.CRITICAL + 1) droidrun_logger = logging.getLogger("droidrun") droidrun_logger.disabled = True droidrun_logger.handlers = [] droidrun_logger.propagate = False droidrun_logger.setLevel(logging.CRITICAL + 1) for logger_name in ["adb", "android", "asyncio", "urllib3", "requests", "httpx", "httpcore"]: logger = logging.getLogger(logger_name) logger.disabled = True logger.handlers = [] logger.propagate = False logger.setLevel(logging.CRITICAL + 1) logging.getLogger().handlers = []
Configure logging verbosity based on debug flag.
configure_logging
python
droidrun/droidrun
droidrun/cli/main.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/main.py
MIT
def run(command: str, device: str | None, provider: str, model: str, steps: int, base_url: str, temperature: float, reasoning: bool, tracing: bool, debug: bool, save_trajectory: bool, trajectory_dir: str): """Run a command on your Android device using natural language.""" # Call our standalone function return run_command(command, device, provider, model, steps, base_url, reasoning, tracing, debug, temperature=temperature, save_trajectory=save_trajectory, trajectory_dir=trajectory_dir)
Run a command on your Android device using natural language.
run
python
droidrun/droidrun
droidrun/cli/main.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/main.py
MIT
async def connect(ip_address: str, port: int): """Connect to a device over TCP/IP.""" try: device = await device_manager.connect(ip_address, port) if device: console.print(f"[green]Successfully connected to {ip_address}:{port}[/]") else: console.print(f"[red]Failed to connect to {ip_address}:{port}[/]") except Exception as e: console.print(f"[red]Error connecting to device: {e}[/]")
Connect to a device over TCP/IP.
connect
python
droidrun/droidrun
droidrun/cli/main.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/main.py
MIT
async def setup(path: str, device: str | None): """Install an APK file and enable it as an accessibility service.""" try: if not os.path.exists(path): console.print(f"[bold red]Error:[/] APK file not found at {path}") return if not device: devices = await device_manager.list_devices() if not devices: console.print("[yellow]No devices connected.[/]") return device = devices[0].serial console.print(f"[blue]Using device:[/] {device}") device_obj = await device_manager.get_device(device) if not device_obj: console.print(f"[bold red]Error:[/] Could not get device object for {device}") return tools = Tools(serial=device) console.print(f"[bold blue]Step 1/2: Installing APK:[/] {path}") result = await tools.install_app(path, False, True) if "Error" in result: console.print(f"[bold red]Installation failed:[/] {result}") return else: console.print(f"[bold green]Installation successful![/]") console.print(f"[bold blue]Step 2/2: Enabling accessibility service[/]") package = "com.droidrun.portal" try: await device_obj._adb.shell(device, "settings put secure enabled_accessibility_services com.droidrun.portal/com.droidrun.portal.DroidrunPortalService") await device_obj._adb.shell(device, "settings put secure accessibility_enabled 1") console.print("[green]Accessibility service enabled successfully![/]") console.print("\n[bold green]Setup complete![/] The DroidRun Portal is now installed and ready to use.") except Exception as e: console.print(f"[yellow]Could not automatically enable accessibility service: {e}[/]") console.print("[yellow]Opening accessibility settings for manual configuration...[/]") await device_obj._adb.shell(device, "am start -a android.settings.ACCESSIBILITY_SETTINGS") console.print("\n[yellow]Please complete the following steps on your device:[/]") console.print(f"1. Find [bold]{package}[/] in the accessibility services list") console.print("2. Tap on the service name") console.print("3. Toggle the switch to [bold]ON[/] to enable the service") console.print("4. Accept any permission dialogs that appear") console.print("\n[bold green]APK installation complete![/] Please manually enable the accessibility service using the steps above.") except Exception as e: console.print(f"[bold red]Error:[/] {e}") import traceback traceback.print_exc()
Install an APK file and enable it as an accessibility service.
setup
python
droidrun/droidrun
droidrun/cli/main.py
https://github.com/droidrun/droidrun/blob/master/droidrun/cli/main.py
MIT
def get_device_serial(self) -> str: """Get the device serial from the instance or environment variable.""" # First try using the instance's serial if self.serial: return self.serial
Get the device serial from the instance or environment variable.
get_device_serial
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def get_device(self) -> Optional[Device]: """Get the device instance using the instance's serial or from environment variable. Returns: Device instance or None if not found """ serial = self.get_device_serial() if not serial: raise ValueError("No device serial specified - set device_serial parameter") device = await self.device_manager.get_device(serial) if not device: raise ValueError(f"Device {serial} not found") return device
Get the device instance using the instance's serial or from environment variable. Returns: Device instance or None if not found
get_device
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
def parse_package_list(self, output: str) -> List[Dict[str, str]]: """Parse the output of 'pm list packages -f' command. Args: output: Raw command output from 'pm list packages -f' Returns: List of dictionaries containing package info with 'package' and 'path' keys """ apps = [] for line in output.splitlines(): if line.startswith("package:"): # Format is: "package:/path/to/base.apk=com.package.name" path_and_pkg = line[8:] # Strip "package:" if "=" in path_and_pkg: path, package = path_and_pkg.rsplit("=", 1) apps.append({"package": package.strip(), "path": path.strip()}) return apps
Parse the output of 'pm list packages -f' command. Args: output: Raw command output from 'pm list packages -f' Returns: List of dictionaries containing package info with 'package' and 'path' keys
parse_package_list
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def get_clickables(self, serial: Optional[str] = None) -> str: """ Get all clickable UI elements from the device using the custom TopViewService. This function interacts with the TopViewService app installed on the device to capture UI elements. The service writes UI data to a JSON file on the device, which is then pulled to the host. If no elements are found initially, it will retry for up to 30 seconds. Args: serial: Optional device serial number Returns: JSON string containing UI elements extracted from the device screen """ try: # Get the device if serial: device_manager = DeviceManager() device = await device_manager.get_device(serial) if not device: raise ValueError(f"Device {serial} not found") else: device = await self.get_device() # Create a temporary file for the JSON with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp: local_path = temp.name try: # Set retry parameters max_total_time = 30 # Maximum total time to try in seconds retry_interval = 1.0 # Time between retries in seconds start_total_time = asyncio.get_event_loop().time() while True: # Check if we've exceeded total time current_time = asyncio.get_event_loop().time() if current_time - start_total_time > max_total_time: raise ValueError(f"Failed to get UI elements after {max_total_time} seconds of retries") # Clear logcat to make it easier to find our output await device._adb.shell(device._serial, "logcat -c") # Trigger the custom service via broadcast to get only interactive elements await device._adb.shell(device._serial, "am broadcast -a com.droidrun.portal.GET_ELEMENTS") # Poll for the JSON file path start_time = asyncio.get_event_loop().time() max_wait_time = 10 # Maximum wait time in seconds poll_interval = 0.2 # Check every 200ms device_path = None while asyncio.get_event_loop().time() - start_time < max_wait_time: # Check logcat for the file path logcat_output = await device._adb.shell(device._serial, "logcat -d | grep \"DROIDRUN_FILE\" | grep \"JSON data written to\" | tail -1") # Parse the file path if present match = re.search(r"JSON data written to: (.*)", logcat_output) if match: device_path = match.group(1).strip() break # Wait before polling again await asyncio.sleep(poll_interval) # Check if we found the file path if not device_path: await asyncio.sleep(retry_interval) continue # Pull the JSON file from the device await device._adb.pull_file(device._serial, device_path, local_path) # Read the JSON file async with aiofiles.open(local_path, "r", encoding="utf-8") as f: json_content = await f.read() # Try to parse the JSON try: ui_data = json.loads(json_content) # Filter out the "type" attribute from all elements filtered_data = [] for element in ui_data: # Create a copy of the element without the "type" attribute filtered_element = {k: v for k, v in element.items() if k != "type"} # Also filter children if present if "children" in filtered_element: filtered_element["children"] = [ {k: v for k, v in child.items() if k != "type"} for child in filtered_element["children"] ] filtered_data.append(filtered_element) # If we got elements, store them and return if filtered_data: # Store the filtered UI data in cache global CLICKABLE_ELEMENTS_CACHE CLICKABLE_ELEMENTS_CACHE = filtered_data # Add a small sleep to ensure UI is fully loaded/processed await asyncio.sleep(0.5) # 500ms sleep # Convert the dictionary to a JSON string before returning return filtered_data # If no elements found, wait and retry await asyncio.sleep(retry_interval) except json.JSONDecodeError: # If JSON parsing failed, wait and retry await asyncio.sleep(retry_interval) continue except Exception as e: # Clean up in case of error with contextlib.suppress(OSError): os.unlink(local_path) raise ValueError(f"Error retrieving clickable elements: {e}") except Exception as e: raise ValueError(f"Error getting clickable elements: {e}")
Get all clickable UI elements from the device using the custom TopViewService. This function interacts with the TopViewService app installed on the device to capture UI elements. The service writes UI data to a JSON file on the device, which is then pulled to the host. If no elements are found initially, it will retry for up to 30 seconds. Args: serial: Optional device serial number Returns: JSON string containing UI elements extracted from the device screen
get_clickables
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def tap_by_index(self, index: int, serial: Optional[str] = None) -> str: """ Tap on a UI element by its index. This function uses the cached clickable elements to find the element with the given index and tap on its center coordinates. Args: index: Index of the element to tap Returns: Result message """ def collect_all_indices(elements): """Recursively collect all indices from elements and their children.""" indices = [] for item in elements: if item.get('index') is not None: indices.append(item.get('index')) # Check children if present children = item.get('children', []) indices.extend(collect_all_indices(children)) return indices def find_element_by_index(elements, target_index): """Recursively find an element with the given index.""" for item in elements: if item.get('index') == target_index: return item # Check children if present children = item.get('children', []) result = find_element_by_index(children, target_index) if result: return result return None try: # Check if we have cached elements if not CLICKABLE_ELEMENTS_CACHE: return "Error: No UI elements cached. Call get_clickables first." # Find the element with the given index (including in children) element = find_element_by_index(CLICKABLE_ELEMENTS_CACHE, index) if not element: # List available indices to help the user indices = sorted(collect_all_indices(CLICKABLE_ELEMENTS_CACHE)) indices_str = ", ".join(str(idx) for idx in indices[:20]) if len(indices) > 20: indices_str += f"... and {len(indices) - 20} more" return f"Error: No element found with index {index}. Available indices: {indices_str}" # Get the bounds of the element bounds_str = element.get('bounds') if not bounds_str: element_text = element.get('text', 'No text') element_type = element.get('type', 'unknown') element_class = element.get('className', 'Unknown class') return f"Error: Element with index {index} ('{element_text}', {element_class}, type: {element_type}) has no bounds and cannot be tapped" # Parse the bounds (format: "left,top,right,bottom") try: left, top, right, bottom = map(int, bounds_str.split(',')) except ValueError: return f"Error: Invalid bounds format for element with index {index}: {bounds_str}" # Calculate the center of the element x = (left + right) // 2 y = (top + bottom) // 2 # Get the device and tap at the coordinates if serial: device_manager = DeviceManager() device = await device_manager.get_device(serial) if not device: return f"Error: Device {serial} not found" else: device = await self.get_device() await device.tap(x, y) # Add a small delay to allow UI to update await asyncio.sleep(0.5) # Create a descriptive response response_parts = [] response_parts.append(f"Tapped element with index {index}") response_parts.append(f"Text: '{element.get('text', 'No text')}'") response_parts.append(f"Class: {element.get('className', 'Unknown class')}") response_parts.append(f"Type: {element.get('type', 'unknown')}") # Add information about children if present children = element.get('children', []) if children: child_texts = [child.get('text') for child in children if child.get('text')] if child_texts: response_parts.append(f"Contains text: {' | '.join(child_texts)}") response_parts.append(f"Coordinates: ({x}, {y})") return " | ".join(response_parts) except ValueError as e: return f"Error: {str(e)}"
Tap on a UI element by its index. This function uses the cached clickable elements to find the element with the given index and tap on its center coordinates. Args: index: Index of the element to tap Returns: Result message
tap_by_index
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
def collect_all_indices(elements): """Recursively collect all indices from elements and their children.""" indices = [] for item in elements: if item.get('index') is not None: indices.append(item.get('index')) # Check children if present children = item.get('children', []) indices.extend(collect_all_indices(children)) return indices
Recursively collect all indices from elements and their children.
collect_all_indices
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
def find_element_by_index(elements, target_index): """Recursively find an element with the given index.""" for item in elements: if item.get('index') == target_index: return item # Check children if present children = item.get('children', []) result = find_element_by_index(children, target_index) if result: return result return None
Recursively find an element with the given index.
find_element_by_index
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def tap_by_coordinates(self, x: int, y: int) -> bool: """ Tap on the device screen at specific coordinates. Args: x: X coordinate y: Y coordinate Returns: Bool indicating success or failure """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: return f"Error: Device {self.serial} not found" else: device = await self.get_device() await device.tap(x, y) print(f"Tapped at coordinates ({x}, {y})") return True except ValueError as e: print(f"Error: {str(e)}") return False
Tap on the device screen at specific coordinates. Args: x: X coordinate y: Y coordinate Returns: Bool indicating success or failure
tap_by_coordinates
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def tap(self, index: int) -> str: """ Tap on a UI element by its index. This function uses the cached clickable elements from the last get_clickables call to find the element with the given index and tap on its center coordinates. Args: index: Index of the element to tap Returns: Result message """ return await self.tap_by_index(index)
Tap on a UI element by its index. This function uses the cached clickable elements from the last get_clickables call to find the element with the given index and tap on its center coordinates. Args: index: Index of the element to tap Returns: Result message
tap
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def swipe( self, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300 ) -> bool: """ Performs a straight-line swipe gesture on the device screen. To perform a hold (long press), set the start and end coordinates to the same values and increase the duration as needed. Args: start_x: Starting X coordinate start_y: Starting Y coordinate end_x: Ending X coordinate end_y: Ending Y coordinate duration_ms: Duration of swipe in milliseconds Returns: Bool indicating success or failure """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: return f"Error: Device {self.serial} not found" else: device = await self.get_device() await device.swipe(start_x, start_y, end_x, end_y, duration_ms) print(f"Swiped from ({start_x}, {start_y}) to ({end_x}, {end_y}) in {duration_ms}ms") return True except ValueError as e: print(f"Error: {str(e)}") return False
Performs a straight-line swipe gesture on the device screen. To perform a hold (long press), set the start and end coordinates to the same values and increase the duration as needed. Args: start_x: Starting X coordinate start_y: Starting Y coordinate end_x: Ending X coordinate end_y: Ending Y coordinate duration_ms: Duration of swipe in milliseconds Returns: Bool indicating success or failure
swipe
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def input_text(self, text: str, serial: Optional[str] = None) -> str: """ Input text on the device using Base64 encoding and broadcast intent. Args: text: Text to input. Can contain spaces, newlines, and special characters including non-ASCII. serial: Optional device serial (for backward compatibility) Returns: Result message """ try: if serial: device_manager = DeviceManager() device = await device_manager.get_device(serial) if not device: return f"Error: Device {serial} not found" else: device = await self.get_device() # Save the current keyboard original_ime = await device._adb.shell(device._serial, "settings get secure default_input_method") original_ime = original_ime.strip() # Enable the Droidrun keyboard await device._adb.shell(device._serial, "ime enable com.droidrun.portal/.DroidrunKeyboardIME") # Set the Droidrun keyboard as the default await device._adb.shell(device._serial, "ime set com.droidrun.portal/.DroidrunKeyboardIME") # Wait for keyboard to change await asyncio.sleep(0.2) # Encode the text to Base64 import base64 encoded_text = base64.b64encode(text.encode()).decode() cmd = f'am broadcast -a com.droidrun.portal.DROIDRUN_INPUT_B64 --es msg "{encoded_text}" -p com.droidrun.portal' await device._adb.shell(device._serial, cmd) # Wait for text input to complete await asyncio.sleep(0.5) # Restore the original keyboard if original_ime and "com.droidrun.portal" not in original_ime: await device._adb.shell(device._serial, f"ime set {original_ime}") return f"Text input completed: {text[:50]}{'...' if len(text) > 50 else ''}" except ValueError as e: return f"Error: {str(e)}" except Exception as e: return f"Error sending text input: {str(e)}"
Input text on the device using Base64 encoding and broadcast intent. Args: text: Text to input. Can contain spaces, newlines, and special characters including non-ASCII. serial: Optional device serial (for backward compatibility) Returns: Result message
input_text
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def press_key(self, keycode: int) -> str: """ Press a key on the device. Common keycodes: - 3: HOME - 4: BACK - 24: VOLUME UP - 25: VOLUME DOWN - 26: POWER - 82: MENU Args: keycode: Android keycode to press """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: return f"Error: Device {self.serial} not found" else: device = await self.get_device() key_names = { 3: "HOME", 4: "BACK", 24: "VOLUME UP", 25: "VOLUME DOWN", 26: "POWER", 82: "MENU", } key_name = key_names.get(keycode, str(keycode)) await device.press_key(keycode) return f"Pressed key {key_name}" except ValueError as e: return f"Error: {str(e)}"
Press a key on the device. Common keycodes: - 3: HOME - 4: BACK - 24: VOLUME UP - 25: VOLUME DOWN - 26: POWER - 82: MENU Args: keycode: Android keycode to press
press_key
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def start_app( self, package: str, activity: str = "" ) -> str: """ Start an app on the device. Args: package: Package name (e.g., "com.android.settings") activity: Optional activity name """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: return f"Error: Device {self.serial} not found" else: device = await self.get_device() result = await device.start_app(package, activity) return result except ValueError as e: return f"Error: {str(e)}"
Start an app on the device. Args: package: Package name (e.g., "com.android.settings") activity: Optional activity name
start_app
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def install_app( self, apk_path: str, reinstall: bool = False, grant_permissions: bool = True ) -> str: """ Install an app on the device. Args: apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all permissions """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: return f"Error: Device {self.serial} not found" else: device = await self.get_device() if not os.path.exists(apk_path): return f"Error: APK file not found at {apk_path}" result = await device.install_app(apk_path, reinstall, grant_permissions) return result except ValueError as e: return f"Error: {str(e)}"
Install an app on the device. Args: apk_path: Path to the APK file reinstall: Whether to reinstall if app exists grant_permissions: Whether to grant all permissions
install_app
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def take_screenshot(self) -> bool: """ Take a screenshot of the device. This function captures the current screen and adds the screenshot to context in the next message. Also stores the screenshot in the screenshots list with timestamp for later GIF creation. """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: raise ValueError(f"Device {self.serial} not found") else: device = await self.get_device() screen_tuple = await device.take_screenshot() self.last_screenshot = screen_tuple[1] # Store screenshot with timestamp self.screenshots.append({ "timestamp": time.time(), "image_data": screen_tuple[1], "format": screen_tuple[0] # Usually 'PNG' }) return screen_tuple except ValueError as e: raise ValueError(f"Error taking screenshot: {str(e)}")
Take a screenshot of the device. This function captures the current screen and adds the screenshot to context in the next message. Also stores the screenshot in the screenshots list with timestamp for later GIF creation.
take_screenshot
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def list_packages( self, include_system_apps: bool = False ) -> List[str]: """ List installed packages on the device. Args: include_system_apps: Whether to include system apps (default: False) Returns: List of package names """ try: if self.serial: device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: raise ValueError(f"Device {self.serial} not found") else: device = await self.get_device() # Use the direct ADB command to get packages with paths cmd = ["pm", "list", "packages", "-f"] if not include_system_apps: cmd.append("-3") output = await device._adb.shell(device._serial, " ".join(cmd)) # Parse the package list using the function packages = self.parse_package_list(output) # Format package list for better readability package_list = [pack["package"] for pack in packages] print(f"Returning {len(package_list)} packages") return package_list except ValueError as e: raise ValueError(f"Error listing packages: {str(e)}")
List installed packages on the device. Args: include_system_apps: Whether to include system apps (default: False) Returns: List of package names
list_packages
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def extract(self, filename: Optional[str] = None) -> str: """Extract and save the current UI state to a JSON file. This function captures the current UI state including all UI elements and saves it to a JSON file for later analysis or reference. Args: filename: Optional filename to save the UI state (defaults to ui_state_TIMESTAMP.json) Returns: Path to the saved JSON file """ try: # Generate default filename if not provided if not filename: timestamp = int(time.time()) filename = f"ui_state_{timestamp}.json" # Ensure the filename ends with .json if not filename.endswith(".json"): filename += ".json" # Get the UI elements ui_elements = await self.get_all_elements(self.serial) # Save to file save_path = os.path.abspath(filename) async with aiofiles.open(save_path, "w", encoding="utf-8") as f: await f.write(json.dumps(ui_elements, indent=2)) return f"UI state extracted and saved to {save_path}" except Exception as e: return f"Error extracting UI state: {e}"
Extract and save the current UI state to a JSON file. This function captures the current UI state including all UI elements and saves it to a JSON file for later analysis or reference. Args: filename: Optional filename to save the UI state (defaults to ui_state_TIMESTAMP.json) Returns: Path to the saved JSON file
extract
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def get_all_elements(self) -> Dict[str, Any]: """ Get all UI elements from the device, including non-interactive elements. This function interacts with the TopViewService app installed on the device to capture all UI elements, even those that are not interactive. This provides a complete view of the UI hierarchy for analysis or debugging purposes. Returns: Dictionary containing all UI elements extracted from the device screen """ try: # Get the device device_manager = DeviceManager() device = await device_manager.get_device(self.serial) if not device: raise ValueError(f"Device {self.serial} not found") # Create a temporary file for the JSON with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp: local_path = temp.name try: # Clear logcat to make it easier to find our output await device._adb.shell(device._serial, "logcat -c") # Trigger the custom service via broadcast to get ALL elements await device._adb.shell(device._serial, "am broadcast -a com.droidrun.portal.GET_ALL_ELEMENTS") # Poll for the JSON file path start_time = asyncio.get_event_loop().time() max_wait_time = 10 # Maximum wait time in seconds poll_interval = 0.2 # Check every 200ms device_path = None while asyncio.get_event_loop().time() - start_time < max_wait_time: # Check logcat for the file path logcat_output = await device._adb.shell(device._serial, "logcat -d | grep \"DROIDRUN_FILE\" | grep \"JSON data written to\" | tail -1") # Parse the file path if present match = re.search(r"JSON data written to: (.*)", logcat_output) if match: device_path = match.group(1).strip() break # Wait before polling again await asyncio.sleep(poll_interval) # Check if we found the file path if not device_path: raise ValueError(f"Failed to find the JSON file path in logcat after {max_wait_time} seconds") # Pull the JSON file from the device await device._adb.pull_file(device._serial, device_path, local_path) # Read the JSON file async with aiofiles.open(local_path, "r", encoding="utf-8") as f: json_content = await f.read() # Clean up the temporary file with contextlib.suppress(OSError): os.unlink(local_path) # Try to parse the JSON import json try: ui_data = json.loads(json_content) return { "all_elements": ui_data, "count": len(ui_data) if isinstance(ui_data, list) else sum(1 for _ in ui_data.get("elements", [])), "message": "Retrieved all UI elements from the device screen" } except json.JSONDecodeError: raise ValueError("Failed to parse UI elements JSON data") except Exception as e: # Clean up in case of error with contextlib.suppress(OSError): os.unlink(local_path) raise ValueError(f"Error retrieving all UI elements: {e}") except Exception as e: raise ValueError(f"Error getting all UI elements: {e}")
Get all UI elements from the device, including non-interactive elements. This function interacts with the TopViewService app installed on the device to capture all UI elements, even those that are not interactive. This provides a complete view of the UI hierarchy for analysis or debugging purposes. Returns: Dictionary containing all UI elements extracted from the device screen
get_all_elements
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
def complete(self, success: bool, reason: str = ""): """ Mark the task as finished. Args: success: Indicates if the task was successful. reason: Reason for failure/success """ if success: self.success = True self.reason = reason or "Task completed successfully." self.finished = True else: self.success = False if not reason: raise ValueError("Reason for failure is required if success is False.") self.reason = reason self.finished = True
Mark the task as finished. Args: success: Indicates if the task was successful. reason: Reason for failure/success
complete
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def get_phone_state(self, serial: Optional[str] = None) -> Dict[str, Any]: """ Get the current phone state including current activity and keyboard visibility. Args: serial: Optional device serial number Returns: Dictionary with current phone state information """ try: # Get the device if serial: device_manager = DeviceManager() device = await device_manager.get_device(serial) if not device: raise ValueError(f"Device {serial} not found") else: device = await self.get_device() # Get the top resumed activity activity_output = await device._adb.shell(device._serial, "dumpsys activity activities | grep topResumedActivity") if not activity_output: # Try alternative command for older Android versions activity_output = await device._adb.shell(device._serial, "dumpsys activity activities | grep ResumedActivity") # Get keyboard visibility state keyboard_output = await device._adb.shell(device._serial, "dumpsys input_method | grep mInputShown") # Process activity information current_activity = "Unable to determine current activity" if activity_output: current_activity = activity_output.strip() # Process keyboard information is_keyboard_shown = False if keyboard_output: is_keyboard_shown = "mInputShown=true" in keyboard_output # Return combined state return { "current_activity": current_activity, "keyboard_shown": is_keyboard_shown, } except Exception as e: return { "error": str(e), "message": f"Error getting phone state: {str(e)}" }
Get the current phone state including current activity and keyboard visibility. Args: serial: Optional device serial number Returns: Dictionary with current phone state information
get_phone_state
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
async def remember(self, information: str) -> str: """ Store important information to remember for future context. This information will be included in future LLM prompts to help maintain context across interactions. Use this for critical facts, observations, or user preferences that should influence future decisions. Args: information: The information to remember Returns: Confirmation message """ if not information or not isinstance(information, str): return "Error: Please provide valid information to remember." # Add the information to memory self.memory.append(information.strip()) # Limit memory size to prevent context overflow (keep most recent items) max_memory_items = 10 if len(self.memory) > max_memory_items: self.memory = self.memory[-max_memory_items:] return f"Remembered: {information}"
Store important information to remember for future context. This information will be included in future LLM prompts to help maintain context across interactions. Use this for critical facts, observations, or user preferences that should influence future decisions. Args: information: The information to remember Returns: Confirmation message
remember
python
droidrun/droidrun
droidrun/tools/actions.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/actions.py
MIT
def load_tools(serial: Optional[str] = None) -> Tuple[Dict[str, Callable[..., Any]], Tools]: """ Initializes the Tools class and returns a dictionary of available tool functions and the Tools instance itself. If serial is not provided, it attempts to find the first connected device. Args: serial: The device serial number. If None, finds the first available device. Returns: A tuple containing: - A dictionary mapping tool names to their corresponding functions. - The initialized Tools instance. Raises: ValueError: If no device serial is provided and no devices are found. """ logger.debug(f"Initializing Tools for device: {serial}") tools_instance = Tools(serial=serial) tool_list = { # UI interaction "swipe": tools_instance.swipe, "input_text": tools_instance.input_text, "press_key": tools_instance.press_key, "tap_by_index": tools_instance.tap_by_index, #"tap_by_coordinates": tools_instance.tap_by_coordinates, # App management "start_app": tools_instance.start_app, "list_packages": tools_instance.list_packages, #state management "remember": tools_instance.remember, "complete": tools_instance.complete, } logger.debug("Base tools loaded.") # Return both the dictionary and the instance, as the agent might need the instance logger.info(f"Tools loaded successfully for device {serial}.") return tool_list, tools_instance
Initializes the Tools class and returns a dictionary of available tool functions and the Tools instance itself. If serial is not provided, it attempts to find the first connected device. Args: serial: The device serial number. If None, finds the first available device. Returns: A tuple containing: - A dictionary mapping tool names to their corresponding functions. - The initialized Tools instance. Raises: ValueError: If no device serial is provided and no devices are found.
load_tools
python
droidrun/droidrun
droidrun/tools/loader.py
https://github.com/droidrun/droidrun/blob/master/droidrun/tools/loader.py
MIT
def __init__( self, task_ids: Optional[List[int]] = None, task_names: Optional[List[str]] = None, llm_provider: str = "OpenAI", llm_model: str = "gpt-4o-mini", temperature: float = 0.2, adb_path: str = "adb", console_port: int = 5554, perform_emulator_setup: bool = False, random_seed: int = 42, results_dir: str = "eval_results", max_steps_per_task: int = 50, task_family: str = registry.TaskRegistry.ANDROID_WORLD_FAMILY, n_task_combinations: int = 1, portal_service_name: str = "com.droidrun.portal/com.droidrun.portal.DroidrunPortalService", progress_file: str = "task_progress.json", use_keepalive: bool = True, keepalive_interval: int = 5 ): """Initialize the benchmark. Args: task_ids: List of task IDs to run (1-116) task_names: List of specific task names to run llm_provider: LLM provider to use (OpenAI, Anthropic, Gemini, etc.) llm_model: Model name to use temperature: Temperature for LLM sampling adb_path: Path to ADB executable console_port: Emulator console port perform_emulator_setup: Whether to perform initial emulator setup random_seed: Random seed for reproducibility results_dir: Directory to save results max_steps_per_task: Maximum steps to allow per task task_family: Task family to benchmark n_task_combinations: Number of parameter combinations per task portal_service_name: Name of the DroidRun accessibility service progress_file: Path to progress tracking file use_keepalive: Whether to use the keepalive service keepalive_interval: Interval in seconds for the keepalive service """ self.task_ids = task_ids self.task_names = task_names self.llm_provider = llm_provider self.llm_model = llm_model self.temperature = temperature self.adb_path = adb_path self.console_port = console_port self.perform_emulator_setup = perform_emulator_setup self.random_seed = random_seed self.results_dir = results_dir self.max_steps_per_task = max_steps_per_task self.task_family = task_family self.n_task_combinations = n_task_combinations self.portal_service_name = portal_service_name self.progress_file = progress_file self.use_keepalive = use_keepalive self.keepalive_interval = keepalive_interval # Components initialized during setup self.env = None self.device_serial = None self.task_registry = None self.result_manager = None self.progress_tracker = None self.keepalive_service = None
Initialize the benchmark. Args: task_ids: List of task IDs to run (1-116) task_names: List of specific task names to run llm_provider: LLM provider to use (OpenAI, Anthropic, Gemini, etc.) llm_model: Model name to use temperature: Temperature for LLM sampling adb_path: Path to ADB executable console_port: Emulator console port perform_emulator_setup: Whether to perform initial emulator setup random_seed: Random seed for reproducibility results_dir: Directory to save results max_steps_per_task: Maximum steps to allow per task task_family: Task family to benchmark n_task_combinations: Number of parameter combinations per task portal_service_name: Name of the DroidRun accessibility service progress_file: Path to progress tracking file use_keepalive: Whether to use the keepalive service keepalive_interval: Interval in seconds for the keepalive service
__init__
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
async def initialize(self): """Initialize all components needed for the benchmark.""" # Initialize environment self.env = initialize_environment( adb_path=self.adb_path, console_port=self.console_port, perform_setup=self.perform_emulator_setup ) if not self.env: logger.error("Failed to initialize environment. Exiting.") sys.exit(1) # Get device serial self.device_serial = await get_device_serial() if not self.device_serial: logger.error("Failed to get device serial. Exiting.") sys.exit(1) # Enable accessibility service accessibility_enabled = await enable_accessibility_service( adb_path=self.adb_path, device_serial=self.device_serial, service_name=self.portal_service_name, disable_first=True ) if not accessibility_enabled: logger.error("Failed to enable accessibility service. Exiting.") sys.exit(1) # Initialize task registry self.task_registry = TaskRegistry(task_family=self.task_family) # Initialize result manager self.result_manager = ResultManager(results_dir=self.results_dir) # Initialize progress tracker self.progress_tracker = ProgressTracker(progress_file=self.progress_file) # Initialize keepalive service self.keepalive_service = OverlayKeepalive( device_serial=self.device_serial, interval=self.keepalive_interval ) logger.info("Benchmark initialization complete")
Initialize all components needed for the benchmark.
initialize
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
def list_tasks(self): """Print the list of available tasks.""" if not self.task_registry: self.task_registry = TaskRegistry(task_family=self.task_family) task_ids = self.task_registry.get_task_ids() print("\nAvailable AndroidWorld Tasks:") print("-----------------------------") print(f"{'ID':<4} {'Task Name':<50}") print("-" * 55) for task_id, task_name in sorted(task_ids.items()): print(f"{task_id:<4} {task_name:<50}")
Print the list of available tasks.
list_tasks
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
async def run_task(self, task_name: str, task_instance): """Run a single task. Args: task_name: Name of the task task_instance: Task instance to run Returns: Task result """ logger.info(f"Running task: {task_name}") # Get task description task_description = get_task_description(task_instance) logger.info(f"Task description: {task_description}") # Create initial result task_result = create_task_result(task_name, task_description) task_result["max_steps"] = self.max_steps_per_task # Initialize task task_initialized = await initialize_task(self.env, task_instance) if not task_initialized: task_result["error"] = "Failed to initialize task" return task_result # Enable accessibility service for the task await enable_accessibility_service( adb_path=self.adb_path, device_serial=self.device_serial, service_name=self.portal_service_name, disable_first=True ) # Start keepalive service if enabled if self.use_keepalive and self.keepalive_service: self.keepalive_service.start() # Create and run agent start_time = time.time() agent = None tools_instance = None try: # Create agent agent, agent_config = await create_agent( device_serial=self.device_serial, task_description=task_description, llm_provider=self.llm_provider, llm_model=self.llm_model, temperature=self.temperature, max_steps=self.max_steps_per_task, vision=True, debug=True ) # Store tools instance for screenshots tools_instance = agent.tools_instance # Run agent agent_result = await run_agent(agent, task_name) # Update result with agent information task_result = update_result_from_agent(task_result, agent_result, agent) # Add screenshots to result if available if hasattr(tools_instance, 'screenshots') and tools_instance.screenshots: task_result["screenshots"] = tools_instance.screenshots except Exception as e: logger.error(f"Error during agent execution: {e}") task_result["error"] = str(e) finally: # Stop keepalive service if it was started if self.use_keepalive and self.keepalive_service and self.keepalive_service.running: self.keepalive_service.stop() # Set execution time end_time = time.time() task_result["execution_time"] = end_time - start_time # Check if task was successful task_result["success"] = check_task_success(self.env, task_instance) return task_result
Run a single task. Args: task_name: Name of the task task_instance: Task instance to run Returns: Task result
run_task
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
async def run_benchmark(self): """Run the benchmark on the selected tasks.""" # Initialize components await self.initialize() # Create task suite task_suite = self.task_registry.create_task_suite( task_ids=self.task_ids, task_names=self.task_names, n_combinations=self.n_task_combinations, random_seed=self.random_seed ) if not task_suite: logger.error("No tasks to run") return # Get the number of completed tasks to skip skip_count = self.progress_tracker.get_completed_tasks() if skip_count > 0: logger.info(f"Skipping {skip_count} completed tasks") if skip_count >= len(task_suite): logger.info("All tasks already completed") return task_suite = task_suite[skip_count:] logger.info(f"Running benchmark with {len(task_suite)} tasks") completed_count = skip_count try: # Run each task for i, (task_name, task_instance) in enumerate(task_suite): try: # Create a task-specific directory in results_dir task_dir = os.path.join(self.results_dir, f"task_{task_name.replace(' ', '_')}") os.makedirs(task_dir, exist_ok=True) # Run the task task_result = await self.run_task(task_name, task_instance) # Save the result with screenshots as GIF if available if "screenshots" in task_result and task_result["screenshots"]: from droidrun.agent.utils.trajectory import create_screenshot_gif base_path = os.path.join(task_dir, f"task_execution") gif_path = create_screenshot_gif(task_result["screenshots"], base_path) if gif_path: task_result["screenshot_gif"] = os.path.basename(gif_path) logger.info(f"Created GIF with {len(task_result['screenshots'])} screenshots") # Remove raw screenshots from JSON to keep it clean del task_result["screenshots"] # Save the result JSON json_path = os.path.join(task_dir, "result.json") with open(json_path, "w") as f: json.dump(task_result, f, indent=2) # Save the result in the result manager as well self.result_manager.save_task_result(task_result) # Update progress if task was successful if task_result["success"]: completed_count += 1 self.progress_tracker.update_progress(completed_count) except Exception as e: logger.error(f"Error running task {task_name}: {e}") finally: # Tear down the task teardown_task(self.env, task_instance) # Print summary self.result_manager.print_summary() finally: # Make sure keepalive service is stopped if self.keepalive_service and self.keepalive_service.running: self.keepalive_service.stop() # Close environment if self.env: logger.info("Closing environment") self.env.close()
Run the benchmark on the selected tasks.
run_benchmark
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
async def main(): """Main entry point for the benchmark script.""" parser = argparse.ArgumentParser(description="Run AndroidWorld benchmark tasks with DroidRun") # Task selection arguments task_group = parser.add_argument_group("Task Selection") task_group.add_argument("--task-ids", type=int, nargs="+", help="Task IDs to run (1-116)") task_group.add_argument("--task-names", type=str, nargs="+", help="Task names to run") task_group.add_argument("--list-tasks", action="store_true", help="List available tasks and exit") task_group.add_argument("--n-task-combinations", type=int, default=1, help="Number of parameter combinations per task") # LLM configuration llm_group = parser.add_argument_group("LLM Configuration") llm_group.add_argument("--llm-provider", type=str, default="OpenAI", help="LLM provider (OpenAI, Anthropic, Gemini, etc.)") llm_group.add_argument("--llm-model", type=str, default="gpt-4o-mini", help="Model name to use") llm_group.add_argument("--temperature", type=float, default=0.2, help="Temperature for LLM sampling") # Environment configuration env_group = parser.add_argument_group("Environment Configuration") env_group.add_argument("--adb-path", type=str, default="adb", help="Path to ADB executable") env_group.add_argument("--console-port", type=int, default=5554, help="Emulator console port") env_group.add_argument("--perform-emulator-setup", action="store_true", help="Perform initial emulator setup (install apps, set permissions)") env_group.add_argument("--portal-service", type=str, default="com.droidrun.portal/com.droidrun.portal.DroidrunPortalService", help="Name of the DroidRun accessibility service") env_group.add_argument("--no-keepalive", action="store_true", help="Disable the keepalive service for overlay toggling") env_group.add_argument("--keepalive-interval", type=int, default=5, help="Interval in seconds for the keepalive service") # Benchmark configuration bench_group = parser.add_argument_group("Benchmark Configuration") bench_group.add_argument("--random-seed", type=int, default=42, help="Random seed for reproducibility") bench_group.add_argument("--results-dir", type=str, default="eval_results", help="Directory to save results") bench_group.add_argument("--max-steps", type=int, default=50, help="Maximum steps per task") bench_group.add_argument("--task-family", type=str, default=registry.TaskRegistry.ANDROID_WORLD_FAMILY, help="Task family to benchmark") bench_group.add_argument("--progress-file", type=str, default="task_progress.json", help="File to track task progress") args = parser.parse_args() # Create benchmark instance benchmark = AndroidWorldBenchmark( task_ids=args.task_ids, task_names=args.task_names, llm_provider=args.llm_provider, llm_model=args.llm_model, temperature=args.temperature, adb_path=args.adb_path, console_port=args.console_port, perform_emulator_setup=args.perform_emulator_setup, random_seed=args.random_seed, results_dir=args.results_dir, max_steps_per_task=args.max_steps, task_family=args.task_family, n_task_combinations=args.n_task_combinations, portal_service_name=args.portal_service, progress_file=args.progress_file, use_keepalive=not args.no_keepalive, keepalive_interval=args.keepalive_interval ) # Just list tasks if requested if args.list_tasks: benchmark.list_tasks() return # Run the benchmark await benchmark.run_benchmark()
Main entry point for the benchmark script.
main
python
droidrun/droidrun
eval/android_world_bench.py
https://github.com/droidrun/droidrun/blob/master/eval/android_world_bench.py
MIT
async def enable_accessibility_service(adb_path: str, device_serial: str, service_name: str, disable_first: bool = False): """Enable the DroidRun accessibility service. This is crucial for DroidRun to function correctly with Android UI interactions. Args: adb_path: Path to ADB executable device_serial: Device serial number service_name: Name of the accessibility service to enable disable_first: Whether to disable all other accessibility services first Returns: bool: True if successful, False otherwise """ if not device_serial: logger.error("Device serial not available for enabling accessibility service") return False logger.info(f"Configuring accessibility service: {service_name}") try: # Helper function to run ADB commands async def run_adb_command(cmd_args, step_name): logger.debug(f"Running ADB command ({step_name}): {' '.join(cmd_args)}") process = await asyncio.create_subprocess_exec( *cmd_args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() stdout_str = stdout.decode().strip() stderr_str = stderr.decode().strip() if process.returncode != 0: logger.error(f"Failed to {step_name}. Return code: {process.returncode}") if stdout_str: logger.error(f"Stdout: {stdout_str}") if stderr_str: logger.error(f"Stderr: {stderr_str}") return False else: logger.debug(f"Successfully {step_name}.") if stdout_str: logger.debug(f"Stdout: {stdout_str}") if stderr_str: logger.debug(f"Stderr: {stderr_str}") return True # Step 1: Disable all accessibility services if requested if disable_first: disable_cmd = [ adb_path, "-s", device_serial, "shell", "settings", "put", "secure", "enabled_accessibility_services", "''" ] if not await run_adb_command(disable_cmd, "disable all accessibility services"): logger.warning("Could not disable accessibility services, proceeding anyway...") else: logger.info("Disabled all accessibility services") await asyncio.sleep(2) # Wait for services to be disabled # Step 2: Enable our specific accessibility service enable_service_cmd = [ adb_path, "-s", device_serial, "shell", "settings", "put", "secure", "enabled_accessibility_services", service_name ] if not await run_adb_command(enable_service_cmd, f"enable service {service_name}"): return False # Critical failure await asyncio.sleep(1) # Short delay # Step 3: Enable accessibility globally enable_global_cmd = [ adb_path, "-s", device_serial, "shell", "settings", "put", "secure", "accessibility_enabled", "1" ] if not await run_adb_command(enable_global_cmd, "enable accessibility globally"): return False # Critical failure await asyncio.sleep(1) # Short delay # Step 4: Disable overlay/box rendering if available disable_overlay_cmd = [ adb_path, "-s", device_serial, "shell", "am", "broadcast", "-a", "com.droidrun.portal.TOGGLE_OVERLAY", "--ez", "overlay_visible", "false" ] if not await run_adb_command(disable_overlay_cmd, "disable box rendering overlay"): logger.warning("Could not disable box rendering overlay, proceeding anyway...") logger.info(f"Successfully configured accessibility service: {service_name}") return True except FileNotFoundError: logger.error(f"ADB not found at path: {adb_path}") return False except Exception as e: logger.exception(f"Error enabling accessibility service: {e}") return False
Enable the DroidRun accessibility service. This is crucial for DroidRun to function correctly with Android UI interactions. Args: adb_path: Path to ADB executable device_serial: Device serial number service_name: Name of the accessibility service to enable disable_first: Whether to disable all other accessibility services first Returns: bool: True if successful, False otherwise
enable_accessibility_service
python
droidrun/droidrun
eval/utils/accessibility.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/accessibility.py
MIT
async def create_agent( device_serial: str, task_description: str, llm_provider: str, llm_model: str, temperature: float = 0.2, max_steps: int = 50, timeout: int = 600, max_retries: int = 3, vision: bool = True, debug: bool = True ) -> Tuple[DroidAgent, Dict[str, Any]]: """Create and configure a DroidRun agent. Args: device_serial: Device serial number task_description: Description of the task llm_provider: LLM provider name llm_model: LLM model name temperature: Temperature for LLM max_steps: Maximum number of steps timeout: Timeout in seconds max_retries: Maximum number of retries Returns: Tuple of (agent, agent configuration) """ logger.info(f"Creating DroidRun agent for task") # Load tools logger.info(f"Loading tools for device: {device_serial}") tool_list, tools_instance = await load_tools(serial=device_serial) # Load LLM logger.info(f"Loading LLM: provider={llm_provider}, model={llm_model}") llm = load_llm( provider_name=llm_provider, model=llm_model, temperature=temperature ) # Create agent agent = DroidAgent( goal=task_description, llm=llm, tools_instance=tools_instance, tool_list=tool_list, max_steps=max_steps, timeout=timeout, max_retries=max_retries, temperature=temperature, vision=vision, debug=debug ) # Store configuration config = { "llm_provider": llm_provider, "llm_model": llm_model, "temperature": temperature, "max_steps": max_steps, "timeout": timeout, "max_retries": max_retries, "vision": vision } logger.info("Agent created successfully") return agent, config
Create and configure a DroidRun agent. Args: device_serial: Device serial number task_description: Description of the task llm_provider: LLM provider name llm_model: LLM model name temperature: Temperature for LLM max_steps: Maximum number of steps timeout: Timeout in seconds max_retries: Maximum number of retries Returns: Tuple of (agent, agent configuration)
create_agent
python
droidrun/droidrun
eval/utils/agent.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/agent.py
MIT
async def run_agent(agent: DroidAgent, task_name: str) -> Dict[str, Any]: """Run the agent on a task. Args: agent: The agent to run task_name: Name of the task Returns: Result data """ logger.info(f"Running agent for task: {task_name}") try: # Run the agent result = await agent.run() logger.info(f"Agent completed task: {task_name}") return result except Exception as e: logger.error(f"Error running agent for task {task_name}: {e}") return None
Run the agent on a task. Args: agent: The agent to run task_name: Name of the task Returns: Result data
run_agent
python
droidrun/droidrun
eval/utils/agent.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/agent.py
MIT
def check_android_world_path(): """Check that the ANDROID_WORLD_PATH environment variable is set and valid.""" android_world_path = os.environ.get("ANDROID_WORLD_PATH", None) if not android_world_path or not os.path.exists(android_world_path): logger.error("ANDROID_WORLD_PATH environment variable not set or path doesn't exist") logger.error("Please set it to the path of your AndroidWorld installation") return False # Add to Python path sys.path.append(android_world_path) return True
Check that the ANDROID_WORLD_PATH environment variable is set and valid.
check_android_world_path
python
droidrun/droidrun
eval/utils/environment.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/environment.py
MIT
def initialize_environment( adb_path: str = "adb", console_port: int = 5554, perform_setup: bool = False ) -> Optional[object]: """Initialize the AndroidWorld environment. Args: adb_path: Path to ADB executable console_port: Emulator console port perform_setup: Whether to perform initial emulator setup Returns: Initialized environment or None if initialization failed """ logger.info(f"Initializing Android environment with ADB at {adb_path}") try: # Load and setup environment env = env_launcher.load_and_setup_env( console_port=console_port, emulator_setup=perform_setup, adb_path=adb_path, ) # Reset environment to start from a clean state env.reset(go_home=True) logger.info("Android environment initialized successfully") return env except Exception as e: logger.exception(f"Failed to initialize Android environment: {e}") return None
Initialize the AndroidWorld environment. Args: adb_path: Path to ADB executable console_port: Emulator console port perform_setup: Whether to perform initial emulator setup Returns: Initialized environment or None if initialization failed
initialize_environment
python
droidrun/droidrun
eval/utils/environment.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/environment.py
MIT
async def get_device_serial() -> Optional[str]: """Get the serial number of the connected Android device. Returns: Device serial number or None if no device found """ try: from droidrun.tools import DeviceManager device_manager = DeviceManager() devices = await device_manager.list_devices() if not devices: logger.error("No devices found. Make sure an emulator or device is running.") return None device_serial = devices[0].serial logger.info(f"Using device with serial: {device_serial}") return device_serial except Exception as e: logger.exception(f"Error getting device serial: {e}") return None
Get the serial number of the connected Android device. Returns: Device serial number or None if no device found
get_device_serial
python
droidrun/droidrun
eval/utils/environment.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/environment.py
MIT
def __init__( self, adb_path: str = "adb", device_serial: Optional[str] = None, interval: int = 5 ): """Initialize the keepalive service. Args: adb_path: Path to ADB executable device_serial: Device serial number interval: Interval in seconds between commands """ self.adb_path = adb_path self.device_serial = device_serial self.interval = interval self.process = None self.running = False
Initialize the keepalive service. Args: adb_path: Path to ADB executable device_serial: Device serial number interval: Interval in seconds between commands
__init__
python
droidrun/droidrun
eval/utils/keepalive.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/keepalive.py
MIT
def start(self): """Start the keepalive service as a subprocess.""" if self.process and self.process.poll() is None: logger.info("Keepalive service is already running") return # Path to the script file script_path = os.path.join(os.path.dirname(__file__), "keepalive_script.py") # Write the script file if it doesn't exist if not os.path.exists(script_path): self._create_script_file(script_path) # Build command cmd = [sys.executable, script_path] if self.adb_path: cmd.extend(["--adb-path", self.adb_path]) if self.device_serial: cmd.extend(["--device-serial", self.device_serial]) cmd.extend(["--interval", str(self.interval)]) # Start the process try: logger.info(f"Starting keepalive service with interval {self.interval}s") self.process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1 ) self.running = True logger.info(f"Keepalive service started (PID: {self.process.pid})") except Exception as e: logger.error(f"Failed to start keepalive service: {e}")
Start the keepalive service as a subprocess.
start
python
droidrun/droidrun
eval/utils/keepalive.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/keepalive.py
MIT
def _create_script_file(self, script_path: str): """Create the keepalive script file. Args: script_path: Path to write the script to """ script_content = '''#!/usr/bin/env python3 """ Minimal keepalive script for DroidRun overlay toggling. """ import subprocess import time import logging import os import argparse import sys import signal logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # Handle termination gracefully def signal_handler(sig, frame): logger.info("Received termination signal, shutting down...") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) def main(): parser = argparse.ArgumentParser(description="Keep DroidRun overlay disabled") parser.add_argument("--adb-path", type=str, help="Path to ADB executable") parser.add_argument("--device-serial", type=str, help="Device serial number") parser.add_argument("--interval", type=int, default=5, help="Interval in seconds between commands") args = parser.parse_args() # Find ADB path if not specified adb_path = args.adb_path or 'adb' # Default to system adb if not specified # Get first device if serial not specified device_serial = args.device_serial if not device_serial: try: result = subprocess.run([adb_path, "devices"], capture_output=True, text=True, check=True) devices = [line.split()[0] for line in result.stdout.splitlines()[1:] if line.strip() and "device" in line] if devices: device_serial = devices[0] logger.info(f"Using first available device: {device_serial}") else: logger.error("No devices found. Please connect a device or specify --device-serial.") return except subprocess.CalledProcessError as e: logger.error(f"Failed to list devices: {e}") return interval = args.interval logger.info(f"Starting keepalive script with {interval} second interval") logger.info(f"ADB path: {adb_path}") logger.info(f"Device serial: {device_serial}") while True: try: cmd = [ adb_path, "-s", device_serial, "shell", "am broadcast -a com.droidrun.portal.TOGGLE_OVERLAY --ez overlay_visible false" ] subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(interval) except subprocess.CalledProcessError as e: logger.error(f"Command failed: {e}") time.sleep(interval) except KeyboardInterrupt: logger.info("Received keyboard interrupt, shutting down...") break if __name__ == "__main__": main() ''' try: with open(script_path, 'w') as f: f.write(script_content) # Make the script executable os.chmod(script_path, 0o755) logger.info(f"Created keepalive script at {script_path}") except Exception as e: logger.error(f"Failed to create keepalive script: {e}")
Create the keepalive script file. Args: script_path: Path to write the script to
_create_script_file
python
droidrun/droidrun
eval/utils/keepalive.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/keepalive.py
MIT
async def disable_overlay_once(adb_path: str, device_serial: str): """Disable the overlay once. Args: adb_path: Path to ADB executable device_serial: Device serial number """ try: cmd = [ adb_path, "-s", device_serial, "shell", "am broadcast -a com.droidrun.portal.TOGGLE_OVERLAY --ez overlay_visible false" ] process = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) await process.communicate() logger.debug("Disabled overlay once") return True except Exception as e: logger.error(f"Failed to disable overlay: {e}") return False
Disable the overlay once. Args: adb_path: Path to ADB executable device_serial: Device serial number
disable_overlay_once
python
droidrun/droidrun
eval/utils/keepalive.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/keepalive.py
MIT
def __init__(self, results_dir: str = "eval_results"): """Initialize the result manager. Args: results_dir: Directory to save results to """ self.results_dir = results_dir self.results = [] # Create results directory if it doesn't exist results_path = Path(results_dir) results_path.mkdir(parents=True, exist_ok=True) # Initialize summary self.summary = { "total_tasks": 0, "successful_tasks": 0, "tasks": [], "success_rate": 0.0, "avg_steps": 0.0, "avg_time": 0.0, "timestamp": datetime.now().isoformat() } # Try to load existing summary summary_file = os.path.join(results_dir, "summary.json") if os.path.exists(summary_file): try: with open(summary_file, "r") as f: self.summary = json.load(f) logger.info(f"Loaded existing summary from {summary_file}") except Exception as e: logger.error(f"Error loading summary file: {e}")
Initialize the result manager. Args: results_dir: Directory to save results to
__init__
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def save_task_result(self, result: Dict[str, Any]): """Save a task result. Args: result: Task result data """ # Add to results list self.results.append(result) # Save to file timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") task_name = result["task_name"].replace(" ", "_") filename = f"{timestamp}_{task_name}.json" filepath = os.path.join(self.results_dir, filename) try: with open(filepath, "w") as f: json.dump(result, f, indent=2) logger.info(f"Saved result for task '{task_name}' to {filepath}") except Exception as e: logger.error(f"Error saving result file: {e}") # Update summary self._update_summary(result)
Save a task result. Args: result: Task result data
save_task_result
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def _update_summary(self, result: Dict[str, Any]): """Update the summary with a new result. Args: result: Task result data """ # Update total tasks self.summary["total_tasks"] += 1 # Update successful tasks if result.get("success", False): self.summary["successful_tasks"] += 1 # Update success rate if self.summary["total_tasks"] > 0: self.summary["success_rate"] = self.summary["successful_tasks"] / self.summary["total_tasks"] # Add simplified task result summary_task = { "task_name": result["task_name"], "success": result.get("success", False), "steps_taken": result.get("steps_taken", 0), "execution_time": result.get("execution_time", 0), "timestamp": result.get("timestamp", datetime.now().isoformat()) } # Add trajectory statistics if available if "trajectory_stats" in result: summary_task["trajectory_stats"] = result["trajectory_stats"] # Initialize trajectory summary stats if not present if "trajectory_summary" not in self.summary: self.summary["trajectory_summary"] = { "avg_total_steps": 0, "avg_planning_steps": 0, "avg_execution_steps": 0, "tasks_with_trajectory": 0 } # Update trajectory summary self.summary["trajectory_summary"]["tasks_with_trajectory"] += 1 tasks_with_traj = self.summary["trajectory_summary"]["tasks_with_trajectory"] # Calculate running averages current_avg_total = self.summary["trajectory_summary"]["avg_total_steps"] current_avg_planning = self.summary["trajectory_summary"]["avg_planning_steps"] current_avg_execution = self.summary["trajectory_summary"]["avg_execution_steps"] new_total = result["trajectory_stats"]["total_steps"] new_planning = result["trajectory_stats"]["planning_steps"] new_execution = result["trajectory_stats"]["execution_steps"] # Update running averages self.summary["trajectory_summary"]["avg_total_steps"] = (current_avg_total * (tasks_with_traj - 1) + new_total) / tasks_with_traj self.summary["trajectory_summary"]["avg_planning_steps"] = (current_avg_planning * (tasks_with_traj - 1) + new_planning) / tasks_with_traj self.summary["trajectory_summary"]["avg_execution_steps"] = (current_avg_execution * (tasks_with_traj - 1) + new_execution) / tasks_with_traj self.summary["tasks"].append(summary_task) # Update averages total_steps = sum(t.get("steps_taken", 0) for t in self.summary["tasks"]) total_time = sum(t.get("execution_time", 0) for t in self.summary["tasks"]) if self.summary["total_tasks"] > 0: self.summary["avg_steps"] = total_steps / self.summary["total_tasks"] self.summary["avg_time"] = total_time / self.summary["total_tasks"] # Save updated summary self._save_summary()
Update the summary with a new result. Args: result: Task result data
_update_summary
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def create_task_result(task_name: str, task_description: str) -> Dict[str, Any]: """Create a new task result object. Args: task_name: Name of the task task_description: Description of the task Returns: Task result object """ return { "task_name": task_name, "task_description": task_description, "success": False, "agent_success": False, "steps_taken": 0, "max_steps": 0, "execution_time": 0, "logs": [], "timestamp": datetime.now().isoformat(), "error": None, "trajectory": [], # Will store the agent's execution trajectory "trajectory_stats": { # Will store statistics about the trajectory "total_steps": 0, "planning_steps": 0, "execution_steps": 0 } }
Create a new task result object. Args: task_name: Name of the task task_description: Description of the task Returns: Task result object
create_task_result
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def update_result_from_agent(result: Dict[str, Any], agent_result: Any, agent: Any) -> Dict[str, Any]: """Update a task result with information from an agent run. Args: result: Task result to update agent_result: Result from agent run agent: Agent instance Returns: Updated task result """ # Extract information from agent result if available if agent_result is not None: if isinstance(agent_result, dict): # Update with values from result dict if "steps_taken" in agent_result: result["steps_taken"] = agent_result["steps_taken"] if "success" in agent_result: result["agent_success"] = agent_result["success"] if "logs" in agent_result: result["logs"] = agent_result["logs"] # Capture final thought if available if "final_thought" in agent_result: result["final_thought"] = agent_result["final_thought"] # Save trajectory information if available if "trajectory" in agent_result: result["trajectory"] = agent_result["trajectory"] # Calculate trajectory statistics plan_steps = sum(1 for step in agent_result["trajectory"] if step["type"].startswith("planner_")) code_steps = sum(1 for step in agent_result["trajectory"] if step["type"].startswith("codeact_")) result["trajectory_stats"] = { "total_steps": len(agent_result["trajectory"]), "planning_steps": plan_steps, "execution_steps": code_steps } logger.info(f"Captured agent trajectory with {len(agent_result['trajectory'])} steps") logger.info(f" - Planning steps: {plan_steps}") logger.info(f" - Execution steps: {code_steps}") # Check if agent marked task as complete via tools_instance if hasattr(agent.tools_instance, 'finished') and agent.tools_instance.finished: result["complete_success"] = agent.tools_instance.success result["complete_reason"] = getattr(agent.tools_instance, 'reason', None) logger.info(f"Agent marked task as complete: success={agent.tools_instance.success}") return result
Update a task result with information from an agent run. Args: result: Task result to update agent_result: Result from agent run agent: Agent instance Returns: Updated task result
update_result_from_agent
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def __init__(self, progress_file: str): """Initialize the progress tracker. Args: progress_file: Path to progress file """ self.progress_file = progress_file self.completed_tasks = 0 # Ensure directory exists if progress_file includes a directory path dirname = os.path.dirname(progress_file) if dirname: # Only create directories if there's actually a directory path os.makedirs(dirname, exist_ok=True) # Try to load existing progress self._load_progress()
Initialize the progress tracker. Args: progress_file: Path to progress file
__init__
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def update_progress(self, completed_tasks: int): """Update progress with the number of completed tasks. Args: completed_tasks: Number of completed tasks """ self.completed_tasks = completed_tasks try: progress_data = { "completed_tasks": self.completed_tasks, "last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S") } with open(self.progress_file, 'w') as f: json.dump(progress_data, f, indent=4) logger.info(f"Updated progress: {self.completed_tasks} tasks completed") except Exception as e: logger.error(f"Error updating progress file: {e}")
Update progress with the number of completed tasks. Args: completed_tasks: Number of completed tasks
update_progress
python
droidrun/droidrun
eval/utils/results.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/results.py
MIT
def __init__(self, task_family: str = registry.TaskRegistry.ANDROID_WORLD_FAMILY): """Initialize the task registry. Args: task_family: The task family to use """ self.task_family = task_family self.registry = registry.TaskRegistry() self.task_dict = self.registry.get_registry(family=task_family) self.task_id_to_name = {} # Build task ID to name mapping for i, task_name in enumerate(sorted(self.task_dict.keys()), 1): self.task_id_to_name[i] = task_name logger.info(f"Found {len(self.task_id_to_name)} tasks in registry")
Initialize the task registry. Args: task_family: The task family to use
__init__
python
droidrun/droidrun
eval/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/task_manager.py
MIT
def create_task_instance(self, task_name: str, random_seed: int = 42) -> Optional[task_eval.TaskEval]: """Create an instance of a task. Args: task_name: Name of the task random_seed: Random seed for parameter generation Returns: Task instance or None if task could not be created """ task_class = self.get_task_class(task_name) if not task_class: logger.warning(f"Task {task_name} not found in registry") return None try: # Generate random parameters random.seed(random_seed) params = task_class.generate_random_params() params["seed"] = random_seed # Create and return task instance task_instance = task_class(params) logger.info(f"Created task instance for {task_name}") return task_instance except NotImplementedError: logger.warning(f"Task {task_name} does not implement generate_random_params()") return None except Exception as e: logger.exception(f"Error creating instance for task {task_name}: {e}") return None
Create an instance of a task. Args: task_name: Name of the task random_seed: Random seed for parameter generation Returns: Task instance or None if task could not be created
create_task_instance
python
droidrun/droidrun
eval/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/task_manager.py
MIT
def filter_tasks(self, task_ids: Optional[List[int]] = None, task_names: Optional[List[str]] = None) -> Dict[str, type]: """Filter tasks based on task IDs or names. Args: task_ids: List of task IDs to filter task_names: List of task names to filter Returns: Dictionary of filtered tasks """ filtered_tasks = {} # Filter by task IDs if task_ids: for task_id in task_ids: if task_id in self.task_id_to_name: task_name = self.task_id_to_name[task_id] if task_name in self.task_dict: filtered_tasks[task_name] = self.task_dict[task_name] else: logger.warning(f"Task {task_name} (ID: {task_id}) not found in registry") else: logger.warning(f"Task ID {task_id} not found in registry") # Filter by task names if task_names: for task_name in task_names: if task_name in self.task_dict: filtered_tasks[task_name] = self.task_dict[task_name] else: logger.warning(f"Task {task_name} not found in registry") # If no filters applied, use all tasks if not filtered_tasks and not task_ids and not task_names: filtered_tasks = self.task_dict return filtered_tasks
Filter tasks based on task IDs or names. Args: task_ids: List of task IDs to filter task_names: List of task names to filter Returns: Dictionary of filtered tasks
filter_tasks
python
droidrun/droidrun
eval/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/task_manager.py
MIT
def create_task_suite(self, task_ids: Optional[List[int]] = None, task_names: Optional[List[str]] = None, n_combinations: int = 1, random_seed: int = 42) -> List[Tuple[str, task_eval.TaskEval]]: """Create a suite of tasks to benchmark. Args: task_ids: List of task IDs to include task_names: List of task names to include n_combinations: Number of parameter combinations per task random_seed: Random seed for reproducibility Returns: List of (task_name, task_instance) tuples """ # Filter tasks based on IDs or names filtered_tasks = self.filter_tasks(task_ids, task_names) # Create task instances task_suite = [] random.seed(random_seed) logger.info(f"Creating task suite with {len(filtered_tasks)} tasks...") for task_name, task_class in filtered_tasks.items(): for i in range(n_combinations): try: # Generate random parameters for the task params = task_class.generate_random_params() # Add a seed for reproducibility params["seed"] = random_seed + i # Create task instance task_instance = task_class(params) task_suite.append((task_name, task_instance)) logger.info(f"Created task: {task_name} (instance {i+1}/{n_combinations})") except Exception as e: logger.error(f"Error creating task {task_name}: {e}") continue logger.info(f"Created task suite with {len(task_suite)} task instances") return task_suite
Create a suite of tasks to benchmark. Args: task_ids: List of task IDs to include task_names: List of task names to include n_combinations: Number of parameter combinations per task random_seed: Random seed for reproducibility Returns: List of (task_name, task_instance) tuples
create_task_suite
python
droidrun/droidrun
eval/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/task_manager.py
MIT
async def initialize_task(env, task_instance: task_eval.TaskEval) -> bool: """Initialize a task in the environment. Args: env: AndroidWorld environment task_instance: Task instance to initialize Returns: True if initialization was successful, False otherwise """ task_name = task_instance.__class__.__name__ logger.info(f"Initializing task: {task_name}") # Reset environment for the task env.reset(go_home=True) # Initialize the task try: # First try to use initialize_task() which is standard in AndroidWorld if hasattr(task_instance, 'initialize_task') and callable(getattr(task_instance, 'initialize_task')): task_instance.initialize_task(env) logger.info(f"Task initialized using initialize_task() method") return True # Fall back to setup() if it exists elif hasattr(task_instance, 'setup') and callable(getattr(task_instance, 'setup')): task_instance.setup(env) logger.info(f"Task initialized using setup() method") return True else: logger.error(f"Task {task_name} has no initialize_task() or setup() method") return False except Exception as e: logger.error(f"Error initializing task {task_name}: {e}") return False
Initialize a task in the environment. Args: env: AndroidWorld environment task_instance: Task instance to initialize Returns: True if initialization was successful, False otherwise
initialize_task
python
droidrun/droidrun
eval/utils/task_manager.py
https://github.com/droidrun/droidrun/blob/master/eval/utils/task_manager.py
MIT