This is an automated email from the ASF dual-hosted git repository.

jamesnetherton 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 4e30036df236 CAMEL-27155: camel-ai-observability - discover the 
implementation through the FactoryFinder instead of reflection (#30329)
4e30036df236 is described below

commit 4e30036df23623b0ad49f5c8e30582b7223be0e6
Author: James Netherton <[email protected]>
AuthorDate: Wed Nov 18 09:47:58 2026 +0000

    CAMEL-27155: camel-ai-observability - discover the implementation through 
the FactoryFinder instead of reflection (#30329)
    
    GenAiObservability resolves a GenAiObservationFactory from the registry or 
the
    ai-observation-factory service instead of invoking GenAiObservabilityImpl 
reflectively.
    The factory is kept as a context plugin and holds its Micrometer backends, 
so a stopped
    CamelContext is no longer kept reachable by static maps. Observability 
still never fails
    the LLM call: a load failure gives a cached no-op factory, and a Micrometer 
backend that
    cannot be linked disables that backend only.
    
    Co-authored-by: Guillaume Nodet <[email protected]>
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../ai/observability/GenAiObservability.java       |  79 ++++++++--------
 .../ai/observability/GenAiObservationFactory.java  |  38 ++++++++
 .../GenAiObservationFactoryRegistryTest.java       |  91 ++++++++++++++++++
 .../org/apache/camel/ai-observation-factory        |   2 +
 .../GenAiMicrometerObservationSupport.java         |   3 +-
 .../ai/observability/GenAiMicrometerSupport.java   |   2 +-
 .../ai/observability/GenAiObservabilityImpl.java   |  76 ++++++++-------
 .../GenAiObservabilityFactoryLinkageErrorTest.java | 103 +++++++++++++++++++++
 .../GenAiObservabilityMetricsLinkageErrorTest.java |  87 +++++++++++++++++
 ...mel-factoryfinder-known-dependencies.properties |   1 +
 .../camel-main-known-dependencies.properties       |   1 -
 11 files changed, 408 insertions(+), 75 deletions(-)

diff --git 
a/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservability.java
 
b/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservability.java
index 0918f85181cc..594ea7b5158d 100644
--- 
a/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservability.java
+++ 
b/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservability.java
@@ -16,30 +16,29 @@
  */
 package org.apache.camel.component.ai.observability;
 
-import java.lang.reflect.Method;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.Exchange;
+import org.apache.camel.ExtendedCamelContext;
+import org.apache.camel.support.ResolverHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * 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.
+ * The concrete tracing and metrics implementation lives in {@code 
camel-ai-observability}, which provides a
+ * {@link GenAiObservationFactory}. Without it, calls return a no-op 
observation.
  */
 public final class GenAiObservability {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(GenAiObservability.class);
-    private static final String IMPL_CLASS = 
"org.apache.camel.component.ai.observability.GenAiObservabilityImpl";
     private static final GenAiObservation NOOP = new NoopGenAiObservation();
-    private static final ImplBridge UNAVAILABLE_BRIDGE = new ImplBridge(null);
-    private static final ConcurrentMap<CamelContext, ImplBridge> BRIDGES = new 
ConcurrentHashMap<>();
+    private static final GenAiObservationFactory NOOP_FACTORY = (exchange, 
context) -> NOOP;
+    private static final Object FACTORY_LOCK = new Object();
     private static final Set<String> INVALID_LEVEL_REPORTED = 
ConcurrentHashMap.newKeySet();
 
     private GenAiObservability() {
@@ -147,46 +146,52 @@ public final class GenAiObservability {
             // the AI framework records this call itself; a second span would 
count it twice
             return NOOP;
         }
-        CamelContext camelContext = exchange.getContext();
-        ImplBridge bridge = BRIDGES.computeIfAbsent(camelContext, 
GenAiObservability::resolveBridge);
-        if (bridge.startMethod == null) {
-            return NOOP;
-        }
+        GenAiObservationFactory factory = factory(exchange.getContext());
         try {
-            return (GenAiObservation) bridge.startMethod.invoke(null, 
exchange, context);
-        } catch (ReflectiveOperationException | LinkageError e) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Unable to start GenAI observation via {}", 
IMPL_CLASS, e);
-            }
+            return factory.start(exchange, context);
+        } catch (RuntimeException | LinkageError e) {
+            // observability must never fail the LLM call, not even with a 
Micrometer or OpenTelemetry version mismatch
+            LOG.debug("Unable to start GenAI observation via {}", factory, e);
             return NOOP;
         }
     }
 
