> ## Documentation Index
> Fetch the complete documentation index at: https://docs.braintrust.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Improve an agent with Braintrust

> Find costly agent behavior with Patterns, compare models with evals, and use Loop and your coding agent to turn the evidence into a verified code change.

## Get started

In this tutorial, you'll use Patterns to find costly behavior in sample support conversations, test whether a cheaper model can handle those requests, then have Loop propose a code change for your coding agent to review.

You'll need:

* A [Braintrust account](https://www.braintrust.dev/signup) with an [API key](https://www.braintrust.dev/app/~/configuration/api-keys)
* A GitHub account
* Python 3.12 or later and `uv`
* A coding agent [connected to Braintrust](https://docs.braintrust.dev/tracing-quickstart.md#connect-to-braintrust)

## Set up the project

You'll work with 600 simulated support conversations, spread over the last two weeks, in which customers ask an agent to change flights, return orders, or fix phone service. Each conversation is a trace with the agent's model and tool calls, a task success score, and metadata about the customer, model, agent version, and cost.

**1. Import the sample conversations**

Download the [sample importer](https://github.com/DaRubberDuckieee/exgentic-patterns-import) and the sample data (about 130 MB), then import the conversations into a new project called **Sample - Support agent - tutorial**:

```bash theme={null}
curl -LO https://raw.githubusercontent.com/DaRubberDuckieee/exgentic-patterns-import/main/convert_and_upload.py
curl -L -o 0007.parquet https://huggingface.co/datasets/Exgentic/traces-v2/resolve/main/data/train/0007.parquet
export BRAINTRUST_API_KEY=<your-api-key> # Replace with your Braintrust API key
uv run --with "pyarrow>=14" convert_and_upload.py \
  --parquet 0007.parquet \
  --org "<your-org>" \
  --project "Sample - Support agent - tutorial" \
  --count 600 --days-back 14 \
  --where '!domain=telecom,model=Kimi-K2.5'
```

Replace `<your-org>` with your organization name. The import should report 600 traces and 20,239 spans.

**2. Check the imported traces**

Open [\*\* Logs\*\*](https://www.braintrust.dev/app/~/logs) and confirm that the conversations appear with their model and tool calls.

![Logs page for the Sample - Support agent - tutorial project, listing imported support-agent traces with their input, output, task\_success score, and duration.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-traces.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=60a81291ad1c5b7894d127151a8fb1db)

![An imported support-agent trace open in Logs, showing its LLM and tool call spans in the tree and the conversation in the Thread tab.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-trace.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=559af0cd95383c54c5c96d8219f578aa)

**3. Set the user and session ID fields**

Ask Loop or your coding agent to set the project's user and session ID fields, so Patterns counts affected users and sessions instead of individual traces:

```text wrap theme={null}
Set the end-user ID field for the "Sample - Support agent - tutorial" project to `metadata.customer_id` and its session ID field to `metadata.session_id`. Verify these fields in its traces and show any existing mappings before changing them.
```

[Run in Loop](https://www.braintrust.dev/app/~/loop?prompt=Set%20the%20end-user%20ID%20field%20for%20the%20%22Sample%20-%20Support%20agent%20-%20tutorial%22%20project%20to%20%60metadata.customer_id%60%20and%20its%20session%20ID%20field%20to%20%60metadata.session_id%60.%20Verify%20these%20fields%20in%20its%20traces%20and%20show%20any%20existing%20mappings%20before%20changing%20them.)

**4. Connect the agent's code**

Loop needs a copy of the agent's code so it can cite the code in findings and open a pull request with a fix. Connect it before you enable Patterns, so discovery can include code evidence.

1. Create a [fork of the sample support-agent repository](https://github.com/DaRubberDuckieee/patterns-demo-support-agent/fork).
2. [Connect GitHub](https://docs.braintrust.dev/loop/github.md) and give Loop access to your fork.
3. Connect the fork to your project, and allow Loop to create pull requests.

![GitHub installation settings in Braintrust Integrations, with Use this installation and Allow Loop to create PRs turned on, and the forked patterns-demo-support-agent repository listed.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-github.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=f6e5b77c9acfb2e5557d31b3fb5edd58)

**5. Enable Patterns**

[Enable Patterns](https://docs.braintrust.dev/patterns-quickstart.md#enable-patterns). Optionally [connect Slack](https://docs.braintrust.dev/admin/organizations.md#enable-slack-integration) and select a channel for alerts.

![Patterns setup panel with a Continue button.](https://mintcdn.com/braintrust/ivt5D4GbvzJJFPHj/images/observe/enable-patterns.png?fit=max\&auto=format\&n=ivt5D4GbvzJJFPHj\&q=85\&s=3f7242f4598bd92719263faba9f7ff79)

![Patterns Slack alert setup with a channel selector and an option to enable without Slack alerting.](https://mintcdn.com/braintrust/ivt5D4GbvzJJFPHj/images/observe/enable-patterns-slack.png?fit=max\&auto=format\&n=ivt5D4GbvzJJFPHj\&q=85\&s=4e49e9c51c9dbcaa2a0a7499f43f0041)

Wait for the first discovery run to finish, which can take 30 minutes or more.

## Find a problem

[** Patterns**](https://docs.braintrust.dev/observe/patterns.md) uses Loop to investigate your traces on a schedule and report recurring problems. Each finding, called a pattern, has a severity, a count of the users or sessions it affects, and the traces that show it. With a connected repository, a pattern can also cite the code involved.

In this section, you'll review a pattern, then focus the discovery rule on cost to find a model that's more expensive than it needs to be. Findings and their titles vary between runs. See [Review and act on patterns](https://docs.braintrust.dev/observe/patterns/review.md) for everything a pattern includes.

**1. Scan the Patterns list**

Open [\*\* Patterns\*\*](https://www.braintrust.dev/app/~/patterns). Each row is a recurring problem with its severity, summary, categories, and when it was first and last seen.

Because you set the user ID field, the counts show how many distinct customers each pattern affects instead of how many traces. A problem that appears in 300 traces might come from a single customer. Compare severity and affected users to decide which pattern to open first.

![Patterns list for the Sample - Support agent - tutorial project, showing patterns with severity, affected users, categories, and first and last seen times.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-patterns.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=92888d78e0c4304c4edbc71fceb75c2e)

**2. Examine a pattern**

Open a pattern and read its summary. Below its name, check [how widespread it is](https://docs.braintrust.dev/observe/patterns/review.md#assess-how-widespread-it-is): the share of traffic it affects and when it was measured. A `~` marks an estimate from a sample.

Open a supporting trace and inspect the highlighted evidence. If the pattern includes code evidence, use the **Code** tab to review the cited implementation. Check that the evidence supports the pattern.

![A pattern report showing 50 affected users, its properties, an impacted users chart, and its summary, next to a supporting trace with the evidence highlighted in the input.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-pattern.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=71a83eaa4e18e13bae620f6430bb8007)

**3. Add a cost concern**

To focus on cost, open **Pattern discovery** from the rules menu. Under **Watch for**, add:

```text wrap theme={null}
Expensive models used for requests a cheaper model could handle just as well.
```

Under **Custom instructions**, enter:

```text wrap theme={null}
Compare costs using metadata.cost_usd. Identify the model, agent version, and request type driving the difference. Distinguish measured costs from potential savings, and suggest what to test before changing models.
```

Click **Save** and then  **Run now**.

![Pattern rule editor for Pattern discovery, with the expensive-models concern under Watch for, the cost instructions under Custom instructions, and the Run now and Save buttons.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-rule.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=173c6fea925b30fc35e6808bba0b741e)

**4. Find a cost pattern**

The run can take a while. To follow its progress, open the rules menu in the page header and click  next to **Pattern discovery**. Loop's thread for the run opens in a new tab, where you can watch the searches it runs and the traces it reads.

When the run finishes, look for a new pattern in the **Cost** category. A cost pattern describes money spent without a better result, such as one model accounting for a large share of spend on a small share of conversations.

Open the pattern and check its evidence:

* **Summary:** Names the expensive model, the agent version, the requests involved, and the cost difference, measured from `metadata.cost_usd`.
* **Models:** If the breakdown is available, compare each model's share of matches with its share of all traffic. If an expensive model's share of matches is much higher than its share of traffic, that model is driving the cost.
* **Evidence:** Open a few supporting traces and confirm the model, agent version, cost, and `task_success` score in each.
* **Failed calls:** Failed or retried model calls raise a conversation's cost, so a cost gap can reflect errors rather than model pricing.

![A Cost pattern named Opus drives support spend in Claude Code, affecting 26 users, with its summary and an evidence trace showing Claude Opus 4.5 model calls and a \$2.53 estimated cost.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-cost-pattern.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=5217f58d4f7df5d3136c89cb52c39c70)

## Compare models

The cost pattern gives you a hypothesis: a cheaper model could handle the same requests. An eval tests that hypothesis on a fixed set of cases.

**1. Build a baseline eval**

With the cost pattern open, click  **Loop agent** at the bottom right. Loop attaches the pattern automatically. Paste this prompt to build a baseline:

```text wrap theme={null}
Create a baseline eval for this cost pattern.

Create a dataset named "Model cost comparison" from representative traces. Each case should include the conversation and tool definitions before a model turn, an expected next action from a successful conversation, and the source trace link. Check that the expected action is correct for that input.

Use the model from the expensive traces to generate the next reply or tool call. Add a quality scorer that checks the response or tool arguments and accepts equivalent correct answers. Record token usage and model information for estimated cost, and report cost per successful case.

Show me the cases and scoring criteria before running the experiment.
```

**2. Run the baseline**

In the conversation, review the cases and scoring criteria Loop proposes. To see every case, open the **Model cost comparison** dataset in [\*\* Datasets\*\*](https://www.braintrust.dev/app/~/datasets), and compare a few cases with their source traces. When they look right, ask Loop to run the baseline:

```text wrap theme={null}
Run the baseline experiment. Record the dataset version, model, and scorer used, and give me the experiment link, quality score, estimated cost, and cost per successful case.
```

When the run finishes, Loop summarizes the results in the conversation. To inspect individual cases and their scores, open the experiment from the link Loop provides.

![Loop conversation summarizing the Claude Opus 4.5 baseline: 4 of 4 cases passed, with estimated generation cost, cost per successful case, and a table of the dataset version, model, scorer, and token usage.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-baseline.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=498254485c21fedbd1d050dbe33d1b98)

**3. Compare a cheaper model**

In the same conversation, ask Loop to compare a cheaper model:

```text wrap theme={null}
Run the same eval with GPT-5.2, keeping the dataset version, context, tools, and scorer unchanged. Compare quality, estimated cost, and cost per successful case with the baseline. Show cases where the models differ and failures that would make the cheaper model unsuitable. Don't change the app yet.
```

**4. Review the comparison**

Read Loop's comparison in the conversation, which lists the cases where the models differ. To check a disagreement, open the case in the experiment and read the scorer's explanation.

![Loop conversation comparing the Opus 4.5 baseline with the GPT-5.2 experiment: equal saved quality scores, lower estimated cost for GPT-5.2, and one case where GPT-5.2 skipped a required tool call.](https://mintcdn.com/braintrust/-fJ-dm-zVKbfv0sL/images/loop/tutorial-compare.png?fit=max\&auto=format\&n=-fJ-dm-zVKbfv0sL\&q=85\&s=2116f722b03719672df235d02d48f4c0)

If the cheaper model's quality is close to the baseline's at a lower cost per successful case, continue to [Make and verify the change](#make-and-verify-the-change), where Loop updates the agent to send these requests to the cheaper model. If quality drops more than you can accept, investigate the failing cases before changing the agent.

## Make and verify the change

Loop turns the eval result into a pull request in your fork that sends those requests to the cheaper model. Before you merge, your coding agent reviews it against the original traces.

**1. Open a pull request with Loop**

Continue in the same Loop conversation:

```text wrap theme={null}
Open a PR in my fork that routes the requests we evaluated to GPT-5.2. Keep other requests on the configured model. Ask me for missing repository, pattern, or experiment links.

Use the agent implementation identified in the evidence traces. Make routing configurable and easy to turn off. Use settings supported by each model, and fall back to the configured model on failure without repeating completed tool actions. Record the actual model and any fallback in new traces.

Add and run tests for routing, unaffected requests, fallback, and routing disabled. Link the pattern, evidence, and both experiments in the PR. Report checks you couldn't run.
```

**2. Review the pull request with your coding agent**

Clone your fork and check out the pull request's branch:

```bash theme={null}
git clone https://github.com/<your-github-username>/patterns-demo-support-agent.git # Replace with your GitHub username
cd patterns-demo-support-agent
git fetch origin
git checkout <pr-branch> # Replace with the branch from Loop's pull request
```

In the pattern's header, select **Investigate**  >  **Copy as prompt**. Paste the brief into your coding agent in your local clone, along with the PR and experiment links. Ask it to review:

```text wrap theme={null}
Review this PR against the pattern and experiments. Don't edit yet.

Retrieve a supporting trace from Braintrust. Check whether the PR changes the agent implementation that produced it and routes that request to the intended model. Check model settings, fallback behavior, and whether traces record the model actually used.

Follow the repository's review instructions. List blocking issues with file and line references, and explain what still needs an end-to-end test. Ask for missing links or access instead of guessing.
```

**3. Test before merging**

Address the blocking issues from the review and run the changed agent on representative conversations before merging. Check task outcomes, the model recorded in new traces, and total cost, including fallbacks.

The new traces should show which requests used the cheaper model and whether they succeeded. If they still use the original model, inspect the routing and fallback behavior before claiming savings.

## Close the loop

Your rating and notes on the pattern tell Loop and your teammates what you did about it.

**1. Rate the pattern**

Under **Is this pattern useful?**, click **Yes** or **No**, add a reason, and click **Submit**. **Yes** lets Loop reopen the pattern if the behavior returns after it closes. **No** closes the pattern and tells Loop not to reopen or recreate a matching pattern while your reason still applies.

**2. Link the pull request**

In the pattern's **Activity**, add a comment with the PR link so teammates can follow the work. Mention a teammate to notify them.

After you deploy the fix, new traces from the updated agent show whether the behavior stopped. Scheduled runs [close patterns whose behavior has stopped](https://docs.braintrust.dev/observe/patterns/review.md#automatic-closure) and reopen them if it returns, with a Slack alert if you set one up.

## Next steps

Apply the workflow to your own agent: [add tracing](https://docs.braintrust.dev/tracing-quickstart.md), use Patterns to identify a problem, and [build an eval](https://docs.braintrust.dev/evaluation-quickstart.md) to test a change.

> [card] [Explore more capabilities](https://docs.braintrust.dev/quickstart-next-steps.md)
>
> Build on the tutorial with Loop, playgrounds, human review, and evals in CI.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.