# Evaluate your agent using MorganaBench benchmarks via web UI

In this tutorial we will evaluate a Search/Tool agent against a MorganaBench benchmark, entirely through the web interface — from downloading the benchmark to reading its per-case scores.

## Overview

Evaluating your agent involves six key steps:

1. **Download the benchmark** - Export the benchmark JSONL file from the MorganaBench UI
2. **Run your agent** - Execute your agent against the benchmark questions locally
3. **Add agent responses** - Populate the benchmark file with your agent's answers
4. **Import the executed benchmark** - Upload the populated benchmark back to MorganaBench
5. **Select evaluation metrics and run evaluation** - Choose the metrics to measure your agent's performance and run the evaluation
6. **Inspect evaluation results** - Review detailed results

Let's walk through each step in detail.

---

## Step 1: Download the Benchmark

Navigate to the **Benchmarks** section in the navigation bar.

![Benchmarks navigation section](/docs/assets/figures/benchmarks-section-spotlighted.png)

First, click the benchmark's name to open its details page. You will notice the page now shows the benchmark's questions and a **Download Benchmark** button in the top right.

![Benchmark selection](/docs/assets/figures/benchmarks-benchmark-spotlighted.png)

Now click **Download Benchmark**. The JSONL file downloads to your machine.

![Benchmark download](/docs/assets/figures/benchmark-download-spotlighted.png)

Open the file in a text editor. You will notice each line is a single JSON object describing one test case — one line per benchmark question.

!!! note
    You may also download the benchmark directly from the **Benchmarks** section, by clicking the three dots located at the end of the benchmark's line and then clicking **Download**

    ![Benchmark download alternative](/docs/assets/figures/benchmark-download-altr-spotlighted.png)

The downloaded file contains all questions, reference answers, and metadata needed for evaluation.

---

## Step 2: Run Your Agent on the Benchmark

With the benchmark file downloaded, we will now run your Search/Tool agent locally against the questions.

First, load the benchmark JSONL file in your agent execution environment. Each line is a JSON object describing a single case. Here is a simple multi-turn conversation between a user and a search agent:

```json
    {
        "inputs": {
            "messages": [
            {"role": "user", "content": "I'm planning a 3-day trip to Paris.
                Give me a short itinerary."},
            {"role": "assistant", "content": "Day 1: Louvre + Seine.
                Day 2: Montmartre. Day 3: Versailles."},
            {"role": "user", "content": "Is Versailles inside Paris?"}
            ]
        },
        "expectations": [
            {"expect": "response", "response": "No. Versailles is a separate city outside
                Paris, typically visited as a day trip."}
        ]
    }
```

