- AI
- Artificial Intelligence
Clients often come to us with a practical question: how can we reduce an AI agent's operating costs without compromising answer quality? The system may already deliver useful results, yet each request may involve more model calls, tokens, or wait time than the team expected. Before choosing an optimization, we need to understand how that work accumulates and which parts of it actually contribute to the result.
The final answer provides only part of that picture. An agent can return a perfectly reasonable recommendation after repeatedly retrieving unsuitable data and asking the model to work through it. Those extra steps are difficult to identify from the user-facing response alone, even though they affect the cost and speed of every interaction.
Telemetry lets us examine that execution path. To show how this works, we built a small synthetic hotel-search agent inspired by a real system. We use OpenTelemetry to follow it from the initial request to its recommendations, identify a limitation in its search tool, and see what changes when we remove that limitation.
Telemetry is the data a system produces while it runs and makes available for analysis. Error events, request durations, and model token counts all contribute to our understanding of application behavior. The ability to understand a system through those signals is known as observability.
Several kinds of signals serve different purposes. Logs describe individual events, such as a failed tool call. Metrics summarize behavior numerically, making it possible to follow request volumes, response times, or error rates across a workload. Traces connect the operations involved in a particular request. In this example, that connected view is especially useful because the sequence of an agent’s actions depends on decisions the model makes. The OpenTelemetry observability primer provides further background on these concepts.
A trace consists of spans, each representing an operation with a name, a start time, and an end time. Spans can be nested: a span for the complete agent run contains individual cycles, and each cycle contains a model request and any hotel searches requested by the model. The enclosing operation is the parent span; its suboperations are child spans. This hierarchy allows us to start with the complete request and examine a particular step in context.
Span attributes add details as key-value pairs, such as the model name, search arguments, or number of hotels returned. Combined with the timeline, they help explain what happened at each stage. OpenTelemetry’s trace documentation describes this structure in more detail.
To generate and transmit this data consistently, we use OpenTelemetry (OTel), an open-source project that provides standards, libraries, and tools for telemetry across different languages and analysis systems. Adding telemetry-producing code to an application is called instrumentation. Existing libraries can instrument some operations automatically, while application-specific steps can be instrumented explicitly.
For storage and inspection, we use Jaeger, an open-source distributed tracing platform. In this setup, OpenTelemetry creates and exports the traces, and Jaeger displays their spans and attributes in a browser. The same approach can follow requests across multiple services; our local example keeps the components small enough to examine directly.
Our demonstration agent, MockTels, searches a dataset of 50 fictional hotels in Wakanda. Each hotel has a location, nightly price, rating, and pet policy. Prices are expressed in fictional credits. The application consists of a language model, a search tool, and the data needed to answer a request such as this:
I’m planning a trip to Wakanda with my cat, Fluffy. Could you recommend some good, affordable hotels where we can stay together? I’d like a rating of at least 4.5 out of 5 and a budget of up to 200 credits per night, preferably less.
The model selects arguments for a tool called search_hotels. The application executes the search and returns the results to the model, which then decides whether it has enough information to make recommendations. Search results are sorted from lowest to highest price and returned in pages of up to 10 records. To inspect more hotels, the model requests another page. One agent cycle consists of a model request followed by any tool calls it asks the application to execute.
In one run, the agent produced the following answer:
Four pet-friendly Wakanda hotels rated 4.5 or higher came up, and all are well under your 200-credit limit. They're listed cheapest first:
| Hotel | Area | Price/night | Rating | Notes |
|---|---|---|---|---|
| Baobab Hearth Lodge | Border Province, Baobab Valley | 66 | 4.6 | Small family lodge with generous breakfasts and a popular cat cushion. |
| Amber Paw Retreat | Merchant Province, Amber Gardens | 81 | 4.5 | Garden cottages with pet beds, and comfortable pillows for people too. |
| Kingfisher Cottage Hotel | River Province, Kingfisher Reach | 89 | 4.7 | River cottages with shaded paths and muddy-paw towels. It has the highest rating of the four. |
| Rooftop Whisker Hotel | Birnin Zana, Rooftop Gardens | 96 | 4.5 | Airy rooms and enclosed rooftop gardens, inspected daily by the resident cat. |
Best value: Baobab Hearth Lodge is the cheapest at 66 credits and is rated 4.6. Its cat cushion sounds like a good fit for Fluffy.
Best reviewed: Kingfisher Cottage Hotel at 89 credits has the top rating, 4.7.
Best location: Rooftop Whisker Hotel is in Birnin Zana. Its enclosed gardens should let Fluffy get some fresh air safely.
Some highly rated hotels didn't make the list because they don't allow pets. These were Little Orchid Inn (4.7), Waterfall Window Hotel (4.8) and Auntie's Tea House (4.6).
I searched the first 30 results, which covered prices up to 96 credits. More hotels may exist at higher prices, but you said you'd prefer to spend less. I can keep searching if you'd like more options.
The recommended hotels satisfy the budget, rating, and pet-policy requirements, so from the user’s perspective the agent has done its job. What the answer does not show is how many model requests it took to get there or how much context the model processed along the way. That is where the trace becomes useful.
The instrumentation follows the application's structure: the full run, its cycles, model requests, and search operations. The snippets below use real OpenTelemetry calls, with placeholder functions for model interaction and message-history management so that the tracing logic remains visible.
The initial setup requires opentelemetry-api, opentelemetry-sdk, and opentelemetry-exporter-otlp-proto-http, together with a running Jaeger instance that accepts OTLP over HTTP. OTLP is OpenTelemetry’s protocol for transmitting telemetry. The Python exporter documentation includes a Docker setup for Jaeger; the interface discussed here is Jaeger 2.22. In our local environment, the trace receiver is available at http://localhost:4318/v1/traces.
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
provider = TracerProvider(
resource=Resource.create({"service.name": "mocktels"})
)
exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("mocktels")The service.name identifies the application in Jaeger, while the tracer creates its spans. The remaining configuration determines how completed spans are processed and where they are sent: BatchSpanProcessor groups them into batches, and the exporter transmits those batches to the configured endpoint. The exporter documentation covers other configuration options.
Application operations can now be wrapped in start_as_current_span. Entering a with block starts the span and makes it current; leaving the block ends it. Spans created inside that context automatically become its children, so the nesting in the code produces the hierarchy visible in the trace.
import json
def run_agent(prompt):
messages = [{"role": "user", "content": prompt}]
with tracer.start_as_current_span("agent.run") as run:
run.set_attribute("gen_ai.operation.name", "invoke_agent")
for turn in range(1, 11):
with tracer.start_as_current_span("agent.cycle") as cycle:
cycle.set_attribute("turn", turn)
with tracer.start_as_current_span("model.request") as span:
response = call_model(messages)
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.usage.input_tokens", response.total_input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", response.output_tokens)
remember_response(messages, response)
if not response.tool_calls:
return response.text
for call in response.tool_calls:
with tracer.start_as_current_span("tool.search_hotels") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("arguments", json.dumps(call.arguments))
hotels = search_hotels(**call.arguments)
span.set_attribute("returned_count", len(hotels))
span.set_attribute("result", json.dumps(hotels))
remember_tool_result(messages, call, hotels)
raise RuntimeError("Model request limit exceeded")Here, call_model represents a function that returns the response text, tool calls, and token counters. remember_response and remember_tool_result append the response and search results to the history used by the next model request. The illustrative total_input_tokens field already includes ordinary input, cache writes, and cache reads. In a production integration, these counters need to be mapped from the provider’s API response with care, since a reported total may already include cached tokens. The example also stops after 10 model requests if the agent has not produced a final answer.
Each recorded field serves a purpose in the investigation. The cycle number establishes the sequence; search arguments and results show what the agent had available; token counters describe the volume the model processed. Duration is already captured by the spans’ start and end times. The operation types and token counters use OpenTelemetry’s gen_ai attribute names, while the other fields are custom attributes. Further instrumentation patterns are covered in the Python instrumentation guide.
Because the exporter sends spans in batches, a short-lived command-line application needs to wait for pending telemetry before exiting. In this example, shutdown happens after run_agent returns or raises an exception, once the root span has ended:
try:
print(run_agent(prompt)) # prompt contains the user's request
finally:
provider.shutdown()With the search arguments, results, and token counts captured, we can now inspect how the agent reached its recommendations.
The local Jaeger interface is available at http://localhost:16686. Selecting the mocktels service brings up the agent’s traces. On the timeline, agent.run covers the complete request, with nested cycles containing model requests and search_hotels calls. Expanding those operations shows how often the agent returned to the search tool and how long each step took.
OpenTelemetry’s GenAI semantic conventions define shared names and meanings for AI-related attributes. For example, gen_ai.operation.name identifies operations such as chat, execute_tool, and invoke_agent; gen_ai.request.model identifies the requested model. The gen_ai.usage.input_tokens and gen_ai.usage.output_tokens attributes hold token counts. Our teaching snippet records operation types and token usage, while the full implementation also includes model names, messages, and standard tool-call fields. Jaeger 2.22 uses these attributes to identify AI operations and display their details in the GenAI tab. Naming a span model.request does not populate those fields automatically; instrumentation must supply them. These conventions are still evolving, so integrations need to be checked against the current documentation.
The cause of the repeated searches becomes clear when you compare the arguments to tool.search_hotels with its results. The user requested a minimum rating of 4.5 and cat-friendly accommodation, but the initial tool accepts only a location, a maximum price, and pagination parameters. As a result, it includes hotels the model must reject before requesting another page. Repeated calls use the same search conditions and an increasing offset (the number of records skipped); count determines the page size.
Every search call completes successfully: the tool is doing exactly what its interface allows. The issue emerges from the relationship between the user’s requirements, the returned data, and the agent’s subsequent actions. The original agent made three searches and four model requests, retrieving pages sequentially before producing its answer.
Each subsequent model request includes the accumulated message history, so it resends previously retrieved results as part of an increasingly long context. Token attributes on the model.request spans make the cost of that repeated processing visible.
The trace points to a specific change: make the search tool apply the criteria the model is currently checking after retrieval.
Adding minimum-rating and pet-policy parameters allows the model to express the user’s requirements directly in the search. A simplified implementation looks like this, with load_hotels() standing in for the dataset loader:
def search_hotels(
location, max_price, count=10, offset=0,
min_rating=None, is_pet_friendly=None,
):
matches = [
hotel for hotel in load_hotels()
if hotel["location"].startswith(location)
and hotel["price"] <= max_price
and (min_rating is None or hotel["rating"] >= min_rating)
and (is_pet_friendly is None
or hotel["petFriendly"] == is_pet_friendly)
]
matches.sort(key=lambda hotel: hotel["price"])
return matches[offset:offset + count]All conditions are applied before pagination, so each page now contains only hotels that satisfy the supplied filters. None leaves a condition unspecified, while False for is_pet_friendly explicitly selects hotels that do not allow pets. The tool’s parameter schema and description exposed to the model also need to reflect the new capabilities. For our request, the expected arguments include min_rating=4.5 and is_pet_friendly=True.
To evaluate the change, we compared two runs with the same request about traveling with a cat. Both used the same model, system instructions, hotel dataset, and limit of 10 records per page. The tool’s capabilities and the description provided to the model were the variables we changed. With the new filters, the agent made one search and two model requests, compared with three searches and four model requests in the original run.
| Measure | Before filtering | After filtering | Reduction |
|---|---|---|---|
| Model requests | 4 | 2 | 50% |
| Search calls | 3 | 1 | 66.7% |
| Input tokens including cache | 9,957 | 3,026 | 69.6% |
| Output tokens | 1,025 | 875 | 14.6% |
| Run duration | 10.18 s | 7.04 s | 30.8% |
The largest change was in input volume: the model received almost 70% fewer tokens. The shorter execution path avoided repeated search cycles and the growing history they produced. Output volume also fell by 14.6%. The corresponding financial savings depend on the model’s input, cache, and output rates, but the reduction in processing is already clear.
The improved agent also finished in 7.04 seconds rather than 10.18 seconds, approximately 31% faster in our comparison. Alongside the lower token count, that gives us a useful view of the change from both sides: less work for the system and less waiting for the user.
Returning to Jaeger makes the improvement easy to follow. The updated tool.search_hotels span shows the values supplied for min_rating and is_pet_friendly, followed by hotels that match the requested criteria. Comparing those results with the final recommendations confirms that the agent still meets the user’s requirements while taking a much shorter route to the answer.
The change itself was small: two additional search parameters and an updated tool description. Telemetry helped us find where that change would matter, then showed its effect across the complete execution path.
The initial business question was how to reduce the cost of an agent that already returned useful answers. Telemetry made it possible to connect repeated model requests to a specific limitation in the search interface, then evaluate a focused change against both resource usage and the user’s requirements. The resulting improvement came from giving the tool the filtering capabilities the task required.
That method extends beyond this small example to ordinary APIs, background jobs, and interactions between services. During a single local run, printing arguments, results, and timings may provide enough information to understand execution. As more agents and requests run concurrently, those messages become harder to reconstruct into complete histories. Structured logs can also be correlated with requests, while traces provide an explicit hierarchy of operations with durations and attributes.
OpenTelemetry also provides a common approach across services and application instances. Preserving the relationship between operations across services requires trace-context propagation: passing the identifiers that let new spans join the same trace. With that context in place, an investigation can follow a request across system boundaries without manually assembling its history from unrelated messages.
In production systems, observability is most useful when teams consider the information needed to evaluate behavior during development. Identifying meaningful operations, preserving their relationships, and recording the context needed to test assumptions gives teams a stronger basis for optimization, even if the first implementation uses structured logs. A practical starting point is one representative workflow traced from request to response. From there, improvements can be tied to the work the system actually performs and checked against the outcome the client needs.
Get actionable insights for your product