UI-TARS: Multimodal GUI Agent

repository·main·Indexed 11 days ago

https://github.com/bytedance/ui-tars

A multimodal agent for automated GUI interaction across desktop, mobile, and web environments. It includes the ui-tars package (v0.1.4) for parsing LLM-generated instructions into structured actions and generating executable pyautogui scripts. Key features include coordinate-based grounding, smart image resizing, and specialized prompt templates for computer use, mobile use, and grounding tasks.

Tokens
9.3K
Snippets
19
Records
31
Agent score
94%

What's inside UI-TARS

  1. Overview of UI-TARS

    main

    UI-TARS is a native GUI agent model designed for seamless interaction with graphical user interfaces (GUIs). Unlike traditional modular frameworks that rely on predefined workflows or manual rules, UI-TARS integrates perception, reasoning, grounding, and memory into a single vision-language model (VLM). This enables end-to-end task automation by processing multimodal inputs (text, images, and interactions) to understand and act upon dynamic interfaces.

    Core Capabilities

    • Cross-Platform Interaction: Uses a unified action framework to support desktop, mobile, and web environments.
    • Multi-Step Task Execution: Capable of handling complex tasks through multi-step trajectories and reasoning.
    • Unified Action Space: Provides standardized action definitions across platforms, including platform-specific gestures like hotkeys and long presses.
    • Reasoning Models: Employs both System 1 (fast, intuitive) and System 2 (deliberate, high-level planning) reasoning, supporting task decomposition and error correction.
    • Memory Systems: Utilizes short-term memory for task-specific context and long-term memory for historical interaction knowledge.
  2. UI-TARS Performance Benchmarks

    main

    UI-TARS models are evaluated across several dimensions of GUI interaction capability, including perception, grounding, and agentic performance in offline and online environments. The model family includes 2B, 7B, and 72B parameter versions.

    Perception Capability

    Evaluates the model's ability to understand visual web and UI elements using benchmarks like VisualWebBench, WebSRC, and SQAshort. UI-TARS-72B leads in VisualWebBench (82.8) and SQAshort (88.6).

    Grounding Capability

    Evaluates the precision of element localization (e.g., clicking the correct icon or text) using ScreenSpot and ScreenSpot v2. UI-TARS-7B and 72B demonstrate high performance across mobile, desktop, and web interfaces.

    Agent Capability

    Evaluates end-to-end task completion in complex environments:

    • Multimodal Mind2Web: Measures element accuracy, operation F1, and step success rate across tasks and domains.
    • Android Control & GUI Odyssey: Evaluates control and grounding in Android environments.
    • Online Agent Evaluation: Measures performance in real-world online environments like OSWorld and AndroidWorld.
  3. Understand UI-TARS-1.5 limitations

    main

    When using UI-TARS-1.5, be aware of the following known limitations:

    • Misuse Risk: Due to its ability to navigate authentication challenges like CAPTCHA, it may be misused for unauthorized access.
    • Computation: Requires substantial computational resources, especially for large-scale tasks or extended gameplay.
    • Hallucination: May generate inaccurate descriptions, misidentify GUI elements, or take suboptimal actions in ambiguous or unfamiliar environments.
    • Model Scale Specialization: The UI-TARS-1.5-7B model is optimized for general computer use and is not specifically optimized for game-based scenarios, whereas the full UI-TARS-1.5 maintains an advantage in gaming environments.
  4. Choose a prompt template for GUI tasks

    main

    UI-TARS provides three distinct prompt templates in codes/ui_tars/prompt.py to guide the agent based on the target environment and desired output format:

    1. COMPUTER_USE: Best for desktop environments (Windows, Linux, macOS). Supports mouse clicks (single, double, right), dragging, keyboard shortcuts, text input, and scrolling. Ideal for browsers, office software, and file management.
    2. MOBILE_USE: Best for mobile devices or Android emulators. Includes mobile-specific actions like long_press, open_app, press_home, and press_back.
    3. GROUNDING: Best for lightweight tasks or model evaluation. It outputs only the Action without any reasoning (Thought), focusing purely on object grounding.
  5. Convert UI-TARS model coordinates to absolute pixels

    main

    The model outputs 2D coordinates in a relative format (0-1000). To map these to actual pixel coordinates on your screen, follow these steps:

    1. Normalize: Divide the model's relative coordinate components by 1000 to get values in the range [0, 1].
    2. Scale: Multiply the normalized values by the image width and height.

    Formula:

    • X_absolute = round(X_relative * image_width / 1000)
    • Y_absolute = round(Y_relative * image_height / 1000)

    Example: For a 1920 × 1080 screen and a model output of (235, 512):

    • X_absolute = round(1920 * 235 / 1000) = 451
    • Y_absolute = round(1080 * 512 / 1000) = 553 Result: (451, 553)
  6. Use UI-TARS via OpenAI Python API

    main

    Once deployed, you can interact with the UI-TARS endpoint using the openai Python library.

    Note on Post-Processing: The model's raw output for actions (e.g., click(start_box='(x,y)')) may need to be post-processed to wrap coordinates in special tokens like <|box_start|> and <|box_end|> for downstream compatibility. The provided example includes an add_box_token function to perform this regex-based transformation.

    Requirements:

    • pip install openai
    • A valid base_url (your HuggingFace endpoint URL) and api_key.
    import json
    import re
    from openai import OpenAI
    
    def add_box_token(input_string):
        # Transforms 'start_box="(x,y)"' into 'start_box="<|box_start|>(x,y)<|box_end|>"'
        if "Action: " in input_string and "start_box=" in input_string:
            suffix = input_string.split("Action: ")[0] + "Action: "
            actions = input_string.split("Action: ")[1:]
            processed_actions = []
            for action in actions:
                action = action.strip()
                coordinates = re.findall(r"(start_box|end_box)='\((\d+),\s*(\d+)\)'", action)
                updated_action = action
                for coord_type, x, y in coordinates:
                    updated_action = updated_action.replace(f"{coord_type}='({x},{y})'", f"{coord_type}='<|box_start|>({x},{y})<|box_end|>'")
                processed_actions.append(updated_action)
            final_string = suffix + "\n\n".join(processed_actions)
        else:
            final_string = input_string
        return final_string
    
    client = OpenAI(
        base_url="https:xxx",
        api_key="hf_xxx"
    )
    
    # Load messages from a local JSON file
    messages = json.load(open("./data/test_messages.json"))
    for message in messages:
        if message["role"] == "assistant":
            message["content"] = add_box_token(message["content"])
    
    chat_completion = client.chat.completions.create(
        model="tgi",
        messages=messages,
        top_p=None,
        temperature=0.0,
        max_tokens=400,
        stream=True
    )
    
    response = ""
    for message in chat_completion:
        response += message.choices[0].delta.content
    print(response)
  7. Process and visualize model coordinate outputs

    main

    UI-TARS models output coordinates in a specific format (e.g., click(start_box='(197,525)')). To use these coordinates for actual GUI interaction, you must map the model's output coordinates back to the original image dimensions. This is necessary because the model operates on a resized version of the image that adheres to specific pixel constraints and divisibility rules.

    Workflow

    1. Parse Coordinates: Extract the raw x and y values from the model's text response using regular expressions.
    2. Determine Resized Dimensions: Use the smart_resize logic to calculate the dimensions (new_width, new_height) the model actually saw. This logic ensures dimensions are divisible by IMAGE_FACTOR (default 28) and stay within MIN_PIXELS and MAX_PIXELS bounds.
    3. Map to Original Image: Calculate the actual pixel position on the original image using the ratio of the model's output to the resized dimensions.

    Note: For a complete implementation of action space parsing, refer to the uitars_agent.py in the OSWorld repository.

    from PIL import Image
    import math
    
    # Constants used by the model's vision processing
    IMAGE_FACTOR = 28
    MIN_PIXELS = 100 * 28 * 28
    MAX_PIXELS = 16384 * 28 * 28
    MAX_RATIO = 200
    
    def round_by_factor(number: int, factor: int) -> int:
        return round(number / factor) * factor
    
    def ceil_by_factor(number: int, factor: int) -> int:
        return math.ceil(number / factor) * factor
    
    def floor_by_factor(number: int, factor: int) -> int:
        return math.floor(number / factor) * factor
    
    def smart_resize(
        height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS
    ) -> tuple[int, int]:
        if max(height, width) / min(height, width) > MAX_RATIO:
            raise ValueError(f"absolute aspect ratio must be smaller than {MAX_RATIO}")
        
        h_bar = max(factor, round_by_factor(height, factor))
        w_bar = max(factor, round_by_factor(width, factor))
        
        if h_bar * w_bar > max_pixels:
            beta = math.sqrt((height * width) / max_pixels)
            h_bar = floor_by_factor(height / beta, factor)
            w_bar = floor_by_factor(width / beta, factor)
        elif h_bar * w_bar < min_pixels:
            beta = math.sqrt(min_pixels / (height * width))
            h_bar = ceil_by_factor(height * beta, factor)
            w_bar = ceil_by_factor(width * beta, factor)
        return h_bar, w_bar
    
    # Example usage for mapping
    img = Image.open('./data/coordinate_process_image.png')
    width, height = img.size
    model_output_width, model_output_height = 197, 525
    
    new_height, new_width = smart_resize(height, width)
    # Map model coordinates back to original image scale
    new_coordinate = (int(model_output_width/new_width * width), int(model_output_height/new_height * height))
    print(f'Mapped Coordinate: {new_coordinate}')
  8. Deploy UI-TARS locally using vLLM

    main

    For fast deployment and inference, use vllm>=0.6.1. You must install transformers and a compatible version of vllm with the correct CUDA version.

    To start an OpenAI-compatible API service, use the vllm.entrypoints.openai.api_server module. It is recommended to set the tensor parallel size (-tp) based on your model size: -tp=1 for 7B models and -tp=4 for 72B models. Use --limit-mm-per-prompt image=5 to allow multiple images in a single prompt.

    # Install dependencies
    pip install -U transformers
    
    # Example for vLLM 0.6.6 with CUDA 12.4
    VLLM_VERSION=0.6.6
    CUDA_VERSION=cu124
    pip install vllm==${VLLM_VERSION} --extra-index-url https://download.pytorch.org/whl/${CUDA_VERSION}
    
    # Start the OpenAI-compatible API service
    python -m vllm.entrypoints.openai.api_server --served-model-name ui-tars \
        --model <path to your model> --limit-mm-per-prompt image=5 -tp <tp>
  9. Deployment Alternatives for UI-TARS

    main

    When choosing a deployment method for UI-TARS, be aware of the following recommendations:

    • GGUF Models: Performance for quantized GGUF models cannot be guaranteed and is currently considered downgraded.
    • Recommended Alternatives:
      • Cloud Deployment: Use cloud-based platforms (e.g., ModelScope) for managed inference.
      • Local Deployment [vLLM]: Recommended if you have sufficient GPU resources available locally.

    For desktop-specific local operation, refer to the UI-TARS-desktop repository. For web automation, use Midscene.js.

  10. Request early research access to UI-TARS-1.5

    main

    Early research access to the top-performing UI-TARS-1.5 model is available for collaborative research. Interested researchers should contact the team via email.

    TARS@bytedance.com
  11. Deploy UI-TARS 1.5 to HuggingFace Inference Endpoints

    main

    To deploy the UI-TARS 1.5 7B model on HuggingFace Inference Endpoints, follow these configuration steps:

    1. Model Selection

    2. Hardware Configuration

    • For the 7B model, it is recommended to use GPU L40S 1GPU 48G (or Nvidia L4 / Nvidia A100).

    3. Container Configuration

    Set the following parameters to handle large inputs and long sequences:

    • Max Input Length (per Query): 65536
    • Max Batch Prefill Tokens: 65536
    • Max Number of Tokens (per Query): 65537

    4. Environment Variables

    Add these variables to ensure stability and support for large image payloads:

    • CUDA_GRAPHS=0: Prevents deployment failures.
    • PAYLOAD_LIMIT=8000000: Prevents request failures when sending large images.

    5. Container URI Update

    After creating the endpoint, navigate to the Container page and update the Container URI to: ghcr.io/huggingface/text-generation-inference:3.2.1 Then, click Update Endpoint to apply the changes.