This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27313-get-genai in repository https://gitbox.apache.org/repos/asf/camel.git
commit 65ce8897d16c6066b1970598643ff9cc099189cf Author: Claus Ibsen <[email protected]> AuthorDate: Sat Nov 21 09:54:45 2026 +0100 CAMEL-27313: camel-jbang - camel get genai shows the model calls, agent runs and tool calls of the genai dev console Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/catalog/docs/ai-observability.adoc | 5 + .../src/main/docs/ai-observability.adoc | 5 + .../jbang-commands/camel-jbang-get-genai.adoc | 32 ++ .../ROOT/pages/jbang-commands/camel-jbang-get.adoc | 1 + .../META-INF/camel-jbang-commands-metadata.json | 2 +- .../dsl/jbang/core/commands/CamelJBangMain.java | 1 + .../core/commands/action/CamelGenAiAction.java | 374 +++++++++++++++++++++ .../core/commands/action/CamelGenAiActionTest.java | 262 +++++++++++++++ .../src/test/resources/golden/cli-help.txt | 34 ++ 9 files changed, 715 insertions(+), 1 deletion(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-observability.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-observability.adoc index 75f4ba24f555..d82814611faf 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-observability.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ai-observability.adoc @@ -225,6 +225,11 @@ The content (`systemInstructions`, `toolDefinitions`, `inputMessages`, `outputMe `toolResult`) is only recorded at level `full`, capped at `camel.aiObservability.contentMaxLength` as on the spans, and only in the answer when asked with `content` or `id`. The messages are in the GenAI messages format of the spans. +With the Camel CLI, `camel get genai` shows the same: the models, and the newest runs with their model calls and +tool calls (`--content` adds the question of each run). `camel get genai --id 7` shows one run with its system +message, question, each model call's answer or tool call's arguments and result, and the final answer; `--watch` +keeps it on screen. + Over HTTP the console is on the management server (`camel run --console`), as text or as JSON: [source,bash] diff --git a/components/camel-ai/camel-ai-observability/src/main/docs/ai-observability.adoc b/components/camel-ai/camel-ai-observability/src/main/docs/ai-observability.adoc index 75f4ba24f555..d82814611faf 100644 --- a/components/camel-ai/camel-ai-observability/src/main/docs/ai-observability.adoc +++ b/components/camel-ai/camel-ai-observability/src/main/docs/ai-observability.adoc @@ -225,6 +225,11 @@ The content (`systemInstructions`, `toolDefinitions`, `inputMessages`, `outputMe `toolResult`) is only recorded at level `full`, capped at `camel.aiObservability.contentMaxLength` as on the spans, and only in the answer when asked with `content` or `id`. The messages are in the GenAI messages format of the spans. +With the Camel CLI, `camel get genai` shows the same: the models, and the newest runs with their model calls and +tool calls (`--content` adds the question of each run). `camel get genai --id 7` shows one run with its system +message, question, each model call's answer or tool call's arguments and result, and the final answer; `--watch` +keeps it on screen. + Over HTTP the console is on the management server (`camel run --console`), as text or as JSON: [source,bash] diff --git a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get-genai.adoc b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get-genai.adoc new file mode 100644 index 000000000000..109e95ab033f --- /dev/null +++ b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get-genai.adoc @@ -0,0 +1,32 @@ + +// AUTO-GENERATED by camel-package-maven-plugin - DO NOT EDIT THIS FILE += camel get genai + +Display the model calls, agent runs and tool calls of the Camel AI components + + +== Usage + +[source,bash] +---- +camel get genai [options] +---- + + + +== Options + +[cols="2,5,1,2",options="header"] +|=== +| Option | Description | Default | Type +| `--content` | Show the question of each agent run (recorded at camel.aiObservability.level=full) | | boolean +| `--duration` | How long to keep watching or following, in millis or as a duration such as 30s (default: until Enter is pressed) | | long +| `--id` | Show one call (an agent run, a model call or a tool call) with its messages | | String +| `--json` | Output the answer of the genai dev console as JSON | | boolean +| `--limit` | The number of the newest agent runs and model calls to show | 20 | int +| `--timeout` | How long to wait for the integration to answer, in millis or as a duration such as 30s | 10000 | long +| `--watch` | Execute periodically and showing output fullscreen | | boolean +| `-h,--help` | Display this help and exit | | boolean +|=== + + diff --git a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get.adoc b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get.adoc index 8eafd3c73b07..7854e9f00c34 100644 --- a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get.adoc +++ b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-get.adoc @@ -30,6 +30,7 @@ camel get [options] | xref:jbang-commands/camel-jbang-get-endpoint.adoc[endpoint] | Get usage of Camel endpoints | xref:jbang-commands/camel-jbang-get-error.adoc[error] | Get captured routing errors of Camel integrations | xref:jbang-commands/camel-jbang-get-event.adoc[event] | Get latest events of Camel integrations +| xref:jbang-commands/camel-jbang-get-genai.adoc[genai] | Display the model calls, agent runs and tool calls of the Camel AI components | xref:jbang-commands/camel-jbang-get-groovy.adoc[groovy] | Groovy Sources used of Camel integrations | xref:jbang-commands/camel-jbang-get-group.adoc[group] | Get status of Camel route groups | xref:jbang-commands/camel-jbang-get-health.adoc[health] | Get health check status of running Camel integrations diff --git a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json index 9a96d6ef804f..5d3cf0c71acd 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json +++ b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json @@ -14,7 +14,7 @@ { "name": "eval", "fullName": "eval", "description": "Evaluate Camel expressions and scripts", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.EvalCommand", "options": [ { "names": "-h,--help", "description": "Display this help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "expression", "fullName": "eval expression", "description": "Evaluates Camel expression", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.action.EvalExpressio [...] { "name": "explain", "fullName": "explain", "description": "Explain what a Camel route does using AI\/LLM", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Explain", "options": [ { "names": "--api-key", "description": "API key for authentication. Also reads ANTHROPIC_API_KEY, OPENAI_API_KEY, WATSONX_APIKEY, or LLM_API_KEY env vars", "javaType": "java.lang.String", "type": "string" }, { "names": "--api-type", "description": "API type: 'ollama', 'openai' (OpenAI-compatible), ' [...] { "name": "export", "fullName": "export", "description": "Export to other runtimes (Camel Main, Spring Boot, or Quarkus)", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Export", "options": [ { "names": "--build-property", "description": "Maven build properties, ex. --build-property=prop1=foo", "javaType": "java.util.List", "type": "array" }, { "names": "--camel-spring-boot-version", "description": "Camel version to use with Spring Boot", "javaType": "java.lang.String", "ty [...] - { "name": "get", "fullName": "get", "description": "Get status of Camel integrations", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.process.CamelStatus", "options": [ { "names": "--watch", "description": "Execute periodically and showing output fullscreen", "javaType": "boolean", "type": "boolean" }, { "names": "-h,--help", "description": "Display this help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "about", "fullName": "get about" [...] + { "name": "get", "fullName": "get", "description": "Get status of Camel integrations", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.process.CamelStatus", "options": [ { "names": "--watch", "description": "Execute periodically and showing output fullscreen", "javaType": "boolean", "type": "boolean" }, { "names": "-h,--help", "description": "Display this help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "about", "fullName": "get about" [...] { "name": "harden", "fullName": "harden", "description": "Suggest security hardening for Camel routes using AI\/LLM", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Harden", "options": [ { "names": "--api-key", "description": "API key for authentication. Also reads OPENAI_API_KEY or LLM_API_KEY env vars", "javaType": "java.lang.String", "type": "string" }, { "names": "--api-type", "description": "API type: 'ollama' or 'openai' (OpenAI-compatible)", "defaultValue": "ollama", [...] { "name": "hawtio", "fullName": "hawtio", "description": "Launch Hawtio web console", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.process.Hawtio", "options": [ { "names": "--host", "description": "Hostname to bind the Hawtio web console to", "defaultValue": "127.0.0.1", "javaType": "java.lang.String", "type": "string" }, { "names": "--open-url,--openUrl", "description": "To automatic open Hawtio web console in the web browser (without an interactive terminal the default [...] { "name": "infra", "fullName": "infra", "description": "List and Run external services for testing and prototyping", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.infra.InfraCommand", "options": [ { "names": "--json", "description": "Output in JSON Format", "javaType": "boolean", "type": "boolean" }, { "names": "-h,--help", "description": "Display this help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "get", "fullName": "infra get", " [...] diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java index 8a098a6d41cc..49568496213a 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java @@ -431,6 +431,7 @@ public class CamelJBangMain implements Command<CommandInvocation> { .addSubcommand("endpoint", CommandTree.lazy(() -> cmd(new ListEndpoint()))) .addSubcommand("error", CommandTree.lazy(() -> cmd(new ListError()))) .addSubcommand("event", CommandTree.lazy(() -> cmd(new ListEvent()))) + .addSubcommand("genai", CommandTree.lazy(() -> cmd(new CamelGenAiAction()))) .addSubcommand("groovy", CommandTree.lazy(() -> cmd(new ListGroovy()))) .addSubcommand("group", CommandTree.lazy(() -> cmd(new CamelRouteGroupStatus()))) .addSubcommand("health", CommandTree.lazy(() -> cmd(new ListHealth()))) diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiAction.java new file mode 100644 index 000000000000..74d6395ae579 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiAction.java @@ -0,0 +1,374 @@ +/* + * 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.action; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.github.freva.asciitable.AsciiTable; +import com.github.freva.asciitable.Column; +import com.github.freva.asciitable.ColumnData; +import com.github.freva.asciitable.HorizontalAlign; +import com.github.freva.asciitable.OverflowBehaviour; +import org.aesh.command.CommandDefinition; +import org.aesh.command.option.Argument; +import org.aesh.command.option.Mixin; +import org.aesh.command.option.Option; +import org.apache.camel.dsl.jbang.core.common.CliExitCode; +import org.apache.camel.dsl.jbang.core.common.JsonOutput; +import org.apache.camel.dsl.jbang.core.common.ProcessFinder.CamelProcess; +import org.apache.camel.dsl.jbang.core.common.TerminalWidthHelper; +import org.apache.camel.util.TimeUtils; +import org.apache.camel.util.json.JsonArray; +import org.apache.camel.util.json.JsonObject; +import org.apache.camel.util.json.Jsoner; + +/** + * The GenAI calls of an integration from the genai dev console of camel-ai-observability: the model calls per model, + * and the newest agent runs with their model calls and tool calls (CAMEL-27313). + */ +@CommandDefinition(name = "genai", + description = "Display the model calls, agent runs and tool calls of the Camel AI components", + generateHelp = true, + footer = { + "Examples:", + " camel get genai", + " camel get genai --content", + " camel get genai --id 7", + " camel get genai --watch" }) +public class CamelGenAiAction extends ActionWatchCommand { + + static final String NO_CONSOLE = "has no genai dev console: set camel.aiObservability.level (detailed records the " + + "agent runs and tool calls, full the messages), and camel run adds " + + "camel-ai-observability"; + private static final String AGENT_RUN = "invoke_agent"; + private static final String TOOL_CALL = "execute_tool"; + + @Argument(description = "Name or pid of running Camel integration") + String name = "*"; + + @Option(name = "limit", description = "The number of the newest agent runs and model calls to show", + defaultValue = "20") + int limit = 20; + + @Option(name = "id", description = "Show one call (an agent run, a model call or a tool call) with its messages") + String id; + + @Option(name = "content", hasValue = false, + description = "Show the question of each agent run (recorded at camel.aiObservability.level=full)") + boolean content; + + @Option(name = "json", hasValue = false, description = "Output the answer of the genai dev console as JSON") + boolean jsonOutput; + + @Mixin + ActionTimeoutMixin timeoutOption; + + @Override + public Integer doWatchCall() throws Exception { + CamelProcess process = findOne(name); + JsonObject answer = executeAction(process, "genai", root -> { + if (id != null) { + root.put("id", id); + } else { + root.put("limit", String.valueOf(Math.max(0, limit))); + if (content) { + root.put("content", "true"); + } + } + }); + if (answer == null || Boolean.FALSE.equals(answer.getBoolean("enabled")) || answer.getString("level") == null) { + printer().printDiagnostic(process.name() + " " + NO_CONSOLE); + return CliExitCode.OK; + } + if (jsonOutput) { + JsonOutput.print(printer(), answer); + return id != null && answer.getMap("call") == null ? CliExitCode.NOT_FOUND : CliExitCode.OK; + } + if (id != null) { + JsonObject call = answer.getMap("call"); + if (call == null) { + printer().printDiagnostic(answer.getStringOrDefault("error", "No GenAI call with id " + id)); + return CliExitCode.NOT_FOUND; + } + printCall(call); + return CliExitCode.OK; + } + printSummary(answer); + printModels(answer); + printCalls(answer); + return CliExitCode.OK; + } + + private void printSummary(JsonObject answer) { + StringBuilder sb = new StringBuilder(); + sb.append("GenAI level: ").append(answer.getString("level")); + if (!Boolean.TRUE.equals(answer.getBoolean("recording"))) { + sb.append(" (not recording: the dev console is off, camel.main.devConsoleEnabled=true)"); + } + sb.append(" Model calls: ").append(number(answer, "modelCalls")) + .append(" Agent runs: ").append(number(answer, "agentRuns")) + .append(" Tool calls: ").append(number(answer, "toolCalls")) + .append(" Failed: ").append(number(answer, "errors")); + printer().println(sb.toString()); + printer().println("Tokens: in " + number(answer, "inputTokens") + " (cached " + number(answer, "cachedInputTokens") + + "), out " + number(answer, "outputTokens")); + } + + private void printModels(JsonObject answer) { + List<JsonObject> models = objects(answer, "models"); + if (models.isEmpty()) { + return; + } + printer().println(""); + printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, models, List.of( + new Column().header("PROVIDER").dataAlign(HorizontalAlign.LEFT).with(m -> text(m, "provider")), + new Column().header("MODEL").dataAlign(HorizontalAlign.LEFT).with(m -> text(m, "model")), + new Column().header("CALLS").dataAlign(HorizontalAlign.RIGHT).with(m -> "" + number(m, "calls")), + new Column().header("FAILED").dataAlign(HorizontalAlign.RIGHT).with(m -> "" + number(m, "errors")), + new Column().header("IN").dataAlign(HorizontalAlign.RIGHT).with(m -> "" + number(m, "inputTokens")), + new Column().header("CACHED").dataAlign(HorizontalAlign.RIGHT) + .with(m -> "" + number(m, "cachedInputTokens")), + new Column().header("OUT").dataAlign(HorizontalAlign.RIGHT).with(m -> "" + number(m, "outputTokens")), + new Column().header("AVG").dataAlign(HorizontalAlign.RIGHT) + .with(m -> number(m, "calls") > 0 + ? TimeUtils.printDuration(number(m, "durationMs") / number(m, "calls"), true) : "")))); + } + + /** The top-level calls, newest first, each agent run followed by its steps. */ + private void printCalls(JsonObject answer) { + List<Row> rows = new ArrayList<>(); + for (JsonObject call : objects(answer, "calls")) { + rows.add(new Row(call, false)); + for (JsonObject step : objects(call, "steps")) { + rows.add(new Row(step, true)); + } + } + if (rows.isEmpty()) { + return; + } + int tw = terminalWidth(); + int callWidth = TerminalWidthHelper.flexWidth(tw, 70, TerminalWidthHelper.noBorderOverhead(9), 20, 60); + List<ColumnData<Row>> columns = new ArrayList<>(); + columns.add(new Column().header("ID").dataAlign(HorizontalAlign.RIGHT).with(r -> text(r.call(), "id"))); + columns.add(new Column().header("AGE").dataAlign(HorizontalAlign.RIGHT).with(Row::age)); + columns.add(new Column().header("ROUTE").dataAlign(HorizontalAlign.LEFT) + .maxWidth(25, OverflowBehaviour.ELLIPSIS_RIGHT) + .with(r -> r.step() ? "" : text(r.call(), "routeId"))); + columns.add(new Column().header("CALL").dataAlign(HorizontalAlign.LEFT) + .maxWidth(callWidth, OverflowBehaviour.ELLIPSIS_RIGHT) + .with(r -> (r.step() ? " " : "") + text(r.call(), "name"))); + columns.add(new Column().header("IN").dataAlign(HorizontalAlign.RIGHT).with(r -> tokens(r.call(), "inputTokens"))); + columns.add(new Column().header("OUT").dataAlign(HorizontalAlign.RIGHT).with(r -> tokens(r.call(), "outputTokens"))); + columns.add(new Column().header("TIME").dataAlign(HorizontalAlign.RIGHT).with(Row::time)); + columns.add(new Column().header("FINISH").dataAlign(HorizontalAlign.LEFT).with(Row::finish)); + if (content) { + columns.add(new Column().header("QUESTION").dataAlign(HorizontalAlign.LEFT) + .maxWidth(Math.max(20, tw / 3), OverflowBehaviour.ELLIPSIS_RIGHT) + .with(r -> r.step() ? "" : oneLine(r.call().getString("question")))); + } + printer().println(""); + printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, columns)); + long more = number(answer, "moreCalls"); + if (more > 0) { + printer().println("+" + more + " older calls (the console keeps the newest 50)"); + } + } + + /** One call with its messages: the question, each step's answer or tool arguments and result, the answer. */ + private void printCall(JsonObject call) { + StringBuilder head = new StringBuilder("#").append(text(call, "id")).append(' ').append(text(call, "name")); + if (call.getString("routeId") != null) { + head.append(" route: ").append(call.getString("routeId")); + } + head.append(" ").append(new Row(call, false).time()); + if (call.get("inputTokens") != null) { + head.append(" tokens: in ").append(number(call, "inputTokens")).append(", out ") + .append(number(call, "outputTokens")); + } + printer().println(head.toString()); + List<JsonObject> steps = objects(call, "steps"); + JsonObject first = steps.stream().filter(s -> !isRunOrTool(s)).findFirst().orElse(null); + String system = first != null ? systemText(content(first).get("systemInstructions")) : null; + if (system == null) { + // camel-openai records the system message with the input of the run, not as system instructions + system = lastText(content(call).get("inputMessages"), "system"); + } + if (system != null) { + printer().println("system: " + system); + } + String question = call.getString("question"); + if (question == null && steps.isEmpty()) { + question = lastText(content(call).get("inputMessages"), "user"); + } + if (question != null) { + printer().println("question: " + question); + } + for (JsonObject step : steps) { + printer().println(" #" + text(step, "id") + " " + text(step, "name") + " " + new Row(step, true).time() + + stepText(step)); + } + String answer = call.getString("answer"); + if (answer == null && steps.isEmpty()) { + answer = lastText(content(call).get("outputMessages"), "assistant"); + } + if (answer != null) { + printer().println("answer: " + answer); + } + if (call.getMap("content") == null && steps.stream().allMatch(s -> s.getMap("content") == null)) { + printer().println("(no messages: they are recorded at camel.aiObservability.level=full)"); + } + } + + /** A model call's answer (text or tool calls), or a tool call's arguments and result. */ + private static String stepText(JsonObject step) { + JsonObject c = content(step); + if (TOOL_CALL.equals(step.getString("operation"))) { + Object args = c.get("toolArguments"); + Object result = c.get("toolResult"); + return args == null && result == null ? "" : ": " + oneLine(str(args)) + " -> " + oneLine(str(result)); + } + List<String> parts = new ArrayList<>(); + if (c.get("outputMessages") instanceof List<?> messages) { + for (Object m : messages) { + if (m instanceof Map<?, ?> message && message.get("parts") instanceof List<?> ps) { + for (Object p : ps) { + if (p instanceof Map<?, ?> part) { + if ("tool_call".equals(part.get("type"))) { + parts.add("tool call " + part.get("name") + " " + oneLine(str(part.get("arguments")))); + } else if ("text".equals(part.get("type")) && part.get("content") != null + && !part.get("content").toString().isBlank()) { + parts.add(oneLine(part.get("content").toString())); + } + } + } + } + } + } + String finish = step.getString("finishReason"); + return (finish != null ? " (" + finish + ")" : "") + (parts.isEmpty() ? "" : ": " + String.join("; ", parts)); + } + + private static String systemText(Object value) { + Object json = value instanceof String s ? parse(s) : value; + if (json instanceof List<?> parts) { + for (Object p : parts) { + if (p instanceof Map<?, ?> part && part.get("content") != null) { + return oneLine(part.get("content").toString()); + } + } + } + return json instanceof String s ? oneLine(s) : null; + } + + private static String lastText(Object messages, String role) { + String found = null; + if (messages instanceof List<?> list) { + for (Object m : list) { + if (m instanceof Map<?, ?> message && role.equals(message.get("role")) + && message.get("parts") instanceof List<?> ps) { + for (Object p : ps) { + if (p instanceof Map<?, ?> part && "text".equals(part.get("type")) && part.get("content") != null) { + found = oneLine(part.get("content").toString()); + } + } + } + } + } + return found; + } + + private static boolean isRunOrTool(JsonObject call) { + String operation = call.getString("operation"); + return AGENT_RUN.equals(operation) || TOOL_CALL.equals(operation); + } + + private static JsonObject content(JsonObject call) { + JsonObject c = call.getMap("content"); + return c != null ? c : new JsonObject(); + } + + private static List<JsonObject> objects(JsonObject json, String key) { + List<JsonObject> list = new ArrayList<>(); + JsonArray array = json.getCollection(key); + if (array != null) { + for (Object o : array) { + if (o instanceof JsonObject jo) { + list.add(jo); + } + } + } + return list; + } + + private static Object parse(String text) { + try { + return Jsoner.deserialize(text); + } catch (Exception e) { + return text; + } + } + + private static String str(Object value) { + if (value == null) { + return ""; + } + return value instanceof Map || value instanceof List ? Jsoner.serialize(value) : value.toString(); + } + + private static String oneLine(String text) { + return text != null ? text.replaceAll("\\s+", " ").strip() : null; + } + + private static String text(JsonObject json, String key) { + String value = json.getString(key); + return value != null ? value : ""; + } + + private static long number(JsonObject json, String key) { + return json.get(key) instanceof Number n ? n.longValue() : 0; + } + + private static String tokens(JsonObject call, String key) { + return call.get(key) instanceof Number n ? n.toString() : ""; + } + + private record Row(JsonObject call, boolean step) { + + String age() { + long timestamp = number(call, "timestamp"); + return step || timestamp <= 0 ? "" : TimeUtils.printSince(timestamp); + } + + String time() { + if (Boolean.TRUE.equals(call.getBoolean("running"))) { + return "running"; + } + return call.get("durationMs") instanceof Number n ? TimeUtils.printDuration(n.longValue(), true) : ""; + } + + String finish() { + String error = call.getString("error"); + if (error != null) { + return "failed: " + error; + } + String finish = call.getString("finishReason"); + return finish != null ? finish : ""; + } + } +} diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiActionTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiActionTest.java new file mode 100644 index 000000000000..ccd6be41a3c1 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGenAiActionTest.java @@ -0,0 +1,262 @@ +/* + * 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.action; + +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import org.apache.camel.dsl.jbang.core.commands.CamelCommandBaseTestSupport; +import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain; +import org.apache.camel.dsl.jbang.core.common.CliExitCode; +import org.apache.camel.dsl.jbang.core.common.ProcessFinder.CamelProcess; +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.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * CAMEL-27313: camel get genai shows the answer of the genai dev console of an integration. + */ +class CamelGenAiActionTest extends CamelCommandBaseTestSupport { + + @BeforeEach + @Override + public void setup() throws Exception { + super.setup(); + useTestHomeDir(); + } + + @Test + void theModelsAndTheRunsWithTheirSteps() throws Exception { + JsonObject answer = console("detailed", run(false)); + answer.put("moreCalls", 3L); + Testable command = command(answer); + + assertThat(command.doWatchCall()).isEqualTo(CliExitCode.OK); + + String output = printer.getOutput(); + assertThat(output) + .contains("GenAI level: detailed Model calls: 2 Agent runs: 1 Tool calls: 1 Failed: 0") + .contains("Tokens: in 338 (cached 195), out 28") + .contains("PROVIDER", "openai", "llama3.2") + .contains("invoke_agent support-agent", " chat llama3.2", " execute_tool lookupOrder", "tool_calls") + .contains("+3 older calls") + .doesNotContain("QUESTION"); + assertThat(output.indexOf("execute_tool")).isBetween(output.indexOf("chat llama3.2"), + output.lastIndexOf("chat llama3.2")); + assertThat(command.sent).containsEntry("action", "genai").containsEntry("limit", "20").doesNotContainKey("content"); + } + + @Test + void contentAddsTheQuestionOfEachRun() throws Exception { + Testable command = command(console("full", run(true))); + command.content = true; + + command.doWatchCall(); + + assertThat(printer.getOutput()).contains("QUESTION", "What is the status of order A-17?"); + assertThat(command.sent).containsEntry("content", "true"); + } + + @Test + void oneCallWithItsMessages() throws Exception { + JsonObject answer = new JsonObject(); + answer.put("level", "full"); + answer.put("call", run(true)); + Testable command = command(answer); + command.id = "5"; + + assertThat(command.doWatchCall()).isEqualTo(CliExitCode.OK); + + assertThat(printer.getOutput()) + .contains("#5 invoke_agent support-agent route: support-agent") + .contains("system: You are a support agent.") + .contains("question: What is the status of order A-17?") + .contains("#6 chat llama3.2", "(tool_calls): tool call lookupOrder {\"orderId\":\"A-17\"}") + .contains("#7 execute_tool lookupOrder", ": {\"orderId\":\"A-17\"} -> DELIVERED") + .contains("answer: The order A-17 is delivered.") + .doesNotContain("no messages"); + assertThat(command.sent).containsEntry("id", "5").doesNotContainKey("limit"); + } + + @Test + void theSystemMessageMayBeInTheInputOfTheRun() throws Exception { + // as camel-openai records it + JsonObject run = run(true); + JsonObject first = (JsonObject) run.<JsonArray> getCollection("steps").get(0); + first.getMap("content").remove("systemInstructions"); + run.put("content", new JsonObject( + Map.of("inputMessages", Jsoner.deserialize( + "[{\"role\":\"system\",\"parts\":[{\"type\":\"text\",\"content\":\"You answer orders.\"}]}]", + (JsonArray) null)))); + JsonObject answer = new JsonObject(); + answer.put("level", "full"); + answer.put("call", run); + Testable command = command(answer); + command.id = "5"; + + command.doWatchCall(); + + assertThat(printer.getOutput()).contains("system: You answer orders."); + } + + @Test + void oneCallWithoutMessagesSaysTheLevel() throws Exception { + JsonObject answer = new JsonObject(); + answer.put("level", "detailed"); + answer.put("call", run(false)); + Testable command = command(answer); + command.id = "5"; + + command.doWatchCall(); + + assertThat(printer.getOutput()).contains("no messages: they are recorded at camel.aiObservability.level=full"); + } + + @Test + void aCallThatIsNoLongerKeptIsNotFound() throws Exception { + JsonObject answer = new JsonObject(); + answer.put("level", "full"); + answer.put("error", "No GenAI call with id 99: it may no longer be kept"); + Testable command = command(answer); + command.id = "99"; + + assertThat(command.doWatchCall()).isEqualTo(CliExitCode.NOT_FOUND); + assertThat(printer.getOutput()).contains("No GenAI call with id 99"); + } + + @Test + void anIntegrationWithoutTheConsoleSaysHowToGetIt() throws Exception { + Testable command = command(new JsonObject(Map.of("enabled", false))); + + assertThat(command.doWatchCall()).isEqualTo(CliExitCode.OK); + assertThat(printer.getOutput()).contains("test " + CamelGenAiAction.NO_CONSOLE); + } + + @Test + void jsonIsTheAnswerOfTheConsole() throws Exception { + Testable command = command(console("detailed", run(false))); + command.jsonOutput = true; + + command.doWatchCall(); + + JsonObject json = Jsoner.deserialize(printer.getOutput(), (JsonObject) null); + assertThat(json.getString("level")).isEqualTo("detailed"); + JsonArray calls = json.getCollection("calls"); + assertThat(calls).hasSize(1); + } + + private Testable command(JsonObject answer) { + return new CamelJBangMain().withPrinter(printer).command(new Testable(answer)); + } + + private static JsonObject console(String level, JsonObject... calls) { + JsonObject model = new JsonObject(); + model.put("provider", "openai"); + model.put("model", "llama3.2"); + model.put("calls", 2L); + model.put("errors", 0L); + model.put("inputTokens", 338L); + model.put("outputTokens", 28L); + model.put("cachedInputTokens", 195L); + model.put("durationMs", 380L); + JsonObject answer = new JsonObject(); + answer.put("recording", true); + answer.put("level", level); + answer.put("modelCalls", 2L); + answer.put("agentRuns", 1L); + answer.put("toolCalls", 1L); + answer.put("errors", 0L); + answer.put("inputTokens", 338L); + answer.put("outputTokens", 28L); + answer.put("cachedInputTokens", 195L); + answer.put("models", new JsonArray(List.of(model))); + answer.put("calls", new JsonArray(List.of((Object[]) calls))); + answer.put("moreCalls", 0L); + return answer; + } + + private static JsonObject run(boolean withContent) { + JsonObject run = call("5", "invoke_agent", "invoke_agent support-agent", 384); + run.put("routeId", "support-agent"); + run.put("timestamp", System.currentTimeMillis() - 5000); + run.put("inputTokens", 338L); + run.put("outputTokens", 28L); + JsonObject first = call("6", "chat", "chat llama3.2", 230); + first.put("inputTokens", 196L); + first.put("outputTokens", 15L); + first.put("finishReason", "tool_calls"); + JsonObject tool = call("7", "execute_tool", "execute_tool lookupOrder", 1); + JsonObject second = call("8", "chat", "chat llama3.2", 151); + second.put("inputTokens", 142L); + second.put("outputTokens", 13L); + second.put("finishReason", "stop"); + if (withContent) { + run.put("question", "What is the status of order A-17?"); + run.put("answer", "The order A-17 is delivered."); + first.put("content", new JsonObject( + Map.of( + "systemInstructions", "[{\"type\":\"text\",\"content\":\"You are a support agent.\"}]", + "outputMessages", Jsoner.deserialize( + "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"\"}," + + "{\"type\":\"tool_call\",\"name\":\"lookupOrder\"," + + "\"arguments\":{\"orderId\":\"A-17\"}}]}]", + (JsonArray) null)))); + tool.put("content", new JsonObject(Map.of("toolArguments", "{\"orderId\":\"A-17\"}", "toolResult", "DELIVERED"))); + } + run.put("steps", new JsonArray(List.of(first, tool, second))); + return run; + } + + private static JsonObject call(String id, String operation, String name, long ms) { + JsonObject call = new JsonObject(); + call.put("id", id); + call.put("operation", operation); + call.put("name", name); + call.put("running", false); + call.put("durationMs", ms); + return call; + } + + /** Bypasses process discovery and the action file, and keeps the options sent with the action. */ + private static class Testable extends CamelGenAiAction { + private final JsonObject answer; + private final JsonObject sent = new JsonObject(); + + Testable(JsonObject answer) { + this.answer = answer; + } + + @Override + protected CamelProcess findOne(String name) { + return new CamelProcess(12345L, "test", new JsonObject()); + } + + @Override + protected JsonObject executeAction(CamelProcess process, String action, Consumer<JsonObject> options) { + sent.put("action", action); + if (options != null) { + options.accept(sent); + } + return answer; + } + } +} diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt index 60d765c1f5e9..445970fbce22 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt +++ b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt @@ -3804,6 +3804,8 @@ get commands: endpoint Get usage of Camel endpoints error Get captured routing errors of Camel integrations event Get latest events of Camel integrations + genai Display the model calls, agent runs and tool calls of the + Camel AI components groovy Groovy Sources used of Camel integrations group Get status of Camel route groups health Get health check status of running Camel integrations @@ -4179,6 +4181,38 @@ Examples: camel get event camel get event --watch +== camel get genai --help +Display the model calls, agent runs and tool calls of the Camel AI components +Usage: camel get genai [-h] [--limit=<limit>] [--id=<id>] [--content] [--json] + [--timeout=<timeout>] [--watch] [--duration=<duration>] + [<name>] + +Options: + -h, --help Display this help and exit + --limit=<limit> The number of the newest agent runs and model calls + to show + Default: 20 + --id=<id> Show one call (an agent run, a model call or a tool + call) with its messages + --content Show the question of each agent run (recorded at + camel.aiObservability.level=full) + --json Output the answer of the genai dev console as JSON + --timeout=<timeout> How long to wait for the integration to answer, in + millis or as a duration such as 30s + Default: 10000 + --watch Execute periodically and showing output fullscreen + --duration=<duration> + How long to keep watching or following, in millis or + as a duration such as 30s (default: until Enter is + pressed) + <name> Name or pid of running Camel integration + +Examples: + camel get genai + camel get genai --content + camel get genai --id 7 + camel get genai --watch + == camel get groovy --help Groovy Sources used of Camel integrations Usage: camel get groovy [-h] [--sort=<sort>] [--watch] [--json]
