This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new cf30bcebb608 CAMEL-27135: camel-jbang - the AI usage view counts only
model calls, and shows the agent runs, cached tokens and the GenAI level
(#30521)
cf30bcebb608 is described below
commit cf30bcebb608105118baa8f49994216246f44507
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 20 22:23:36 2026 +0100
CAMEL-27135: camel-jbang - the AI usage view counts only model calls, and
shows the agent runs, cached tokens and the GenAI level (#30521)
The AI usage view and the Ollama view counted every GenAI span as a model
call, so at level detailed the agent runs and tool calls showed as calls with 0
tokens. Count only the model calls, fall back to gen_ai.provider.name, add a
CACHED column and total (also for the AI panel's own requests), a summary line
with the agent runs, their model and tool calls and the GenAI level, and show
the panel's tool time only when it called tools.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../images/jbang/camel-tui-ai-usage-agent-runs.png | Bin 0 -> 309583 bytes
.../modules/ROOT/pages/camel-jbang-tui-ai.adoc | 11 ++
.../camel/dsl/jbang/core/commands/tui/AiPanel.java | 25 +---
.../dsl/jbang/core/commands/tui/AiUsageEntry.java | 43 ++++++
.../dsl/jbang/core/commands/tui/AiUsageSource.java | 23 +++
.../dsl/jbang/core/commands/tui/AiUsageStats.java | 165 ++++++++++++++-------
.../core/commands/tui/GenAiSpanUsageExtractor.java | 154 +++++++++++++++++--
.../dsl/jbang/core/commands/tui/OllamaMonitor.java | 7 +-
.../core/commands/tui/AiPanelGenAiUsageTest.java | 96 +++++++++++-
.../dsl/jbang/core/commands/tui/AiPanelTest.java | 55 ++++---
.../commands/tui/GenAiSpanUsageExtractorTest.java | 161 +++++++++++++++++++-
.../jbang/core/commands/tui/OllamaMonitorTest.java | 30 ++++
.../jbang/core/commands/tui/SourceSizeTest.java | 3 +-
13 files changed, 658 insertions(+), 115 deletions(-)
diff --git
a/docs/user-manual/modules/ROOT/images/jbang/camel-tui-ai-usage-agent-runs.png
b/docs/user-manual/modules/ROOT/images/jbang/camel-tui-ai-usage-agent-runs.png
new file mode 100644
index 000000000000..a492788e0a0b
Binary files /dev/null and
b/docs/user-manual/modules/ROOT/images/jbang/camel-tui-ai-usage-agent-runs.png
differ
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-ai.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-ai.adoc
index 2393f3e820b2..4efa14d86ade 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-ai.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-ai.adoc
@@ -212,6 +212,17 @@ average time per question (and per request in brackets),
the model table has an
the average per request for that model, and the *Time per question* chart next
to the token chart shows the
two side by side for each question, so you can see whether a slow answer was
the model or the tools.
+The integration rows count model calls only. At the GenAI observability level
`detailed` or `full`
+(`camel.aiObservability.level`), an agent run is recorded as an `invoke_agent`
span with one span per model call
+and one per tool call. The view counts its model calls, and a third summary
line gives the agent runs, their model
+and tool calls, and the level the spans were recorded at. At the default level
`basic`, agent runs and tool calls
+are not traced: camel-openai records each model call, and
camel-langchain4j-agent records a whole run as one call.
+The summary line then tells how to see them. The *CACHED* column shows the
input tokens served from the provider's
+prompt cache: for the panel's own requests when the provider reports them, and
for the integration from level
+`detailed` on.
+
+image::jbang/camel-tui-ai-usage-agent-runs.png[The AI Usage view of an
integration whose agent calls a route tool, at GenAI level detailed]
+
== What asks first
Camel TUI is a developer tool: the model works on your own machine, with your
own integrations, and runs the
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index a97b99228f98..bbe5c7000aa4 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -292,11 +292,6 @@ class AiPanel {
private boolean statsView;
boolean spanRefreshRequested;
- enum AiUsageSource {
- TUI,
- ROUTE
- }
-
/**
* One conversation line. For assistant replies {@code elapsedMs} is the
wall-clock time of the whole turn,
* {@code aiMs} the part spent waiting for the model and {@code toolMs}
the part spent executing the
@@ -362,24 +357,6 @@ class AiPanel {
}
}
- record AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
- int totalTokens, long latencyMs, String stopReason, Instant
timestamp,
- AiUsageSource source, String routeId, int question) {
-
- AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
- int totalTokens, long latencyMs, String stopReason,
Instant timestamp) {
- this(model, provider, inputTokens, outputTokens, totalTokens,
latencyMs, stopReason, timestamp,
- AiUsageSource.TUI, null, 0);
- }
-
- AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
- int totalTokens, long latencyMs, String stopReason,
Instant timestamp,
- AiUsageSource source, String routeId) {
- this(model, provider, inputTokens, outputTokens, totalTokens,
latencyMs, stopReason, timestamp,
- source, routeId, 0);
- }
- }
-
void setContext(MonitorContext ctx) {
this.ctx = ctx;
}
@@ -1891,7 +1868,7 @@ class AiPanel {
response.usage().inputTokens(),
response.usage().outputTokens(),
response.usage().totalTokens(), latencyMs,
response.stopReason(), Instant.now(),
- AiUsageSource.TUI, null, questionCounter));
+ AiUsageSource.TUI, null, questionCounter,
response.usage().cachedTokens()));
noteMeasuredPrompt(response.usage());
if (ctx != null && ctx.ollamaMonitor != null && client.apiType() ==
LlmClient.ApiType.ollama) {
// the Ollama tab shows this request with the timings Ollama
returned
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageEntry.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageEntry.java
new file mode 100644
index 000000000000..fdeaf1d7dc26
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageEntry.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.commands.tui;
+
+import java.time.Instant;
+
+/**
+ * One model round trip. {@code question} is the sequence number of the panel
question the request was made for (a
+ * question takes several round trips when the model calls tools), so usage
can be grouped per question; it is 0 for
+ * route requests, which belong to no question. {@code cachedInputTokens} are
the input tokens served from the
+ * provider's prompt cache (part of {@code inputTokens}), when known.
+ */
+record AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
+ int totalTokens, long latencyMs, String stopReason, Instant timestamp,
+ AiUsageSource source, String routeId, int question, int
cachedInputTokens) {
+
+ AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
+ int totalTokens, long latencyMs, String stopReason, Instant
timestamp) {
+ this(model, provider, inputTokens, outputTokens, totalTokens,
latencyMs, stopReason, timestamp,
+ AiUsageSource.TUI, null, 0, 0);
+ }
+
+ AiUsageEntry(String model, String provider, int inputTokens, int
outputTokens,
+ int totalTokens, long latencyMs, String stopReason, Instant
timestamp,
+ AiUsageSource source, String routeId) {
+ this(model, provider, inputTokens, outputTokens, totalTokens,
latencyMs, stopReason, timestamp,
+ source, routeId, 0, 0);
+ }
+}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageSource.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageSource.java
new file mode 100644
index 000000000000..3ab2c215cb66
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageSource.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.commands.tui;
+
+/** Where an AI request was made: by the TUI's AI panel, or by a route of the
monitored integration. */
+enum AiUsageSource {
+ TUI,
+ ROUTE
+}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageStats.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageStats.java
index debc04ffceba..99f4deb7caab 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageStats.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiUsageStats.java
@@ -20,6 +20,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
@@ -41,9 +42,9 @@ import dev.tamboui.widgets.table.Cell;
import dev.tamboui.widgets.table.Row;
import dev.tamboui.widgets.table.Table;
import dev.tamboui.widgets.table.TableState;
+import org.apache.camel.component.ai.observability.GenAiObservabilityLevel;
import org.apache.camel.dsl.jbang.core.commands.LlmClient;
-import org.apache.camel.dsl.jbang.core.commands.tui.AiPanel.AiUsageEntry;
-import org.apache.camel.dsl.jbang.core.commands.tui.AiPanel.AiUsageSource;
+import
org.apache.camel.dsl.jbang.core.commands.tui.GenAiSpanUsageExtractor.GenAiActivity;
import static
org.apache.camel.dsl.jbang.core.commands.tui.AiPanel.formatSeconds;
@@ -55,6 +56,9 @@ import static
org.apache.camel.dsl.jbang.core.commands.tui.AiPanel.formatSeconds
*/
final class AiUsageStats {
+ static final String BASIC_LEVEL_HINT
+ = "agent runs and tool calls are not traced;
camel.aiObservability.level=detailed adds them";
+
private final List<AiUsageEntry> usageHistory = new
CopyOnWriteArrayList<>();
/** Per answered question: [aiMs, toolMs, toolCalls], in order, for the
time chart in the usage view. */
private final List<long[]> turnTimings = new CopyOnWriteArrayList<>();
@@ -133,6 +137,7 @@ final class AiUsageStats {
// Compute aggregates
int totalInput = 0;
+ int totalCached = 0;
int totalOutput = 0;
int totalTokens = 0;
long totalLatency = 0;
@@ -141,6 +146,7 @@ final class AiUsageStats {
int routeRequests = 0;
for (AiUsageEntry e : entries) {
totalInput += e.inputTokens();
+ totalCached += e.cachedInputTokens();
totalOutput += e.outputTokens();
totalTokens += e.totalTokens();
totalLatency += e.latencyMs();
@@ -155,16 +161,7 @@ final class AiUsageStats {
int questionCount = countQuestions(entries);
// Per-model aggregation
- Map<String, long[]> perModel = new LinkedHashMap<>();
- for (AiUsageEntry e : entries) {
- String key = modelTableKey(e);
- long[] stats = perModel.computeIfAbsent(key, k -> new long[5]);
- stats[0]++; // requests
- stats[1] += e.inputTokens();
- stats[2] += e.outputTokens();
- stats[3] += e.totalTokens();
- stats[4] += e.latencyMs();
- }
+ Map<String, long[]> perModel = perModel(entries);
// Tokens per question (panel requests only): the round trips made for
one question share its sequence
// number. Grouping by that, rather than by a pause between requests,
keeps a follow-up typed right after the
@@ -180,9 +177,12 @@ final class AiUsageStats {
turnTokens.set(last, turnTokens.get(last) + e.totalTokens());
}
- // Layout: summary (2 rows) + model table (header + models + 1 blank)
+ chart (fill)
+ // Layout: summary (2 rows, 3 with GenAI spans) + model table (header
+ models + 1 blank) + chart (fill)
+ Style dimStyle = Theme.muted();
+ Style cyanStyle = Style.EMPTY.fg(Theme.accent());
+ Line activityLine = activityLine(activity(), dimStyle, cyanStyle);
int tableRows = perModel.size() + 1;
- int summaryRows = 2;
+ int summaryRows = activityLine != null ? 3 : 2;
int chartMinRows = 4;
boolean hasChart = area.height() > summaryRows + tableRows +
chartMinRows + 1;
@@ -198,8 +198,6 @@ final class AiUsageStats {
// --- Summary ---
Rect summaryArea = sections.get(0);
- Style dimStyle = Theme.muted();
- Style cyanStyle = Style.EMPTY.fg(Theme.accent());
List<Line> summaryLines = new ArrayList<>();
summaryLines.add(Line.from(
Span.styled("Requests: ", dimStyle),
@@ -214,6 +212,8 @@ final class AiUsageStats {
Span.styled(LlmClient.formatTokens(totalInput),
Theme.success()),
Span.styled(" / out: ", dimStyle),
Span.styled(LlmClient.formatTokens(totalOutput),
Theme.label()),
+ Span.styled(totalCached > 0 ? " / cached: " : "", dimStyle),
+ Span.styled(totalCached > 0 ?
LlmClient.formatTokens(totalCached) : "", Theme.success()),
Span.styled(")", dimStyle)));
summaryLines.add(Line.from(
Span.styled("Avg per question: ", dimStyle),
@@ -222,15 +222,39 @@ final class AiUsageStats {
Span.styled(" (" + formatSeconds(totalLatency / requestCount)
+ " per request)", dimStyle),
Span.styled(" AI time: ", dimStyle),
Span.styled(formatSeconds(totalLatency), cyanStyle),
- Span.styled(" Tool time: ", dimStyle),
- Span.styled(formatSeconds(sessionToolTimeMs), cyanStyle),
- Span.styled(" (" + sessionToolCalls + " calls)", dimStyle)));
+ // the tools of this panel; the integration's tool calls are
on the agent runs line
+ Span.styled(sessionToolCalls > 0 ? " Tool time: " : "",
dimStyle),
+ Span.styled(sessionToolCalls > 0 ?
formatSeconds(sessionToolTimeMs) : "", cyanStyle),
+ Span.styled(sessionToolCalls > 0 ? " (" + sessionToolCalls + "
calls)" : "", dimStyle)));
+ if (activityLine != null) {
+ summaryLines.add(activityLine);
+ }
frame.renderWidget(
Paragraph.from(new Text(summaryLines, Alignment.LEFT)),
summaryArea);
- // --- Per-model table ---
- Rect tableArea = sections.get(1);
+ renderModelTable(frame, sections.get(1), perModel, cyanStyle);
+
+ // --- Charts per question: tokens on the left, AI vs tool time on the
right ---
+ if (hasChart && (turnTokens.size() > 1 || turnTimings.size() > 1)) {
+ Rect chartsArea = sections.get(2);
+ List<long[]> timings = new ArrayList<>(turnTimings);
+ boolean showTime = timings.size() > 1 && chartsArea.width() >= 40;
+ List<Rect> halves = showTime
+ ? Layout.horizontal().constraints(Constraint.fill(),
Constraint.length(1), Constraint.fill())
+ .split(chartsArea)
+ : List.of(chartsArea);
+ if (turnTokens.size() > 1) {
+ renderTokensPerQuestion(frame, halves.get(0), turnTokens);
+ }
+ if (showTime) {
+ renderTimePerQuestion(frame, halves.get(2), timings);
+ }
+ }
+ }
+
+ /** One row per model: requests, input, cached, output and total tokens,
and the average time. */
+ private void renderModelTable(Frame frame, Rect tableArea, Map<String,
long[]> perModel, Style cyanStyle) {
List<Row> rows = new ArrayList<>();
for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
long[] s = entry.getValue();
@@ -238,6 +262,7 @@ final class AiUsageStats {
Cell.from(Span.styled(entry.getKey(), cyanStyle)),
Cell.from(String.valueOf(s[0])),
Cell.from(LlmClient.formatTokens((int) s[1])),
+ Cell.from(s[5] > 0 ? LlmClient.formatTokens((int) s[5]) :
"-"),
Cell.from(LlmClient.formatTokens((int) s[2])),
Cell.from(LlmClient.formatTokens((int) s[3])),
Cell.from(formatSeconds(s[4] / s[0]))));
@@ -248,6 +273,7 @@ final class AiUsageStats {
Cell.from(Span.styled("MODEL", Style.EMPTY.bold())),
Cell.from(Span.styled("REQS", Style.EMPTY.bold())),
Cell.from(Span.styled("INPUT", Style.EMPTY.bold())),
+ Cell.from(Span.styled("CACHED", Style.EMPTY.bold())),
Cell.from(Span.styled("OUTPUT", Style.EMPTY.bold())),
Cell.from(Span.styled("TOTAL", Style.EMPTY.bold())),
Cell.from(Span.styled("AVG/REQ", Style.EMPTY.bold()))))
@@ -257,6 +283,7 @@ final class AiUsageStats {
Constraint.length(8),
Constraint.length(8),
Constraint.length(8),
+ Constraint.length(8),
Constraint.length(8))
.build();
// PgUp/PgDn scroll the models that do not fit below the header
@@ -264,23 +291,6 @@ final class AiUsageStats {
statsScrollOffset = Math.max(0, Math.min(statsScrollOffset,
rows.size() - visibleModels));
statsTableState.setOffset(statsScrollOffset);
frame.renderStatefulWidget(table, tableArea, statsTableState);
-
- // --- Charts per question: tokens on the left, AI vs tool time on the
right ---
- if (hasChart && (turnTokens.size() > 1 || turnTimings.size() > 1)) {
- Rect chartsArea = sections.get(2);
- List<long[]> timings = new ArrayList<>(turnTimings);
- boolean showTime = timings.size() > 1 && chartsArea.width() >= 40;
- List<Rect> halves = showTime
- ? Layout.horizontal().constraints(Constraint.fill(),
Constraint.length(1), Constraint.fill())
- .split(chartsArea)
- : List.of(chartsArea);
- if (turnTokens.size() > 1) {
- renderTokensPerQuestion(frame, halves.get(0), turnTokens);
- }
- if (showTime) {
- renderTimePerQuestion(frame, halves.get(2), timings);
- }
- }
}
private void renderTokensPerQuestion(Frame frame, Rect chartArea,
List<Integer> turnTokens) {
@@ -378,6 +388,52 @@ final class AiUsageStats {
return combined;
}
+ /** The agent runs and tool calls of the integration since the last reset,
and its GenAI observability level. */
+ GenAiActivity activity() {
+ return GenAiSpanUsageExtractor.activity(otelSpans.get(), usageResetAt);
+ }
+
+ /**
+ * The agent runs with their model and tool calls, or at level basic,
where they are not traced, how to see them.
+ * {@code null} when the integration recorded no Camel GenAI spans.
+ */
+ private static Line activityLine(GenAiActivity activity, Style dimStyle,
Style cyanStyle) {
+ if (activity.level() == null) {
+ return null;
+ }
+ String level = activity.level().name().toLowerCase(Locale.ROOT);
+ if (activity.level() == GenAiObservabilityLevel.BASIC) {
+ return Line.from(
+ Span.styled("GenAI level: ", dimStyle),
+ Span.styled(level, cyanStyle),
+ Span.styled(" " + BASIC_LEVEL_HINT, dimStyle));
+ }
+ return Line.from(
+ Span.styled("Agent runs: ", dimStyle),
+ Span.styled(String.valueOf(activity.agentRuns()), cyanStyle),
+ Span.styled(" (model calls: ", dimStyle),
+ Span.styled(String.valueOf(activity.agentModelCalls()),
cyanStyle),
+ Span.styled(" / tool calls: ", dimStyle),
+ Span.styled(String.valueOf(activity.toolCalls()), cyanStyle),
+ Span.styled(") GenAI level: ", dimStyle),
+ Span.styled(level, cyanStyle));
+ }
+
+ /** Per model: requests, input, output and total tokens, latency, cached
input tokens. */
+ private static Map<String, long[]> perModel(List<AiUsageEntry> entries) {
+ Map<String, long[]> perModel = new LinkedHashMap<>();
+ for (AiUsageEntry e : entries) {
+ long[] stats = perModel.computeIfAbsent(modelTableKey(e), k -> new
long[6]);
+ stats[0]++; // requests
+ stats[1] += e.inputTokens();
+ stats[2] += e.outputTokens();
+ stats[3] += e.totalTokens();
+ stats[4] += e.latencyMs();
+ stats[5] += e.cachedInputTokens();
+ }
+ return perModel;
+ }
+
private static String modelTableKey(AiUsageEntry entry) {
String modelProvider = entry.model() + " (" + entry.provider() + ")";
if (entry.source() == AiUsageSource.ROUTE) {
@@ -387,11 +443,6 @@ final class AiUsageStats {
return "[tui] " + modelProvider;
}
- /**
- * One model round trip. {@code question} is the sequence number of the
panel question the request was made for (a
- * question takes several round trips when the model calls tools), so
usage can be grouped per question; it is 0 for
- * route requests, which belong to no question.
- */
/**
* How many questions the panel's own requests were made for: a question
takes one request per model round trip, and
* consecutive requests with the same question number belong to one
question. Route calls do not count.
@@ -422,15 +473,16 @@ final class AiUsageStats {
+ "their usage here.";
}
int totalInput = 0;
+ int totalCached = 0;
int totalOutput = 0;
int totalTokens = 0;
long totalLatency = 0;
long tuiLatency = 0;
int tuiRequests = 0;
int routeRequests = 0;
- Map<String, long[]> perModel = new LinkedHashMap<>();
for (AiUsageEntry e : entries) {
totalInput += e.inputTokens();
+ totalCached += e.cachedInputTokens();
totalOutput += e.outputTokens();
totalTokens += e.totalTokens();
totalLatency += e.latencyMs();
@@ -440,13 +492,8 @@ final class AiUsageStats {
tuiRequests++;
tuiLatency += e.latencyMs();
}
- long[] stats = perModel.computeIfAbsent(modelTableKey(e), k -> new
long[5]);
- stats[0]++;
- stats[1] += e.inputTokens();
- stats[2] += e.outputTokens();
- stats[3] += e.totalTokens();
- stats[4] += e.latencyMs();
}
+ Map<String, long[]> perModel = perModel(entries);
StringBuilder sb = new StringBuilder();
sb.append("**AI usage:** ").append(entries.size()).append("
request(s)");
if (routeRequests > 0) {
@@ -456,7 +503,20 @@ final class AiUsageStats {
sb.append("\n\n");
sb.append("- **Tokens:** ").append(LlmClient.formatTokens(totalTokens))
.append(" (in ").append(LlmClient.formatTokens(totalInput))
- .append(", out
").append(LlmClient.formatTokens(totalOutput)).append(")\n");
+ .append(", out ").append(LlmClient.formatTokens(totalOutput));
+ if (totalCached > 0) {
+ sb.append(", cached ").append(LlmClient.formatTokens(totalCached));
+ }
+ sb.append(")\n");
+ GenAiActivity activity = activity();
+ if (activity.level() == GenAiObservabilityLevel.BASIC) {
+ sb.append("- **GenAI level:** basic
(").append(BASIC_LEVEL_HINT).append(")\n");
+ } else if (activity.level() != null) {
+ sb.append("- **Agent runs:** ").append(activity.agentRuns())
+ .append(" (").append(activity.agentModelCalls()).append("
model call(s), ")
+ .append(activity.toolCalls()).append(" tool call(s)),
**GenAI level:** ")
+
.append(activity.level().name().toLowerCase(Locale.ROOT)).append("\n");
+ }
int questionCount = countQuestions(entries);
sb.append("- **Avg per question:** ")
.append(formatSeconds(questionCount > 0 ? tuiLatency /
questionCount : totalLatency / entries.size()))
@@ -471,12 +531,13 @@ final class AiUsageStats {
sb.append("- **Last request:**
").append(LlmClient.formatTokens(last.totalTokens()))
.append(" tokens in
").append(formatSeconds(last.latencyMs())).append("\n");
}
- sb.append("\n| Model | Reqs | In | Out | Total | Avg/req
|\n|---|---|---|---|---|---|\n");
+ sb.append("\n| Model | Reqs | In | Cached | Out | Total | Avg/req
|\n|---|---|---|---|---|---|---|\n");
for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
long[] stats = entry.getValue();
sb.append("| ").append(entry.getKey())
.append(" | ").append(stats[0])
.append(" | ").append(LlmClient.formatTokens((int)
stats[1]))
+ .append(" | ").append(stats[5] > 0 ?
LlmClient.formatTokens((int) stats[5]) : "-")
.append(" | ").append(LlmClient.formatTokens((int)
stats[2]))
.append(" | ").append(LlmClient.formatTokens((int)
stats[3]))
.append(" | ").append(formatSeconds(stats[4] / stats[0]))
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractor.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractor.java
index ad78b4972c25..dcfd1f8c2a22 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractor.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractor.java
@@ -18,19 +18,56 @@ package org.apache.camel.dsl.jbang.core.commands.tui;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.apache.camel.component.ai.observability.GenAiAttributes;
+import org.apache.camel.component.ai.observability.GenAiObservabilityLevel;
+import org.apache.camel.component.ai.observability.GenAiOperationName;
/**
* Converts OTel spans exported from monitored Camel integrations into AI
usage entries for the TUI stats view.
*/
final class GenAiSpanUsageExtractor {
+ /**
+ * The GenAI operations that are not a model call: an agent run and a tool
call (observability level detailed and
+ * above), and {@code create_agent} of the OpenTelemetry conventions,
which AI frameworks may record.
+ */
+ private static final Set<String> NON_MODEL_OPERATIONS = Set.of(
+ GenAiOperationName.INVOKE_AGENT.value(),
GenAiOperationName.EXECUTE_TOOL.value(), "create_agent");
+
+ /** The attributes only recorded at observability level detailed and
above. */
+ private static final List<String> DETAILED_ATTRIBUTES = List.of(
+ GenAiAttributes.PROVIDER_NAME, GenAiAttributes.AGENT_NAME,
GenAiAttributes.TOOL_NAME,
+ GenAiAttributes.CONVERSATION_ID,
GenAiAttributes.CACHE_READ_INPUT_TOKENS);
+
+ /** The attributes only recorded at observability level full. */
+ private static final List<String> FULL_ATTRIBUTES = List.of(
+ GenAiAttributes.INPUT_MESSAGES, GenAiAttributes.OUTPUT_MESSAGES,
GenAiAttributes.SYSTEM_INSTRUCTIONS,
+ GenAiAttributes.TOOL_CALL_ARGUMENTS,
GenAiAttributes.TOOL_CALL_RESULT);
+
+ private static final int MAX_PARENT_HOPS = 50;
+
+ /**
+ * The agent runs and tool calls among the GenAI spans, and the
observability level they were recorded at.
+ *
+ * @param agentRuns the {@code invoke_agent} spans
+ * @param agentModelCalls the model calls made inside an agent run
+ * @param toolCalls the {@code execute_tool} spans
+ * @param level the level the Camel GenAI spans show, or {@code
null} when there are none
+ */
+ record GenAiActivity(int agentRuns, int agentModelCalls, int toolCalls,
GenAiObservabilityLevel level) {
+
+ static final GenAiActivity NONE = new GenAiActivity(0, 0, 0, null);
+ }
+
private GenAiSpanUsageExtractor() {
}
+ /** Any GenAI span: a model call, an agent run or a tool call. */
static boolean isGenAiSpan(SpanEntry span) {
if (span == null || span.attributes() == null) {
return false;
@@ -38,16 +75,36 @@ final class GenAiSpanUsageExtractor {
return span.attributes().containsKey(GenAiAttributes.OPERATION_NAME);
}
- static List<AiPanel.AiUsageEntry> extract(List<SpanEntry> spans) {
+ /**
+ * A GenAI span of one model call (chat, embeddings, generate_content,
...), not an agent run or a tool call. An
+ * operation the Camel observability does not know, such as one recorded
by an AI framework, counts as a model call.
+ */
+ static boolean isModelCall(SpanEntry span) {
+ return isGenAiSpan(span) &&
!NON_MODEL_OPERATIONS.contains(operation(span));
+ }
+
+ /** The provider of a GenAI span: {@code gen_ai.system}, else the newer
{@code gen_ai.provider.name}. */
+ static String provider(Map<String, Object> attrs) {
+ String provider = stringAttr(attrs, GenAiAttributes.SYSTEM);
+ if (isBlank(provider) || "unknown".equalsIgnoreCase(provider)) {
+ String name = stringAttr(attrs, GenAiAttributes.PROVIDER_NAME);
+ if (!isBlank(name)) {
+ return name;
+ }
+ }
+ return provider;
+ }
+
+ static List<AiUsageEntry> extract(List<SpanEntry> spans) {
if (spans == null || spans.isEmpty()) {
return List.of();
}
- List<AiPanel.AiUsageEntry> entries = new ArrayList<>();
+ List<AiUsageEntry> entries = new ArrayList<>();
for (SpanEntry span : spans) {
- if (!isGenAiSpan(span)) {
+ if (!isModelCall(span)) {
continue;
}
- AiPanel.AiUsageEntry entry = toUsageEntry(span);
+ AiUsageEntry entry = toUsageEntry(span);
if (entry != null) {
entries.add(entry);
}
@@ -55,7 +112,7 @@ final class GenAiSpanUsageExtractor {
return List.copyOf(entries);
}
- private static AiPanel.AiUsageEntry toUsageEntry(SpanEntry span) {
+ private static AiUsageEntry toUsageEntry(SpanEntry span) {
Map<String, Object> attrs = span.attributes();
String requestModel = stringAttr(attrs, GenAiAttributes.REQUEST_MODEL);
String responseModel = stringAttr(attrs,
GenAiAttributes.RESPONSE_MODEL);
@@ -64,7 +121,7 @@ final class GenAiSpanUsageExtractor {
model = span.name() != null ? span.name() : "unknown";
}
- String provider = stringAttr(attrs, GenAiAttributes.SYSTEM);
+ String provider = provider(attrs);
if (isBlank(provider)) {
provider = "unknown";
}
@@ -72,6 +129,7 @@ final class GenAiSpanUsageExtractor {
int inputTokens = intAttr(attrs, GenAiAttributes.INPUT_TOKENS);
int outputTokens = intAttr(attrs, GenAiAttributes.OUTPUT_TOKENS);
int totalTokens = inputTokens + outputTokens;
+ int cachedInputTokens = intAttr(attrs,
GenAiAttributes.CACHE_READ_INPUT_TOKENS);
long latencyMs = span.durationMs() > 0 ? span.durationMs() : 0;
String stopReason = stringAttr(attrs, GenAiAttributes.FINISH_REASONS);
@@ -79,7 +137,7 @@ final class GenAiSpanUsageExtractor {
? Instant.ofEpochSecond(0, span.startEpochNanos())
: Instant.EPOCH;
- return new AiPanel.AiUsageEntry(
+ return new AiUsageEntry(
model,
provider,
inputTokens,
@@ -88,8 +146,86 @@ final class GenAiSpanUsageExtractor {
latencyMs,
stopReason,
timestamp,
- AiPanel.AiUsageSource.ROUTE,
- span.routeId());
+ AiUsageSource.ROUTE,
+ span.routeId(),
+ 0,
+ cachedInputTokens);
+ }
+
+ /**
+ * Counts the agent runs, their model calls and the tool calls among the
spans started at or after {@code since},
+ * and tells the observability level from the attributes of the Camel
GenAI spans: the level is not exported with
+ * the spans, but each level records attributes the level below does not.
+ */
+ static GenAiActivity activity(List<SpanEntry> spans, Instant since) {
+ if (spans == null || spans.isEmpty()) {
+ return GenAiActivity.NONE;
+ }
+ long sinceNanos = since != null && since.isAfter(Instant.EPOCH)
+ ? since.getEpochSecond() * 1_000_000_000L + since.getNano() :
0;
+ Map<String, SpanEntry> byId = new HashMap<>();
+ for (SpanEntry span : spans) {
+ if (span != null && span.spanId() != null) {
+ byId.put(span.spanId(), span);
+ }
+ }
+ int agentRuns = 0;
+ int agentModelCalls = 0;
+ int toolCalls = 0;
+ GenAiObservabilityLevel level = null;
+ for (SpanEntry span : spans) {
+ if (!isGenAiSpan(span) || span.startEpochNanos() < sinceNanos) {
+ continue;
+ }
+ String operation = operation(span);
+ if (GenAiOperationName.INVOKE_AGENT.value().equals(operation)) {
+ agentRuns++;
+ } else if
(GenAiOperationName.EXECUTE_TOOL.value().equals(operation)) {
+ toolCalls++;
+ } else if (isModelCall(span) && insideAgentRun(span, byId)) {
+ agentModelCalls++;
+ }
+ if (span.isCamelSpan()) {
+ GenAiObservabilityLevel spanLevel = levelOf(span, operation);
+ if (level == null || spanLevel.includes(level)) {
+ level = spanLevel;
+ }
+ }
+ }
+ return new GenAiActivity(agentRuns, agentModelCalls, toolCalls, level);
+ }
+
+ private static GenAiObservabilityLevel levelOf(SpanEntry span, String
operation) {
+ Map<String, Object> attrs = span.attributes();
+ for (String key : FULL_ATTRIBUTES) {
+ if (attrs.containsKey(key)) {
+ return GenAiObservabilityLevel.FULL;
+ }
+ }
+ if (NON_MODEL_OPERATIONS.contains(operation)) {
+ return GenAiObservabilityLevel.DETAILED;
+ }
+ for (String key : DETAILED_ATTRIBUTES) {
+ if (attrs.containsKey(key)) {
+ return GenAiObservabilityLevel.DETAILED;
+ }
+ }
+ return GenAiObservabilityLevel.BASIC;
+ }
+
+ private static boolean insideAgentRun(SpanEntry span, Map<String,
SpanEntry> byId) {
+ SpanEntry current = span;
+ for (int hops = 0; hops < MAX_PARENT_HOPS && current != null &&
!current.isRoot(); hops++) {
+ current = byId.get(current.parentSpanId());
+ if (current != null &&
GenAiOperationName.INVOKE_AGENT.value().equals(operation(current))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String operation(SpanEntry span) {
+ return span.attributes() != null ? stringAttr(span.attributes(),
GenAiAttributes.OPERATION_NAME) : null;
}
private static String stringAttr(Map<String, Object> attrs, String key) {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
index 40609043b784..5899edddbef3 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
@@ -644,11 +644,12 @@ final class OllamaMonitor {
List<RequestEntry> fresh = new ArrayList<>();
synchronized (lock) {
for (SpanEntry span : spans) {
- if (!GenAiSpanUsageExtractor.isGenAiSpan(span) ||
span.spanId() == null) {
+ // agent runs and tool calls are not requests to Ollama
(observability level detailed)
+ if (!GenAiSpanUsageExtractor.isModelCall(span) ||
span.spanId() == null) {
continue;
}
- Object system = span.attributes().get(GenAiAttributes.SYSTEM);
- if (system == null ||
!system.toString().toLowerCase(Locale.ROOT).contains("ollama")) {
+ String system =
GenAiSpanUsageExtractor.provider(span.attributes());
+ if (system == null ||
!system.toLowerCase(Locale.ROOT).contains("ollama")) {
continue;
}
if (!seenSpanIds.add(span.spanId())) {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelGenAiUsageTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelGenAiUsageTest.java
index f6703801c68f..17008e72a9ab 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelGenAiUsageTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelGenAiUsageTest.java
@@ -17,6 +17,7 @@
package org.apache.camel.dsl.jbang.core.commands.tui;
import java.time.Instant;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
@@ -46,14 +47,14 @@ class AiPanelGenAiUsageTest {
void combinedUsageIncludesRouteGenAiSpans() {
AiPanel panel = new AiPanel();
panel.setOtelSpans(spans);
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"gpt-4o-mini", "openai", 10, 5, 15, 1000, "stop",
Instant.now()));
spans.set(List.of(routeSpan("route-chat", "gpt-4o", 100, 20)));
assertThat(panel.combinedUsageEntriesForTesting()).hasSize(2);
assertThat(panel.combinedUsageEntriesForTesting())
- .anyMatch(entry -> entry.source() ==
AiPanel.AiUsageSource.ROUTE
+ .anyMatch(entry -> entry.source() == AiUsageSource.ROUTE
&& "route-chat".equals(entry.routeId()));
}
@@ -62,7 +63,7 @@ class AiPanelGenAiUsageTest {
AiPanel panel = new AiPanel();
panel.setOtelSpans(spans);
panel.open();
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"gpt-4o-mini", "openai", 10, 5, 15, 1000, "stop",
Instant.now()));
spans.set(List.of(routeSpan("orders", "gpt-4o", 50, 10)));
panel.toggleStatsViewForTesting();
@@ -85,7 +86,7 @@ class AiPanelGenAiUsageTest {
panel.setOtelSpans(spans);
panel.open();
for (int i = 0; i < 12; i++) {
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"model-" + (char) ('a' + i), "openai", 10, 5, 15, 1000,
"stop", Instant.now()));
}
panel.toggleStatsViewForTesting();
@@ -138,6 +139,93 @@ class AiPanelGenAiUsageTest {
.contains("GenAI observability");
}
+ @Test
+ void statsViewCountsOnlyTheModelCallsOfAnAgentRun() {
+ AiPanel panel = new AiPanel();
+ panel.setOtelSpans(spans);
+ panel.open();
+ spans.set(agentRunSpans());
+ panel.toggleStatsViewForTesting();
+
+ assertThat(panel.combinedUsageEntriesForTesting()).hasSize(2);
+ String rendered = render(panel, new Rect(0, 0, 140, 24));
+ assertThat(rendered)
+ .contains("integration: 2")
+ .contains("cached: 800")
+ .contains("CACHED")
+ .contains("Agent runs: 1")
+ .contains("model calls: 2")
+ .contains("tool calls: 1")
+ .contains("GenAI level: detailed")
+ .doesNotContain("execute_tool")
+ // the panel itself called no tools: its tool time would read
as the integration's
+ .doesNotContain("Tool time");
+ }
+
+ @Test
+ void statsViewExplainsLevelBasic() {
+ AiPanel panel = new AiPanel();
+ panel.setOtelSpans(spans);
+ panel.open();
+ spans.set(List.of(routeSpan("orders", "gpt-4o", 50, 10)));
+ panel.toggleStatsViewForTesting();
+
+ assertThat(render(panel, new Rect(0, 0, 140, 24)))
+ .contains("GenAI level: basic")
+ .contains("agent runs and tool calls are not traced");
+ }
+
+ @Test
+ void usageSummaryListsAgentRunsAndCachedTokens() {
+ spans.set(agentRunSpans());
+
+ AiUsageStats stats = new AiUsageStats();
+ stats.setOtelSpans(spans);
+ assertThat(stats.summary())
+ .contains("2 request(s) (0 from this panel, 2 from the
integration)")
+ .contains("cached 800")
+ .contains("**Agent runs:** 1 (2 model call(s), 1 tool
call(s)), **GenAI level:** detailed")
+ .contains("| Model | Reqs | In | Cached | Out | Total |
Avg/req |");
+ }
+
+ /** An agent run at level detailed: invoke_agent with two chat calls and a
tool call under it. */
+ private static List<SpanEntry> agentRunSpans() {
+ long start = Instant.now().getEpochSecond() * 1_000_000_000L;
+ SpanEntry agent = new SpanEntry(
+ "trace-1", "agent", "", "invoke_agent support", "INTERNAL",
"OK", start, start + 3_000_000_000L, 3000,
+ "support", null, "camel",
+ Map.of(GenAiAttributes.OPERATION_NAME, "invoke_agent",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1",
+ GenAiAttributes.AGENT_NAME, "support"));
+ SpanEntry tool = new SpanEntry(
+ "trace-1", "tool", "agent", "execute_tool lookupOrder",
"INTERNAL", "OK", start, start + 200_000_000L,
+ 200, "support", null, "camel",
+ Map.of(GenAiAttributes.OPERATION_NAME, "execute_tool",
GenAiAttributes.TOOL_NAME, "lookupOrder"));
+ return List.of(agent,
+ chatSpan("chat1", start, 1000, 100, 0),
+ tool,
+ chatSpan("chat2", start, 1200, 100, 800));
+ }
+
+ private static SpanEntry chatSpan(String spanId, long start, int input,
int output, long cached) {
+ Map<String, Object> attrs = new HashMap<>(
+ Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1",
+ GenAiAttributes.INPUT_TOKENS, input,
+ GenAiAttributes.OUTPUT_TOKENS, output));
+ if (cached > 0) {
+ attrs.put(GenAiAttributes.CACHE_READ_INPUT_TOKENS, cached);
+ }
+ return new SpanEntry(
+ "trace-1", spanId, "agent", "chat gpt-4.1", "CLIENT", "OK",
start, start + 1_000_000_000L, 1000,
+ "support", null, "camel", attrs);
+ }
+
private static SpanEntry routeSpan(String routeId, String model, int
input, int output) {
return new SpanEntry(
"trace-1",
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
index a24dd65997ee..83de46ed6848 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
@@ -159,6 +159,21 @@ class AiPanelTest {
assertTrue(panel.conversationForTesting().stream().anyMatch(entry ->
entry.role() == AiRole.USER));
}
+ @Test
+ void usageOfThePanelKeepsTheCachedTokensTheProviderReports() throws
Exception {
+ AiPanel panel = new AiPanel();
+ RecordingLlmClient client = new RecordingLlmClient("ok", new
LlmClient.TokenUsage(1000, 50, 1050, 800, 0, 0, 0, 0));
+ panel.setClientForTesting(client);
+ panel.open();
+
+ type(panel, "what routes are running?");
+ panel.handleKeyEvent(KeyEvent.ofKey(KeyCode.ENTER, KeyModifiers.NONE));
+
+ assertTrue(client.awaitAnswer(5, TimeUnit.SECONDS));
+ await().atMost(5, TimeUnit.SECONDS).untilAsserted(
+ () -> assertTrue(panel.usageSummary().contains("cached 800"),
panel.usageSummary()));
+ }
+
@Test
void slashInputDoesNotGoToLlm() {
AiPanel panel = new AiPanel();
@@ -1498,21 +1513,21 @@ class AiPanelTest {
panel.setClientForTesting(new RecordingLlmClient("ok"));
// question 1 took three round trips, question 2 one; a route call is
not a question
Instant now = Instant.now();
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"m", "ollama", 4_000, 20, 4_020, 3_000, "tool_calls", now,
- AiPanel.AiUsageSource.TUI, null, 1));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ AiUsageSource.TUI, null, 1, 0));
+ panel.recordUsageForTesting(new AiUsageEntry(
"m", "ollama", 4_100, 20, 4_120, 1_000, "tool_calls", now,
- AiPanel.AiUsageSource.TUI, null, 1));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ AiUsageSource.TUI, null, 1, 0));
+ panel.recordUsageForTesting(new AiUsageEntry(
"m", "ollama", 4_300, 90, 4_390, 2_000, "stop", now,
- AiPanel.AiUsageSource.TUI, null, 1));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ AiUsageSource.TUI, null, 1, 0));
+ panel.recordUsageForTesting(new AiUsageEntry(
"m", "ollama", 4_400, 30, 4_430, 2_000, "stop", now,
- AiPanel.AiUsageSource.TUI, null, 2));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ AiUsageSource.TUI, null, 2, 0));
+ panel.recordUsageForTesting(new AiUsageEntry(
"m", "ollama", 400, 30, 430, 8_000, "stop", now,
- AiPanel.AiUsageSource.ROUTE, "chat-route", 0));
+ AiUsageSource.ROUTE, "chat-route", 0, 0));
assertEquals(2,
AiUsageStats.countQuestions(panel.combinedUsageEntriesForTesting()));
String summary = panel.usageSummary();
@@ -1526,9 +1541,9 @@ class AiPanelTest {
panel.setClientForTesting(new RecordingLlmClient("ok"));
assertTrue(panel.usageSummary().startsWith("No AI usage yet"));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"qwen3.6:35b-a3b", "ollama", 3000, 100, 3100, 5000,
"end_turn", Instant.now()));
- panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+ panel.recordUsageForTesting(new AiUsageEntry(
"qwen3.6:35b-a3b", "ollama", 3200, 200, 3400, 2000,
"end_turn", Instant.now()));
String summary = panel.usageSummary();
@@ -1537,7 +1552,7 @@ class AiPanelTest {
assertTrue(summary.contains("- **Tokens:** 6.5k (in 6.2k, out 300)"),
summary);
// two requests without a question number are one question of 7.0s
assertTrue(summary.contains("- **Avg per question:** 7.0s (3.5s per
request)"), summary);
- assertTrue(summary.contains("| [tui] qwen3.6:35b-a3b (ollama) | 2 |
6.2k | 300 | 6.5k | 3.5s |"), summary);
+ assertTrue(summary.contains("| [tui] qwen3.6:35b-a3b (ollama) | 2 |
6.2k | - | 300 | 6.5k | 3.5s |"), summary);
assertTrue(summary.contains("- **Last request:** 3.4k tokens in
2.0s"), summary);
}
@@ -1579,10 +1594,10 @@ class AiPanelTest {
assertFalse(TuiTestHelper.bufferToString(buffer).contains("Tokens per
question:"));
}
- private static AiPanel.AiUsageEntry usage(int tokens, Instant at, int
question) {
- return new AiPanel.AiUsageEntry(
+ private static AiUsageEntry usage(int tokens, Instant at, int question) {
+ return new AiUsageEntry(
"qwen3.6:35b-a3b", "ollama", tokens - 100, 100, tokens, 1000,
"end_turn", at,
- AiPanel.AiUsageSource.TUI, null, question);
+ AiUsageSource.TUI, null, question, 0);
}
@Test
@@ -1915,11 +1930,17 @@ class AiPanelTest {
private static final class RecordingLlmClient extends LlmClient {
private final String response;
+ private final TokenUsage usage;
private final CountDownLatch answered = new CountDownLatch(1);
private volatile String lastQuestion;
RecordingLlmClient(String response) {
+ this(response, TokenUsage.EMPTY);
+ }
+
+ RecordingLlmClient(String response, TokenUsage usage) {
this.response = response;
+ this.usage = usage;
withModel("test-model");
withApiType(ApiType.openai);
}
@@ -1939,7 +1960,7 @@ class AiPanelTest {
}
}
answered.countDown();
- return new ChatResponse(response, null, "end_turn", false,
TokenUsage.EMPTY);
+ return new ChatResponse(response, null, "end_turn", false, usage);
}
String lastQuestion() {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractorTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractorTest.java
index 67cb3204ec7c..fb9b2fc12208 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractorTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractorTest.java
@@ -17,10 +17,12 @@
package org.apache.camel.dsl.jbang.core.commands.tui;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.component.ai.observability.GenAiAttributes;
+import org.apache.camel.component.ai.observability.GenAiObservabilityLevel;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -48,11 +50,11 @@ class GenAiSpanUsageExtractorTest {
GenAiAttributes.OUTPUT_TOKENS, 45,
GenAiAttributes.FINISH_REASONS, "stop"));
- List<AiPanel.AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(span));
+ List<AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(span));
assertThat(entries).hasSize(1);
- AiPanel.AiUsageEntry entry = entries.get(0);
- assertThat(entry.source()).isEqualTo(AiPanel.AiUsageSource.ROUTE);
+ AiUsageEntry entry = entries.get(0);
+ assertThat(entry.source()).isEqualTo(AiUsageSource.ROUTE);
assertThat(entry.model()).isEqualTo("gpt-4o-mini");
assertThat(entry.provider()).isEqualTo("openai");
assertThat(entry.inputTokens()).isEqualTo(120);
@@ -73,7 +75,7 @@ class GenAiSpanUsageExtractorTest {
GenAiAttributes.INPUT_TOKENS, "10",
GenAiAttributes.OUTPUT_TOKENS, "0"));
- List<AiPanel.AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(camelSpan, genAi));
+ List<AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(camelSpan, genAi));
assertThat(entries).hasSize(1);
assertThat(entries.get(0).model()).isEqualTo("text-embedding-3-small");
@@ -96,12 +98,163 @@ class GenAiSpanUsageExtractorTest {
.isEqualTo("embeddings unknown-model");
}
+ @Test
+ void isModelCallLeavesOutAgentRunsAndToolCalls() {
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"chat")))).isTrue();
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"embeddings"))))
+ .isTrue();
+ // an operation recorded by an AI framework, unknown to the Camel
observability, still is a model call
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"text_completion"))))
+ .isTrue();
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"invoke_agent"))))
+ .isFalse();
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"execute_tool"))))
+ .isFalse();
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"create_agent"))))
+ .isFalse();
+
assertThat(GenAiSpanUsageExtractor.isModelCall(span(Map.of("http.method",
"GET")))).isFalse();
+ }
+
+ @Test
+ void extractCountsOnlyTheModelCallsOfAnAgentRun() {
+ List<SpanEntry> run = agentRun();
+
+ List<AiUsageEntry> entries = GenAiSpanUsageExtractor.extract(run);
+
+ assertThat(entries).hasSize(2);
+ assertThat(entries).allSatisfy(entry -> {
+ assertThat(entry.model()).isEqualTo("gpt-4.1");
+ assertThat(entry.provider()).isEqualTo("openai");
+ });
+
assertThat(entries).extracting(AiUsageEntry::totalTokens).containsExactly(1100,
1300);
+
assertThat(entries).extracting(AiUsageEntry::cachedInputTokens).containsExactly(0,
800);
+ }
+
+ @Test
+ void extractFallsBackToProviderName() {
+ SpanEntry span = span(Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.PROVIDER_NAME, "anthropic",
+ GenAiAttributes.REQUEST_MODEL, "claude-sonnet-5-5"));
+ SpanEntry unknownSystem = span(Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "unknown",
+ GenAiAttributes.PROVIDER_NAME, "ollama",
+ GenAiAttributes.REQUEST_MODEL, "qwen3:8b"));
+
+
assertThat(GenAiSpanUsageExtractor.extract(List.of(span)).get(0).provider()).isEqualTo("anthropic");
+
assertThat(GenAiSpanUsageExtractor.extract(List.of(unknownSystem)).get(0).provider()).isEqualTo("ollama");
+ }
+
+ @Test
+ void activityCountsAgentRunsAndToolCalls() {
+ List<SpanEntry> spans = new ArrayList<>(agentRun());
+ // a model call outside any agent run
+ spans.add(span("s9", "", "chat gpt-4.1", Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1")));
+
+ GenAiSpanUsageExtractor.GenAiActivity activity =
GenAiSpanUsageExtractor.activity(spans, Instant.EPOCH);
+
+ assertThat(activity.agentRuns()).isEqualTo(1);
+ assertThat(activity.agentModelCalls()).isEqualTo(2);
+ assertThat(activity.toolCalls()).isEqualTo(1);
+
assertThat(activity.level()).isEqualTo(GenAiObservabilityLevel.DETAILED);
+ }
+
+ @Test
+ void activityTellsTheObservabilityLevel() {
+ SpanEntry basic = span(Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1"));
+ SpanEntry full = span("s2", "", "chat gpt-4.1", Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.INPUT_MESSAGES,
"[{\"role\":\"user\",\"parts\":[]}]"));
+ SpanEntry framework = new SpanEntry(
+ "trace-1", "s3", "", "chat", "CLIENT", "OK", 0, 0, 10, null,
null, "dev.langchain4j",
+ Map.of(GenAiAttributes.OPERATION_NAME, "chat",
GenAiAttributes.PROVIDER_NAME, "openai"));
+
+ assertThat(GenAiSpanUsageExtractor.activity(List.of(basic),
Instant.EPOCH).level())
+ .isEqualTo(GenAiObservabilityLevel.BASIC);
+ assertThat(GenAiSpanUsageExtractor.activity(List.of(basic, full),
Instant.EPOCH).level())
+ .isEqualTo(GenAiObservabilityLevel.FULL);
+ // the spans of an AI framework do not tell the level of the Camel
observability
+ assertThat(GenAiSpanUsageExtractor.activity(List.of(framework),
Instant.EPOCH).level()).isNull();
+ assertThat(GenAiSpanUsageExtractor.activity(List.of(),
Instant.EPOCH).level()).isNull();
+ }
+
+ @Test
+ void activityLeavesOutSpansBeforeTheReset() {
+ Instant afterTheRun = Instant.parse("2026-08-13T12:00:01Z");
+
+ GenAiSpanUsageExtractor.GenAiActivity activity =
GenAiSpanUsageExtractor.activity(agentRun(), afterTheRun);
+
+ assertThat(activity.agentRuns()).isZero();
+ assertThat(activity.toolCalls()).isZero();
+ assertThat(activity.level()).isNull();
+ }
+
@Test
void extractReturnsEmptyListForNullOrEmptyInput() {
assertThat(GenAiSpanUsageExtractor.extract(null)).isEmpty();
assertThat(GenAiSpanUsageExtractor.extract(List.of())).isEmpty();
}
+ /** An agent run at level detailed: invoke_agent, then chat, execute_tool
and chat nested under it. */
+ private static List<SpanEntry> agentRun() {
+ SpanEntry agent = span("agent", "", "invoke_agent support", Map.of(
+ GenAiAttributes.OPERATION_NAME, "invoke_agent",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1",
+ GenAiAttributes.AGENT_NAME, "support",
+ GenAiAttributes.FINISH_REASONS, "stop"));
+ SpanEntry chat1 = span("chat1", "agent", "chat gpt-4.1", Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1",
+ GenAiAttributes.INPUT_TOKENS, 1000,
+ GenAiAttributes.OUTPUT_TOKENS, 100,
+ GenAiAttributes.FINISH_REASONS, "tool_calls"));
+ // the execute_tool span has no system nor model
+ SpanEntry tool = span("tool", "agent", "execute_tool lookupOrder",
Map.of(
+ GenAiAttributes.OPERATION_NAME, "execute_tool",
+ GenAiAttributes.TOOL_NAME, "lookupOrder"));
+ SpanEntry chat2 = span("chat2", "agent", "chat gpt-4.1", Map.of(
+ GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.SYSTEM, "openai",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.REQUEST_MODEL, "gpt-4.1",
+ GenAiAttributes.INPUT_TOKENS, 1200,
+ GenAiAttributes.OUTPUT_TOKENS, 100,
+ GenAiAttributes.CACHE_READ_INPUT_TOKENS, 800L,
+ GenAiAttributes.FINISH_REASONS, "stop"));
+ return List.of(agent, chat1, tool, chat2);
+ }
+
+ private static SpanEntry span(String spanId, String parentSpanId, String
name, Map<String, Object> attributes) {
+ return new SpanEntry(
+ "trace-1",
+ spanId,
+ parentSpanId,
+ name,
+ "CLIENT",
+ "OK",
+ Instant.parse("2026-08-13T12:00:00Z").getEpochSecond() *
1_000_000_000L,
+ Instant.parse("2026-08-13T12:00:00.250Z").getEpochSecond() *
1_000_000_000L,
+ 250,
+ "route-a",
+ null,
+ "camel",
+ attributes);
+ }
+
private static SpanEntry span(Map<String, Object> attributes) {
return span("chat gpt-4o-mini", attributes);
}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
index d336ffa6be97..6489b4c76283 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
@@ -146,6 +146,36 @@ class OllamaMonitorTest {
assertEquals(OllamaMonitor.MAX_REQUESTS + 5,
monitor.snapshot().totals().requests());
}
+ @Test
+ void agentRunAndToolSpansAreNotOllamaRequests() {
+ OllamaMonitor monitor = new OllamaMonitor();
+ SpanEntry chat = genAiSpan("s1", "ollama", "qwen3:8b", "agent-route",
300, 40, 900);
+ Map<String, Object> agentAttrs = new HashMap<>(chat.attributes());
+ agentAttrs.put(GenAiAttributes.OPERATION_NAME, "invoke_agent");
+ agentAttrs.remove(GenAiAttributes.INPUT_TOKENS);
+ agentAttrs.remove(GenAiAttributes.OUTPUT_TOKENS);
+ SpanEntry agent = new SpanEntry(
+ "trace-1", "s0", null, "invoke_agent agent-route", "INTERNAL",
"OK", chat.startEpochNanos(),
+ chat.endEpochNanos(), 1500, "agent-route", null, null,
agentAttrs);
+ SpanEntry tool = new SpanEntry(
+ "trace-1", "s2", "s0", "execute_tool lookup", "INTERNAL",
"OK", chat.startEpochNanos(),
+ chat.endEpochNanos(), 20, "agent-route", null, null,
+ Map.of(GenAiAttributes.OPERATION_NAME, "execute_tool",
GenAiAttributes.TOOL_NAME, "lookup"));
+ // at level detailed only gen_ai.provider.name may name the provider
+ Map<String, Object> providerOnly = new HashMap<>(chat.attributes());
+ providerOnly.remove(GenAiAttributes.SYSTEM);
+ providerOnly.put(GenAiAttributes.PROVIDER_NAME, "ollama");
+ SpanEntry chat2 = new SpanEntry(
+ "trace-1", "s3", "s0", chat.name(), "CLIENT", "OK",
chat.startEpochNanos(), chat.endEpochNanos(), 700,
+ "agent-route", null, null, providerOnly);
+
+ monitor.ingestSpans(List.of(agent, chat, tool, chat2));
+
+ List<RequestEntry> requests = monitor.snapshot().requests();
+ assertEquals(2, requests.size());
+ assertTrue(requests.stream().allMatch(r ->
"qwen3:8b".equals(r.model())));
+ }
+
@Test
void routeSpansBecomeRouteRequestsOnlyForOllamaAndOnlyOnce() {
OllamaMonitor monitor = new OllamaMonitor();
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceSizeTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceSizeTest.java
index f4bb1bde10d5..4b3ebcfd243e 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceSizeTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceSizeTest.java
@@ -56,9 +56,8 @@ class SourceSizeTest {
/** The files and the methods (class.method) over the limits, and the most
lines each may have. */
private static final String OVER_THE_LIMITS = """
- AiPanel.java 3093
+ AiPanel.java 3070
AiPanel.runAgentLoop 156
- AiUsageStats.render 166
CamelMonitor.java 2632
DiagramSupport.java 2360
DiagramSupport.loadHighlightedNativeDiagramInBackground 200