google / cel-cpp

Fast, portable, non-Turing complete expression evaluation (C++)
https://cel.dev
Apache License 2.0
174 stars 52 forks source link

Is there any example about how to add user-defined macros or functions in cel-cpp #213

Open lshmouse opened 1 year ago

lshmouse commented 1 year ago

We use cel-cpp to write some rules for trigger the action when some condition matched. For some sophisticated rules,we need use some user-defined macros or functions, for example: compute the 3D IOU for two 3D objects(proto message), compute the included angle of two 3D vector and so on.

After search the codebase, we can not find examples about how to add user-defined macros or functions in cel-cpp.

keshav861 commented 7 months ago

I think this example is good to understand and to add user defined macros or functions in cel cpp for 3D IOU prototype. example :-

include "eval/eval/evaluator.h"

include "eval/public/cel_function.h"

include "eval/public/cel_function_registry.h"

include "eval/public/cel_options.h"

// Custom function to compute 3D IOU cel::Status Compute3DIoU(cel::CelValue* result, const std::vector& args) { // Implement the logic to compute 3D IOU return cel::Status::OK; }

// Custom function to compute included angle of two 3D vectors cel::Status ComputeIncludedAngle(cel::CelValue* result, const std::vector& args) { // Implement the logic to compute included angle return cel::Status::OK; }

int main() { // Create a CEL function registry auto registry = std::make_shared();

// Register custom functions with the registry
registry->RegisterFunction("Compute3DIoU", Compute3DIoU);
registry->RegisterFunction("ComputeIncludedAngle", ComputeIncludedAngle);

// Create a CEL evaluator with custom function registry
cel::InterpreterOptions options;
options.mutable_function_registry()->Register(std::move(registry));
cel::Interpreter interpreter(options);

// Example expression with custom functions
std::string expression = "Compute3DIoU(obj1, obj2) > 0.5 && ComputeIncludedAngle(vec1, vec2) < 90";

// Evaluate the expression
cel::Activation activation;
auto status_or = interpreter.Evaluate(expression, activation);
if (status_or.ok()) {
    // Handle result
} else {
    // Handle error
}

return 0;

}