# Evaluate your agent using externally available benchmarks via the CLI

In this tutorial, we will learn how to take a benchmark that came from an external source, rather than
from MorganaBench, and evaluate your agent on this benchmark using the MorganaBench CLI. Through this
experience, we will also learn about using the MorganaBench SDK to write files in the format our system
expects as input.

## Overview

Evaluating an agent on externally available benchmarks involves the following key steps:

1. Run your agent and write its input and output to a file in MorganaBench format.
2. Create an evaluation with the MorganaBench CLI by uploading the file and selecting metrics.
3. Download and inspect the results when MorganaBench is done evaluating.

In this tutorial, we will use the _watsonxDocsQA_ dataset from IBM Research, which comprises both a corpus and a corresponding benchmark. We
will build a simple agent grounded in the corpus and use MorganaBench to evaluate its responses to the queries in the benchmark.

## Setup

You will need:

- A MorganaBench account.
- The URL of your MorganaBench server, or the public server: `https://morganabench.morganalabs.ai/`.
- Python and a Python virtual environment.
- The MorganaBench CLI (`mb`). If you do not have it yet, install it with:

    ```bash
    curl -fsSL https://raw.githubusercontent.com/morganalabs/mb-cli/main/install.sh | bash
    ```

Confirm that the CLI is installed:

```bash
mb version
```

Then log in:

=== "macOS and Linux"

    ```bash
    export URL=https://morganabench.morganalabs.ai/
    mb login --url "$URL" --email you@example.com
    ```

=== "Windows PowerShell"

    ```powershell
    $env:URL = "https://morganabench.morganalabs.ai/"
    mb login --url $env:URL --email you@example.com
    ```

The CLI prompts for your password and stores the resulting access token for subsequent commands. You can confirm that authentication worked with:

```bash
mb whoami
```

Next, install the Python dependencies needed for the tutorial, assuming that you have activated your virtual environment and use `pip`.

```bash
# for importing the dataset
pip install pandas pyarrow huggingface-hub

# for building our agent
pip install llama-index
pip install llama-index-embeddings-bedrock # <-- or another embedding provider
pip install llama-index-llms-bedrock-converse # <-- or another LLM provider

# for writing output in MorganaBench format
pip install morgana-bench-SDK
```

## Build the agent and run it on the benchmark

First, we will import the data into a `corpus` subdirectory in our project. Here is a short script to do this:

```{.python title="import_corpus.py"}
import os

import pandas as pd

# create corpus dir
os.makedirs("./corpus", exist_ok=True)

# load the corpus from HuggingFace
url = "hf://datasets/ibm-research/watsonxDocsQA/corpus/train-00000-of-00001.parquet"
corpus_df = pd.read_parquet(url)

# write each document to a `corpus/<doc_id>.md` file
for row in corpus_df.itertuples(index=False):
    filename = "corpus" + os.sep + row.doc_id + ".md"
    with open(filename, "w", encoding="utf-8") as f:
        print(row.md_document, file=f)
```

Now we run the script:

```bash
python import_corpus.py
```

At this point, you should see a subdirectory named `corpus` with the corresponding markdown files. Let's verify:

=== "macOS and Linux"

    ```bash
    ls corpus | head -n 3
    ```

=== "Windows PowerShell"

    ```powershell
    Get-ChildItem corpus | Select-Object -First 3 -ExpandProperty Name
    ```

You should see output like:

```bash
00205C92C52FA28DB619EE1F9C8D76FE8564DB88.md
0093065541AA4C3E90E47E3ACE89596155EA1735.md
0108F00736882AC35E3C56CD3CE0D91BCB5798A8.md
```

Now let's inspect one of them:

=== "macOS and Linux"

    ```bash
    cat corpus/00205C92C52FA28DB619EE1F9C8D76FE8564DB88.md
    ```

=== "Windows PowerShell"

    ```powershell
    Get-Content corpus/00205C92C52FA28DB619EE1F9C8D76FE8564DB88.md
    ```

You should see output like:

```markdown
# History node #

History nodes are most often used for sequential data, such as time series data\.

They are used to create new fields containing data from fields in previous records\. When using a History node, you may want to use data that is presorted by a particular field\. You can use a Sort node to do this\.

<!-- </article "role="article" "> -->
```

This is one of the documents our agent will use to answer questions.

