luigidemasi commented on code in PR #27494:
URL: https://github.com/apache/camel/pull/27494#discussion_r4217016059


##########
components/camel-ai/camel-semantic/src/main/java/org/apache/camel/semantic/SemanticEvaluationBuilder.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * 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.semantic;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.util.StringHelper;
+
+/** Fluent definition of an expert-owned evaluation. All DSLs build the same 
immutable declaration. */
+public final class SemanticEvaluationBuilder {
+    private final SemanticEvaluationsBuilder parent;
+    private final Map<String, Object> parameters = new LinkedHashMap<>();
+    private final Map<String, String> criteria = new LinkedHashMap<>();
+    private final List<String> levels = new ArrayList<>();
+    private String threshold;
+    private String uncertainty;
+    private boolean normalizeUncertaintyPolicy;
+    private String operation;
+    private String expert;
+    private String state;
+
+    /** Create a standalone declaration, completed with {@link 
#build(CamelContext)}. */
+    public SemanticEvaluationBuilder() {
+        this(null);
+    }
+
+    SemanticEvaluationBuilder(SemanticEvaluationsBuilder parent) {
+        this.parent = parent;
+    }
+
+    public SemanticEvaluationBuilder operation(String operation) {
+        this.operation = operation;
+        return this;
+    }
+
+    /** Select an instruction-driven operation by type, such as boolean, 
choice or score. */
+    public SemanticEvaluationBuilder type(String type) {
+        return operation(type.toLowerCase(Locale.ROOT));
+    }
+
+    public SemanticEvaluationBuilder expert(String expert) {
+        this.expert = expert;
+        return this;
+    }
+
+    String getExpert() {
+        return expert != null ? expert : parent != null ? parent.getExpert() : 
null;
+    }
+
+    public SemanticEvaluationBuilder state(String state) {
+        this.state = state;
+        return this;
+    }
+
+    public SemanticEvaluationBuilder parameter(String name, Object value) {
+        if (parameters.containsKey(name)) {
+            throw new IllegalArgumentException("Duplicate semantic parameter: 
" + name);
+        }
+        parameters.put(name, value);
+        return this;
+    }
+
+    public SemanticEvaluationBuilder parameters(Map<String, ?> values) {
+        values.forEach(this::parameter);
+        return this;
+    }
+
+    public SemanticEvaluationBuilder instructions(String instructions) {
+        return parameter("instructions", instructions);
+    }
+
+    public SemanticEvaluationBuilder criterion(String name, String 
description) {
+        if (criteria.containsKey(name)) {
+            throw new IllegalArgumentException("Duplicate semantic criterion: 
" + name);
+        }
+        criteria.put(name, description);
+        return this;
+    }
+
+    public SemanticEvaluationBuilder level(String level) {
+        levels.add(level);
+        return this;
+    }
+
+    public SemanticEvaluationBuilder threshold(double threshold) {
+        return parameter("threshold", threshold);
+    }
+
+    public SemanticEvaluationBuilder threshold(String threshold) {
+        this.threshold = threshold;
+        return this;
+    }
+
+    public SemanticEvaluationBuilder uncertainty(double uncertainty) {
+        return parameter("uncertainty", uncertainty);
+    }
+
+    public SemanticEvaluationBuilder uncertainty(String uncertainty) {
+        this.uncertainty = uncertainty;
+        return this;
+    }
+
+    public SemanticEvaluationBuilder uncertaintyPolicy(String policy) {
+        parameter("uncertaintyPolicy", policy);
+        normalizeUncertaintyPolicy = true;
+        return this;
+    }
+
+    public SemanticEvaluationsBuilder end() {
+        if (parent == null) {
+            throw new IllegalStateException("Complete a standalone declaration 
with build(context)");
+        }
+        return parent;
+    }
+
+    public void register() {
+        end().register();
+    }
+
+    /** Build an immutable declaration, resolving placeholders in parameter 
values while retaining their types. */
+    public SemanticEvaluation build(CamelContext context) {
+        Map<String, Object> values = new LinkedHashMap<>(parameters);
+        if (!criteria.isEmpty() || !levels.isEmpty()) {
+            if (values.containsKey("criteria") || !criteria.isEmpty() && 
!levels.isEmpty()) {
+                throw new IllegalArgumentException("Duplicate parameter 
'criteria'");
+            }
+            values.put("criteria", !criteria.isEmpty() ? criteria : levels);
+        }
+        for (String numeric : List.of("threshold", "uncertainty")) {
+            String text = numeric.equals("threshold") ? threshold : 
uncertainty;
+            if (text != null) {
+                if (values.containsKey(numeric)) {
+                    throw new IllegalArgumentException("Duplicate parameter '" 
+ numeric + "'");
+                }
+                try {
+                    values.put(numeric, 
Double.valueOf(context.resolvePropertyPlaceholders(text)));
+                } catch (NumberFormatException invalid) {
+                    throw new IllegalArgumentException("Parameter '" + numeric 
+ "' must be a valid number");
+                }
+            }
+        }
+        values.replaceAll((name, value) -> resolve(context, value));
+        if (normalizeUncertaintyPolicy && values.get("uncertaintyPolicy") 
instanceof String policy) {
+            values.put("uncertaintyPolicy",
+                    
StringHelper.asEnumConstantValue(policy).toLowerCase(Locale.ROOT).replace('_', 
'-'));
+        }
+        return new SemanticEvaluation(
+                operation, getExpert(), state != null ? state : parent != null 
? parent.getState() : null, values);
+    }
+
+    private static Object resolve(CamelContext context, Object value) {
+        if (value instanceof String text) {
+            return context.resolvePropertyPlaceholders(text);
+        }
+        if (value instanceof Map<?, ?> map) {
+            Map<Object, Object> resolved = new LinkedHashMap<>();

Review Comment:
   Resolving with the existing validation behavior. Non-string keys are already 
rejected by `SemanticEvaluation.immutableValue()`; they are not silently 
accepted. Keeping the intermediate map avoids an early `ClassCastException` and 
preserves the common `IllegalArgumentException` diagnostic, as covered by 
`nonStringNestedKeysFailWithValidationError()`.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-semantic/src/test/java/org/apache/camel/semantic/SemanticInitializationTest.java:
##########
@@ -77,6 +76,38 @@ void concurrentQuestionRegistryCreationReturnsOneInstance() 
throws Exception {
         }
     }
 
+    @Test
+    void cachedRegistryLookupDoesNotWaitForAnotherContext() throws Exception {
+        ExecutorService callers = Executors.newFixedThreadPool(2);
+        CountDownLatch entered = new CountDownLatch(1);
+        CountDownLatch release = new CountDownLatch(1);
+        try (var creating = new DefaultCamelContext(); var cached = new 
DefaultCamelContext()) {
+            var expected = SemanticEvaluations.get(cached);
+            
creating.getCamelContextExtension().lazyAddContextPlugin(SemanticEvaluations.class,
 () -> {
+                entered.countDown();
+                try {
+                    assertThat(release.await(30, TimeUnit.SECONDS)).isTrue();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                return null;

Review Comment:
   Clarified in 
[384c0e7f7de1](https://github.com/apache/camel/commit/384c0e7f7de14a473b201a4ef05f6d8ee0a0423d)
 and 
[96e6d465f016](https://github.com/apache/camel/commit/96e6d465f016856fb43c7e95b8e67818cda8112d).
 The lazy supplier intentionally leaves the plugin absent after releasing the 
lookup gate, so `SemanticEvaluations.get()` creates and registers a real 
instance. The explanatory comment and assertion description now state that 
behavior. The non-null assertion is therefore correct and remains in place.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
components/camel-ai/camel-typesafe-ai/src/main/java/org/apache/camel/component/typesafeai/TypeSafeAiSemanticAdapter.java:
##########
@@ -94,36 +160,86 @@ public Map<String, SemanticResult> 
evaluateBatch(Map<String, SemanticQuestion> q
         return results;
     }
 
-    private Map<String, Object> definition(SemanticQuestion question) {
+    private Map<String, Object> definition(SemanticEvaluation question) {
         validate(question);
         Map<String, Object> definition = new HashMap<>();
-        definition.put("instructions", question.getInstructions());
+        definition.put("instructions", 
question.getParameters().get("instructions"));
         definition.put("type", type(question));
-        if (question.getType() == SemanticQuestion.Type.SCORE) {
-            definition.put("criteria", question.getLevels());
-        } else if (!question.getCriteria().isEmpty()) {
-            definition.put("criteria", question.getCriteria());
+        if ("score".equals(question.getOperation())) {
+            definition.put("criteria", levels(question));
+        } else if (!criteria(question).isEmpty()) {
+            definition.put("criteria", criteria(question));
         }
         return definition;
     }
 
-    private String type(SemanticQuestion question) {
-        return switch (question.getType()) {
-            case BOOLEAN -> "noul";
-            case CHOICE -> "choice";
-            case SCORE -> "score";
+    private String type(SemanticEvaluation question) {
+        return switch (question.getOperation()) {
+            case "boolean" -> "noul";
+            case "choice" -> "choice";
+            case "score" -> "score";
+            default -> throw new IllegalArgumentException("Unsupported 
TypeSafe AI operation");
         };
     }
 
-    private SemanticResult result(SemanticQuestion question, JsonObject 
answer, JsonObject response) {
+    private SemanticResult result(SemanticEvaluation question, JsonObject 
answer, JsonObject response) {
         Map<String, Double> probabilities = new HashMap<>();
         if (answer.get("probabilities") instanceof Map<?, ?> values) {
             values.forEach((key, value) -> probabilities.put((String) key, 
((Number) value).doubleValue()));
         }
-        return new SemanticResult(
-                question.getType() == SemanticQuestion.Type.BOOLEAN ? null : 
answer.get(type(question)),
-                question.getType() == SemanticQuestion.Type.BOOLEAN ? 
answer.getDouble("noul") : null,
+        Double probability = "boolean".equals(question.getOperation()) ? 
answer.getDouble("noul") : null;
+        Object value = switch (question.getOperation()) {
+            case "boolean" -> booleanDecision(question, probability);

Review Comment:
   Thanks for confirming this in [your latest 
review](https://github.com/apache/camel/pull/27494#pullrequestreview-5453768092).
 The three HTTP regressions in 
[96e6d465f016](https://github.com/apache/camel/commit/96e6d465f016856fb43c7e95b8e67818cda8112d)
 establish that missing `noul`, the named answer or `answers` fail in the 
client validation layer before adapter mapping. Resolving this thread with the 
existing diagnostics preserved.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/SimplePredicateExpression.java:
##########
@@ -0,0 +1,32 @@
+/*
+ * 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.language.simple;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Expression;
+import org.apache.camel.Predicate;
+
+/**
+ * Opts a Simple function into using its predicate contract for negation, 
including any validation in
+ * {@link #matches(org.apache.camel.Exchange)}. Existing expressions retain 
value-based truthiness, even when they also
+ * implement {@link Predicate}.
+ */
+public interface SimplePredicateExpression extends Expression, Predicate {

Review Comment:
   Confirmed present at the current head: 
[96e6d465f016](https://github.com/apache/camel/commit/96e6d465f016856fb43c7e95b8e67818cda8112d)
 adds `@since 4.23` to `SimplePredicateExpression`. Resolving following your 
acknowledgment in [your latest 
review](https://github.com/apache/camel/pull/27494#pullrequestreview-5453768092).
   
   _AI-generated by Codex on behalf of @luigidemasi._



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