Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions api/src/main/java/org/apache/flink/agents/api/EventType.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@

package org.apache.flink.agents.api;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* Compile-time constants for built-in event types, sourced from each {@code XxxEvent.EVENT_TYPE}.
*
Expand All @@ -40,5 +46,24 @@ public final class EventType {
public static final String ContextRetrievalResponseEvent =
org.apache.flink.agents.api.event.ContextRetrievalResponseEvent.EVENT_TYPE;

/**
* Returns all built-in constants as an unmodifiable {@code name → event-type value} map.
* Enumerated reflectively from the {@code public static final String} fields of this class so
* newly added constants are picked up automatically. Iteration order is unspecified.
*/
public static Map<String, String> allConstants() {
Map<String, String> constants = new LinkedHashMap<>();
for (Field field : EventType.class.getFields()) {
if (Modifier.isStatic(field.getModifiers()) && field.getType() == String.class) {
try {
constants.put(field.getName(), (String) field.get(null));
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read EventType." + field.getName(), e);
}
}
}
return Collections.unmodifiableMap(constants);
}

private EventType() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@
/**
* Marks a method as an agent action triggered by matching events.
*
* <p>Each {@link #value()} entry is an event type name string. Use the {@code EVENT_TYPE} constants
* on built-in event classes, the {@link org.apache.flink.agents.api.EventType} constants, or plain
* strings for custom events. Multiple entries combine with OR.
* <p>Each {@link #value()} entry is an event type name string or a boolean condition expression.
* Use the {@code EVENT_TYPE} constants on built-in event classes, the {@link
* org.apache.flink.agents.api.EventType} constants, or plain strings for custom events. Multiple
* entries combine with OR.
*
* <pre>{@code
* // Built-in event type via the EventType constant
Expand All @@ -40,8 +41,25 @@
* // User-defined event type
* @Action("MyCustomEvent")
*
* // Event type containing '.' or '-': quote it
* @Action("'com.example.order-created'")
*
* // Multiple types (OR semantics)
* @Action({EventType.InputEvent, "MyCustomEvent"})
*
* // Boolean condition expressions, matched against the event's type and attributes:
*
* // Type match plus an attribute comparison
* @Action("type == EventType.InputEvent && score > 5")
*
* // Quoted type literal for a custom event containing '.' or '-'
* @Action("type == 'com.ios.orderEvent' && score > 10")
*
* // Attribute key containing '.' or '-': index access, then a field
* @Action("score_name['batch-3.12'].region > 10")
*
* // Test a special-character key with 'in' before indexing it
* @Action("'batch-3.12' in score_name && score_name['batch-3.12'].region > 10")
* }</pre>
*
* <p>For a cross-language action, set {@link #target()} to a {@link PythonFunction} with a
Expand All @@ -61,9 +79,9 @@
@Retention(RetentionPolicy.RUNTIME)
public @interface Action {
/**
* Event type name strings; multiple entries have OR semantics. Named {@code value} (not {@code
* triggerConditions}) to enable the {@code @Action({...})} shorthand (JLS §9.7.3); corresponds
* to Python's {@code *trigger_conditions}.
* Event type name strings or boolean condition expressions; multiple entries have OR semantics.
* Named {@code value} (not {@code triggerConditions}) to enable the {@code @Action({...})}
* shorthand (JLS §9.7.3); corresponds to Python's {@code *trigger_conditions}.
*/
String[] value();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@
/** The set of configuration options for agents parameters. */
public class AgentConfigOptions {

/** Behaviour when a trigger condition throws or returns a non-Boolean at evaluation time. */
public enum ConditionEvaluationFailureStrategy {
/** Log WARN and treat the action as not matching. Streaming-safe default. */
WARN_AND_SKIP,
/** Rethrow as {@code IllegalStateException}; triggers Flink task failover. */
FAIL
}

/**
* The config parameter specifies which event logger implementation to use. Defaults to {@link
* LoggerType#SLF4J}, which surfaces events in Flink's Web UI; setting {@link LoggerType#FILE}
Expand All @@ -33,6 +41,19 @@ public class AgentConfigOptions {
public static final ConfigOption<LoggerType> EVENT_LOGGER_TYPE =
new ConfigOption<>("eventLoggerType", LoggerType.class, LoggerType.SLF4J);

/**
* Controls how trigger condition evaluation handles runtime exceptions and non-Boolean results.
* Defaults to {@link ConditionEvaluationFailureStrategy#WARN_AND_SKIP} for streaming safety;
* set to {@link ConditionEvaluationFailureStrategy#FAIL} on strict-semantics pipelines to
* trigger failover.
*/
public static final ConfigOption<ConditionEvaluationFailureStrategy>
CONDITION_EVALUATION_FAILURE_STRATEGY =
new ConfigOption<>(
"action.trigger-condition.evaluate-failure-strategy",
ConditionEvaluationFailureStrategy.class,
ConditionEvaluationFailureStrategy.WARN_AND_SKIP);

/** The config parameter specifies the directory for the FileEvent file. */
public static final ConfigOption<String> BASE_LOG_DIR =
new ConfigOption<>("baseLogDir", String.class, null);
Expand Down
11 changes: 10 additions & 1 deletion dist/src/main/resources/META-INF/NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ This project bundles the following dependencies under the Apache Software Licens
- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.2
- com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2
- com.fasterxml:classmate:1.7.0
- dev.cel:cel:0.12.0
- dev.cel:common:0.12.0
- dev.cel:compiler:0.12.0
- dev.cel:protobuf:0.12.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dev.cel:common:0.12.0
dev.cel:compiler:0.12.0
dev.cel:runtime:0.12.0
dev.cel:v1alpha1:0.12.0

- dev.cel:runtime:0.12.0
- dev.cel:v1alpha1:0.12.0
- org.apache.logging.log4j:log4j-api:2.23.1
- org.apache.logging.log4j:log4j-core:2.23.1
- org.apache.logging.log4j:log4j-slf4j-impl:2.23.1
Expand All @@ -24,6 +30,7 @@ This project bundles the following dependencies under the Apache Software Licens
- com.openai:openai-java-core:4.8.0
- com.openai:openai-java-client-okhttp:4.8.0
- co.elastic.clients:elasticsearch-java:8.19.0
- com.google.auto.value:auto-value-annotations:1.11.0
- com.google.guava:guava:33.5.0-jre
- com.google.guava:failureaccess:1.0.1
- com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
Expand Down Expand Up @@ -181,7 +188,9 @@ See bundled license files for details.
This project bundles the following dependencies under the BSD 3-Clause license.
See bundled license files for details.

- com.google.protobuf:protobuf-java:3.25.5
- com.google.protobuf:protobuf-java:4.33.5
- com.google.re2j:re2j:1.8
- org.antlr:antlr4-runtime:4.13.2
- org.ow2.asm:asm:9.3

This project bundles the following dependencies under the EPL2 license.
Expand Down
28 changes: 28 additions & 0 deletions dist/src/main/resources/META-INF/licenses/LICENSE.antlr4-runtime
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither name of copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 changes: 32 additions & 0 deletions dist/src/main/resources/META-INF/licenses/LICENSE.re2j
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
This is a work derived from Russ Cox's RE2 in Go, whose license
http://golang.org/LICENSE is as follows:

Copyright (c) 2009 The Go Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.

* Neither the name of Google Inc. nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1 change: 1 addition & 0 deletions docs/content/docs/operations/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ Here is the list of all built-in core configuration options.
| `baseLogDir` | (none) | String | Base directory for file-based event logs. If not set, uses `java.io.tmpdir/flink-agents`. Setting this value also implicitly switches `eventLoggerType` to `file`. |
| `prettyPrint` | false | boolean | Whether to enable pretty-printed JSON format for event logs. When set to `true`, each event is written as formatted multi-line JSON instead of JSONL (JSON Lines) format. {{< hint info >}}Note: enabling this option makes the log file no longer valid JSONL format. {{< /hint >}} |
| `event-listeners` | none | `List<String>` | The list of event listener class names. Each class must implement the EventListener interface and provide a public no-argument constructor. {{< hint warning >}} Note: Currently, custom event listeners are only supported in Java. {{< /hint >}} |
| `action.trigger-condition.evaluate-failure-strategy` | `WARN_AND_SKIP` | ConditionEvaluationFailureStrategy | Strategy for handling a trigger-condition expression that throws or returns a non-boolean value at evaluation time. <br/>The option value could be:<br/> <ul><li>`WARN_AND_SKIP` (default): log a WARN and treat the action as not matching, keeping the stream running.</li> <li>`FAIL`: rethrow as `IllegalStateException`, triggering Flink task failover.</li></ul> |
| `error-handling-strategy` | ErrorHandlingStrategy.FAIL | ErrorHandlingStrategy | Strategy for handling errors during model requests, include timeout and unexpected output schema. <br/>The option value could be:<br/> <ul><li>`ErrorHandlingStrategy.FAIL`</li> <li>`ErrorHandlingStrategy.RETRY`</li> <li>`ErrorHandlingStrategy.IGNORE`</li> |
| `max-retries` | 3 | int | Number of retries when using `ErrorHandlingStrategy.RETRY`. |
| `retry-wait-interval` | 1 | int | Base wait interval in seconds between retries when using `ErrorHandlingStrategy.RETRY`. Uses exponential backoff: the actual wait time for the Nth retry is `retry-wait-interval * 2^(N-1)` seconds. For example, with default 1s, waits are 1s, 2s, 4s, etc. Retry count and total wait time are reported in `ChatResponseEvent` and recorded as metrics (`retryCount`, `retryWaitSec`) under the connection name. |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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.flink.agents.integration.test;

import org.apache.flink.agents.api.Event;
import org.apache.flink.agents.api.EventType;
import org.apache.flink.agents.api.InputEvent;
import org.apache.flink.agents.api.OutputEvent;
import org.apache.flink.agents.api.agents.Agent;
import org.apache.flink.agents.api.annotation.Action;
import org.apache.flink.agents.api.context.RunnerContext;

/**
* Agent exercising {@code @Action} trigger conditions end-to-end: one action fires on every input
* event, one is gated by a condition expression on the input value, one uses a {@code
* has()}-guarded expression, and one re-emits each input as a custom dotted/hyphenated event type
* consumed by a quoted-type-name action routed via the type index.
*/
public class ConditionTriggerIntegrationAgent extends Agent {

@Action(EventType.InputEvent)
public static void onAnyInput(Event event, RunnerContext ctx) {
Object input = InputEvent.fromEvent(event).getInput();
ctx.sendEvent(new OutputEvent("all:" + input));
}

@Action("type == EventType.InputEvent && input > 5")
public static void onHighInput(Event event, RunnerContext ctx) {
Object input = InputEvent.fromEvent(event).getInput();
ctx.sendEvent(new OutputEvent("high:" + input));
}

@Action("has(input) && input > 5")
public static void onGuardedHighInput(Event event, RunnerContext ctx) {
Object input = InputEvent.fromEvent(event).getInput();
ctx.sendEvent(new OutputEvent("guard:" + input));
}

/** Re-emits every input as a custom dotted/hyphenated event type. */
@Action(EventType.InputEvent)
public static void reEmitAsCustomType(Event event, RunnerContext ctx) {
Object input = InputEvent.fromEvent(event).getInput();
Event custom = new Event("com.example.order-scored");
custom.setAttr("v", input);
ctx.sendEvent(custom);
}

/** Quoted complex type name: routed via the type index, no condition evaluation. */
@Action("'com.example.order-scored'")
public static void onQuotedCustomType(Event event, RunnerContext ctx) {
ctx.sendEvent(new OutputEvent("quoted:" + event.getAttr("v")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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.flink.agents.integration.test;

import org.apache.flink.agents.api.AgentsExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

/**
* End-to-end test for {@code @Action} trigger conditions in a full Flink pipeline: an unconditioned
* action must fire for every input record, condition-gated actions must fire only for records
* matching their expression, and a second typed action exercises typed fan-out plus
* quoted-type-name routing via the type index.
*/
public class ConditionTriggerIntegrationTest {

@Test
public void testConditionGatedActionsFireSelectively() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);

// Two records above the threshold (9, 7), two below (2, 4).
DataStream<Integer> inputStream = env.fromElements(2, 9, 4, 7);

AgentsExecutionEnvironment agentsEnv =
AgentsExecutionEnvironment.getExecutionEnvironment(env);

DataStream<Object> outputStream =
agentsEnv
.fromDataStream(inputStream, (KeySelector<Integer, Integer>) value -> value)
.apply(new ConditionTriggerIntegrationAgent())
.toDataStream();

CloseableIterator<Object> results = outputStream.collectAsync();
agentsEnv.execute();

List<String> outputs = new ArrayList<>();
while (results.hasNext()) {
outputs.add((String) results.next());
}
results.close();

assertThat(outputs.stream().filter(o -> o.startsWith("all:")))
.as("unconditioned action must fire for every record")
.containsExactlyInAnyOrder("all:2", "all:9", "all:4", "all:7");
assertThat(outputs.stream().filter(o -> o.startsWith("high:")))
.as("condition-gated action must fire only for records > 5")
.containsExactlyInAnyOrder("high:9", "high:7");
assertThat(outputs.stream().filter(o -> o.startsWith("guard:")))
.as("has()-guarded action must fire only for records > 5")
.containsExactlyInAnyOrder("guard:9", "guard:7");
assertThat(outputs.stream().filter(o -> o.startsWith("quoted:")))
.as("quoted dotted/hyphenated type must route via the type index")
.containsExactlyInAnyOrder("quoted:2", "quoted:9", "quoted:4", "quoted:7");
assertThat(outputs).hasSize(12);
}
}
Loading
Loading