davsclaus commented on code in PR #25337:
URL: https://github.com/apache/camel/pull/25337#discussion_r3726106086
##########
components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIProducer.java:
##########
@@ -602,23 +609,66 @@ private void enforceAgenticTokenBudget(
}
private void processStreaming(Exchange exchange,
ChatCompletionCreateParams params) {
+ String requestModel = params.model().toString();
+ ChatCompletionCreateParams streamingParams = params.toBuilder()
+
.streamOptions(ChatCompletionStreamOptions.builder().includeUsage(true).build())
Review Comment:
**Behavioral change — `streamOptions(includeUsage=true)` injected
unconditionally**
This modifies the outgoing API payload for ALL streaming requests, causing
the stream to include a final chunk with token usage data. Two concerns:
1. **Downstream consumers** iterating the stream chunks may receive an
unexpected usage-only chunk they don't handle
2. **Non-OpenAI providers** accessed through camel-openai may not support
this option, potentially causing 400 errors
This should either be opt-in (gated behind the
`camel.ai.observability.enabled` property) or at minimum documented as a
behavioral change in the upgrade guide entry. Currently the upgrade guide does
not mention this streaming behavior change.
##########
components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservability.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.component.ai.observability;
+
+import java.util.Optional;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+
+/**
+ * Entry point for GenAI observability in Camel AI producers.
+ * <p/>
+ * The concrete tracing and metrics implementation lives in {@code
camel-ai-observability} and is loaded via reflection
+ * when that module is on the classpath. Without it, calls return a no-op
observation.
+ */
+public final class GenAiObservability {
+
+ private static final String IMPL_CLASS =
"org.apache.camel.component.ai.observability.GenAiObservabilityImpl";
+ private static final GenAiObservation NOOP = new NoopGenAiObservation();
+
+ private GenAiObservability() {
+ }
+
+ /**
+ * Whether GenAI observability is enabled for the given context.
+ */
+ public static boolean isEnabled(CamelContext camelContext) {
+ if (camelContext == null) {
+ return false;
+ }
+ Optional<String> property
+ =
camelContext.getPropertiesComponent().resolveProperty(GenAiObservabilityProperties.ENABLED);
+ if (property.isPresent()) {
+ return Boolean.parseBoolean(property.get().trim());
+ }
+ return true;
+ }
+
+ /**
+ * Starts a GenAI observation for a single LLM client call. Returns a
no-op when disabled, when
+ * {@code camel-ai-observability} is absent, or when no backend is
available.
+ */
+ public static GenAiObservation start(Exchange exchange,
GenAiObservationContext context) {
+ if (exchange == null || context == null ||
!isEnabled(exchange.getContext())) {
+ return NOOP;
+ }
+ CamelContext camelContext = exchange.getContext();
+ if (camelContext.getClassResolver().resolveClass(IMPL_CLASS) == null) {
+ return NOOP;
+ }
+ try {
+ Class<?> implClass =
camelContext.getClassResolver().resolveClass(IMPL_CLASS);
+ return (GenAiObservation) implClass.getMethod("start",
Exchange.class, GenAiObservationContext.class)
+ .invoke(null, exchange, context);
+ } catch (Throwable t) {
Review Comment:
**Two issues in `start()`:**
1. **Double class resolution** — `resolveClass(IMPL_CLASS)` is called twice
(line 62 and line 66). Store the result in a local variable and reuse it.
2. **`catch (Throwable t)` is too broad** — This swallows fatal `Error`
types (`OutOfMemoryError`, `StackOverflowError`). The impl module's
`resolveMetricsBackend()` correctly catches `ReflectiveOperationException |
LinkageError`. This catch should do the same.
```suggestion
Class<?> implClass =
camelContext.getClassResolver().resolveClass(IMPL_CLASS);
if (implClass == null) {
return NOOP;
}
try {
return (GenAiObservation) implClass.getMethod("start",
Exchange.class, GenAiObservationContext.class)
.invoke(null, exchange, context);
} catch (ReflectiveOperationException | LinkageError e) {
return NOOP;
}
```
##########
components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiObservabilityImpl.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.component.ai.observability;
+
+import java.lang.reflect.Constructor;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.telemetry.Span;
+import org.apache.camel.telemetry.SpanLifecycleManager;
+import org.apache.camel.telemetry.SpanStorageManagerExchange;
+import org.apache.camel.telemetry.Tracer;
+import
org.apache.camel.telemetry.propagation.CamelHeadersSpanContextPropagationExtractor;
+import org.apache.camel.util.ObjectHelper;
+
+/**
+ * GenAI observability implementation loaded reflectively from {@link
GenAiObservability}.
+ */
+public final class GenAiObservabilityImpl {
+
+ private static final GenAiObservation NOOP = new NoopGenAiObservation();
+ private static final String CLIENT_SPAN_KIND = "CLIENT";
+ private static final String METER_REGISTRY_CLASS =
"io.micrometer.core.instrument.MeterRegistry";
+ private static final String MICROMETER_SUPPORT_CLASS
+ =
"org.apache.camel.component.ai.observability.GenAiMicrometerSupport";
+
+ private GenAiObservabilityImpl() {
+ }
+
+ /**
+ * Starts a GenAI observation for a single LLM client call. Returns a
no-op when no backend is available.
+ */
+ public static GenAiObservation start(Exchange exchange,
GenAiObservationContext context) {
+ Tracer tracer = exchange.getContext().hasService(Tracer.class);
+ GenAiMetricsBackend metricsBackend =
resolveMetricsBackend(exchange.getContext());
+ if (tracer == null && (metricsBackend == null ||
!metricsBackend.isAvailable())) {
+ return NOOP;
+ }
+ return new DefaultGenAiObservation(exchange, context, tracer,
metricsBackend);
+ }
+
+ private static GenAiMetricsBackend resolveMetricsBackend(CamelContext
camelContext) {
+ try {
+ Class.forName(METER_REGISTRY_CLASS);
+ Class<?> supportClass = Class.forName(MICROMETER_SUPPORT_CLASS);
+ Constructor<?> constructor =
supportClass.getDeclaredConstructor(CamelContext.class);
+ return (GenAiMetricsBackend) constructor.newInstance(camelContext);
+ } catch (ReflectiveOperationException | LinkageError e) {
+ return null;
+ }
+ }
+
+ private static final class DefaultGenAiObservation implements
GenAiObservation {
+
+ private final Exchange exchange;
+ private final GenAiObservationContext context;
+ private final Tracer tracer;
+ private final GenAiMetricsBackend metricsBackend;
+ private final long startNanos;
+ private Span span;
+ private GenAiUsage usage;
+ private Throwable error;
+ private boolean closed;
+
+ private DefaultGenAiObservation(
+ Exchange exchange,
GenAiObservationContext context, Tracer tracer,
+ GenAiMetricsBackend metricsBackend) {
+ this.exchange = exchange;
+ this.context = context;
+ this.tracer = tracer;
+ this.metricsBackend = metricsBackend;
+ this.startNanos = System.nanoTime();
+ startSpan();
+ }
+
+ private void startSpan() {
+ if (tracer == null || tracer.getSpanLifecycleManager() == null) {
+ return;
+ }
+ SpanStorageManagerExchange storage = new
SpanStorageManagerExchange();
+ Span parent = storage.peek(exchange);
+ SpanLifecycleManager lifecycleManager =
tracer.getSpanLifecycleManager();
+ var extractor = new
CamelHeadersSpanContextPropagationExtractor(exchange.getIn().getHeaders());
+ span = lifecycleManager.create(context.spanName(),
CLIENT_SPAN_KIND, parent, extractor);
+ lifecycleManager.activate(span);
+ applyContextAttributes(span, context, null, null);
+ }
+
+ @Override
+ public void recordSuccess(GenAiUsage usage) {
+ this.usage = usage;
+ }
+
+ @Override
+ public void recordError(Throwable error) {
+ this.error = error;
+ }
+
+ @Override
+ public void close() {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ closeSpan();
+ recordMetrics();
+ }
+
+ private void closeSpan() {
+ if (span == null || tracer == null ||
tracer.getSpanLifecycleManager() == null) {
+ return;
+ }
+ SpanLifecycleManager lifecycleManager =
tracer.getSpanLifecycleManager();
+ if (error != null) {
+ span.setError(true);
+ span.setTag(GenAiAttributes.ERROR_TYPE,
error.getClass().getSimpleName());
+ }
+ if (usage != null) {
+ applyContextAttributes(span, context, usage, error == null ?
usage.responseModel() : null);
+ }
+ lifecycleManager.deactivate(span);
+ lifecycleManager.close(span);
+ span = null;
+ }
+
+ private void recordMetrics() {
+ if (metricsBackend == null) {
+ return;
+ }
+ metricsBackend.recordMetrics(context, usage, error, startNanos);
+ }
+
+ private static void applyContextAttributes(
+ Span span, GenAiObservationContext context, GenAiUsage usage,
String responseModel) {
+ span.setTag(GenAiAttributes.OPERATION_NAME,
context.operationName().value());
+ span.setTag(GenAiAttributes.SYSTEM,
nullToUnknown(context.system()));
+ span.setTag(GenAiAttributes.REQUEST_MODEL,
nullToUnknown(context.requestModel()));
+ if (ObjectHelper.isNotEmpty(context.componentScheme())) {
+ span.setTag(GenAiAttributes.CAMEL_COMPONENT,
context.componentScheme());
+ }
+ if (responseModel != null && !responseModel.isBlank()) {
+ span.setTag(GenAiAttributes.RESPONSE_MODEL, responseModel);
+ }
+ if (usage != null) {
+ if (usage.inputTokens() != null) {
+ span.setTag(GenAiAttributes.INPUT_TOKENS,
usage.inputTokens().toString());
+ }
+ if (usage.outputTokens() != null) {
+ span.setTag(GenAiAttributes.OUTPUT_TOKENS,
usage.outputTokens().toString());
+ }
+ if (usage.finishReason() != null) {
+ span.setTag(GenAiAttributes.FINISH_REASONS,
usage.finishReason());
+ }
+ if (usage.responseModel() != null &&
!usage.responseModel().isBlank()) {
+ span.setTag(GenAiAttributes.RESPONSE_MODEL,
usage.responseModel());
Review Comment:
**`RESPONSE_MODEL` set redundantly, defeating the error-path guard**
The `responseModel` parameter is set conditionally at line 156, then
`usage.responseModel()` unconditionally overwrites it at line 169. On the error
path, `closeSpan()` passes `null` as `responseModel` (via `error == null ?
usage.responseModel() : null`) intending to suppress it, but this second block
defeats that guard since `usage.responseModel()` may still be non-null.
Either remove the redundant second block, or adjust the logic so the
error-path intent is preserved.
##########
components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/Headers.java:
##########
@@ -56,6 +56,12 @@ public class Headers {
@Metadata(description = "The Total Token Count.", javaType = "int")
public static final String TOTAL_TOKEN_COUNT =
"CamelLangChain4jAgentTotalTokenCount";
+ @Metadata(description = "The request model name.", javaType = "String")
+ public static final String REQUEST_MODEL =
"CamelLangChain4jAgentRequestModel";
+
+ @Metadata(description = "The response model name.", javaType = "String")
+ public static final String RESPONSE_MODEL =
"CamelLangChain4jAgentResponseModel";
Review Comment:
**`RESPONSE_MODEL` header is declared but never populated by the agent
producer.**
The `LangChain4jAgentProducer` never sets this header because the
langchain4j `Result<String>` doesn't expose a response model name. The constant
appears in the catalog/endpoint-dsl, creating a misleading API surface for
users who see it in the documentation.
Either:
- Remove the constant until the agent producer can actually populate it, or
- Add a Javadoc note that this is reserved for future use when langchain4j
exposes response model information
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]