Skip to main content

MLflow Tutorial for AI Agents in Python — Part 1: Trace Your First Claude Call with MLflow

· 31 min read
Jagdish Kumawat
Founder @ Dewiride

An AI agent that answers customers is only as trustworthy as your ability to see what it did: what it was asked, what it sent to the model, what came back, how long it took and what it cost. This series teaches MLflow's tools for exactly that, on a real Claude-powered support agent. In Part 1 you start your own MLflow server, build the agent, and trace your first conversation with it.

This is Part 1 of the series.

  1. Part 1: Trace Your First Claude Call with MLflow (you are here)

Every command and output on this page is real, captured while building the project.

What You'll Have at the End of the Series​

Each part teaches one piece of MLflow's tools for generative AI, on the same support agent, all on your own computer. By the end of the series you'll know how to:

  • trace every call your agent makes to Claude, with its tokens and cost (this part);
  • trace the agent's own steps, such as the tools it calls, as one tree per request;
  • follow users and conversations across many requests;
  • search, tag and debug traces when something goes wrong;
  • collect feedback from the people using the agent;
  • build an evaluation dataset from real conversations;
  • judge the agent's answers automatically, with MLflow's built-in judges and judges of your own, Claude Opus 5.5 among them;
  • evaluate whole conversations, not only single answers;
  • version the agent's prompt in MLflow's Prompt Registry, and compare versions of the agent;
  • monitor it in use, with judges that score new traces as they arrive, and a checklist for running it safely.

The series MLflow Tutorial for Machine Learning in Python covers the other half of MLflow: experiments, models and serving for classic machine learning.

What MLflow Tracing Is​

MLflow is a free, open-source platform for building and running AI and machine learning applications. Its tracing records what an application does each time it runs, the way a flight recorder does.

WordWhat it meansIn this part
Tracking serverA small web server on your computer that stores the records and shows them in the MLflow UIhttp://127.0.0.1:8080
ExperimentA folder for related records, usually one per applicationstore-support-agent
TraceThe record of one request: what came in, what went out, how long it tookOne per customer message
SpanOne step inside a trace, with its own inputs, outputs and timingThe call to Claude, Messages.create
AutologgingMLflow recording a library's calls for you, with no code at each callmlflow.anthropic.autolog()

The Example Agent​

The series follows a customer support agent for Cedarfield Outdoor, a made-up online shop for camping and hiking gear. Customers chat with it in a terminal. It answers questions about shipping, returns, refunds, exchanges, warranty and price adjustments from the shop's support handbook, and sends anything else to the support team's email address.

It runs on Claude Opus 5.5 through the Anthropic Python SDK. This part builds the agent's first version, a question-and-answer chat, and traces it. Later parts add tools, sessions and evaluations, and each one teaches the MLflow piece that goes with it.

What This Part Costs​

