HsbcJone commented on code in PR #1352:
URL: https://github.com/apache/flink-agents/pull/1352#discussion_r4477238411


##########
api/src/main/java/org/apache/flink/agents/api/event/UserDefinedContext.java:
##########
@@ -0,0 +1,49 @@
+/*
+ * 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.api.event;
+
+import org.apache.flink.agents.api.Event;
+
+import javax.annotation.Nullable;
+
+/**
+ * Optional opaque application data carried on a built-in request and echoed 
on its response.
+ *
+ * <p>The value is not interpreted, not injected into prompts or tool 
arguments, and omitted
+ * entirely when absent so existing events keep their serialized shape.
+ */
+final class UserDefinedContext {
+
+    static final String ATTRIBUTE = "context";
+
+    private UserDefinedContext() {}
+
+    static void set(Event event, @Nullable Object context) {
+        if (context == null) {
+            event.getAttributes().remove(ATTRIBUTE);
+        } else {
+            event.setAttr(ATTRIBUTE, context);

Review Comment:
   Addressed in `fc8f2663`: `UserDefinedContext.attach` now deep-snapshots 
maps/lists (including nested ones) via `snapshot()`, and the regression test 
reuses one map across two requests to assert A keeps `summary` while B gets 
`risk`.



##########
docs/content/docs/development/create-agent/events.md:
##########
@@ -278,3 +278,48 @@ Event that your Actions can handle to continue the 
workflow:
 | Call tools | `ToolRequestEvent`, `ToolResponseEvent` | [Tool Use]({{< ref 
"docs/development/calling-llms/tool_use#built-in-events-and-actions" >}}) |
 | Retrieve context | `ContextRetrievalRequestEvent`, 
`ContextRetrievalResponseEvent` | [Vector Stores]({{< ref 
"docs/development/vector-search/vector_stores#built-in-events-and-actions" >}}) 
|
 | Call a decision model | `DecisionRequestEvent`, `DecisionResponseEvent` | 
[Decision Models]({{< ref "docs/development/decision_models#event-driven-calls" 
>}}) |
+
+### Request context
+
+Chat, tool, context-retrieval, and decision request events accept an optional 
`context`
+value: a map or other JSON-compatible object your Action uses to tell 
responses apart.

Review Comment:
   Addressed in `fc8f2663`: for the eight built-in request/response events, 
`Event.from_json` keeps `context` as the parsed JSON (no `Row` reconstruction), 
with a regression covering `{"type":"Row","values":[1],"label":"keep"}`. Docs 
in `events.md` note that `context` round-trips as plain JSON.



##########
api/src/test/java/org/apache/flink/agents/api/event/RequestContextTest.java:
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.api.event;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.ChatResult;
+import org.apache.flink.agents.api.chat.messages.ToolCallBlock;
+import org.apache.flink.agents.api.decision.DecisionRequest;
+import org.apache.flink.agents.api.decision.DecisionResult;
+import org.apache.flink.agents.api.tools.ToolResponse;
+import org.apache.flink.agents.api.vectorstores.Document;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Optional opaque context on built-in request and response events. */
+class RequestContextTest {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    private static Map<String, Object> context() {
+        Map<String, Object> context = new LinkedHashMap<>();
+        context.put("task", "summary");
+        context.put("item_id", "42");
+        context.put("n", 1);
+        context.put("ok", true);
+        context.put("tags", List.of("a"));
+        return context;
+    }
+
+    @Test
+    void omittedContextIsAbsentFromTheSerializedEvent() throws Exception {
+        ChatRequestEvent request = new ChatRequestEvent("model", 
List.of(ChatMessage.user("hi")));
+        assertThat(request.getContext()).isNull();
+        assertThat(request.getAttributes()).doesNotContainKey("context");
+        
assertThat(MAPPER.writeValueAsString(request)).doesNotContain("\"context\"");
+
+        ChatResponseEvent response =
+                ChatResponseEvent.success(
+                        UUID.randomUUID(), new 
ChatResult(ChatMessage.assistant("ok")));
+        assertThat(response.getContext()).isNull();
+        
assertThat(MAPPER.writeValueAsString(response)).doesNotContain("\"context\"");
+    }
+
+    @Test
+    void emptyContextIsKeptAndNullClearsIt() {
+        Map<String, Object> empty = new HashMap<>();
+        ChatRequestEvent request =
+                new ChatRequestEvent("model", 
List.of(ChatMessage.user("hi"))).withContext(empty);
+        assertThat(request.getAttributes()).containsKey("context");
+        assertThat(request.getContext()).isEqualTo(empty);
+
+        request.withContext(null);
+        assertThat(request.getAttributes()).doesNotContainKey("context");
+        assertThat(request.getContext()).isNull();
+    }
+
+    @Test
+    void eachRequestAndResponseRoundTripsItsOwnContext() throws Exception {
+        Map<String, Object> context = context();
+        UUID requestId = UUID.randomUUID();
+        DecisionRequest decisionRequest =
+                new DecisionRequest(
+                        "evidence",
+                        Map.of("urgent", 
DecisionRequest.Question.predicate("Needs attention?")));
+        DecisionResult decisionResult =
+                new DecisionResult(
+                        Map.of("urgent", new 
DecisionResult.PredicateAnswer(0.8)),
+                        null,
+                        null,
+                        Map.of());
+
+        List<Event> events =
+                List.of(
+                        new ChatRequestEvent(
+                                        "model",
+                                        List.of(ChatMessage.user("hi")),
+                                        Map.of("tone", "brief"),
+                                        null,
+                                        context)
+                                .withContext(List.of("also-a-context")),
+                        new ChatRequestEvent(
+                                "model", List.of(ChatMessage.user("hi")), 
null, null, "summary-42"),
+                        ChatResponseEvent.success(
+                                        requestId, new 
ChatResult(ChatMessage.assistant("ok")))
+                                .withContext(context),
+                        ChatResponseEvent.failed(requestId, "TimeoutException: 
timed out", 1, 2)
+                                .withContext(context),
+                        new ToolRequestEvent(
+                                "model",
+                                List.of(new ToolCallBlock("call-1", "lookup", 
Map.of("x", 1))),
+                                context),
+                        new ToolResponseEvent(
+                                        requestId,
+                                        Map.of("call-1", 
ToolResponse.text("ok")),
+                                        Map.of("call-1", true),
+                                        Map.of())
+                                .withContext(context),
+                        new ContextRetrievalRequestEvent("what is flink", 
"store", 2, context),
+                        new ContextRetrievalResponseEvent(
+                                        requestId,
+                                        "what is flink",
+                                        List.of(new Document("body", Map.of(), 
"d1")))
+                                .withContext(context),
+                        new DecisionRequestEvent("decision", decisionRequest, 
Map.of(), context),
+                        DecisionResponseEvent.success(requestId, 
decisionResult, 0, 0)
+                                .withContext(context),
+                        DecisionResponseEvent.failed(requestId, "provider 
down", 2, 3)
+                                .withContext(context));
+
+        for (Event event : events) {
+            Event restored = Event.fromJson(MAPPER.writeValueAsString(event));
+            assertThat(restored).isInstanceOf(event.getClass());
+            
assertThat(restored.getAttr("context")).isEqualTo(event.getAttr("context"));
+            assertThat(restored.getId()).isEqualTo(event.getId());
+        }
+    }
+
+    @Test
+    void foreignJsonContextSurvivesTheCrossLanguageBoundary() throws Exception 
{

Review Comment:
   Done in `fc8f2663`: added `chat_request_event_with_context` / 
`chat_response_event_with_context` fixtures under 
`e2e-test/cross-language-event-snapshots/` and wired them into the Java and 
Python snapshot suites.



##########
plan/src/test/java/org/apache/flink/agents/plan/actions/ChatModelActionRetryTest.java:
##########
@@ -1279,6 +1281,177 @@ void truncatedConversionIsRejectedBeforeParsing() 
throws Exception {
                                         Map.of("promptTokens", 9L, 
"completionTokens", 0L))));
     }
 
+    @Test
+    void omittedContextStaysOffTheResponse() throws Exception {
+        configureRetryStrategy(0, 0);
+        when(mockChatModel.chat(any(), any(), 
any())).thenReturn(ChatFixtures.response("hello"));
+
+        ChatRequestEvent request =
+                new ChatRequestEvent(
+                        "test-model",
+                        List.of(ChatMessage.user("hi")),
+                        Map.of("tone", "brief"),
+                        null);
+        ChatModelAction.processChatRequestOrToolResponse(request, mockCtx);
+
+        ChatResponseEvent response = 
ChatResponseEvent.fromEvent(sentEvents.get(0));
+        assertThat(response.getContext()).isNull();
+        assertThat(response.getAttributes()).doesNotContainKey("context");
+        assertThat(response.getRequestId()).isEqualTo(request.getId());
+        assertThat(response.getAttachments()).isEmpty();
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void successFailureAndRetryEchoContextWithoutTouchingThePrompt() throws 
Exception {
+        Map<String, Object> context = new LinkedHashMap<>();
+        context.put("task", "summary");
+        context.put("item_id", "42");
+        context.put("n", 1);
+        context.put("ok", true);
+        context.put("tags", List.of("a"));
+        Map<String, Object> promptArgs = Map.of("tone", "brief");
+        List<ChatMessage> messages = List.of(ChatMessage.user("hi"));
+
+        configureRetryStrategy(1, 0);
+        when(mockChatModel.chat(any(), any(), any()))
+                .thenThrow(new IllegalStateException("transient"))
+                .thenReturn(ChatFixtures.response("done"));
+        ChatRequestEvent request =
+                new ChatRequestEvent("test-model", messages, promptArgs, 
null).withContext(context);
+        request.setAttachment("trace", "keep-on-request");
+        ChatModelAction.processChatRequestOrToolResponse(request, mockCtx);
+
+        ChatResponseEvent response = 
ChatResponseEvent.fromEvent(sentEvents.get(0));
+        assertThat(response.isSuccess()).isTrue();
+        assertThat(response.getContext()).isEqualTo(context);
+        assertThat(response.getRetryCount()).isEqualTo(1);
+        assertThat(response.getAttachments()).isEmpty();
+        assertThat(response.getRequestId()).isEqualTo(request.getId());
+
+        ArgumentCaptor<List<ChatMessage>> messagesCaptor = 
ArgumentCaptor.forClass(List.class);
+        ArgumentCaptor<Map<String, Object>> promptCaptor = 
ArgumentCaptor.forClass(Map.class);
+        verify(mockChatModel, times(2))
+                .chat(messagesCaptor.capture(), promptCaptor.capture(), any());
+        assertThat(promptCaptor.getAllValues()).containsOnly(promptArgs);
+        assertThat(messagesCaptor.getAllValues())
+                .allSatisfy(sent -> 
assertThat(sent).containsExactlyElementsOf(messages));
+
+        sentEvents.clear();
+        when(mockChatModel.chat(any(), any(), any()))
+                .thenThrow(new IllegalStateException("persistent"));
+        ChatRequestEvent failing =
+                new ChatRequestEvent("test-model", messages, promptArgs, 
null).withContext(context);
+        ChatModelAction.processChatRequestOrToolResponse(failing, mockCtx);
+        ChatResponseEvent failed = 
ChatResponseEvent.fromEvent(sentEvents.get(0));
+        assertThat(failed.isFailed()).isTrue();
+        assertThat(failed.getError()).contains("persistent");
+        assertThat(failed.getContext()).isEqualTo(context);
+        assertThat(failed.getRequestId()).isEqualTo(failing.getId());
+    }
+
+    @Test
+    void toolRoundsKeepTheInitialContextAndDoNotCopyItOntoToolRequests() 
throws Exception {
+        configureRetryStrategy(0, 0);
+        Map<String, Object> contextA = Map.of("task", "summary", "item_id", 
"42");
+        Map<String, Object> contextB = Map.of("task", "risk_assessment", 
"item_id", "42");
+        Map<String, Object> toolCall =
+                Map.of(
+                        "id",
+                        "call-1",
+                        "type",
+                        "function",
+                        "function",
+                        Map.of("name", "lookup", "arguments", Map.of("x", 1)));
+        when(mockChatModel.chat(any(), any(), any()))
+                .thenReturn(ChatFixtures.response("", List.of(toolCall)))
+                .thenReturn(ChatFixtures.response("", List.of(toolCall)))
+                .thenReturn(ChatFixtures.response("risk done"))
+                .thenReturn(ChatFixtures.response("summary done"));
+
+        ChatRequestEvent requestA =
+                new ChatRequestEvent(
+                                "test-model",
+                                List.of(ChatMessage.user("a")),
+                                Map.of("who", "a"),
+                                null)
+                        .withContext(contextA);
+        ChatRequestEvent requestB =
+                new ChatRequestEvent(
+                                "test-model",
+                                List.of(ChatMessage.user("b")),
+                                Map.of("who", "b"),
+                                null)
+                        .withContext(contextB);
+        ChatModelAction.processChatRequestOrToolResponse(requestA, mockCtx);
+        ChatModelAction.processChatRequestOrToolResponse(requestB, mockCtx);
+
+        ToolRequestEvent toolA = ToolRequestEvent.fromEvent(sentEvents.get(0));
+        ToolRequestEvent toolB = ToolRequestEvent.fromEvent(sentEvents.get(1));
+        assertThat(toolA.getContext()).isNull();
+        assertThat(toolB.getContext()).isNull();
+        
assertThat(toolA.getToolCalls().get(0).getInput()).containsExactly(Map.entry("x",
 1));
+        assertThat(toolA.getAttachments()).isEmpty();
+
+        @SuppressWarnings("unchecked")
+        Map<UUID, Map<String, Object>> parked =
+                (Map<UUID, Map<String, Object>>)
+                        
sensoryMemory.get("_TOOL_REQUEST_EVENT_CONTEXT").getValue();
+        Object checkpointed =

Review Comment:
   Done in `fc8f2663`: `ChatModelActionContextRecoveryTest` restores the full 
`MemoryUpdate` through `ActionStateSerde`, processes the matching 
`ToolResponseEvent`, and asserts the final `ChatResponseEvent` carries the 
original request context.



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