CogAgent Documentation

repository·main·Indexed 22 days ago

https://github.com/zai-org/cogagent

An open-source Vision-Language Model (VLM) designed as a GUI Agent capable of perceiving and interacting with computer interfaces via screenshots and natural language. The CogAgent-9B-20241220 model, based on GLM-4V-9B, supports bilingual interaction and complex GUI tasks. Documentation covers client and server setup, OpenAI-compatible API deployment via vLLM, multi-turn fine-tuning data preparation, and hardware requirements for SFT and LoRA training on NVIDIA and Huawei Ascend NPU devices.

Tokens
13K
Snippets
42
Records
68
Agent score
78%

What's inside CogAgent

  1. Overview of CogAgent-9B-20241220

    main

    CogAgent is an open-source Vision-Language Model (VLM) based GUI Agent. The latest version, CogAgent-9B-20241220, is built upon the GLM-4V-9B base model and is optimized for GUI perception, reasoning accuracy, and action space completeness.

    Key features include:

    • Bilingual Support: Supports both Chinese and English interaction via screenshots and natural language.
    • High Performance: Leads in GUI localization (Screenspot), single-step operations (OmniAct), and multi-step operations (OSWorld).
    • Versatility: Capable of handling complex GUI tasks through visual and textual inputs.
  2. Understand CogAgent model outputs

    main

    CogAgent returns responses as plain strings (not JSON). Depending on the requested format, the output may include:

    • Sensitivity Labels: <<敏感操作>> (Sensitive) or <<一般操作>> (General). Only returned if Sensitive is in the format string.
    • Status/Plan/Action: Descriptive fields explaining the current state, the intended plan, or the specific action to take.
    • Grounded Operation: A structured description of the physical interaction, including:
      • box: Coordinates of the execution area.
      • element_type: The type of element being interacted with.
      • element_info: A description of the element.
      • An action command (e.g., CLICK, TYPE, SCROLL_DOWN).
  3. Understand the relationship between CogVLM and CogAgent

    main

    CogAgent is an open-source Visual Language Model (VLM) specifically optimized for GUI Agents, built upon the foundation of CogVLM.

    Key differences include:

    • CogVLM: A powerful VLM (e.g., CogVLM-17B) designed for high-resolution image understanding (490x490) and multi-turn dialogue across various cross-modal benchmarks.
    • CogAgent: An improved version (e.g., CogAgent-18B) that supports higher resolution image understanding (1120x1120) and adds specialized capabilities for GUI-based agent tasks. It significantly outperforms existing models on GUI operation datasets like AITW and Mind2Web.
  4. Execute Key Gestures (Combinations)

    main

    To perform key combinations (e.g., Ctrl+F), use the GESTURE action. It takes an actions parameter, which is a list of three specific sub-actions:

    1. KEY_DOWN(key='...'): Press a key without releasing it.
    2. KEY_PRESS(key='...'): Press and release a key.
    3. KEY_UP(key='...'): Release a previously pressed key.

    Example (Ctrl+A): GESTURE(actions=[KEY_DOWN(key='Lcontrol'), KEY_PRESS(key='A'), KEY_UP(key='Lcontrol')])

    GESTURE(actions=[KEY_DOWN(key='Lcontrol'), KEY_PRESS(key='A'), KEY_UP(key='Lcontrol')])
  5. Interpret CogAgent Model Outputs

    main

    CogAgent outputs data as a string; it does not support JSON output. You must parse the string according to the requested format.

    Key components of the output include:

    • General answer section: A summary text appearing before the formatted data.
    • Plan / Status / Action: Fields describing the model's reasoning, current environment state, or intended next step.
    • Grounded Operation: A detailed command containing:
      • box: Coordinate region for execution.
      • element_type: The type of UI element.
      • element_info: Description of the element.
    • Sensitive operations: If requested, the model will tag operations as <<敏感操作>> (sensitive) or <<一般操作>> (general).
  6. Format multi-round fine-tuning data for CogAgent

    main

    To fine-tune the cogagent-9b-20241220 model using multi-round dialogue, organize your data in a JSON format where each entry contains a messages array.

    Key requirements:

    • Each entry must include an image path.
    • The user role's content must include a Task description and a History steps section.
    • The History steps section must include all previous operations (e.g., CLICK, SCROLL_DOWN, TYPE) to provide context for the current step.
    • For intermediate steps, the assistant response should end with <<General Operation>>.
    • For the final step in a process, the assistant response should end with <<END>>.
    {
      "messages": [
        {
          "role": "user",
          "content": "Task: ...\n(Platform: Mac)\n(Answer in Action-Operation-Sensitive format.)\nHistory steps: \n0. CLICK(box=[[588,946,616,985]], element_info='System Settings')\t...\n",
          "image": "images/0000000000336.png"
        },
        {
          "role": "assistant",
          "content": "Action: ...\nGrounded Operation:CLICK(box=[[655,842,671,857]], element_info='...')\n<<General Operation>>"
        }
      ]
    }
  7. Important Constraints for CogAgent Usage

    main

    When integrating CogAgent, keep these critical requirements in mind:

    1. Image Requirement: The model requires images as input. Pure text prompts are insufficient for GUI agent tasks.
    2. No Continuous Dialogue: The model does not maintain internal state like a chatbot. You must manually manage and pass the execution history in every prompt.
    3. Strict Parsing: Because the output is a raw string and not JSON, your parser must be strictly aligned with the requested format to avoid errors.
  8. Install client-side dependencies on macOS

    main

    To set up the CogAgent client on macOS, follow these steps to ensure tkinter and the virtual environment are correctly configured.

    Note: Do not use conda or virtualenv as they may cause tkinter to malfunction. Use the built-in venv module with the --copies flag.

    1. Install python-tk and project dependencies:
    brew install python-tk
    pip install -r requirements.txt
    1. Verify tkinter installation:
    /opt/homebrew/bin/python3 -m tkinter
    1. Create a virtual environment using --copies:
    /opt/homebrew/bin/python3 -m venv --copies /path/to/your/venv
    1. Verify the virtual environment's tkinter:
    /path/to/your/venv/bin/python3 -m tkinter
    1. Create a caches directory for model images:
    mkdir caches
    brew install python-tk
    pip install -r requirements.txt
    
    # Create venv with copies to avoid tkinter issues
    /opt/homebrew/bin/python3 -m venv --copies /Users/zr/Code/CogAgent/venv
    
    mkdir caches
  9. Run CogAgent via CLI demo

    main

    To run a local inference using transformers, ensure you have Python 3.10.16+ and the required dependencies installed. Use cli_demo.py for a command-line interface where you provide an image path. If the model returns bounding boxes (bbox), it will save an image showing the target area in the specified --output_image_path.

    # Install dependencies
    pip install -r requirements.txt
    
    # Run CLI inference
    python inference/cli_demo.py \
        --model_dir THUDM/cogagent-9b-20241220 \
        --platform "Mac" \
        --max_length 4096 \
        --top_k 1 \
        --output_image_path ./results \
        --format_key status_action_op_sensitive
  10. Prepare multi-turn fine-tuning data

    main

    CogAgent uses a specific conversation format for multi-turn fine-tuning. The data should be organized in a JSON format where each entry contains a messages list.

    Key requirements:

    • Role-based loss masking: Different roles are assigned different loss_mask values to calculate loss for multi-turn responses in a single pass.
    • Image requirement: Every data entry must include an image path.
    • History steps: For the cogagent-9b-20241220 model, the user role's content must include a History steps: section containing all previous operations in the sequence.
    • Termination:
      • Intermediate steps should return <<一般操作>> (General Operation).
      • The final step in a complete process should return <<END>>.

    Example structure:

    {
      "messages": [
        {
          "role": "user",
          "content": "Task: ...\nHistory steps: \n0. CLICK(...) ...",
          "image": "images/0000000000336.png"
        },
        {
          "role": "assistant",
          "content": "Action: ...\nGrounded Operation:CLICK(...)\n<<一般操作>>"
        }
      ]
    }
    {
      "messages": [
        {
          "role": "user",
          "content": "Task: 在系统设置的桌面与程序坞部分,开启调度中心板块中“显示器具有单独空间”的选项\n(Platform: Mac)\n(Answer in Action-Operation-Sensitive format.)\nHistory steps: \n0. CLICK(box=[[588,946,616,985]], element_info='系统设置')\t点击屏幕下方的“系统设置”菜单,从而打开系统设置\n1. CLICK(box=[[227,561,297,585]], element_info='桌面与程序坞')\t点击左侧菜单中的“桌面与程序坞”选项,进入桌面与程序坞的设置界面.\n2. SCROLL_DOWN(box=[[367,39,691,929]], step_count=75, element_info='滚动')\t在当前屏幕的右侧滚动区域中,向下滚动以查看更多选项.\n",
          "image": "images/0000000000336.png"
        },
        {
          "role": "assistant",
          "content": "Action: 点击“调度中心”板块中的“显示器具有单独空间”选项,从而开启该功能.\nGrounded Operation:CLICK(box=[[655,842,671,857]], element_info='“显示器具有单独空间”的开关按钮')\n<<一般操作>>"
        }
      ]
    }
  11. Format user input prompts for CogAgent

    main

    CogAgent (cogagent-9b-20241220) is an Agent-class execution model, not a conversational model. It does not support continuous dialogue natively; instead, you must provide the full execution history in every new request to maintain context.

    To achieve optimal GUI Agent performance, you must follow a strict input format. The prompt should be constructed in the following order: query = f'{task}{history}{platform}{format}'

    Key Components:

    • task: A concise text description of the user's goal.
    • history: A list of previous steps. Even if there is no history, you must include the string History steps: .
    • platform: The operating system identifier.
    • format: The desired output structure.
    • [Continue] (Optional): To ask the model to continue its previous response, insert [Continue]\n immediately after the {task} field.
    current_platform = identify_os() # "Mac" or "WIN" or "Mobile"
    platform_str = f"(Platform: {current_platform})\n"
    format_str = "(Answer in Action-Operation-Sensitive format.)\n"
    
    history_str = "\nHistory steps: "
    for index, (grounded_op_func, action) in enumerate(zip(history_grounded_op_funcs, history_actions)):
       history_str += f"\n{index}. {grounded_op_func}\t{action}"
    
    query = f"Task: {task}{history_str}\n{platform_str}{format_str}"