|
| 1 | +package dev.cel.tools.ai; |
| 2 | + |
| 3 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 4 | + |
| 5 | +import com.google.common.base.Ascii; |
| 6 | +import com.google.common.collect.ImmutableCollection; |
| 7 | +import com.google.common.collect.ImmutableList; |
| 8 | +import com.google.common.collect.ImmutableSet; |
| 9 | +import com.google.common.io.Resources; |
| 10 | +import com.google.protobuf.Descriptors.FileDescriptor; |
| 11 | +import dev.cel.bundle.Cel; |
| 12 | +import dev.cel.bundle.CelEnvironment; |
| 13 | +import dev.cel.bundle.CelEnvironmentException; |
| 14 | +import dev.cel.bundle.CelEnvironmentYamlParser; |
| 15 | +import dev.cel.bundle.CelFactory; |
| 16 | +import dev.cel.common.CelContainer; |
| 17 | +import dev.cel.common.CelOptions; |
| 18 | +import dev.cel.common.types.CelType; |
| 19 | +import dev.cel.common.types.CelTypeProvider; |
| 20 | +import dev.cel.common.types.OpaqueType; |
| 21 | +import dev.cel.expr.ai.Agent; |
| 22 | +import dev.cel.expr.ai.AgentMessage; |
| 23 | +import dev.cel.expr.ai.AgentMessage.Part; |
| 24 | +import dev.cel.expr.ai.ClassificationLabel; |
| 25 | +import dev.cel.expr.ai.Finding; |
| 26 | +import dev.cel.parser.CelStandardMacro; |
| 27 | +import dev.cel.runtime.CelFunctionBinding; |
| 28 | +import java.io.IOException; |
| 29 | +import java.net.URL; |
| 30 | +import java.util.ArrayList; |
| 31 | +import java.util.List; |
| 32 | +import java.util.Optional; |
| 33 | + |
| 34 | +final class AgenticPolicyEnvironment { |
| 35 | + |
| 36 | + private static final CelOptions CEL_OPTIONS = |
| 37 | + CelOptions.current() |
| 38 | + .enableTimestampEpoch(true) |
| 39 | + .populateMacroCalls(true) |
| 40 | + .build(); |
| 41 | + |
| 42 | + private static final Cel CEL_BASE_ENV = |
| 43 | + CelFactory.standardCelBuilder() |
| 44 | + .setContainer(CelContainer.ofName("cel.expr.ai")) // TODO: config? |
| 45 | + .addFileTypes(Agent.getDescriptor().getFile()) |
| 46 | + .setStandardMacros(CelStandardMacro.STANDARD_MACROS) |
| 47 | + .setTypeProvider(new AgentTypeProvider()) |
| 48 | + .addFunctionBindings( |
| 49 | + CelFunctionBinding.from( |
| 50 | + "AgentMessage_threatFindings", |
| 51 | + ImmutableList.of(AgentMessage.class), |
| 52 | + (args) -> getFindings((AgentMessage) args[0], "threats", ClassificationLabel.Category.THREAT) |
| 53 | + ), |
| 54 | + CelFunctionBinding.from( |
| 55 | + "ai.finding_string_double", |
| 56 | + ImmutableList.of(String.class, Double.class), |
| 57 | + (args) -> Finding.newBuilder() |
| 58 | + .setValue((String) args[0]) |
| 59 | + .setConfidence((Double) args[1]) |
| 60 | + .build() |
| 61 | + ), |
| 62 | + CelFunctionBinding.from( |
| 63 | + "optional_type(list(Finding))_hasAll_list(Finding)", |
| 64 | + ImmutableList.of(Optional.class, List.class), |
| 65 | + (args) -> hasAllFindings((Optional<List<Finding>>) args[0], (List<Finding>) args[1]) |
| 66 | + ) |
| 67 | + ) |
| 68 | + .setOptions(CEL_OPTIONS) |
| 69 | + .build(); |
| 70 | + |
| 71 | + private static Optional<List<Finding>> getFindings(AgentMessage msg, String labelName, ClassificationLabel.Category category) { |
| 72 | + List<Finding> results = new ArrayList<>(); |
| 73 | + |
| 74 | + for (Part part : msg.getPartsList()) { |
| 75 | + if (part.hasPrompt()) { |
| 76 | + // TODO: Collect from classification |
| 77 | + results.add(Finding.newBuilder().setValue("prompt_injection").setConfidence(1.0d).build()); |
| 78 | + } else if (part.hasToolCall()) { |
| 79 | + // TODO: Collect from classification |
| 80 | + } |
| 81 | + |
| 82 | + } |
| 83 | + |
| 84 | + if (results.isEmpty()) { |
| 85 | + return Optional.empty(); |
| 86 | + } |
| 87 | + |
| 88 | + return Optional.of(results); |
| 89 | + } |
| 90 | + |
| 91 | + private static boolean hasAllFindings(Optional<List<Finding>> sourceOpt, List<Finding> required) { |
| 92 | + if (!sourceOpt.isPresent()) { |
| 93 | + return false; |
| 94 | + } |
| 95 | + List<Finding> source = sourceOpt.get(); |
| 96 | + |
| 97 | + return required.stream().allMatch(req -> |
| 98 | + source.stream().anyMatch(act -> |
| 99 | + act.getValue().equals(req.getValue()) && |
| 100 | + act.getConfidence() >= req.getConfidence() |
| 101 | + ) |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + static Cel newInstance() { |
| 106 | + Cel celEnv = CEL_BASE_ENV; |
| 107 | + |
| 108 | + celEnv = extendFromConfig(celEnv, "environment/agent_env.yaml"); |
| 109 | + celEnv = extendFromConfig(celEnv, "environment/common_env.yaml"); |
| 110 | + return extendFromConfig(celEnv, "environment/tool_call_env.yaml"); |
| 111 | + } |
| 112 | + |
| 113 | + private static Cel extendFromConfig(Cel cel, String yamlConfigPath) { |
| 114 | + String yamlEnv; |
| 115 | + try { |
| 116 | + yamlEnv = readFile(yamlConfigPath); |
| 117 | + } catch (IOException e) { |
| 118 | + String errorMsg = String.format("Failed to read %s: %s", yamlConfigPath, e.getMessage()); |
| 119 | + throw new IllegalArgumentException(errorMsg, e); |
| 120 | + } |
| 121 | + try { |
| 122 | + CelEnvironment env = CelEnvironmentYamlParser.newInstance().parse(yamlEnv); |
| 123 | + return env.extend(cel, CEL_OPTIONS); |
| 124 | + } catch (CelEnvironmentException e) { |
| 125 | + String errorMsg = String.format("Failed to extend CEL environment from %s: %s", yamlConfigPath, e.getMessage()); |
| 126 | + throw new IllegalArgumentException(errorMsg, e); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + private static String readFile(String path) throws IOException { |
| 131 | + URL url = Resources.getResource(Ascii.toLowerCase(path)); |
| 132 | + return Resources.toString(url, UTF_8); |
| 133 | + } |
| 134 | + |
| 135 | + private static final class AgentTypeProvider implements CelTypeProvider { |
| 136 | + private static final OpaqueType AGENT_MESSAGE_SET_TYPE = OpaqueType.create("cel.expr.ai.AgentMessageSet"); |
| 137 | + |
| 138 | + private static final ImmutableSet<CelType> ALL_TYPES = ImmutableSet.of(AGENT_MESSAGE_SET_TYPE); |
| 139 | + |
| 140 | + @Override |
| 141 | + public ImmutableCollection<CelType> types() { |
| 142 | + return ALL_TYPES; |
| 143 | + } |
| 144 | + @Override |
| 145 | + public Optional<CelType> findType(String typeName) { |
| 146 | + if (typeName.equals(AGENT_MESSAGE_SET_TYPE.name())) { |
| 147 | + return Optional.of(AGENT_MESSAGE_SET_TYPE); |
| 148 | + } |
| 149 | + |
| 150 | + return Optional.empty(); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private AgenticPolicyEnvironment() {} |
| 155 | +} |
0 commit comments