Next, we build our [LlamaIndex](https://www.llamaindex.ai/) agent. We use AWS Bedrock for document embeddings and the
LLM, which you can replace if you wish to use a different provider.

```{.python title="agent.py"}
import sys

from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.tools import QueryEngineTool
from llama_index.embeddings.bedrock import BedrockEmbedding
from llama_index.llms.bedrock_converse import BedrockConverse


def build_agent() -> FunctionAgent:
    # define embedder and LLM
    embed_model = BedrockEmbedding(
        model_name="amazon.titan-embed-text-v2:0",
        embed_batch_size=1,
        num_workers=64,
    )
    llm = BedrockConverse(model="global.anthropic.claude-haiku-4-5-20251001-v1:0")

    # create a tool that searches in our corpus
    print("Reading directory corpus into an in-memory index", file=sys.stderr)
    docs = SimpleDirectoryReader("./corpus", recursive=True).load_data()
    index = VectorStoreIndex.from_documents(docs, use_async=True, embed_model=embed_model)
    search_corpus_tool = QueryEngineTool.from_defaults(
        query_engine=index.as_query_engine(llm=llm, similarity_top_k=5),
        name="search_corpus",
        description="Search the corpus.",
    )

    # create an agent that uses this tool. Each `run` gets a fresh context, so one agent
    # instance serves any number of concurrent examples.
    print("Initializing agent", file=sys.stderr)
    return FunctionAgent(
        tools=[search_corpus_tool],
        llm=llm,
        system_prompt=(
            'Always either answer concisely based on the corpus, or respond with "I don\'t know".'
            ' Always answer directly to the query, and avoid a preamble like "according to the corpus"'
            ' or "according to the knowledge base".'
        ),
    )
```

We will use the `build_agent` function defined above in our script that runs the agent on the benchmark. Before showing the script, we will first
become familiar with the MorganaBench SDK classes used to produce data that MorganaBench can consume. Paste the following code snippet into your
terminal:

```bash
python << 'EOF'
import mb.entities as mbe
example = mbe.Example(
    inputs=mbe.Inputs(messages=[
        mbe.ChatMessage.user("Who was the King of England in 2025?")
    ]),
    expectations=[mbe.ExpectedResponse(response="King Charles III")],
    outputs=mbe.Outputs(response="We serve no kings")
)
print(example.model_dump_json(indent=2, exclude_none=True))
EOF
```

The output should look like this:

```json
{
  "inputs": {
    "messages": [
      {
        "role": "user",
        "content": "Who was the King of England in 2025?"
      }
    ]
  },
  "expectations": [
    {
      "expect": "response",
      "response": "King Charles III"
    }
  ],
  "outputs": {
    "response": "We serve no kings",
    "trace": []
  }
}
```

We can see that the `Example` object is divided into three parts: `inputs`, containing the agent's input; `expectations`, containing what we expect the agent
to produce (ground truth); and `outputs`, containing the agent's actual output. See the **[SDKs and Data Formats](https://sdk.morganalabs.ai/)** page for more information.

In practice, MorganaBench accepts a file consisting of _JSON Lines_ (NDJSON), which means that we print each `Example` object on one line and do not supply the `indent=2`
argument to the JSON-dumping function. So, without further ado, here is the script that reads the Q&As from the HuggingFace dataset,
runs the agent, and prints `Example` objects.

```{.python title="run_agent.py"}
import asyncio
import sys

import mb.entities as mbe
import pandas as pd

from agent import build_agent  # <-- the agent we just built


async def run_agent_on_benchmark() -> None:
    agent = build_agent()
    benchmark_url = "hf://datasets/ibm-research/watsonxDocsQA/question_answers/train-00000-of-00001.parquet"
    benchmark = pd.read_parquet(benchmark_url)
    total_conversations = len(benchmark)
    for conversation_number, row in enumerate(benchmark.itertuples(), start=1):
        # invoke the agent
        question = row.question
        response = await agent.run(question)

        # print `Example` object
        out_example = mbe.Example(
            inputs=mbe.Inputs(messages=[mbe.ChatMessage.user(question)]),
            expectations=[mbe.ExpectedResponse(response=row.correct_answer)],
            outputs=mbe.Outputs(response=str(response)),
        )
        print(out_example.model_dump_json(exclude_none=True))
        print(
            f"Completed {conversation_number} of {total_conversations} conversations",
            file=sys.stderr,
        )


asyncio.run(run_agent_on_benchmark())
```

The slight asynchronous I/O complexity is a requirement of LlamaIndex. Now we can run our agent on the benchmark and produce an executed benchmark
in a format MorganaBench can consume:

```bash
python run_agent.py > executed_benchmark.jsonl
```

The script prints progress, such as `Completed 3 of 10 conversations`, to your terminal while preserving the JSON Lines output in
`executed_benchmark.jsonl`.

Within a few minutes, typically two to five minutes, the script should finish and leave an `executed_benchmark.jsonl` file containing one example object on each line:

=== "macOS and Linux"

    ```bash
    head -n 1 executed_benchmark.jsonl
    ```

=== "Windows PowerShell"

    ```powershell
    Get-Content executed_benchmark.jsonl -TotalCount 1
    ```

Example output:

```{.json .code-wrap}
{"inputs":{"messages":[{"role":"user","content":"What foundation models have been built by IBM?"}]},"expectations":[{"expect":"response","response":"Foundation models built by IBM include: \ngranite-13b-chat-v2\ngranite-13b-chat-v1\ngranite-13b-instruct-v1\""}],"outputs":{"response":"IBM has built a family of foundation models called **Granite**. …","trace":[]}}
```

We can see that all fields are filled appropriately. Now that we have run our agent and produced an executed benchmark file, we can proceed to evaluation.

## Create an evaluation on MorganaBench

Before creating the evaluation, list the metrics that MorganaBench can compute:

```bash
mb metrics list
```

For this tutorial, we will use `ground_truth_alignment`, which compares each agent response with the corresponding expected response.

Create the evaluation by passing the executed benchmark file and the selected metric:

```bash
mb eval create "Watson QA" \
    --file executed_benchmark.jsonl \
    --metrics ground_truth_alignment
```

The CLI uploads the file and waits for the evaluation to finish. Its output should look similar to:

```text
Uploading executed_benchmark.jsonl...
Evaluation created: cde79124223a48ecb923c7265063197a
Waiting for evaluation cde79124223a48ecb923c7265063197a...
  Status: pending
  Status: processing
  ...
  Status: ready
```

The final `ready` status means that scoring is complete. Keep the evaluation ID printed after `Evaluation created`; we will use it in the next steps.

## Inspect the results

Retrieve the completed evaluation, replacing the example ID below with the ID printed by `mb eval create`:

```bash
mb eval get cde79124223a48ecb923c7265063197a
```

The output includes the evaluation metadata and aggregate results. The `results` field should contain an entry similar to this reduced example:

```json
{
  "results": {
    "ground_truth_alignment": {
      "confidence_interval": [
        0.838,
        0.995
      ],
      "mean_score": 0.917
    }
  }
}
```

Evaluation results depend on the responses produced by the actual agent run, so they will not necessarily match these values. In this example,
the ground-truth alignment score is 91.7%, with a confidence interval from 83.8% to 99.5%.

The aggregate score is useful for understanding overall performance. To inspect the score and rationale for each example, download the detailed results:

```bash
mb eval download cde79124223a48ecb923c7265063197a -o watson-qa-results.jsonl
```

The output should look like:

```text
Downloaded to watson-qa-results.jsonl
```

Inspect the first evaluated example:

=== "macOS and Linux"

    ```bash
    head -n 1 watson-qa-results.jsonl | python -m json.tool
    ```

=== "Windows PowerShell"

    ```powershell
    Get-Content watson-qa-results.jsonl -TotalCount 1 | python -m json.tool
    ```

The downloaded file contains the original `inputs`, `expectations`, and `outputs`, together with the assessments produced by MorganaBench:

```json
{
  "assessments": [
    {
      "name": "ground_truth_alignment",
      "value": 1.0,
      "rationale": "The response is consistent with the expected answer."
    }
  ]
}
```

Each `value` is the score for one example. When available, `rationale` explains why the scorer assigned that value. Use these per-example
results to investigate individual successes and failures that are hidden by the aggregate score.

## Summary

You have learned how to use an externally supplied benchmark to evaluate an agent with MorganaBench from the command line. You have also learned
how to use the MorganaBench SDK to produce an executed benchmark in a format that MorganaBench can consume, select an evaluation metric, and
download both aggregate and per-example results.

## Next steps

- Learn what each metric measures in [Metrics](../reference/metrics.md).
- Automate the whole flow, from corpus through benchmark and evaluation, with the [CI pipeline example](../cli-guide/index.md#ci-pipeline-scripted).
- Explore every `mb eval` flag in the [CLI Guide: Evaluation](../cli-guide/evaluation.md).