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 4c7013e49a45 CAMEL-27313: camel-jbang - the AI usage view reads the
GenAI calls from the genai dev console (#30543)
4c7013e49a45 is described below
commit 4c7013e49a45e6154d959a08c18a230b28fa2c69
Author: Claus Ibsen <[email protected]>
AuthorDate: Sat Nov 21 09:42:12 2026 +0100
CAMEL-27313: camel-jbang - the AI usage view reads the GenAI calls from the
genai dev console (#30543)
The Camel TUI AI usage view (Ctrl+U) reads the GenAI calls of the
integration from the genai dev console instead of the span dump: no --observe
needed, the level comes from the console, and the view refreshes every 2
seconds while it is open. It says when the integration does not record because
its dev console is off. GenAiSpanUsageExtractor is removed; the Spans and
Ollama tabs keep reading the spans.
_Claude Code on behalf of Claus Ibsen_
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../modules/ROOT/pages/camel-jbang-tui-ai.adoc | 20 +-
.../camel/dsl/jbang/core/commands/tui/AiPanel.java | 11 +-
.../dsl/jbang/core/commands/tui/AiUsageStats.java | 57 +++--
.../dsl/jbang/core/commands/tui/CamelMonitor.java | 11 +-
.../core/commands/tui/DataRefreshService.java | 31 +++
.../jbang/core/commands/tui/GenAiConsoleUsage.java | 140 +++++++++++
.../core/commands/tui/GenAiSpanUsageExtractor.java | 70 ------
.../dsl/jbang/core/commands/tui/TabRegistry.java | 1 +
.../core/commands/tui/AiPanelGenAiUsageTest.java | 165 ++++++------
.../core/commands/tui/GenAiConsoleUsageTest.java | 124 +++++++++
.../commands/tui/GenAiSpanUsageExtractorTest.java | 280 ---------------------
.../jbang/core/commands/tui/SourceSizeTest.java | 2 +-
12 files changed, 436 insertions(+), 476 deletions(-)
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 4efa14d86ade..c32e98bc92d2 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
@@ -84,7 +84,7 @@ cycles backward.
| Send the last question again, starting from a clean turn in the model
history.
| `/usage [reset]` (`/u`)
-| Print the AI usage so far in the chat: requests, tokens in and out, average
latency, one line per model (and per route when GenAI spans are observed), and
the last request. *Ctrl+U* opens the full view with the per-question chart.
`/usage reset` clears the counters and the chart without touching the
conversation; GenAI spans recorded before the reset are hidden from the view as
well.
+| Print the AI usage so far in the chat: requests, tokens in and out, average
latency, one line per model (and per route for the GenAI calls of the
integration), and the last request. *Ctrl+U* opens the full view with the
per-question chart. `/usage reset` clears the counters and the chart without
touching the conversation; GenAI calls the integration made before the reset
are hidden from the view as well.
| `/copy` (`/y`), `/export` (`/e`)
| The same as *Ctrl+Y* (copy the last response) and *Ctrl+E* (export the
conversation to Markdown). Copying is code-aware: when the response has one
fenced code block only the code is copied (without the fences and the prose,
which is what selecting it with the mouse cannot give you because of the panel
borders); when it has several, a picker lists the blocks with their language
and size plus the whole response; when it has none, the whole response is
copied.
@@ -204,7 +204,10 @@ still copies only the code of a block.
Press *Ctrl+U* while the AI panel is open to toggle the AI Usage view. It
shows token consumption from
the embedded AI prompt (*TUI ask*) and from LLM calls made by the monitored
integration (*integration*),
-the latter taken from OpenTelemetry GenAI spans when observability is enabled
on the integration. The
+the latter taken from the `genai` dev console of camel-ai-observability. That
needs no tracer and no `--observe`:
+`camel run` adds camel-ai-observability when a `camel.aiObservability` option
is set (such as the level), and the
+console records while the dev console is on, as with `camel run`. The view
refreshes every few seconds while it is
+open. The
*Tokens per question* chart has one bar per question you asked, so a question
that needed several tool
calls shows as a single bar. The summary line splits the session time into *AI
time* (waiting for the
model) and *Tool time* (running the TUI tools the model called, with the
number of calls), the summary line gives the
@@ -213,13 +216,12 @@ the average per request for that model, and the *Time per
question* chart next t
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.
+(`camel.aiObservability.level`), the console records each agent run with its
model calls and tool calls. The view
+counts its model calls, and a third summary line gives the agent runs, their
model and tool calls, and the level of
+the integration. At the default level `basic`, agent runs and tool calls are
not recorded: 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,
+and it also says when the integration does not record because its dev console
is off. The *CACHED* column shows the
+input tokens served from the provider's prompt cache, when the provider
reports them.
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]
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 b79c92b6d771..0bde898f9cad 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
@@ -69,7 +69,6 @@ import
org.apache.camel.dsl.jbang.core.commands.ai.AnswerChecks;
import org.apache.camel.dsl.jbang.core.commands.ai.AppFeatures;
import org.apache.camel.dsl.jbang.core.commands.ai.ToolConfirms;
import org.apache.camel.dsl.jbang.core.common.ExampleHelper;
-import org.apache.camel.dsl.jbang.core.common.genai.SpanEntry;
import org.apache.camel.dsl.jbang.run.common.Printer;
import org.apache.camel.util.json.JsonObject;
@@ -291,7 +290,7 @@ class AiPanel {
/** The question the current turn answers, for grouping its requests on
the Ollama tab. */
private volatile String currentQuestion;
private boolean statsView;
- boolean spanRefreshRequested;
+ boolean usageRefreshRequested;
/**
* One conversation line. For assistant replies {@code elapsedMs} is the
wall-clock time of the whole turn,
@@ -381,8 +380,8 @@ class AiPanel {
toolSet.setMcpInfo(active, port);
}
- void setOtelSpans(AtomicReference<List<SpanEntry>> otelSpans) {
- usage.setOtelSpans(otelSpans);
+ void setGenAiUsage(AtomicReference<GenAiConsoleUsage> genAiUsage) {
+ usage.setGenAiUsage(genAiUsage);
}
synchronized List<LogEntry> getActivityLog() {
@@ -2313,7 +2312,7 @@ class AiPanel {
statsView = !statsView;
usage.resetScroll();
if (statsView) {
- spanRefreshRequested = true;
+ usageRefreshRequested = true;
}
}
@@ -2580,7 +2579,7 @@ class AiPanel {
statsView = !statsView;
usage.resetScroll();
if (statsView) {
- spanRefreshRequested = true;
+ usageRefreshRequested = true;
}
}
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 ec2566aef039..82bc4b17fdd6 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
@@ -44,9 +44,7 @@ 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.common.genai.GenAiSpans;
import org.apache.camel.dsl.jbang.core.common.genai.GenAiSpans.GenAiActivity;
-import org.apache.camel.dsl.jbang.core.common.genai.SpanEntry;
import static
org.apache.camel.dsl.jbang.core.commands.tui.AiPanel.formatSeconds;
@@ -66,14 +64,18 @@ final class AiUsageStats {
private final List<long[]> turnTimings = new CopyOnWriteArrayList<>();
private volatile long sessionToolTimeMs;
private volatile int sessionToolCalls;
- /** Route usage (GenAI spans) recorded before this instant is left out
after a {@code /usage reset}. */
+ static final String NOT_RECORDING_HINT
+ = "not recorded: the dev console of the integration is off
(camel.main.devConsoleEnabled=true)";
+
+ /** Route usage (GenAI calls) recorded before this instant is left out
after a {@code /usage reset}. */
private volatile Instant usageResetAt = Instant.EPOCH;
- private AtomicReference<List<SpanEntry>> otelSpans = new
AtomicReference<>(List.of());
+ private AtomicReference<GenAiConsoleUsage> genAiUsage = new
AtomicReference<>(GenAiConsoleUsage.NONE);
private final TableState statsTableState = new TableState();
private int statsScrollOffset;
- void setOtelSpans(AtomicReference<List<SpanEntry>> otelSpans) {
- this.otelSpans = otelSpans != null ? otelSpans : new
AtomicReference<>(List.of());
+ /** The GenAI calls of the integration, from its genai dev console. */
+ void setGenAiUsage(AtomicReference<GenAiConsoleUsage> genAiUsage) {
+ this.genAiUsage = genAiUsage != null ? genAiUsage : new
AtomicReference<>(GenAiConsoleUsage.NONE);
}
/** A request of the panel, or of an ACP agent. */
@@ -93,8 +95,8 @@ final class AiUsageStats {
}
/**
- * Forgets the usage recorded so far: the panel's own requests are
dropped, and route usage from spans that were
- * exported before now is hidden (the spans themselves stay, as the Spans
tab owns them).
+ * Forgets the usage recorded so far: the panel's own requests are
dropped, and the GenAI calls of the integration
+ * made before now are hidden (the integration keeps them).
*/
void reset() {
usageHistory.clear();
@@ -131,7 +133,8 @@ final class AiUsageStats {
if (entries.isEmpty()) {
frame.renderWidget(
Paragraph.from(Line.from(Span.styled(
- "No AI usage data yet. Ask a question, or run an
integration with GenAI observability and --observe.",
+ "No AI usage data yet. Ask a question, or run an
integration with GenAI observability "
+ +
"(camel.aiObservability.level=detailed).",
Style.EMPTY.dim()))),
area);
return;
@@ -179,10 +182,10 @@ final class AiUsageStats {
turnTokens.set(last, turnTokens.get(last) + e.totalTokens());
}
- // Layout: summary (2 rows, 3 with GenAI spans) + model table (header
+ models + 1 blank) + chart (fill)
+ // Layout: summary (2 rows, 3 with GenAI calls) + 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);
+ Line activityLine = activityLine(activity(),
genAiUsage.get().recording(), dimStyle, cyanStyle);
int tableRows = perModel.size() + 1;
int summaryRows = activityLine != null ? 3 : 2;
int chartMinRows = 4;
@@ -378,13 +381,10 @@ final class AiUsageStats {
List<AiUsageEntry> combinedUsageEntries() {
List<AiUsageEntry> combined = new ArrayList<>(usageHistory.size() + 8);
combined.addAll(usageHistory);
- List<SpanEntry> spans = otelSpans.get();
- if (spans != null && !spans.isEmpty()) {
- Instant since = usageResetAt;
- for (AiUsageEntry entry : GenAiSpanUsageExtractor.extract(spans)) {
- if (!entry.timestamp().isBefore(since)) {
- combined.add(entry);
- }
+ Instant since = usageResetAt;
+ for (AiUsageEntry entry : genAiUsage.get().modelCalls()) {
+ if (!entry.timestamp().isBefore(since)) {
+ combined.add(entry);
}
}
return combined;
@@ -392,18 +392,24 @@ final class AiUsageStats {
/** The agent runs and tool calls of the integration since the last reset,
and its GenAI observability level. */
GenAiActivity activity() {
- return GenAiSpans.activity(otelSpans.get(), usageResetAt);
+ return genAiUsage.get().activity(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.
+ * {@code null} when the integration has no genai dev console.
*/
- private static Line activityLine(GenAiActivity activity, Style dimStyle,
Style cyanStyle) {
+ private static Line activityLine(GenAiActivity activity, boolean
recording, Style dimStyle, Style cyanStyle) {
if (activity.level() == null) {
return null;
}
String level = activity.level().name().toLowerCase(Locale.ROOT);
+ if (!recording) {
+ return Line.from(
+ Span.styled("GenAI level: ", dimStyle),
+ Span.styled(level, cyanStyle),
+ Span.styled(" " + NOT_RECORDING_HINT, dimStyle));
+ }
if (activity.level() == GenAiObservabilityLevel.BASIC) {
return Line.from(
Span.styled("GenAI level: ", dimStyle),
@@ -471,8 +477,8 @@ final class AiUsageStats {
String summary() {
List<AiUsageEntry> entries = combinedUsageEntries();
if (entries.isEmpty()) {
- return "No AI usage yet. Ask a question, or run an integration
with GenAI observability and --observe to see "
- + "their usage here.";
+ return "No AI usage yet. Ask a question, or run an integration
with GenAI observability "
+ + "(camel.aiObservability.level=detailed) to see their
usage here.";
}
int totalInput = 0;
int totalCached = 0;
@@ -511,7 +517,10 @@ final class AiUsageStats {
}
sb.append(")\n");
GenAiActivity activity = activity();
- if (activity.level() == GenAiObservabilityLevel.BASIC) {
+ if (activity.level() != null && !genAiUsage.get().recording()) {
+ sb.append("- **GenAI level:**
").append(activity.level().name().toLowerCase(Locale.ROOT)).append(" (")
+ .append(NOT_RECORDING_HINT).append(")\n");
+ } else 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())
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
index 7e27276e0596..13378173d497 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
@@ -937,7 +937,7 @@ public class CamelMonitor extends CamelCommand {
mcpFacade.setLaunchManager(actionsPopup.getLaunchManager());
mcpFacade.setFullScan(dataService::forceFullScan,
dataService::fullScansDone);
aiPanel.setMcpFacade(mcpFacade);
- aiPanel.setOtelSpans(dataService.otelSpans());
+ aiPanel.setGenAiUsage(dataService.genAiUsage());
mcpFacade.setAiActivityLog(aiPanel::getActivityLog);
actionsPopup.setAiActivityLog(aiPanel::getActivityLog);
}
@@ -2460,10 +2460,11 @@ public class CamelMonitor extends CamelCommand {
* what the active tab shows (each tab fetches its own in {@link
MonitorTab#refreshWhileVisible()}).
*/
private void refreshConditionalData() {
- if (aiPanel.isOpen() && aiPanel.isStatsView()
- && ctx.selectedPid != null && aiPanel.spanRefreshRequested) {
- aiPanel.spanRefreshRequested = false;
- dataService.refreshSpanData();
+ if (aiPanel.isOpen() && aiPanel.isStatsView() && ctx.selectedPid !=
null) {
+ // at once when the view opens, then every few seconds while it is
open
+ boolean now = aiPanel.usageRefreshRequested;
+ aiPanel.usageRefreshRequested = false;
+ dataService.refreshGenAiData(now);
}
if (ollamaMonitor != null) {
// cheap and throttled: keeps the More menu's Ollama entry in step
with whether a server answers
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataRefreshService.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataRefreshService.java
index 2e0f9b6e304c..0e0c3e867cc6 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataRefreshService.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataRefreshService.java
@@ -99,6 +99,9 @@ class DataRefreshService {
private final Map<String, Long> traceFilePositions = new
ConcurrentHashMap<>();
// OTel span data -- shared between CamelMonitor and SpansTab
private final AtomicReference<List<SpanEntry>> otelSpans = new
AtomicReference<>(List.of());
+ private final AtomicReference<GenAiConsoleUsage> genAiUsage = new
AtomicReference<>(GenAiConsoleUsage.NONE);
+ private static final long GENAI_REFRESH_MS = 2000;
+ private volatile long lastGenAiRefresh;
private final Map<String, Integer> lastReloadCount = new
ConcurrentHashMap<>();
private volatile String reloadNotification;
@@ -153,6 +156,11 @@ class DataRefreshService {
return otelSpans;
}
+ /** The GenAI calls of the selected integration, for the AI usage view. */
+ AtomicReference<GenAiConsoleUsage> genAiUsage() {
+ return genAiUsage;
+ }
+
MetricsCollector metrics() {
return metrics;
}
@@ -772,6 +780,29 @@ class DataRefreshService {
}
}
+ // ---- GenAI data ----
+
+ /**
+ * The GenAI calls of the selected integration, from the genai dev console
of camel-ai-observability: when asked
+ * {@code now}, else at most every {@value #GENAI_REFRESH_MS} millis.
+ */
+ void refreshGenAiData(boolean now) {
+ String pid = ctx.selectedPid;
+ long time = System.currentTimeMillis();
+ if (pid == null || !now && time - lastGenAiRefresh < GENAI_REFRESH_MS)
{
+ return;
+ }
+ lastGenAiRefresh = time;
+ try {
+ JsonObject action = new JsonObject();
+ action.put("action", "genai");
+ action.put("limit", String.valueOf(GenAiConsoleUsage.LIMIT));
+ genAiUsage.set(GenAiConsoleUsage.from(ctx.executeAction(pid,
action, 3000)));
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+
// ---- Error data ----
void refreshErrorData(List<Long> pids) {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsage.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsage.java
new file mode 100644
index 000000000000..c0f2a0c3c084
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsage.java
@@ -0,0 +1,140 @@
+/*
+ * 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;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.component.ai.observability.GenAiObservabilityLevel;
+import org.apache.camel.dsl.jbang.core.common.genai.GenAiSpans.GenAiActivity;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * The GenAI calls of the monitored integration for the AI usage view, from
the {@code genai} dev console of
+ * camel-ai-observability (the {@code genai} action of the CLI connector). The
console records without a tracer, so the
+ * view needs no {@code --observe}, and it states the observability level.
+ *
+ * @param level the level of the integration, or {@code null} when it has
no genai console
+ * @param recording whether the console records: only while the dev console
is enabled
+ * @param modelCalls the model calls, made in an agent run or not
+ * @param runs the agent runs, with how many model calls and tool calls
each made
+ */
+record GenAiConsoleUsage(GenAiObservabilityLevel level, boolean recording,
List<AiUsageEntry> modelCalls, List<Run> runs) {
+
+ /** The top-level calls asked of the console: all it keeps. */
+ static final int LIMIT = 50;
+
+ static final GenAiConsoleUsage NONE = new GenAiConsoleUsage(null, false,
List.of(), List.of());
+
+ private static final String AGENT_RUN = "invoke_agent";
+ private static final String TOOL_CALL = "execute_tool";
+
+ /** An agent run (or a tool call outside a run, with no model calls): when
it started and what it called. */
+ record Run(Instant timestamp, boolean agentRun, int modelCalls, int
toolCalls) {
+ }
+
+ /** The answer of the genai action; {@link #NONE} when the integration has
no genai console. */
+ static GenAiConsoleUsage from(JsonObject answer) {
+ if (answer == null ||
Boolean.FALSE.equals(answer.getBoolean("enabled")) || answer.getString("level")
== null) {
+ return NONE;
+ }
+ GenAiObservabilityLevel level;
+ try {
+ level = GenAiObservabilityLevel.parse(answer.getString("level"));
+ } catch (IllegalArgumentException e) {
+ level = GenAiObservabilityLevel.BASIC;
+ }
+ List<AiUsageEntry> modelCalls = new ArrayList<>();
+ List<Run> runs = new ArrayList<>();
+ for (JsonObject call : objects(answer, "calls")) {
+ String operation = call.getString("operation");
+ if (!AGENT_RUN.equals(operation) && !TOOL_CALL.equals(operation)) {
+ modelCalls.add(entry(call, null));
+ continue;
+ }
+ int models = 0;
+ int tools = TOOL_CALL.equals(operation) ? 1 : 0;
+ for (JsonObject step : objects(call, "steps")) {
+ String stepOperation = step.getString("operation");
+ if (TOOL_CALL.equals(stepOperation)) {
+ tools++;
+ } else if (!AGENT_RUN.equals(stepOperation)) {
+ models++;
+ modelCalls.add(entry(step, call.getString("routeId")));
+ }
+ }
+ runs.add(new Run(timestamp(call), AGENT_RUN.equals(operation),
models, tools));
+ }
+ return new GenAiConsoleUsage(
+ level, Boolean.TRUE.equals(answer.getBoolean("recording")),
List.copyOf(modelCalls),
+ List.copyOf(runs));
+ }
+
+ /** The agent runs, their model calls and the tool calls started at or
after {@code since}, and the level. */
+ GenAiActivity activity(Instant since) {
+ int agentRuns = 0;
+ int agentModelCalls = 0;
+ int toolCalls = 0;
+ for (Run run : runs) {
+ if (since == null || !run.timestamp().isBefore(since)) {
+ agentRuns += run.agentRun() ? 1 : 0;
+ agentModelCalls += run.modelCalls();
+ toolCalls += run.toolCalls();
+ }
+ }
+ return new GenAiActivity(agentRuns, agentModelCalls, toolCalls, level);
+ }
+
+ private static AiUsageEntry entry(JsonObject call, String runRouteId) {
+ String model = call.getString("model") != null ?
call.getString("model") : call.getString("name");
+ String provider = call.getString("provider") != null ?
call.getString("provider") : "unknown";
+ int in = (int) number(call, "inputTokens");
+ int out = (int) number(call, "outputTokens");
+ String routeId = call.getString("routeId") != null ?
call.getString("routeId") : runRouteId;
+ return new AiUsageEntry(
+ model != null ? model : "unknown", provider, in, out, in +
out, number(call, "durationMs"),
+ call.getString("finishReason"), timestamp(call),
AiUsageSource.ROUTE, routeId, 0,
+ (int) number(call, "cachedInputTokens"));
+ }
+
+ private static Instant timestamp(JsonObject call) {
+ long millis = number(call, "timestamp");
+ return millis > 0 ? Instant.ofEpochMilli(millis) : Instant.EPOCH;
+ }
+
+ private static long number(JsonObject json, String key) {
+ return json.get(key) instanceof Number n ? Math.max(0, n.longValue())
: 0;
+ }
+
+ private static List<JsonObject> objects(JsonObject json, String key) {
+ List<JsonObject> list = new ArrayList<>();
+ if (json.get(key) instanceof List<?> items) {
+ for (Object item : items) {
+ if (item instanceof JsonObject jo) {
+ list.add(jo);
+ } else if (item instanceof Map<?, ?> map) {
+ JsonObject jo = new JsonObject();
+ map.forEach((k, v) -> jo.put(String.valueOf(k), v));
+ list.add(jo);
+ }
+ }
+ }
+ return list;
+ }
+}
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
deleted file mode 100644
index 8a5983a021a7..000000000000
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractor.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.camel.component.ai.observability.GenAiAttributes;
-import org.apache.camel.dsl.jbang.core.common.genai.GenAiSpans;
-import org.apache.camel.dsl.jbang.core.common.genai.SpanEntry;
-
-/**
- * Converts the GenAI model calls among the OTel spans of a monitored Camel
integration into AI usage entries for the
- * TUI stats view. Which span is a model call is decided by {@link
GenAiSpans}, shared with the MCP server.
- */
-final class GenAiSpanUsageExtractor {
-
- private GenAiSpanUsageExtractor() {
- }
-
- static List<AiUsageEntry> extract(List<SpanEntry> spans) {
- if (spans == null || spans.isEmpty()) {
- return List.of();
- }
- List<AiUsageEntry> entries = new ArrayList<>();
- for (SpanEntry span : spans) {
- if (GenAiSpans.isModelCall(span)) {
- entries.add(toUsageEntry(span));
- }
- }
- return List.copyOf(entries);
- }
-
- private static AiUsageEntry toUsageEntry(SpanEntry span) {
- Map<String, Object> attrs = span.attributes();
- String model = GenAiSpans.model(attrs);
- if (model == null) {
- model = span.name() != null ? span.name() : "unknown";
- }
- String provider = GenAiSpans.provider(attrs);
- if (provider == null) {
- provider = "unknown";
- }
- int inputTokens = (int) GenAiSpans.number(attrs,
GenAiAttributes.INPUT_TOKENS);
- int outputTokens = (int) GenAiSpans.number(attrs,
GenAiAttributes.OUTPUT_TOKENS);
- int cachedInputTokens = (int) GenAiSpans.number(attrs,
GenAiAttributes.CACHE_READ_INPUT_TOKENS);
- long latencyMs = Math.max(0, span.durationMs());
- Instant timestamp = span.startEpochNanos() > 0 ?
Instant.ofEpochSecond(0, span.startEpochNanos()) : Instant.EPOCH;
- return new AiUsageEntry(
- model, provider, inputTokens, outputTokens, inputTokens +
outputTokens, latencyMs,
- GenAiSpans.text(attrs, GenAiAttributes.FINISH_REASONS),
timestamp, AiUsageSource.ROUTE, span.routeId(),
- 0, cachedInputTokens);
- }
-}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TabRegistry.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TabRegistry.java
index b39f8028bb87..3acb851b6517 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TabRegistry.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TabRegistry.java
@@ -383,6 +383,7 @@ class TabRegistry {
activeMoreTab.onTabSelected();
}
dataService.otelSpans().set(List.of());
+ dataService.genAiUsage().set(GenAiConsoleUsage.NONE);
filesBrowser.reset();
}
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 338aef5b1a22..5b501d0f789c 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,9 +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;
import dev.tamboui.buffer.Buffer;
@@ -27,8 +25,8 @@ import dev.tamboui.layout.Rect;
import dev.tamboui.terminal.Frame;
import dev.tamboui.tui.event.KeyCode;
import dev.tamboui.tui.event.KeyEvent;
-import org.apache.camel.component.ai.observability.GenAiAttributes;
-import org.apache.camel.dsl.jbang.core.common.genai.SpanEntry;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -36,22 +34,22 @@ import static org.assertj.core.api.Assertions.assertThat;
class AiPanelGenAiUsageTest {
- private AtomicReference<List<SpanEntry>> spans;
+ private AtomicReference<GenAiConsoleUsage> genAi;
@BeforeEach
void setUp() {
Theme.resetForTesting();
- spans = new AtomicReference<>(List.of());
+ genAi = new AtomicReference<>(GenAiConsoleUsage.NONE);
}
@Test
- void combinedUsageIncludesRouteGenAiSpans() {
+ void combinedUsageIncludesTheGenAiCallsOfTheIntegration() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
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)));
+ genAi.set(console("detailed", chat("route-chat", "gpt-4o", 100, 20,
0)));
assertThat(panel.combinedUsageEntriesForTesting()).hasSize(2);
assertThat(panel.combinedUsageEntriesForTesting())
@@ -62,11 +60,11 @@ class AiPanelGenAiUsageTest {
@Test
void statsViewRendersRouteAndTuiBreakdown() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
panel.open();
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)));
+ genAi.set(console("detailed", chat("orders", "gpt-4o", 50, 10, 0)));
panel.toggleStatsViewForTesting();
Rect area = new Rect(0, 0, 120, 24);
@@ -84,7 +82,7 @@ class AiPanelGenAiUsageTest {
@Test
void pageDownScrollsTheModelsOfTheStatsView() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
panel.open();
for (int i = 0; i < 12; i++) {
panel.recordUsageForTesting(new AiUsageEntry(
@@ -111,23 +109,23 @@ class AiPanelGenAiUsageTest {
}
@Test
- void togglingStatsViewRequestsSpanRefresh() {
+ void togglingStatsViewRequestsUsageRefresh() {
AiPanel panel = new AiPanel();
- assertThat(panel.spanRefreshRequested).isFalse();
+ assertThat(panel.usageRefreshRequested).isFalse();
panel.toggleStatsViewForTesting();
assertThat(panel.isStatsView()).isTrue();
- assertThat(panel.spanRefreshRequested).isTrue();
+ assertThat(panel.usageRefreshRequested).isTrue();
panel.toggleStatsViewForTesting();
assertThat(panel.isStatsView()).isFalse();
- assertThat(panel.spanRefreshRequested).isTrue();
+ assertThat(panel.usageRefreshRequested).isTrue();
}
@Test
void statsViewShowsGuidanceWhenNoDataAvailable() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
panel.open();
panel.toggleStatsViewForTesting();
@@ -143,9 +141,9 @@ class AiPanelGenAiUsageTest {
@Test
void statsViewCountsOnlyTheModelCallsOfAnAgentRun() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
panel.open();
- spans.set(agentRunSpans());
+ genAi.set(console("detailed", agentRun()));
panel.toggleStatsViewForTesting();
assertThat(panel.combinedUsageEntriesForTesting()).hasSize(2);
@@ -166,9 +164,9 @@ class AiPanelGenAiUsageTest {
@Test
void statsViewExplainsLevelBasic() {
AiPanel panel = new AiPanel();
- panel.setOtelSpans(spans);
+ panel.setGenAiUsage(genAi);
panel.open();
- spans.set(List.of(routeSpan("orders", "gpt-4o", 50, 10)));
+ genAi.set(console("basic", chat("orders", "gpt-4o", 50, 10, 0)));
panel.toggleStatsViewForTesting();
assertThat(render(panel, new Rect(0, 0, 140, 24)))
@@ -176,12 +174,28 @@ class AiPanelGenAiUsageTest {
.contains("agent runs and tool calls are not traced");
}
+ @Test
+ void statsViewSaysWhenTheIntegrationDoesNotRecord() {
+ AiPanel panel = new AiPanel();
+ panel.setGenAiUsage(genAi);
+ panel.open();
+ panel.recordUsageForTesting(new AiUsageEntry(
+ "gpt-4o-mini", "openai", 10, 5, 15, 1000, "stop",
Instant.now()));
+ JsonObject off = answer("detailed");
+ off.put("recording", false);
+ genAi.set(GenAiConsoleUsage.from(off));
+ panel.toggleStatsViewForTesting();
+
+ assertThat(render(panel, new Rect(0, 0, 160, 24)))
+ .contains("not recorded: the dev console of the integration is
off");
+ }
+
@Test
void usageSummaryListsAgentRunsAndCachedTokens() {
- spans.set(agentRunSpans());
+ genAi.set(console("detailed", agentRun()));
AiUsageStats stats = new AiUsageStats();
- stats.setOtelSpans(spans);
+ stats.setGenAiUsage(genAi);
assertThat(stats.summary())
.contains("2 request(s) (0 from this panel, 2 from the
integration)")
.contains("cached 800")
@@ -189,65 +203,54 @@ class AiPanelGenAiUsageTest {
.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));
+ /** The answer of the genai action of the integration, as the CLI
connector gives it. */
+ private static GenAiConsoleUsage console(String level, JsonObject...
calls) {
+ return GenAiConsoleUsage.from(answer(level, calls));
+ }
+
+ private static JsonObject answer(String level, JsonObject... calls) {
+ JsonObject answer = new JsonObject();
+ answer.put("recording", true);
+ answer.put("level", level);
+ answer.put("calls", new JsonArray(List.of((Object[]) calls)));
+ return answer;
+ }
+
+ /** An agent run at level detailed: two model calls and a tool call. */
+ private static JsonObject agentRun() {
+ JsonObject run = call("invoke_agent", "invoke_agent support",
"support");
+ run.put("agentName", "support");
+ JsonObject tool = call("execute_tool", "execute_tool lookupOrder",
null);
+ tool.put("toolName", "lookupOrder");
+ run.put("steps", new JsonArray(
+ List.of(
+ chat(null, "gpt-4.1", 1000, 100, 0), tool,
chat("support", "gpt-4.1", 1200, 100, 800))));
+ return run;
+ }
+
+ private static JsonObject chat(String routeId, String model, long input,
long output, long cached) {
+ JsonObject chat = call("chat", "chat " + model, routeId);
+ chat.put("provider", "openai");
+ chat.put("model", model);
+ chat.put("inputTokens", input);
+ chat.put("outputTokens", output);
if (cached > 0) {
- attrs.put(GenAiAttributes.CACHE_READ_INPUT_TOKENS, cached);
+ chat.put("cachedInputTokens", cached);
+ }
+ chat.put("finishReason", "stop");
+ return chat;
+ }
+
+ private static JsonObject call(String operation, String name, String
routeId) {
+ JsonObject call = new JsonObject();
+ call.put("operation", operation);
+ call.put("name", name);
+ if (routeId != null) {
+ call.put("routeId", routeId);
}
- 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",
- "span-1",
- "",
- "chat " + model,
- "CLIENT",
- "OK",
- Instant.now().getEpochSecond() * 1_000_000_000L,
- Instant.now().getEpochSecond() * 1_000_000_000L + 500_000_000L,
- 500,
- routeId,
- null,
- "camel",
- Map.of(
- GenAiAttributes.OPERATION_NAME, "chat",
- GenAiAttributes.SYSTEM, "openai",
- GenAiAttributes.REQUEST_MODEL, model,
- GenAiAttributes.RESPONSE_MODEL, model,
- GenAiAttributes.INPUT_TOKENS, input,
- GenAiAttributes.OUTPUT_TOKENS, output,
- GenAiAttributes.FINISH_REASONS, "stop"));
+ call.put("timestamp", Instant.now().toEpochMilli());
+ call.put("running", false);
+ call.put("durationMs", 1000L);
+ return call;
}
}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsageTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsageTest.java
new file mode 100644
index 000000000000..6d995d01f66c
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiConsoleUsageTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.component.ai.observability.GenAiObservabilityLevel;
+import org.apache.camel.dsl.jbang.core.common.genai.GenAiSpans.GenAiActivity;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * CAMEL-27313: the AI usage view reads the GenAI calls of the integration
from its genai dev console.
+ */
+class GenAiConsoleUsageTest {
+
+ private static final long T0 = 1_795_255_200_000L;
+
+ @Test
+ void noConsoleIsNoUsage() {
+
assertThat(GenAiConsoleUsage.from(null)).isSameAs(GenAiConsoleUsage.NONE);
+ assertThat(GenAiConsoleUsage.from(new JsonObject(Map.of("enabled",
false)))).isSameAs(GenAiConsoleUsage.NONE);
+ assertThat(GenAiConsoleUsage.NONE.activity(null).level()).isNull();
+ }
+
+ @Test
+ void theModelCallsOfTheRunsAndOutsideThemAreUsageEntries() throws
Exception {
+ JsonObject run = call("invoke_agent", "support", T0 + 1000);
+ // a model call made by the route of a tool has no route of its own:
the run's is used
+ run.put("steps", new JsonArray(
+ List.of(chat(null, T0 + 1100, 300, 40, 270),
call("execute_tool", null, T0 + 1200),
+ chat("support", T0 + 1300, 400, 20, 0))));
+ JsonObject answer = answer("full", chat("orders", T0, 10, 5, 0), run);
+
+ // as the action file carries it: JSON text read back
+ GenAiConsoleUsage usage = GenAiConsoleUsage.from((JsonObject)
Jsoner.deserialize(answer.toJson()));
+
+ assertThat(usage.level()).isEqualTo(GenAiObservabilityLevel.FULL);
+ assertThat(usage.recording()).isTrue();
+
assertThat(usage.modelCalls()).extracting(AiUsageEntry::routeId).containsExactly("orders",
"support", "support");
+ AiUsageEntry first = usage.modelCalls().get(1);
+ assertThat(first.source()).isEqualTo(AiUsageSource.ROUTE);
+ assertThat(first.model()).isEqualTo("granite4:3b");
+ assertThat(first.provider()).isEqualTo("ollama");
+ assertThat(first.totalTokens()).isEqualTo(340);
+ assertThat(first.cachedInputTokens()).isEqualTo(270);
+ assertThat(first.latencyMs()).isEqualTo(100);
+ assertThat(first.timestamp()).isEqualTo(Instant.ofEpochMilli(T0 +
1100));
+
+ GenAiActivity activity = usage.activity(Instant.EPOCH);
+ assertThat(activity.agentRuns()).isEqualTo(1);
+ assertThat(activity.agentModelCalls()).isEqualTo(2);
+ assertThat(activity.toolCalls()).isEqualTo(1);
+ }
+
+ @Test
+ void theActivitySinceAResetLeavesOutTheRunsBefore() {
+ JsonObject old = call("invoke_agent", "support", T0);
+ old.put("steps", new JsonArray(List.of(chat("support", T0, 1, 1, 0))));
+ JsonObject recent = call("invoke_agent", "support", T0 + 60_000);
+ recent.put("steps", new JsonArray(List.of(call("execute_tool", null,
T0 + 60_100))));
+
+ GenAiActivity activity = GenAiConsoleUsage.from(answer("detailed",
recent, old))
+ .activity(Instant.ofEpochMilli(T0 + 30_000));
+
+ assertThat(activity.agentRuns()).isEqualTo(1);
+ assertThat(activity.agentModelCalls()).isZero();
+ assertThat(activity.toolCalls()).isEqualTo(1);
+
assertThat(activity.level()).isEqualTo(GenAiObservabilityLevel.DETAILED);
+ }
+
+ private static JsonObject answer(String level, JsonObject... calls) {
+ JsonObject answer = new JsonObject();
+ answer.put("recording", true);
+ answer.put("level", level);
+ answer.put("calls", new JsonArray(List.of((Object[]) calls)));
+ return answer;
+ }
+
+ private static JsonObject chat(String routeId, long timestamp, long input,
long output, long cached) {
+ JsonObject chat = call("chat", routeId, timestamp);
+ chat.put("name", "chat granite4:3b");
+ chat.put("provider", "ollama");
+ chat.put("model", "granite4:3b");
+ chat.put("inputTokens", input);
+ chat.put("outputTokens", output);
+ if (cached > 0) {
+ chat.put("cachedInputTokens", cached);
+ }
+ return chat;
+ }
+
+ private static JsonObject call(String operation, String routeId, long
timestamp) {
+ JsonObject call = new JsonObject();
+ call.put("operation", operation);
+ if (routeId != null) {
+ call.put("routeId", routeId);
+ }
+ call.put("timestamp", timestamp);
+ call.put("running", false);
+ call.put("durationMs", 100L);
+ return call;
+ }
+}
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
deleted file mode 100644
index 6b2136ff2040..000000000000
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanUsageExtractorTest.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * 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;
-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.apache.camel.dsl.jbang.core.common.genai.GenAiSpans;
-import org.apache.camel.dsl.jbang.core.common.genai.SpanEntry;
-import org.junit.jupiter.api.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-class GenAiSpanUsageExtractorTest {
-
- @Test
- void isGenAiSpanRequiresOperationNameAttribute() {
- SpanEntry genAi = span(Map.of(GenAiAttributes.OPERATION_NAME, "chat"));
- SpanEntry other = span(Map.of("http.method", "GET"));
-
- assertThat(GenAiSpans.isGenAiSpan(genAi)).isTrue();
- assertThat(GenAiSpans.isGenAiSpan(other)).isFalse();
- assertThat(GenAiSpans.isGenAiSpan(null)).isFalse();
- }
-
- @Test
- void extractMapsGenAiSemanticConventionAttributes() {
- SpanEntry span = span(Map.of(
- GenAiAttributes.OPERATION_NAME, "chat",
- GenAiAttributes.SYSTEM, "openai",
- GenAiAttributes.REQUEST_MODEL, "gpt-4o-mini",
- GenAiAttributes.RESPONSE_MODEL, "gpt-4o-mini",
- GenAiAttributes.INPUT_TOKENS, 120,
- GenAiAttributes.OUTPUT_TOKENS, 45,
- GenAiAttributes.FINISH_REASONS, "stop"));
-
- List<AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(span));
-
- assertThat(entries).hasSize(1);
- 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);
- assertThat(entry.outputTokens()).isEqualTo(45);
- assertThat(entry.totalTokens()).isEqualTo(165);
- assertThat(entry.latencyMs()).isEqualTo(250);
- assertThat(entry.stopReason()).isEqualTo("stop");
- assertThat(entry.routeId()).isEqualTo("route-a");
- }
-
- @Test
- void extractIgnoresNonGenAiSpans() {
- SpanEntry camelSpan = span(Map.of("camel.routeId", "r1"));
- SpanEntry genAi = span(Map.of(
- GenAiAttributes.OPERATION_NAME, "embeddings",
- GenAiAttributes.SYSTEM, "openai",
- GenAiAttributes.REQUEST_MODEL, "text-embedding-3-small",
- GenAiAttributes.INPUT_TOKENS, "10",
- GenAiAttributes.OUTPUT_TOKENS, "0"));
-
- List<AiUsageEntry> entries =
GenAiSpanUsageExtractor.extract(List.of(camelSpan, genAi));
-
- assertThat(entries).hasSize(1);
- assertThat(entries.get(0).model()).isEqualTo("text-embedding-3-small");
- }
-
- @Test
- void extractFallsBackToRequestModelAndSpanName() {
- SpanEntry requestOnly = span("chat gpt-4", Map.of(
- GenAiAttributes.OPERATION_NAME, "chat",
- GenAiAttributes.REQUEST_MODEL, "gpt-4",
- GenAiAttributes.SYSTEM, "anthropic"));
-
- SpanEntry nameFallback = span("embeddings unknown-model", Map.of(
- GenAiAttributes.OPERATION_NAME, "embeddings",
- GenAiAttributes.REQUEST_MODEL, "unknown",
- GenAiAttributes.SYSTEM, "openai"));
-
-
assertThat(GenAiSpanUsageExtractor.extract(List.of(requestOnly)).get(0).model()).isEqualTo("gpt-4");
-
assertThat(GenAiSpanUsageExtractor.extract(List.of(nameFallback)).get(0).model())
- .isEqualTo("embeddings unknown-model");
- }
-
- @Test
- void isModelCallLeavesOutAgentRunsAndToolCalls() {
-
assertThat(GenAiSpans.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"chat")))).isTrue();
-
assertThat(GenAiSpans.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(GenAiSpans.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"text_completion"))))
- .isTrue();
-
assertThat(GenAiSpans.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"invoke_agent"))))
- .isFalse();
-
assertThat(GenAiSpans.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"execute_tool"))))
- .isFalse();
-
assertThat(GenAiSpans.isModelCall(span(Map.of(GenAiAttributes.OPERATION_NAME,
"create_agent"))))
- .isFalse();
- assertThat(GenAiSpans.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")));
-
- GenAiSpans.GenAiActivity activity = GenAiSpans.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(GenAiSpans.activity(List.of(basic), Instant.EPOCH).level())
- .isEqualTo(GenAiObservabilityLevel.BASIC);
- assertThat(GenAiSpans.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(GenAiSpans.activity(List.of(framework),
Instant.EPOCH).level()).isNull();
- assertThat(GenAiSpans.activity(List.of(),
Instant.EPOCH).level()).isNull();
- }
-
- @Test
- void activityLeavesOutSpansBeforeTheReset() {
- Instant afterTheRun = Instant.parse("2026-08-13T12:00:01Z");
-
- GenAiSpans.GenAiActivity activity = GenAiSpans.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);
- }
-
- private static SpanEntry span(String name, Map<String, Object> attributes)
{
- return new SpanEntry(
- "trace-1",
- "span-1",
- "",
- 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);
- }
-}
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 ab08a284f92a..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,7 +56,7 @@ 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 3071
+ AiPanel.java 3070
AiPanel.runAgentLoop 156
CamelMonitor.java 2632
DiagramSupport.java 2360