For more details regarding the MorganaBench benchmark schema and features, see the [MorganaBench JSONL format overview](https://sdk.morganalabs.ai/jsonl_format).

Now, extract the cases from the benchmark. For the last question in each case, invoke your agent to generate a response using the conversation prefix as context. For the case above, here is the last question:

```json
    {"role": "user", "content": "Is Versailles inside Paris?"}
```

Finally, collect all agent responses. This step happens outside the MorganaBench UI, in your own development environment where your agent operates.

---

## Step 3: Add Agent Responses to the Benchmark

Now that you have your agent's responses, we will populate the benchmark JSON file with them to generate the executed benchmark JSONL file.

The benchmark JSONL has a specific [schema](https://sdk.morganalabs.ai/jsonl_format#executed-benchmark-jsonl-add-outputs-response) for agent responses. For each case, add your agent's response in the designated `outputs` field:

```json
    {
        "inputs": {
            "messages": [
            {"role": "user", "content": "I'm planning a 3-day trip to Paris.
                Give me a short itinerary."},
            {"role": "assistant", "content": "Day 1: Louvre + Seine.
                Day 2: Montmartre. Day 3: Versailles."},
            {"role": "user", "content": "Is Versailles inside Paris?"}
            ]
        },
        "expectations": [
            {"expect": "response", "response": "No. Versailles is a separate city outside
                Paris, typically visited as a day trip."}
        ],
        "outputs": {
            "response": "your agent's answer goes here"
        }
    }
```

Ensure the response format matches the expected [schema](https://sdk.morganalabs.ai/jsonl_format#executed-benchmark-jsonl-add-outputs-response) (response, trace, citations, etc.), then save the executed benchmark JSONL file with agent responses included.

The executed benchmark JSONL file is now ready to be uploaded back to MorganaBench for evaluation.

---

## Example Implementation: Agent Execution and Response Collection (Steps 2 and 3)

This section provides a complete working example covering Steps 2 and 3 of the evaluation workflow. It shows how to build a search agent using LlamaIndex and AWS Bedrock, run it against a MorganaBench benchmark, and generate the executed benchmark file required for evaluation.

### Overview

The example agent:

- Searches a local document corpus to answer questions
- Outputs responses in MorganaBench-compliant format
- Generates an executed benchmark file ready for UI import

### Prerequisites

**1. Create and navigate to a new project directory**

**2. Install required packages**

For users managing dependencies with pip:

```bash
# Install MorganaBench SDK from the private GitLab registry
pip install morgana-bench-sdk

# Install LlamaIndex and AWS Bedrock integrations
pip install llama-index llama-index-embeddings-bedrock llama-index-llms-bedrock-converse
```

!!! note "Alternative: Using uv for dependency management"
    If you prefer to use `uv`, create a `pyproject.toml` file with the following configuration:

    ```toml
    [project]
    name = "agent-eval"
    version = "0.1.0"
    requires-python = ">=3.12"
    dependencies = [
        "morgana-bench-sdk",
        "llama-index",
        "llama-index-embeddings-bedrock",
        "llama-index-llms-bedrock-converse"
    ]

    [[tool.uv.index]]
    name = "gitlab"
    url = "https://gitlab.com/api/v4/projects/56367249/packages/pypi/simple"
    ```

    Then run: `uv sync`

**3. Download the benchmark file**

Download the example benchmark file to your project directory:

```bash
curl -o Inaugural_speeches_benchmark.jsonl https://raw.githubusercontent.com/MorganaLabs/dms-documentation/main/docs/content/assets/benchmarks/Inaugural_speeches_benchmark.jsonl
```

**4. Download the document corpus**

Download the [inaugural corpus](https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/inaugural.zip) and extract it to your project root (this will create an `inaugural/` directory):

```bash
curl -L -o inaugural.zip https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/inaugural.zip
unzip inaugural.zip -d .
rm inaugural.zip
```

### Agent Implementation

Create a file named `agent.py` with the following code:

**What this agent does:**

1. Configures AWS Bedrock models (Claude Haiku for LLM, Titan for embeddings)
2. Loads documents from the `./inaugural` directory and builds a vector search index
3. Creates a search tool that retrieves the top 5 most relevant documents
4. Implements a `FunctionAgent` that answers questions using the search tool
5. Processes benchmark examples from stdin, runs the agent on each question, and writes the executed benchmark to stdout

```python
import asyncio
import sys

import mb.entities as mbe
from llama_index.core import Settings, 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

print("Initializing agent...", file=sys.stderr, flush=True)

# Configure AWS Bedrock models
print("  - Configuring LLM (Claude Haiku) and embeddings (Titan)...", file=sys.stderr, flush=True)
Settings.llm = BedrockConverse(model="global.anthropic.claude-haiku-4-5-20251001-v1:0")
Settings.embed_model = BedrockEmbedding(model_name="amazon.titan-embed-text-v2:0")

# Load documents and build search index
print("  - Loading documents from corpus...", file=sys.stderr, flush=True)
docs = SimpleDirectoryReader("./inaugural", recursive=True).load_data()
print(f"  - Loaded {len(docs)} documents", file=sys.stderr, flush=True)

print("  - Building vector search index...", file=sys.stderr, flush=True)
index = VectorStoreIndex.from_documents(docs)

print("  - Creating search tool...", file=sys.stderr, flush=True)
search_corpus = QueryEngineTool.from_defaults(
    query_engine=index.as_query_engine(similarity_top_k=5),
    name="search_corpus",
    description="Search the corpus.",
)

# Create the agent
print("  - Creating FunctionAgent...", file=sys.stderr, flush=True)
agent = FunctionAgent(
    tools=[search_corpus],
    llm=Settings.llm,
    system_prompt="Always either answer based on the corpus, or respond with \"I don't know\". Provide your answer in the user's language.",
)

print("✓ Agent initialized successfully\n", file=sys.stderr, flush=True)

async def run_agent_on_benchmark():
    print("Starting benchmark processing...", file=sys.stderr, flush=True)
    line_number = 0
    for line in sys.stdin:
        line_number += 1
        print(f"\n[{line_number}] Processing example...", file=sys.stderr, flush=True)

        # parse `Example` from raw json
        example = mbe.Example.model_validate_json(line)
        query = example.inputs.messages[-1].content
        print(f"[{line_number}] Query: {query[:80]}{'...' if len(query) > 80 else ''}", file=sys.stderr, flush=True)

        # run agent
        print(f"[{line_number}] Running agent...", file=sys.stderr, flush=True)
        response = await agent.run(user_msg=query)

        # put response into the `Example`
        example.outputs = mbe.Outputs(response=str(response))

        # serialize the `Example` back to stdout
        print(example.model_dump_json(), file=sys.stdout)
        print(f"[{line_number}] ✓ Completed", file=sys.stderr, flush=True)

    print(f"\n✓ Finished processing {line_number} examples", file=sys.stderr, flush=True)

asyncio.run(run_agent_on_benchmark())
```

### Running the Agent

**Test run (first 10 examples):**

Process a subset of the benchmark to verify your setup before running the full evaluation:

```bash
head -n 10 Inaugural_speeches_benchmark.jsonl | python agent.py > Inaugural_speeches_benchmark_executed_head.jsonl
```

You will notice progress lines printed to your terminal, ending with `[10] ✓ Completed`. If you see an `AccessDenied` or connection error instead, you have probably not enabled Bedrock model access for your region.

This command:

- Reads the first 10 cases from `Inaugural_speeches_benchmark.jsonl`
- Pipes them through the agent script
- Writes the executed benchmark to `Inaugural_speeches_benchmark_executed_head.jsonl`

**Full benchmark run:**

To process all cases in the benchmark:

```bash
cat Inaugural_speeches_benchmark.jsonl | python agent.py > Inaugural_speeches_benchmark_executed.jsonl
```

!!! note "Progress monitoring"
    The agent script includes built-in progress logging that prints to `stderr`. You'll see initialization steps, document counts, and per-example progress as the agent runs. These messages won't interfere with the JSON output written to the file.

### Expected Output

The executed benchmark file (`Inaugural_speeches_benchmark_executed_head.jsonl` or `Inaugural_speeches_benchmark_executed.jsonl`) will contain one JSON object per line, with the original benchmark data plus your agent's responses in the `outputs` field. This file is ready to be imported in Step 4.

---

## Step 4: Import the Executed Benchmark

Return to the MorganaBench UI to upload your executed benchmark.

First, navigate to the **Evaluations** section.

![Evaluations navigation section](/docs/assets/figures/evaluations-section-spotlighted.png)

Now click the **Create Evaluation** button on the top right of the page.

![create evaluation](/docs/assets/figures/create-evaluation-spotlighted.png)

Use the **Agent Output** box to upload your executed benchmark JSONL file.

![upload executed benchmark](/docs/assets/figures/evaluations-upload-spotlighted.png)

The system validates the file format and associates it with the original benchmark. When the file is accepted you will notice it appears in the **Agent Output** box with a green check, and its case count matches the benchmark.

!!! note "Troubleshooting"
    - If the JSONL file cannot be associated with its original benchmark file, you will receive the following warning

        ![upload executed benchmark warning 1](/docs/assets/figures/evaluation-upload-warning1.png)

    - If the JSONL file is invalid, you will receive an error message describing the detected issue

        ![upload executed benchmark error 1](/docs/assets/figures/evaluation-upload-error1.png)

Now add an evaluation name and optional description in the **Evaluation Details** box.

![evaluation details](/docs/assets/figures/evaluations-details-spotlighted.png)

Click the **Next: Select Metrics** button below, or **Select Metrics** on the upper-left.

![evaluation next metrics](/docs/assets/figures/evaluations-next-metrics-spotlighted.png)

The executed benchmark JSONL file is now ready to be evaluated.

---

## Step 5: Select Evaluation Metrics and Run Evaluation

Choose which metrics to use for evaluating your agent's performance.

The list of available metrics is determined according to the benchmark type. For a full description of each metric and how to read its scores, see [Metrics](../reference/metrics.md).

**Search benchmark metrics:**

In these descriptions, the response is JSON object "outputs"."response", the reference answer is the item of "expectations" with "expect" set to "response", the retrieved documents are JSON object "outputs"."citations"\[\]."document_id", and the user's request is JSON object "inputs"."messages"\[last\]."content". Each score is averaged across the benchmark.

- **Ground Truth Alignment** - The degree to which the reference answer is covered by the response. It is scored from `0.0` to `1.0`, and higher is better.

- **Faithfulness** - The degree to which the response is supported by the retrieved documents. It is scored from `0.0` to `1.0`, and higher is better.

- **Context Sufficiency** - The degree to which the reference answer is supported by the retrieved documents. It is scored from `0.0` to `1.0`, and higher is better.

- **Ground Truth Contradiction** - The degree to which the reference answer is contradicted by the response. It is scored from `0.0` to `1.0`, and lower is better.

- **Relevance to Request** - The degree to which the response is relevant to the user's request. It is scored from `0.0` to `1.0`, and higher is better.

- **Refusal** - The rate at which the agent refuses requests it was expected to answer. Each case scores `0` or `1`, and lower is better.

**Tool benchmark metrics:**

- **Tool-Call Correctness** - The rate at which the agent makes every expected tool call with the right arguments. Each case scores `0` or `1`, and higher is better.

- **No-Tool-Call Correctness** - How correct the agent's response is when no tool call is expected. It is scored from `0.0` to `1.0`, and higher is better.

Review the list of available metrics and select the ones most relevant to your evaluation goals (you may select more than one).

![evaluations select metrics](/docs/assets/figures/evaluations-select-metrics-spotlighted.png)

You will notice the page shows your remaining evaluation credits and the estimated cost (both in terms of number of cases).

![evaluations credits](/docs/assets/figures/evaluations-credits-spotlighted.png)

You will also see the estimated evaluation time.

![evaluations estimated time](/docs/assets/figures/evaluations-estimated-time-spotlighted.png)

Now click the **Run evaluation** button on the bottom right to evaluate your executed benchmark.

![evaluations run evaluation](/docs/assets/figures/evaluations-run-button-spotlighted.png)

The page switches to the progress view. Continue to Step 6 to watch the run and read the results.

---

## Step 6: Inspect Evaluation Results

Monitor evaluation progress and review detailed results.

**Progress monitoring and benchmark details**

You will notice the evaluation progress updating (this may take some time depending on benchmark size and number of evaluation metrics chosen).

![evaluations progress](/docs/assets/figures/evaluations-progress-spotlighted.png)

The page also shows evaluation information details (ID, creation time, linked benchmarks, linked corpus, number of cases, and selected metrics).

![evaluations details](/docs/assets/figures/evaluations-information-spotlighted.png)

Once complete, inspect the evaluation results.

**Results inspection**

- **Overview** Overall scores for each selected metric (mean value and a 95% confidence interval), colored by how good the score is and with a confidence badge. See [Reading a score](../reference/metrics.md#reading-a-score).

![evaluations overall scores](/docs/assets/figures/evaluations-results-spotlighted.png)

- **Case details** Per-case breakdown showing individual performance.

  - Perform metric based filtering, e.g., GT ≥ 0.7 or GT ∈ [0.5,0.7]

  - View the scored metrics for each case or failures and their possible explanation

  - Hovering over various areas of each case you may:

    - View the full user queries, responses, of each turn

    - View agent response, and expected agent response of last turn

    - View the categories used to generate each turn

![evaluations results detailed](/docs/assets/figures/evaluations-results-detailed-spotlighted.png)

- **Segments** One metric at a time, broken down by one dimension of the benchmark, or by two crossed.

  - Compare a segment with the evaluation's overall score, shown in the **All** row (and column)

  - Spot scores that are not precise enough to trust (marked with a low-confidence icon)

  - Select a cell to open its cases on the **Case details** tab

![evaluations results segments](/docs/assets/figures/evaluation-segments-by-segment.png)

See [Segment analysis](../reference/segments.md).

- **Issues** The segments that score significantly worse than the evaluation overall, worst first. Selecting a card opens its cases.

See [Issues](../reference/issues.md).

**Example assessment structure:**

After evaluation completes, each example in your executed benchmark will include an `assessments` object containing the evaluation results for each selected metric. Here's an example:

```json
{
  "id": "d5c4172c-34b7-4fae-973b-46540766bc33",
  "inputs": {
    "messages": [
      {
        "role": "user",
        "content": "What two specific methods of communication and transportation does the speaker mention as having changed the theory of government?"
      }
    ]
  },
  "expectations": [
    {"expect": "response", "response": "The telegraph for communicating thought and rapid transit by steam."}
  ],
  "outputs": {
    "response": "Based on the corpus, the two specific methods are: 1. Telegraph (communication) 2. Steam (transportation)"
  },
  "assessments": {
    "ground_truth_alignment": {
      "score": 0.92,
      "explanation": "The agent correctly identified both the telegraph and steam as the two methods. The response is accurate and directly answers the question, with only minor formatting differences from the reference."
    },
    "refusal": {
      "score": 0.0,
      "explanation": "The agent provided a substantive answer without refusing."
    }
  }
}
```

Key assessment fields:

- **score**: A numeric value (0.0 to 1.0) indicating performance on the metric

- **explanation**: Details why the score was assigned

Each selected metric appears in the `assessments` object with its score and explanation.

**Additional post-evaluation actions:**

- Download evaluation results (the executed benchmark JSONL file, with `assessment` objects included)

![evaluations download results](/docs/assets/figures/evaluations-results-download-spotlighted.png)

- Add metrics and re-evaluate by clicking the `Add Metrics to Evaluation`

![evaluations add metrics](/docs/assets/figures/evaluations-results-add-eval-spotlighted.png)

- Select additional metrics and click `Calculate Metrics` to re-evaluate your agent (repeat Step 6)

  ![evaluations add metrics and re-evaluate](/docs/assets/figures/evaluations-add-metrics-spotlighted.png)

---

## Conclusion

You have evaluated a working Search/Tool agent against a MorganaBench benchmark and read its per-case scores. You now have a repeatable loop for measuring your agent as you improve it.

---

## Next Steps

After reviewing your evaluation results:

- Identify areas where your agent performs well or poorly

- Analyze specific failure cases to understand gaps

- Iterate on your agent design and re-evaluate

- Select other metrics to enrich your evaluation

- Compare multiple evaluation runs to track improvement over time

---

## Tips and Best Practices

- **Consistent format**: Ensure your agent responses match the expected JSON [schema](https://sdk.morganalabs.ai/jsonl_format) exactly

- **Complete responses**: Include all required fields (response text, citations, confidence scores, etc.)

- **Metadata tracking**: Add metadata to your agent responses (model version, parameters, timestamp) for future reference

- **Baseline comparison**: Run multiple agents or configurations to compare performance

- **Metric selection**: Choose metrics that align with your specific use case and success criteria