atiaomar1978-hub commented on code in PR #25337:
URL: https://github.com/apache/camel/pull/25337#discussion_r3726144957


##########
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:
   Fixed in `5f196cf`: `stream_options.include_usage=true` is now set only when 
`GenAiObservability.isEnabled()` is true. Documented in the 4.22 upgrade guide.



##########
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:
   Fixed in `5f196cf`: single `resolveClass` lookup; catch narrowed to 
`ReflectiveOperationException | LinkageError`.



##########
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:
   Fixed in `5f196cf`: removed redundant `usage.responseModel()` span tag so 
the error-path guard in `closeSpan()` is effective.



##########
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:
   Addressed in `5f196cf`: updated `@Metadata` description to note the agent 
producer does not set this header when langchain4j Result lacks a response 
model. Upgrade guide updated accordingly.



-- 
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]

Reply via email to