-    private static ImplBridge resolveBridge(CamelContext camelContext) {
-        Class<?> implClass = 
camelContext.getClassResolver().resolveClass(IMPL_CLASS);
-        if (implClass == null) {
-            LOG.info(
-                    "GenAI observability is enabled but camel-ai-observability 
is not on the classpath; "
-                     + "spans and metrics will not be emitted");
-            return UNAVAILABLE_BRIDGE;
-        }
-        try {
-            Method startMethod = implClass.getMethod("start", Exchange.class, 
GenAiObservationContext.class);
-            return new ImplBridge(startMethod);
-        } catch (ReflectiveOperationException | LinkageError e) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Unable to resolve GenAI observability bridge from 
{}", IMPL_CLASS, e);
+    private static GenAiObservationFactory factory(CamelContext camelContext) {
+        // kept as a context plugin so it goes away with its context
+        ExtendedCamelContext extension = 
camelContext.getCamelContextExtension();
+        GenAiObservationFactory factory = 
extension.getContextPlugin(GenAiObservationFactory.class);
+        if (factory == null) {
+            synchronized (FACTORY_LOCK) {
+                factory = 
extension.getContextPlugin(GenAiObservationFactory.class);
+                if (factory == null) {
+                    factory = resolveFactory(camelContext);
+                    extension.addContextPlugin(GenAiObservationFactory.class, 
factory);
+                }
             }
-            return UNAVAILABLE_BRIDGE;
         }
+        return factory;
     }
 
-    private static final class ImplBridge {
-        private final Method startMethod;
-
-        private ImplBridge(Method startMethod) {
-            this.startMethod = startMethod;
+    private static GenAiObservationFactory resolveFactory(CamelContext 
camelContext) {
+        GenAiObservationFactory factory;
+        try {
+            factory = 
camelContext.getRegistry().findSingleByType(GenAiObservationFactory.class);
+            if (factory == null) {
+                factory = ResolverHelper.resolveService(camelContext, 
GenAiObservationFactory.FACTORY,
+                        GenAiObservationFactory.class).orElse(null);
+            }
+        } catch (RuntimeException | LinkageError e) {
+            // a broken classpath must not fail the LLM call; the no-op 
factory is kept so this is reported once
+            LOG.warn("Unable to load the GenAI observability implementation; 
spans and metrics will not be emitted", e);
+            return NOOP_FACTORY;
+        }
+        if (factory == null) {
+            LOG.info(
+                    "GenAI observability is enabled but camel-ai-observability 
is not on the classpath; "
+                     + "spans and metrics will not be emitted");
+            return NOOP_FACTORY;
         }
+        return factory;
     }
 
     private static final class NoopGenAiObservation implements 
GenAiObservation {
diff --git 
a/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservationFactory.java
 
b/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservationFactory.java
new file mode 100644
index 000000000000..b5cb10c45205
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-observability-api/src/main/java/org/apache/camel/component/ai/observability/GenAiObservationFactory.java
@@ -0,0 +1,38 @@
+/*
+ * 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 org.apache.camel.Exchange;
+
+/**
+ * Creates GenAI observations. {@code camel-ai-observability} provides the 
implementation, discovered through the Camel
+ * {@code FactoryFinder} under {@link #FACTORY}, or bound in the registry.
+ *
+ * @since 4.24
+ */
+public interface GenAiObservationFactory {
+
+    /**
+     * Service factory key.
+     */
+    String FACTORY = "ai-observation-factory";
+
+    /**
+     * Starts a GenAI observation for a single LLM client call. Returns a 
no-op when no backend is available.
+     */
+    GenAiObservation start(Exchange exchange, GenAiObservationContext context);
+}
diff --git 
a/components/camel-ai/camel-ai-observability-api/src/test/java/org/apache/camel/component/ai/observability/GenAiObservationFactoryRegistryTest.java
 
b/components/camel-ai/camel-ai-observability-api/src/test/java/org/apache/camel/component/ai/observability/GenAiObservationFactoryRegistryTest.java
new file mode 100644
index 000000000000..6590a15d0efc
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-observability-api/src/test/java/org/apache/camel/component/ai/observability/GenAiObservationFactoryRegistryTest.java
@@ -0,0 +1,91 @@
+/*
+ * 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.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GenAiObservationFactoryRegistryTest extends ExchangeTestSupport {
+
+    private final AtomicInteger started = new AtomicInteger();
+    private final GenAiObservation observation = new GenAiObservation() {
+        @Override
+        public void recordSuccess(GenAiUsage usage) {
+        }
+
+        @Override
+        public void recordError(Throwable error) {
+        }
+
+        @Override
+        public void close() {
+        }
+    };
+
+    @Test
+    void shouldUseFactoryFromRegistry() {
+        context.getRegistry().bind("genAiObservationFactory", 
(GenAiObservationFactory) (exchange, ctx) -> {
+            started.incrementAndGet();
+            return observation;
+        });
+
+        assertThat(GenAiObservability.start(newExchange(), 
observationContext())).isSameAs(observation);
+        assertThat(started).hasValue(1);
+    }
+
+    @Test
+    void shouldReturnNoopWhenFactoryFails() {
+        context.getRegistry().bind("genAiObservationFactory", 
(GenAiObservationFactory) (exchange, ctx) -> {
+            throw new IllegalStateException("boom");
+        });
+
+        GenAiObservation result = GenAiObservability.start(newExchange(), 
observationContext());
+
+        assertThat(result).isNotNull().isNotSameAs(observation);
+        result.close();
+    }
+
+    @Test
+    void shouldReturnNoopWhenFactoryFailsWithLinkageError() {
+        // as a handler built against another Micrometer version would
+        context.getRegistry().bind("genAiObservationFactory", 
(GenAiObservationFactory) (exchange, ctx) -> {
+            throw new NoSuchMethodError("'void 
io.micrometer.observation.Observation$Context.example()'");
+        });
+
+        GenAiObservation result = GenAiObservability.start(newExchange(), 
observationContext());
+
+        assertThat(result).isNotNull().isNotSameAs(observation);
+        result.close();
+    }
+
+    private Exchange newExchange() {
+        return new DefaultExchange(context);
+    }
+
+    private static GenAiObservationContext observationContext() {
+        return GenAiObservationContext.builder()
+                .operationName(GenAiOperationName.CHAT)
+                .requestModel("gpt-4o")
+                .build();
+    }
+}
diff --git 
a/components/camel-ai/camel-ai-observability/src/generated/resources/META-INF/services/org/apache/camel/ai-observation-factory
 
b/components/camel-ai/camel-ai-observability/src/generated/resources/META-INF/services/org/apache/camel/ai-observation-factory
new file mode 100644
index 000000000000..ebcfec01d6bf
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-observability/src/generated/resources/META-INF/services/org/apache/camel/ai-observation-factory
@@ -0,0 +1,2 @@
+# Generated by camel build tools - do NOT edit this file!
+class=org.apache.camel.component.ai.observability.GenAiObservabilityImpl
diff --git 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerObservationSupport.java
 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerObservationSupport.java
index 57cbe2d6e86c..be7c5025b71b 100644
--- 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerObservationSupport.java
+++ 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerObservationSupport.java
@@ -28,8 +28,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Micrometer Observation-backed instrumentation. Loaded reflectively only 
when {@link ObservationRegistry} is on the
- * classpath.
+ * Micrometer Observation-backed instrumentation. Only loaded when {@link 
ObservationRegistry} is on the classpath.
  */
 final class GenAiMicrometerObservationSupport implements 
GenAiMicrometerObservationBackend {
 
diff --git 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerSupport.java
 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerSupport.java
index 35bbef8bb662..e23a30195248 100644
--- 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerSupport.java
+++ 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiMicrometerSupport.java
@@ -29,7 +29,7 @@ import org.apache.camel.support.CamelContextHelper;
 import org.apache.camel.util.ObjectHelper;
 
 /**
- * Micrometer-backed metrics recording. Loaded reflectively only when {@link 
MeterRegistry} is on the classpath.
+ * Micrometer-backed metrics recording. Only loaded when {@link MeterRegistry} 
is on the classpath.
  */
 final class GenAiMicrometerSupport implements GenAiMetricsBackend {
 
diff --git 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiObservabilityImpl.java
 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiObservabilityImpl.java
index 0f8e5862107d..85eaea7a83c7 100644
--- 
a/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiObservabilityImpl.java
+++ 
b/components/camel-ai/camel-ai-observability/src/main/java/org/apache/camel/component/ai/observability/GenAiObservabilityImpl.java
@@ -16,16 +16,14 @@
  */
 package org.apache.camel.component.ai.observability;
 
-import java.lang.reflect.Constructor;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 import java.util.function.Supplier;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.Exchange;
+import org.apache.camel.spi.annotations.JdkService;
 import org.apache.camel.telemetry.Span;
 import org.apache.camel.telemetry.SpanLifecycleManager;
 import org.apache.camel.telemetry.SpanStorageManagerExchange;
@@ -36,9 +34,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * GenAI observability implementation loaded reflectively from {@link 
GenAiObservability}.
+ * GenAI observability implementation, discovered by {@link 
GenAiObservability} through the factory finder.
  */
-public final class GenAiObservabilityImpl {
+@JdkService(GenAiObservationFactory.FACTORY)
+public final class GenAiObservabilityImpl implements GenAiObservationFactory {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(GenAiObservabilityImpl.class);
     private static final GenAiObservation NOOP = new NoopGenAiObservation();
@@ -47,28 +46,21 @@ public final class GenAiObservabilityImpl {
             = 
"org.apache.camel.micrometer.observability.MicrometerObservabilityTracer";
     private static final String INTERNAL_SPAN_KIND = "INTERNAL";
     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 static final String OBSERVATION_REGISTRY_CLASS = 
"io.micrometer.observation.ObservationRegistry";
-    private static final String OBSERVATION_SUPPORT_CLASS
-            = 
"org.apache.camel.component.ai.observability.GenAiMicrometerObservationSupport";
     private static final GenAiMetricsBackend NO_METRICS_BACKEND = new 
NoMetricsBackend();
     private static final GenAiMicrometerObservationBackend 
NO_OBSERVATION_BACKEND = new NoObservationBackend();
-    private static final ConcurrentMap<CamelContext, GenAiMetricsBackend> 
METRICS_BACKENDS = new ConcurrentHashMap<>();
-    private static final ConcurrentMap<CamelContext, 
GenAiMicrometerObservationBackend> OBSERVATION_BACKENDS
-            = new ConcurrentHashMap<>();
 
-    private GenAiObservabilityImpl() {
-    }
+    // one instance per CamelContext (GenAiObservability keeps it as a context 
plugin), so the backends found in its
+    // registry are resolved once and go away with it
+    private volatile Backends backends;
 
-    /**
-     * 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) {
+    @Override
+    public GenAiObservation start(Exchange exchange, GenAiObservationContext 
context) {
         CamelContext camelContext = exchange.getContext();
-        GenAiMicrometerObservationBackend observationBackend = 
resolveObservationBackend(camelContext);
+        Backends resolved = backends(camelContext);
+        GenAiMicrometerObservationBackend observationBackend = 
resolved.observation();
         Tracer tracer = camelContext.hasService(Tracer.class);
-        GenAiMetricsBackend metricsBackend = 
resolveMetricsBackend(camelContext);
+        GenAiMetricsBackend metricsBackend = resolved.metrics();
         if (!observationBackend.isAvailable() && tracer == null && 
!metricsBackend.isAvailable()) {
             return NOOP;
         }
@@ -88,42 +80,58 @@ public final class GenAiObservabilityImpl {
         return false;
     }
 
-    private static GenAiMetricsBackend resolveMetricsBackend(CamelContext 
camelContext) {
-        return METRICS_BACKENDS.computeIfAbsent(camelContext, 
GenAiObservabilityImpl::createMetricsBackend);
+    private Backends backends(CamelContext camelContext) {
+        Backends answer = backends;
+        if (answer == null) {
+            synchronized (this) {
+                answer = backends;
+                if (answer == null) {
+                    answer = new Backends(createMetricsBackend(camelContext), 
createObservationBackend(camelContext));
+                    backends = answer;
+                }
+            }
+        }
+        return answer;
     }
 
     private static GenAiMetricsBackend createMetricsBackend(CamelContext 
camelContext) {
         try {
+            // Micrometer is optional: GenAiMicrometerSupport only loads once 
the presence check passes
             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 new GenAiMicrometerSupport(camelContext);
+        } catch (ClassNotFoundException e) {
             if (LOG.isDebugEnabled()) {
                 LOG.debug("Micrometer metrics backend unavailable for GenAI 
observability", e);
             }
             return NO_METRICS_BACKEND;
+        } catch (RuntimeException | LinkageError e) {
+            // such as a Micrometer version mismatch: only this backend is 
disabled, the others keep working
+            LOG.warn("Unable to create the Micrometer metrics backend for 
GenAI observability; it is disabled", e);
+            return NO_METRICS_BACKEND;
         }
     }
 
-    private static GenAiMicrometerObservationBackend 
resolveObservationBackend(CamelContext camelContext) {
-        return OBSERVATION_BACKENDS.computeIfAbsent(camelContext, 
GenAiObservabilityImpl::createObservationBackend);
-    }
-
     private static GenAiMicrometerObservationBackend 
createObservationBackend(CamelContext camelContext) {
         try {
+            // Micrometer Observation is optional: 
GenAiMicrometerObservationSupport only loads once the presence
+            // check passes
             Class.forName(OBSERVATION_REGISTRY_CLASS);
-            Class<?> supportClass = Class.forName(OBSERVATION_SUPPORT_CLASS);
-            Constructor<?> constructor = 
supportClass.getDeclaredConstructor(CamelContext.class);
-            return (GenAiMicrometerObservationBackend) 
constructor.newInstance(camelContext);
-        } catch (ReflectiveOperationException | LinkageError e) {
+            return new GenAiMicrometerObservationSupport(camelContext);
+        } catch (ClassNotFoundException e) {
             if (LOG.isDebugEnabled()) {
                 LOG.debug("Micrometer Observation backend unavailable for 
GenAI observability", e);
             }
             return NO_OBSERVATION_BACKEND;
+        } catch (RuntimeException | LinkageError e) {
+            // such as a Micrometer version mismatch: only this backend is 
disabled, the others keep working
+            LOG.warn("Unable to create the Micrometer Observation backend for 
GenAI observability; it is disabled", e);
+            return NO_OBSERVATION_BACKEND;
         }
     }
 
+    private record Backends(GenAiMetricsBackend metrics, 
GenAiMicrometerObservationBackend observation) {
+    }
+
     private static final class DefaultGenAiObservation implements 
GenAiObservation {
 
         private static final SpanStorageManagerExchange STORAGE = new 
SpanStorageManagerExchange();
diff --git 
a/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityFactoryLinkageErrorTest.java
 
b/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityFactoryLinkageErrorTest.java
new file mode 100644
index 000000000000..6f10c71ee184
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityFactoryLinkageErrorTest.java
@@ -0,0 +1,103 @@
+/*
+ * 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.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.spi.Injector;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+/**
+ * An implementation that is found but cannot be linked (such as 
camel-telemetry excluded from the classpath) must not
+ * fail the LLM call, and is only tried once.
+ */
+class GenAiObservabilityFactoryLinkageErrorTest extends ExchangeTestSupport {
+
+    private final AtomicInteger attempts = new AtomicInteger();
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.setInjector(new FailingImplInjector(context.getInjector()));
+        return context;
+    }
+
+    @Test
+    void shouldReturnNoopWhenTheImplementationCannotBeLoaded() {
+        GenAiObservationContext observationContext = 
GenAiObservationContext.builder()
+                .operationName(GenAiOperationName.CHAT)
+                .requestModel("test-model")
+                .build();
+
+        assertThatCode(() -> {
+            GenAiObservability.start(new DefaultExchange(context), 
observationContext).close();
+            GenAiObservability.start(new DefaultExchange(context), 
observationContext).close();
+        }).doesNotThrowAnyException();
+        assertThat(attempts).hasValue(1);
+    }
+
+    private final class FailingImplInjector implements Injector {
+
+        private final Injector delegate;
+
+        private FailingImplInjector(Injector delegate) {
+            this.delegate = delegate;
+        }
+
+        private void failForImpl(Class<?> type) {
+            if (type == GenAiObservabilityImpl.class) {
+                attempts.incrementAndGet();
+                throw new 
NoClassDefFoundError("org/apache/camel/telemetry/Tracer");
+            }
+        }
+
+        @Override
+        public <T> T newInstance(Class<T> type) {
+            failForImpl(type);
+            return delegate.newInstance(type);
+        }
+
+        @Override
+        public <T> T newInstance(Class<T> type, String factoryMethod) {
+            failForImpl(type);
+            return delegate.newInstance(type, factoryMethod);
+        }
+
+        @Override
+        public <T> T newInstance(Class<T> type, Class<?> factoryClass, String 
factoryMethod) {
+            failForImpl(type);
+            return delegate.newInstance(type, factoryClass, factoryMethod);
+        }
+
+        @Override
+        public <T> T newInstance(Class<T> type, boolean postProcessBean) {
+            failForImpl(type);
+            return delegate.newInstance(type, postProcessBean);
+        }
+
+        @Override
+        public boolean supportsAutoWiring() {
+            return delegate.supportsAutoWiring();
+        }
+    }
+}
diff --git 
a/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityMetricsLinkageErrorTest.java
 
b/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityMetricsLinkageErrorTest.java
new file mode 100644
index 000000000000..96d7f9700461
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-observability/src/test/java/org/apache/camel/component/ai/observability/GenAiObservabilityMetricsLinkageErrorTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.observation.Observation;
+import io.micrometer.observation.ObservationHandler;
+import io.micrometer.observation.ObservationRegistry;
+import org.apache.camel.spi.Registry;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.DefaultRegistry;
+import org.apache.camel.test.junit6.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * A Micrometer metrics backend that cannot be linked (such as a mismatched 
Micrometer jar) disables the metrics only:
+ * the calls are still observed.
+ */
+class GenAiObservabilityMetricsLinkageErrorTest extends ExchangeTestSupport {
+
+    @Override
+    protected Registry createCamelRegistry() throws Exception {
+        return new DefaultRegistry() {
+            @Override
+            public <T> Set<T> findByType(Class<T> type) {
+                failForMeterRegistry(type);
+                return super.findByType(type);
+            }
+
+            @Override
+            public <T> T findSingleByType(Class<T> type) {
+                failForMeterRegistry(type);
+                return super.findSingleByType(type);
+            }
+        };
+    }
+
+    private static void failForMeterRegistry(Class<?> type) {
+        if (type == MeterRegistry.class) {
+            throw new 
NoClassDefFoundError("io/micrometer/core/instrument/Meter$Id");
+        }
+    }
+
+    @Test
+    void shouldKeepObservingWhenTheMetricsBackendCannotBeLoaded() {
+        AtomicInteger stopped = new AtomicInteger();
+        ObservationRegistry observationRegistry = ObservationRegistry.create();
+        observationRegistry.observationConfig().observationHandler(new 
ObservationHandler<>() {
+            @Override
+            public void onStop(Observation.Context context) {
+                stopped.incrementAndGet();
+            }
+
+            @Override
+            public boolean supportsContext(Observation.Context context) {
+                return true;
+            }
+        });
+        context.getRegistry().bind("observationRegistry", observationRegistry);
+
+        GenAiObservation observation = GenAiObservability.start(new 
DefaultExchange(context),
+                
GenAiObservationContext.builder().operationName(GenAiOperationName.CHAT).requestModel("test-model").build());
+        observation.recordSuccess(GenAiUsage.of(1, 1, "stop", "test-model"));
+        observation.close();
+
+        assertThat(stopped).hasValue(1);
+    }
+}
diff --git 
a/dsl/camel-kamelet-main/src/generated/resources/camel-factoryfinder-known-dependencies.properties
 
b/dsl/camel-kamelet-main/src/generated/resources/camel-factoryfinder-known-dependencies.properties
index d443ddd53974..caa7f12a597c 100644
--- 
a/dsl/camel-kamelet-main/src/generated/resources/camel-factoryfinder-known-dependencies.properties
+++ 
b/dsl/camel-kamelet-main/src/generated/resources/camel-factoryfinder-known-dependencies.properties
@@ -15,6 +15,7 @@
 ## limitations under the License.
 ## ---------------------------------------------------------------------------
 
+META-INF/services/org/apache/camel/ai-observation-factory=camel:ai-observability
 
META-INF/services/org/apache/camel/avro-rpc-http-server-factory=camel:avro-rpc-jetty
 META-INF/services/org/apache/camel/bean-processor-factory=camel:bean
 META-INF/services/org/apache/camel/bean-proxy-factory=camel:bean
diff --git 
a/dsl/camel-kamelet-main/src/main/resources/camel-main-known-dependencies.properties
 
b/dsl/camel-kamelet-main/src/main/resources/camel-main-known-dependencies.properties
index 33f8d75d85d7..1d6dd3e6cd21 100644
--- 
a/dsl/camel-kamelet-main/src/main/resources/camel-main-known-dependencies.properties
+++ 
b/dsl/camel-kamelet-main/src/main/resources/camel-main-known-dependencies.properties
@@ -84,7 +84,6 @@ dev.langchain4j.model.embedding.onnx = 
dev.langchain4j:langchain4j-embeddings:${
 org.apache.camel.component.typesafeai.TypeSafeAiSemanticAdapter = 
camel:semantic-typesafe-ai
 org.apache.camel.component.wolfdefender.WolfDefenderSemanticAdapter = 
camel:semantic-wolf-defender
 
-org.apache.camel.component.ai.observability.GenAiObservabilityImpl = 
camel:ai-observability
 # camel-main property prefix (same pattern as camel.opentelemetry) — resolves 
ai-observability when GenAI observability config is accessed
 camel.aiObservability = camel:ai-observability
 

Reply via email to