MLflow is free, and everything in this part runs on your computer. The Claude API is paid and has no free tier: Claude Opus 5.5 costs $4 per million input tokens and $20 per million output tokens (Anthropic's pricing). The three questions asked in this part cost $0.015, as MLflow itself reports at the end. A spend limit on your key in the Claude Console caps what a mistake can cost.

Prerequisites​

  • A Claude API key, from the Claude Console, on an account with billing set up.
  • uv and Python 3.15. This part uses uv 0.13.10 and Python 3.15.2. Check them with uv --version and uv python find 3.15.

Step 1: Create a Folder for the Tracking Server​

The tracking server gets its own project, so it can keep running while you work on the agent:

Terminal
uv init --bare --python 3.15 mlflow-server
cd mlflow-server
Output
Initialized project `mlflow-server` at `/Users/you/source/mlflow-server`

uv init --bare creates only a pyproject.toml; --python 3.15 pins the Python version.

Step 2: Install MLflow with Its GenAI Extra​

Terminal
uv add "mlflow[genai]"
Output (excerpt)
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3
Creating virtual environment at: .venv
Resolved 106 packages in 2.28s
Prepared 12 packages in 2.71s
Installed 102 packages in 978ms
+ mlflow==3.18.0
+ mlflow-skinny==3.18.0
+ mlflow-tracing==3.18.0

[genai] asks for MLflow's optional packages for generative AI. MLflow's Token Usage and Cost page recommends it for the server: "It is recommended to start your MLflow server with the extra installed, even if you don't need cost tracking." Later parts use what it adds, such as the AI Gateway. The quotes stop the shell from reading the square brackets.

Step 3: Start the Tracking Server​

Terminal
uv run mlflow server --port 8080
Output (excerpt)
Backend store URI not provided. Using sqlite:///mlflow.db
Registry store URI not provided. Using backend store URI.
2026/11/30 17:10:29 INFO mlflow.store.db.utils: Creating initial MLflow database tables...
2026/11/30 17:10:29 INFO mlflow.store.db.utils: Updating database tables
[MLflow] Security middleware enabled with default settings (localhost-only). To allow connections from other hosts, use --host 0.0.0.0 and configure --allowed-hosts and --cors-allowed-origins.
2026/11/30 17:10:30 INFO: Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
/Users/you/source/mlflow-server/.venv/lib/python3.15/site-packages/mlflow/server/fastapi_app.py:24: StarletteDeprecationWarning: starlette.middleware.wsgi is deprecated and will be removed in a future release. Please refer to https://github.com/abersheeran/a2wsgi as a replacement.
from starlette.middleware.wsgi import WSGIResponder, build_environ
2026/11/30 17:10:37 INFO mlflow.server.jobs.utils: Registered online_scoring_scheduler periodic task (runs every 1 minute)
2026/11/30 17:10:37 INFO mlflow.server.jobs.utils: Registered trace_archival_scheduler periodic task (polls every 1 minute and no-ops when trace archival is disabled or unconfigured)
2026/11/30 17:10:37 INFO mlflow.server.jobs.utils: Registered issue_detection_scheduler periodic task (polls every 15 minutes and no-ops when no experiment has a detection schedule)
2026/11/30 17:10:37 INFO mlflow.server.jobs.utils: SQL trace rollup scheduler was not registered because rollups are disabled
2026/11/30 17:10:44 INFO: Application startup complete.

A terminal running uv run mlflow server --port 8080: sqlite:///mlflow.db as the backend store, the database tables being created, the localhost-only security middleware, Uvicorn running on http://127.0.0.1:8080, a StarletteDeprecationWarning, three registered scheduler tasks and Application startup complete.

The server is running at http://127.0.0.1:8080, storing everything in mlflow.db in this folder. How to Start an MLflow Tracking Server on Your Computer explains each startup line. Two things are new with the genai extra:

Leave this terminal open. Everything below happens in a second terminal.

Step 4: Create the Agent's Project​

In a second terminal, go back to the folder that holds mlflow-server and create the agent's project next to it:

Terminal 2
uv init --package --name store-support-agent --python 3.15 dewiride-store-support-agent
cd dewiride-store-support-agent
uv add mlflow anthropic pydantic-settings
Output (excerpt)
Initialized project `store-support-agent` at `/Users/you/source/dewiride-store-support-agent`
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 101 packages in 838ms
Built store-support-agent @ file:///Users/you/source/dewiride-store-support-agent
Prepared 4 packages in 425ms
Installed 97 packages in 992ms
+ anthropic==2.14.0
+ mlflow==3.18.0
+ pydantic-settings==2.16.3

uv init --package makes a project whose code lives in an installable package, src/store_support_agent/, so it can have its own commands. The three packages are:

  • mlflow: the client side of MLflow, which sends traces to the server. The agent doesn't need the genai extra; the server has it.
  • anthropic: Anthropic's official SDK for calling Claude.
  • pydantic-settings: reads the agent's settings from a .env file and checks them.

Step 5: Add the Settings​

The agent reads its API key, model and MLflow address from a .env file. Create .env.example as the template, which is safe to share:

.env.example
# Your Claude API key, from the API keys page of the Claude Console (platform.claude.com). Keep it secret.
ANTHROPIC_API_KEY=
# The Claude model that answers customers.
SUPPORT_CLAUDE_MODEL=claude-opus-5-5
# How much Claude thinks before it answers: low, medium, high, xhigh or max. More effort means more tokens.
SUPPORT_EFFORT=medium
# The MLflow tracking server that receives the agent's traces.
MLFLOW_TRACKING_URI=http://127.0.0.1:8080
# The MLflow experiment that groups the agent's traces.
MLFLOW_EXPERIMENT_NAME=store-support-agent

Copy it to .env and paste your key after ANTHROPIC_API_KEY=. How to Get a Claude API Key shows where to create one.

Terminal 2
cp .env.example .env

.env holds your secret key, so keep it out of Git. Add these lines at the end of .gitignore:

.gitignore (add at the end)

# Your settings and Claude API key: never commit them
.env

The settings class reads and checks those values. Create src/store_support_agent/config.py:

src/store_support_agent/config.py
"""Settings, read from environment variables and the .env file."""

from functools import lru_cache
from typing import Annotated, Literal

from pydantic import Field, Secret
from pydantic_settings import BaseSettings, SettingsConfigDict

# A secret text that must not be empty. The constraint goes on the text inside the secret.
ApiKey = Secret[Annotated[str, Field(min_length=1)]]


class Settings(BaseSettings):
"""The Claude API key and model the agent uses, and where it sends its traces."""

model_config = SettingsConfigDict(
env_prefix="SUPPORT_",
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)

anthropic_api_key: ApiKey = Field(
validation_alias="ANTHROPIC_API_KEY",
description="Your Claude API key, from the Claude Console.",
)
claude_model: str = Field(
default="claude-opus-5-5",
min_length=1,
description="The Claude model that answers customers.",
)
effort: Literal["low", "medium", "high", "xhigh", "max"] = Field(
default="medium",
description="How much Claude thinks before it answers. More effort means more tokens.",
)
max_tokens: int = Field(
default=16000,
gt=0,
description="The most tokens one reply may use, thinking included.",
)
mlflow_tracking_uri: str = Field(
default="http://127.0.0.1:8080",
validation_alias="MLFLOW_TRACKING_URI",
description="The address of the MLflow tracking server.",
)
mlflow_experiment_name: str = Field(
default="store-support-agent",
min_length=1,
validation_alias="MLFLOW_EXPERIMENT_NAME",
description="The MLflow experiment that groups the agent's traces.",
)


@lru_cache
def get_settings() -> Settings:
"""Read the settings once, then reuse the same object everywhere."""
return Settings()

What each part does:

  • env_prefix="SUPPORT_" makes the agent's own settings read SUPPORT_CLAUDE_MODEL, SUPPORT_EFFORT and SUPPORT_MAX_TOKENS, so they can't clash with other programs' variables. The key and the two MLflow settings keep their usual names with validation_alias; they're the names the Anthropic SDK and MLflow themselves read.
  • The API key is a secret, so it prints as ********** in logs and errors, and it must not be empty. My first version used SecretStr with min_length=1, and an empty key gave a confusing message: Fixed: "Value should have at least 1 item after validation, not 0" for an Empty Pydantic SecretStr shows why Secret[Annotated[str, Field(min_length=1)]] is the right form.
  • effort accepts only the five levels Claude knows, so a typo stops the agent at startup instead of failing on the first customer.
  • max_tokens is the most one reply may use. On Claude Opus 5.5 that includes thinking, so it's generous.

Step 6: Write the Handbook and the Instructions​

The agent answers from the shop's handbook. Save it as src/store_support_agent/handbook.md:

src/store_support_agent/handbook.md
# Cedarfield Outdoor customer service handbook

Cedarfield Outdoor is an online shop for camping and hiking gear. It ships to addresses in the United States.

## Shipping

- Standard shipping takes 3 to 5 business days. It costs $6.95, and it's free on orders of $75 or more.
- Express shipping takes 1 to 2 business days and costs $19.95, whatever the order total.
- Orders placed before 2 p.m. Eastern Time on a business day leave the warehouse the same day. Later orders leave the next business day.
- Every order gets a tracking number by email when it leaves the warehouse.
- Cedarfield Outdoor doesn't ship outside the United States or to P.O. boxes.

## Returns

- Customers can return items within 30 days of delivery.
- Returned items must be unused and in their original packaging, with the tags attached.
- Items marked "Final sale" can't be returned.
- Tents and sleeping bags that have been used outdoors can't be returned unless they are defective.
- To start a return, the customer needs their order number and the email address used for the order.
- Return shipping is free when the item is defective or Cedarfield Outdoor sent the wrong item. Otherwise, $6.95 is taken off the refund.

## Refunds

- Refunds go back to the original payment method within 5 business days after the return reaches the warehouse.
- Shipping costs aren't refunded, unless the item was defective or Cedarfield Outdoor made a mistake.
- Gift cards can't be refunded or exchanged for cash.

## Exchanges

- Cedarfield Outdoor doesn't swap items directly. To get a different size or color, the customer returns the item and places a new order.

## Warranty

- Every product has a 1-year warranty against manufacturing defects. Tents and backpacks have 2 years.
- The warranty doesn't cover normal wear and tear, accidents, or damage from misuse.
- A warranty claim needs the order number and photos of the defect, sent to the support team by email.

## Price adjustments

- If an item's price drops within 14 days of delivery, the customer can ask for the difference back, once per order.

## The support team

- The support team answers emails at support@cedarfield.example, Monday to Friday, 9 a.m. to 5 p.m. Eastern Time, usually within one business day.
- Hand these to the support team: parcels that arrived damaged (with photos), payment disputes, complaints about staff, and anything the handbook doesn't cover.

Then the instructions Claude follows, the system prompt, in src/store_support_agent/prompts.py:

src/store_support_agent/prompts.py
"""The instructions Claude follows as the shop's support agent."""

from importlib.resources import files

HANDBOOK = files("store_support_agent").joinpath("handbook.md").read_text(encoding="utf-8")

SYSTEM_PROMPT = f"""You are the customer support agent of Cedarfield Outdoor, an online shop for \
camping and hiking gear. Customers chat with you in a terminal window.

Answer questions about the shop's shipping, returns, refunds, exchanges, warranty and price \
adjustments, using only the handbook below. When the handbook doesn't answer a question, say so \
and give the support team's email address. You can't see orders, accounts or payments, so for \
anything about a specific order, ask the customer to email the support team.

Keep replies short and friendly: two to four sentences of plain text, without Markdown.

<handbook>
{HANDBOOK}
</handbook>"""

files("store_support_agent") finds the handbook inside the installed package, wherever the agent is started from. The handbook goes inside <handbook> tags so Claude can tell the shop's rules from its own instructions, and "using only the handbook below" keeps it from inventing policies.

Step 7: Write the Agent​

src/store_support_agent/agent.py holds one conversation and sends it to Claude:

src/store_support_agent/agent.py
"""The support agent: sends the conversation to Claude and returns its answer."""

import logging

import anthropic
from anthropic.types import MessageParam

from store_support_agent.config import Settings
from store_support_agent.prompts import SYSTEM_PROMPT

logger = logging.getLogger(__name__)

FALLBACK_REPLY = (
"Sorry, I can't help with that here. "
"Please email our support team at support@cedarfield.example."
)


class SupportAgent:
"""One conversation between a customer and the shop's support agent."""

def __init__(self, client: anthropic.Anthropic, settings: Settings) -> None:
self._client = client
self._settings = settings
self._messages: list[MessageParam] = []

def reply(self, customer_message: str) -> str:
"""Send the customer's message, with the conversation so far, and return the answer."""
self._messages.append({"role": "user", "content": customer_message})
try:
response = self._client.messages.create(
model=self._settings.claude_model,
max_tokens=self._settings.max_tokens,
system=[
{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}
],
messages=self._messages,
output_config={"effort": self._settings.effort},
)
except anthropic.APIError:
# The message never got an answer, so it leaves the conversation.
self._messages.pop()
raise

if response.stop_reason == "refusal":
# Claude declined. Any partial output isn't an answer, so the message leaves too.
self._messages.pop()
category = response.stop_details.category if response.stop_details else None
logger.warning("Claude declined a message (category: %s)", category)
return FALLBACK_REPLY

# Keep Claude's whole turn, thinking included, so the next request sends it back unchanged.
self._messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "max_tokens":
logger.warning(
"A reply reached max_tokens (%d) and was cut short", response.usage.output_tokens
)

answer = "".join(block.text for block in response.content if block.type == "text")
if not answer:
logger.warning("Claude returned no text (stop reason: %s)", response.stop_reason)
return FALLBACK_REPLY
return answer

The agent.py file in a macOS-style code window: the SupportAgent class keeps the conversation in a list and its reply method calls client.messages.create with the model, max_tokens, the cached system prompt, the messages and the effort, then handles refusals, cut-off replies and empty answers.

Each piece, with a guide for the details:

One choice is about MLflow. Anthropic's documentation also offers a server-side fallback that retries a refused request on another model. It's a beta, reached through client.beta.messages.create, and MLflow 3.18.0's Anthropic autologging records messages.create only. I checked: with autologging on, a request through client.beta.messages.create left no trace, and the same request through client.messages.create left one. So the agent uses the regular call and handles refusals itself.

Step 8: Turn On Tracing​

This is the whole MLflow part of this step, in src/store_support_agent/tracing.py:

src/store_support_agent/tracing.py
"""Send the agent's traces to the MLflow tracking server."""

import mlflow

from store_support_agent.config import Settings


def start_tracing(settings: Settings) -> None:
"""Point MLflow at the tracking server and the experiment, then trace every Claude call."""
mlflow.set_tracking_uri(settings.mlflow_tracking_uri)
mlflow.set_experiment(settings.mlflow_experiment_name)
mlflow.anthropic.autolog()

The tracing.py file in a macOS-style code window: start_tracing sets MLflow's tracking URI and experiment from the settings, then calls mlflow.anthropic.autolog().

Three lines:

  1. mlflow.set_tracking_uri(...) sends everything to your server. Without it, MLflow 3.18 would write to an mlflow.db file in the folder you run from.
  2. mlflow.set_experiment(...) files the traces under store-support-agent, and creates that experiment on first use.
  3. mlflow.anthropic.autolog() patches the Anthropic SDK, so every messages.create call becomes a trace with no change to the agent's code. MLflow's Anthropic page lists what it records: the prompts and responses, latencies, the model name, settings such as max_tokens, tool calls, token usage and exceptions.

The agent works with or without these lines; tracing only watches. How to Trace Claude API Calls with MLflow shows the same three lines in a ten-line script.

Step 9: Write the Chat​

src/store_support_agent/chat.py is the terminal chat a customer uses:

src/store_support_agent/chat.py
"""A terminal chat with the shop's support agent."""

import logging
import sys

import anthropic
from pydantic import ValidationError

from store_support_agent.agent import SupportAgent
from store_support_agent.config import get_settings
from store_support_agent.tracing import start_tracing

logger = logging.getLogger(__name__)

WELCOME = "Cedarfield Outdoor support. Ask a question, /new starts over, /quit leaves."


def main() -> None:
"""Chat with the support agent in the terminal until the customer quits."""
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
try:
settings = get_settings()
except ValidationError as error:
problems = "; ".join(f"{e['loc'][0]}: {e['msg']}" for e in error.errors())
sys.exit(f"Check your .env file. {problems}")

start_tracing(settings)
client = anthropic.Anthropic(api_key=settings.anthropic_api_key.get_secret_value())
agent = SupportAgent(client, settings)

print(WELCOME)
while True:
try:
message = input("You: ").strip()
except EOFError, KeyboardInterrupt:
print()
break
if not message:
continue
if message == "/quit":
break
if message == "/new":
agent = SupportAgent(client, settings)
print("Started a new conversation.")
continue

try:
answer = agent.reply(message)
except anthropic.AuthenticationError:
sys.exit("Claude rejected the API key. Check ANTHROPIC_API_KEY in your .env file.")
except anthropic.RateLimitError:
print("Claude is busy right now. Please try again in a minute.")
continue
except anthropic.APIConnectionError:
print("Can't reach Claude. Check your internet connection, then try again.")
continue
except anthropic.APIStatusError as error:
logger.warning(
"Claude API error %s (request ID %s)", error.status_code, error.request_id
)
print("Something went wrong on Claude's side. Please try again.")
continue
print(f"Agent: {answer}")

What it does, in order:

  • Checks the settings first. A missing or empty value stops the chat with one line per problem, such as Check your .env file. ANTHROPIC_API_KEY: String should have at least 1 character, instead of a long traceback.
  • Starts tracing, then creates the Anthropic client with the key from the settings.
  • Loops until the customer types /quit or presses Ctrl+C or Ctrl+D. /new starts a fresh conversation. except EOFError, KeyboardInterrupt: without brackets needs Python 3.14 or newer; this project requires 3.15.
  • Turns API errors into plain sentences. A wrong key ends the chat; a busy API or a lost connection lets the customer try again: How to Handle Claude API Errors in Python. The log line for other errors records the status and the request ID, never the key or the customer's words.

Finally, give the chat a command. uv init --package added a [project.scripts] entry for the package itself; replace it in pyproject.toml:

pyproject.toml (changed lines)
[project.scripts]
support-chat = "store_support_agent.chat:main"

uv run support-chat now runs main() from chat.py. The package's src/store_support_agent/__init__.py keeps only a one-line description:

src/store_support_agent/__init__.py
"""A customer-support agent for Cedarfield Outdoor, built on Claude and traced with MLflow."""

Step 10: Chat with the Agent​

With the server still running in the first terminal:

Terminal 2
uv run support-chat

Ask three questions, then type /quit:

Output
2026/11/30 17:11:00 INFO mlflow.tracking.fluent: Experiment with name 'store-support-agent' does not exist. Creating a new experiment.
Cedarfield Outdoor support. Ask a question, /new starts over, /quit leaves.
You: Hi! How long does standard shipping take, and how much does it cost?
Agent: Hi there! Standard shipping takes 3 to 5 business days and costs $6.95, and it's free on orders of $75 or more. Orders placed before 2 p.m. Eastern Time on a business day leave our warehouse the same day, and you'll get a tracking number by email once your order ships.
You: Can I return a tent I used on a camping trip last weekend?
Agent: Unfortunately, tents that have been used outdoors can't be returned unless they're defective. If something is wrong with it, like a broken pole or a faulty seam, you can return it within 30 days of delivery with free return shipping, and tents also have a 2-year warranty against manufacturing defects. For a defect, just email support@cedarfield.example with your order number and photos of the problem.
You: Do you accept PayPal?
Agent: I'm sorry, but my handbook doesn't cover which payment methods we accept. The support team can answer that for you at support@cedarfield.example. They reply Monday to Friday, 9 a.m. to 5 p.m. Eastern Time, usually within one business day.
You: /quit
2026/11/30 17:11:06 INFO mlflow.tracing.export.async_export_queue: Flushing the async trace logging queue before program exit. This may take a while...

The chat in a terminal: MLflow creates the store-support-agent experiment, the agent greets the customer, answers the shipping and used-tent questions from the handbook, sends the PayPal question to the support team's email, and MLflow flushes its traces when the customer quits.

The agent answered from the handbook: the shipping prices, the rule on used tents with the warranty as the way forward, and an honest "my handbook doesn't cover" for PayPal. Your answers will be worded differently; Claude doesn't repeat itself word for word.

MLflow added two lines of its own. The first chat created the store-support-agent experiment. At the end, MLflow finished sending traces it was writing in the background. Each customer message made one trace: three in all.

Step 11: Open the MLflow UI​

Open http://127.0.0.1:8080 in your browser:

The MLflow home page with GenAI selected in the sidebar: Getting Started cards for tracing, evaluation, prompts and the AI Gateway, and Recent Experiments listing store-support-agent and Default.

On your first visit, the MLflow Assistant panel may open on the right; close it with its ×. Make sure GenAI is selected at the top of the sidebar, then click store-support-agent under Recent Experiments. The experiment opens on its Overview:

The store-support-agent experiment's Overview: a sidebar with Overview, Traces, Issues, Dashboard, Sessions and the evaluation and prompt pages, and on the right the quality-loop steps, starting with TRACE: 3 traces.

The sidebar lists everything this series will use, from Traces to Judges, Datasets and Prompts. TRACE 3 traces confirms the chat's three messages arrived.

Step 12: Read the Traces​

Click Traces in the sidebar. If a Detect Issues tip pops up, click Got it:

The Traces page: three traces from 5 minutes ago, newest first, the PayPal, tent and shipping questions as inputs, the start of each reply's JSON as output, durations of 1.4 to 2.1 seconds, state OK, and 1482, 1379 and 1181 tokens.

One row per customer message: the question, the start of Claude's reply, how long the call took, and its tokens. The token counts grow with each message because every call sends the whole conversation so far. How to View a Trace in the MLflow UI tours the rest of this page.

Step 13: Open a Trace​

Click the first question, the shipping one:

The trace view: Trace 489f48a7, Success, 2.05 seconds, 1.2K tokens, about $0.0077; the span Messages.create with claude-opus-5-5; the Inputs show the user's question, max_tokens 16000, the model, output_config effort medium and the start of the system prompt.

This is exactly what the agent sent to Claude. The trace has one span, Messages.create, named after the SDK method, and its Inputs show the customer's question, max_tokens 16000, the model, effort: medium and the system prompt with the whole handbook. If an answer is ever wrong, this is where you check what Claude was actually given.

Scroll down to Outputs:

The Outputs of the span: Claude's answer about standard shipping, then the response fields: the message id, container null, and content with a thinking block whose thinking text is empty and a text block with the answer.

The answer first, then the whole response. Its content starts with a thinking block: Claude Opus 5.5 thought before answering, but by default it returns only a signature, not the thinking text, so thinking is empty. The text block after it is the answer. The PayPal reply had no thinking block at all: on a simple question, Claude can answer without thinking.

Step 14: See What Each Reply Cost​

Rest the mouse on 1.2K tokens in the top bar:

The Usage breakdown popup: input tokens 1061, cache read 0, cache write 1033, output tokens 120, total 1181.

Of the 1,061 input tokens, 1,033 were the system prompt and handbook, written to the cache on this first call; the other 28 were the question. The 120 output tokens include 22 of thinking. Now rest the mouse on ≈$0.0077:

The Cost breakdown popup: input cost $0.005277, output cost $0.0024, total about $0.0077, with the note that cost is estimated from token usage and public model pricing.

MLflow priced the call at Claude Opus 5.5's rates: the cache write at $5 per million tokens, the question at $4 and the output at $20, $0.0077 in all. The next two traces show the cache paying off: each read the same 1,033 tokens at $0.20 per million instead of $4, which is why the tent question cost $0.0044 even though Claude sent more output.

How to See the Token Usage and Cost of LLM Calls in MLflow reads the same numbers from Python.

Step 15: See the Totals on the Dashboard​

Click Dashboard in the sidebar and scroll down on the Usage tab:

The Dashboard's Usage tab: Token Usage 4.04K with 3.66K input, 383 output, 2.07K cache read and 1.03K cache write; Tokens per Trace 1.35K on average; Cost Breakdown about $0.015478 with claude-opus-5-5 at 100 percent; and Cost Over Time.

The whole chat: 4,042 tokens, 2,066 of them read from the cache, and $0.015478 for three answers. As the agent handles more conversations, these charts show how its usage and cost change from day to day.

Two notes on MLflow's documentation, which I reported as mlflow/mlflow#28299. It places these charts on the experiment's Overview tab; in MLflow 3.18.0 they're under Dashboard. It also says cost tracking needs the server installed with the genai extra; in 3.18.0 a server without it still prices calls, from a price table that ships with MLflow. The extra is still worth having, for the reasons in Step 2.

Your Folders Now Look Like This​

source/
source/
├── mlflow-server/
│ ├── .venv/
│ ├── mlflow.db
│ ├── pyproject.toml
│ └── uv.lock
└── dewiride-store-support-agent/
├── .env
├── .env.example
├── .gitignore
├── .python-version
├── .venv/
├── README.md
├── pyproject.toml
├── uv.lock
└── src/
└── store_support_agent/
├── __init__.py
├── agent.py
├── chat.py
├── config.py
├── handbook.md
├── prompts.py
└── tracing.py

mlflow.db holds the experiment and its three traces. Part 2 continues from here.

Stop the Server When You're Done​

In the first terminal, press Ctrl+C. The server stops after its workers shut down; mlflow.db keeps every trace, and uv run mlflow server --port 8080 in mlflow-server brings them all back.

To remove everything from this part instead:

  • delete the mlflow-server and dewiride-store-support-agent folders;
  • in the Claude Console, delete the API key if you created it only for this series.

The Claude API bills only for calls you make, so a stopped agent costs nothing.

Common Mistakes​

MistakeWhat happensDo this instead
Running the chat before starting the serverThe chat works, but MLflow can't deliver the tracesStart the server first, in its own terminal
Leaving ANTHROPIC_API_KEY emptyCheck your .env file. ANTHROPIC_API_KEY: String should have at least 1 characterPaste your key into .env
Committing .envYour API key ends up in GitKeep .env in .gitignore; share .env.example
Printing response.content[0].textThe first block can be a thinking block, which has no textJoin the text blocks, as the agent does
Calling Claude through client.beta.messagesMLflow 3.18.0's autologging doesn't record itUse client.messages.create

Troubleshooting​

SymptomLikely causeFix
The Traces page is emptyAnother tracking URI or experiment in .envCheck MLFLOW_TRACKING_URI and MLFLOW_EXPERIMENT_NAME
Claude rejected the API keyThe key is wrong or revokedCreate a new key and update .env
StarletteDeprecationWarning when the server startsMLflow's own code, with Starlette 1.10.0Harmless; see the fix post linked in Step 3
Every reply costs as much as the firstThe system prompt changes between calls, so the cache never hitsKeep the system prompt identical between calls

FAQ​

Why Claude Opus 5.5?​

It's Anthropic's current Opus model, and at $4 and $20 per million tokens each short answer in this part cost less than a cent. The series also uses it as the judge that grades the agent's answers in later parts.

Does tracing slow the agent down?​

MLflow sends traces in the background, so the customer doesn't wait for them; that's the "Flushing the async trace logging queue" line at the end.

Are customer messages stored?​

Yes: each trace keeps the full request and response, including what the customer typed. Treat mlflow.db like any other customer data. Later parts show how to redact sensitive values.

Can I use another Claude model?​

Yes. Set SUPPORT_CLAUDE_MODEL in .env, such as claude-sonnet-5-5. MLflow 3.18.0's bundled price table includes it, so costs keep working.

Conclusion​

You started an MLflow 3.18 tracking server with the genai extra, built a Claude-powered support agent with its settings, handbook, prompt and terminal chat, and turned on tracing with three lines. The first chat produced three traces showing exactly what the agent sent to Claude, what came back, the thinking, the prompt cache at work, and a cost of $0.015 for three answers.

Part 2, coming next, gives the agent tools, such as looking up an order, and traces each step the agent takes, not only its calls to Claude.

Additional Resources​