AgentBench

repository·main·Indexed 25 days ago

https://github.com/thudm/agentbench

A comprehensive benchmark for evaluating Large Language Models (LLMs) as autonomous agents across diverse environments, including Operating Systems, Databases, and Knowledge Graphs. It features a standard evaluation framework (v0.2) and a Function-Calling (FC) version integrated with AgentRL, supporting tasks such as alfworld, dbbench, knowledgegraph, os_interaction, and webshop.

Tokens
13.6K
Snippets
11
Records
78
Agent score
86%

What's inside AgentBench

  1. Overview of AgentBench Datasets

    main

    AgentBench is a benchmark consisting of eight distinct task environments designed to evaluate LLMs as agents across various domains:

    • Operating System: Evaluates Bash command execution in Docker environments (144 samples).
    • Database: Evaluates SQL operation capabilities on real databases (MySQL).
    • Knowledge Graph: Evaluates decision-making in complex knowledge graphs (Freebase) via tool calls.
    • Digital Card Game: Evaluates strategic decision-making in a turn-based strategy game (Aquawar).
    • Lateral Thinking Puzzle: Evaluates reasoning and questioning skills in a social deduction-style game.
    • Householding (ALFWorld): Evaluates task completion in simulated home environments via text interfaces.
    • Web Shopping (WebShop): Evaluates e-commerce navigation and product selection based on attributes.
    • Web Browsing (Mind2Web): Evaluates complex task execution across diverse real-world websites using HTML elements.
  2. Understand the AgentBench Framework Architecture

    main

    AgentBench is a decoupled framework designed to evaluate LLMs as agents across diverse environments. It consists of three main components that communicate via HTTP:

    1. Task Server: Hosts task environments (e.g., OS, DB, Web). It provides task descriptions and environmental feedback.
    2. Agent Server: Provides an interface for the Agent to perform inference based on historical data (e.g., a FastChat deployment for local models).
    3. Client: Coordinates the entire process. It uses an Assigner to manage task/model allocation, an Agent Client to talk to the Agent Server, and a Task Client to talk to the Task Controller.

    Components can be deployed on a single machine or across multiple machines.

  3. Architecture of the AgentBench Framework

    main

    The AgentBench framework is designed with decoupled components that communicate via HTTP, allowing for independent deployment and scaling. The architecture consists of three main parts:

    1. Task Server: Hosts the task environments. It provides task descriptions and environment feedback based on agent responses.
    2. Agent Server: Provides an interface for the reasoning agent. It can be any server type (e.g., FastChat for local models or direct API implementations for hosted models).
    3. Client: Orchestrates the entire process by coordinating the Agent and Task servers based on configuration files.
  4. Batch start tasks using start_task.yaml

    main

    The start_task.yaml file is used in conjunction with src.start_task to automate the batch startup of task_worker instances.

    Fields available in start_task.yaml:

    • definition: Defines the tasks, typically imported from task_assembly.yaml.
    • start (Optional): Specifies which tasks to start. The key is the task name, and the value is the number of workers to start for that task.
    • controller_address (Optional): The address of the controller. Defaults to http://localhost:5000/api/.
  5. Deploy and Test Models using AgentBench

    main

    To test a model (e.g., ChatGLM2-6B) on specific tasks (e.g., WebShop and DBBench), follow these steps:

    1. Deploy the Agent Server: Use a tool like FastChat to host your local model and provide an Agent Server interface.
    2. Configure Task Servers: Modify the Task Server configuration files to deploy the required task environments (e.g., WebShop and DBBench) separately.
    3. Configure and Start the Client: Edit the Client configuration file to specify the use of FastchatClient and indicate which tasks (WebShop, DBBench) to test. Then, start the Client.
  6. Configure and Run the AgentBench Client

    main

    The Client manages the execution flow using three internal components:

    • Assigner: Uses a real-time maximum network flow algorithm to match available Agents and Tasks to test samples based on concurrency limits defined in configuration files.
    • Agent Client: Implements the Agent Server interface, exposing AgentClient.inference(self, history).
    • Task Client: Communicates with the Task Controller using TaskClient.run_sample(self, index, agent), which handles the bidirectional forwarding of outputs between the Agent and the Task.

    Example Workflow

    To test a model (e.g., ChatGLM2-6B) on specific tasks (e.g., WebShop and DBBench):

    1. Deploy the model using FastChat to create an Agent Server.
    2. Modify the Task Server configuration to deploy the WebShop and DBBench environments.
    3. Modify the Client configuration to specify the FastchatClient and the target tasks (WebShop, DBBench), then start the client.
  7. Run evaluations with assigner

    main
    The assigner script starts the evaluation process, reading configuration and saving results in real-time to a specified output directory. If the directory specified in the output field already exists, assigner will attempt to resume evaluation from existing results. Note that assigner overwrites the configuration file in the output directory every time it starts.
  8. Start the task_controller

    main

    The task_controller is the core component of the task server responsible for managing all task_workers. It should be started first and is recommended to be kept running and globally unique. All API interfaces use the /api/ prefix. By default, it runs on port 5000.

    python -m src.server.task_controller -p 3000
  9. Deploy KnowledgeGraph service locally

    main

    The KnowledgeGraph (KG) task depends on an online service. To deploy it locally:

    1. Download the database and set up the service using freebase-setup.
    2. In /configs/tasks/kg.yaml, update the sparql_url field from the default online URL to your local service API URL: sparql_url: "<your service api of sparql>"

    Note: You must start the KG service before starting the agent task services.

  10. Migrate from AgentBench v0.1 to current version

    main

    If you are upgrading a custom task from AgentBench v0.1, follow these steps:

    1. Replace get_data with get_indices: Instead of binding data to self in __init__ and retrieving it via index in start_sample, implement get_indices(). If your dataset is a list, you can return list(range(len(self.data))).
    2. Replace predict_single with start_sample:
      • Change the method signature from def to async def.
      • Change session.action(...) to await session.action(...).
      • Ensure the return value is a TaskSampleExecutionResult and explicitly set the status field.
    3. Replace metrics with calculate_overall: Rename your metrics calculation method to calculate_overall. If you want to keep the old logic, you can have calculate_overall call your existing self.metrics method.

    Note: The predict_all method is no longer supported in the new framework.

  11. Implement a custom Task in AgentBench

    main

    To create a new task, inherit from the Task class and implement its required interface.

    Required Methods:

    • __init__(self, name: str, concurrency: int = 1, *args, **kwargs): Initializes the task. name is typically specified in the config, and concurrency defines the maximum concurrency supported within a single worker.
    • get_indices(self) -> List[SampleIndex]: Returns a list of all test sample indices. SampleIndex can be an int or str.
    • async start_sample(self, index: SampleIndex, session: Session) -> TaskSampleExecutionResult: Contains the logic for a single test sample. Use the session object to interact with the Agent.
    • calculate_overall(self, results: List[TaskOutput]) -> Dict[str, Any]: Calculates the final score/metrics after all samples are tested. The returned dictionary is saved to overall.json.
    • release(self): Performs cleanup after the entire worker process finishes (not after each sample).

    Interacting with the Agent via Session:

    • session.inject(item: Union[ChatHistoryItem, List[ChatHistoryItem]]): Inserts one or more history records into the session.
    • await session.action(*injection) -> AgentOutput: Waits for the Agent's response. You can optionally pass history items to be injected simultaneously.

    Handling AgentOutput:

    When calling session.action, always check the AgentOutputStatus. If the status is CANCELLED, you must terminate the sample execution quickly to avoid impacting subsequent tests.

    class VirtualTask(Task):
        def __init__(self, *args, **kwargs) -> None:
            super().__init__(name="virtual-task", *args, **kwargs)
    
        def get_indices(self) -> List[Any]:
            return list(range(10))
    
        async def start_sample(self, index, session: Session):
            print("task start sample")
            for loop_times in range(3):
                await asyncio.sleep(1)
                res = await session.action(
                    {"role": "user", "content": "Loop: %d" % loop_times}
                )
                print("TASK", res.content)
            return TaskSampleExecutionResult(
                status=SampleStatus.COMPLETED,
                result={"result": "ok"},
            )
    
        def calculate_overall(self, results: List[TaskOutput]) -> Dict[str, Any]:
            return {"score": 0.4}
  12. Quick Start: Original AgentBench (v0.2) Setup

    main

    To use the original AgentBench (v0.2) for tasks like dbbench-std and os-std, follow these steps:

    1. Install Dependencies: It is highly recommended to use Python 3.9 via conda due to pinned scientific dependencies.

      cd AgentBench
      conda create -n agent-bench python=3.9
      conda activate agent-bench
      pip install -r requirements.txt
    2. Prepare Docker Images:

      docker pull mysql
      docker pull ubuntu
      docker build -f data/os_interaction/res/dockerfiles/default data/os_interaction/res/dockerfiles --tag local-os/default
      docker build -f data/os_interaction/res/dockerfiles/packages data/os_interaction/res/dockerfiles --tag local-os/packages
      docker build -f data/os_interaction/res/dockerfiles/ubuntu data/os_interaction/res/dockerfiles --tag local-os/ubuntu
    3. Configure Agent: Add your OpenAI API Key to configs/agents/openai-chat.yaml. You can verify the configuration by running:

      python -m src.client.agent_test

      To test a specific agent:

      python -m src.client.agent_test --config configs/agents/api_agents.yaml --agent gpt-3.5-turbo-0613
    4. Start Task Server: Launch task workers (ensure ports 5000-5015 are available):

      python -m src.start_task -a

      For low-resource machines, use the lite preset:

      python -m src.start_task -a --config configs/start_task_lite.yaml
    5. Run Assigner: Initiate the actual task tests:

      python -m src.assigner

      If using the lite preset:

      python -m src.assigner --config configs/assignments/lite.yaml
    # Install dependencies
    conda create -n agent-bench python=3.9
    conda activate agent-bench
    pip install -r requirements.txt
    
    # Start task server
    python -m src.start_task -a
    
    # Start assigner
    python -m src.assigner