|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.kyuubi.engine.dataagent.runtime; |
| 19 | + |
| 20 | +import com.openai.models.chat.completions.ChatCompletionAssistantMessageParam; |
| 21 | +import com.openai.models.chat.completions.ChatCompletionMessageParam; |
| 22 | +import java.util.List; |
| 23 | +import org.apache.kyuubi.engine.dataagent.runtime.event.AgentEvent; |
| 24 | +import org.apache.kyuubi.engine.dataagent.runtime.middleware.AgentMiddleware; |
| 25 | +import org.apache.kyuubi.engine.dataagent.runtime.middleware.ApprovalMiddleware; |
| 26 | +import org.apache.kyuubi.engine.dataagent.runtime.middleware.Decision; |
| 27 | +import org.apache.kyuubi.engine.dataagent.runtime.middleware.ToolInvocation; |
| 28 | +import org.apache.kyuubi.engine.dataagent.tool.ToolRegistry; |
| 29 | +import org.slf4j.Logger; |
| 30 | +import org.slf4j.LoggerFactory; |
| 31 | + |
| 32 | +/** |
| 33 | + * Composite {@link AgentMiddleware} — folds a list of middlewares into one. Hook ordering follows |
| 34 | + * the onion model: {@code before*} / {@code on*Start} run first-to-last, {@code after*} / {@code |
| 35 | + * on*Finish} run last-to-first. |
| 36 | + * |
| 37 | + * <p>Component middlewares are internal framework code. If one throws during ordinary hook |
| 38 | + * dispatch, the agent run fails via {@link ReactAgent#run}; lifecycle cleanup hooks ({@link |
| 39 | + * #onAgentFinish}, {@link #onSessionClose}, {@link #onStop}) swallow exceptions so later |
| 40 | + * middlewares still get a chance to release state. |
| 41 | + */ |
| 42 | +final class MiddlewareDispatcher implements AgentMiddleware { |
| 43 | + |
| 44 | + private static final Logger LOG = LoggerFactory.getLogger(MiddlewareDispatcher.class); |
| 45 | + |
| 46 | + private final List<AgentMiddleware> middlewares; |
| 47 | + private final ApprovalMiddleware approvalMiddleware; |
| 48 | + |
| 49 | + MiddlewareDispatcher(List<AgentMiddleware> middlewares) { |
| 50 | + this.middlewares = middlewares; |
| 51 | + this.approvalMiddleware = findApprovalMiddleware(middlewares); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Resolve a pending approval request. Not part of {@link AgentMiddleware} — special accessor for |
| 56 | + * the approval flow. |
| 57 | + */ |
| 58 | + boolean resolveApproval(String requestId, boolean approved) { |
| 59 | + if (approvalMiddleware == null) return false; |
| 60 | + return approvalMiddleware.resolve(requestId, approved); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void onRegister(ToolRegistry registry) { |
| 65 | + for (AgentMiddleware mw : middlewares) { |
| 66 | + mw.onRegister(registry); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + public void onAgentStart(AgentRunContext ctx) { |
| 72 | + for (AgentMiddleware mw : middlewares) { |
| 73 | + mw.onAgentStart(ctx); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public void onAgentFinish(AgentRunContext ctx) { |
| 79 | + // Runs even when the agent body threw, so swallow here to ensure every middleware's cleanup |
| 80 | + // gets a chance to run; otherwise we'd leak session state in later middlewares. |
| 81 | + for (int i = middlewares.size() - 1; i >= 0; i--) { |
| 82 | + try { |
| 83 | + middlewares.get(i).onAgentFinish(ctx); |
| 84 | + } catch (Exception e) { |
| 85 | + LOG.warn("Middleware onAgentFinish error", e); |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + @Override |
| 91 | + public void onSessionClose(String sessionId) { |
| 92 | + for (AgentMiddleware mw : middlewares) { |
| 93 | + try { |
| 94 | + mw.onSessionClose(sessionId); |
| 95 | + } catch (Exception e) { |
| 96 | + LOG.warn("Middleware onSessionClose error", e); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + public void onStop() { |
| 103 | + for (AgentMiddleware mw : middlewares) { |
| 104 | + try { |
| 105 | + mw.onStop(); |
| 106 | + } catch (Exception e) { |
| 107 | + LOG.warn("Middleware onStop error", e); |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Fold {@code onEvent} in onion order. Returns PROCEED if untouched, REPLACE with the final event |
| 114 | + * if any middleware rewrote it, or ABORT if any short-circuited. |
| 115 | + */ |
| 116 | + @Override |
| 117 | + public Decision<AgentEvent> onEvent(AgentRunContext ctx, AgentEvent event) { |
| 118 | + AgentEvent current = event; |
| 119 | + for (AgentMiddleware mw : middlewares) { |
| 120 | + Decision<AgentEvent> d = mw.onEvent(ctx, current); |
| 121 | + if (d.kind() == Decision.Kind.ABORT) return d; |
| 122 | + if (d.kind() == Decision.Kind.REPLACE) current = d.replacement(); |
| 123 | + } |
| 124 | + return Decision.of(event, current); |
| 125 | + } |
| 126 | + |
| 127 | + /** |
| 128 | + * Fold {@code beforeLlmCall} in onion order so later middlewares see rewritten messages. Returns |
| 129 | + * PROCEED if untouched, REPLACE with the final value if any did, or ABORT if any short-circuited. |
| 130 | + */ |
| 131 | + @Override |
| 132 | + public Decision<List<ChatCompletionMessageParam>> beforeLlmCall( |
| 133 | + AgentRunContext ctx, List<ChatCompletionMessageParam> messages) { |
| 134 | + List<ChatCompletionMessageParam> current = messages; |
| 135 | + for (AgentMiddleware mw : middlewares) { |
| 136 | + Decision<List<ChatCompletionMessageParam>> d = mw.beforeLlmCall(ctx, current); |
| 137 | + if (d.kind() == Decision.Kind.ABORT) return d; |
| 138 | + if (d.kind() == Decision.Kind.REPLACE) current = d.replacement(); |
| 139 | + } |
| 140 | + return Decision.of(messages, current); |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Fold {@code afterLlmCall} in reverse onion order so earlier middlewares see rewritten |
| 145 | + * responses. Returns the final response, or ABORT if any middleware short-circuits. |
| 146 | + */ |
| 147 | + @Override |
| 148 | + public Decision<ChatCompletionAssistantMessageParam> afterLlmCall( |
| 149 | + AgentRunContext ctx, ChatCompletionAssistantMessageParam response) { |
| 150 | + ChatCompletionAssistantMessageParam current = response; |
| 151 | + for (int i = middlewares.size() - 1; i >= 0; i--) { |
| 152 | + Decision<ChatCompletionAssistantMessageParam> d = |
| 153 | + middlewares.get(i).afterLlmCall(ctx, current); |
| 154 | + if (d.kind() == Decision.Kind.ABORT) return d; |
| 155 | + if (d.kind() == Decision.Kind.REPLACE) current = d.replacement(); |
| 156 | + } |
| 157 | + return Decision.of(response, current); |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Fold {@code beforeToolCall} in onion order so later middlewares can further rewrite. Returns |
| 162 | + * PROCEED if untouched, REPLACE with the final invocation otherwise, or ABORT if any middleware |
| 163 | + * denies the call. |
| 164 | + */ |
| 165 | + @Override |
| 166 | + public Decision<ToolInvocation> beforeToolCall(AgentRunContext ctx, ToolInvocation call) { |
| 167 | + ToolInvocation current = call; |
| 168 | + for (AgentMiddleware mw : middlewares) { |
| 169 | + Decision<ToolInvocation> d = mw.beforeToolCall(ctx, current); |
| 170 | + if (d.kind() == Decision.Kind.ABORT) return d; |
| 171 | + if (d.kind() == Decision.Kind.REPLACE) current = d.replacement(); |
| 172 | + } |
| 173 | + return Decision.of(call, current); |
| 174 | + } |
| 175 | + |
| 176 | + /** |
| 177 | + * Fold {@code afterToolCall} in reverse onion order so earlier middlewares see rewritten results. |
| 178 | + * Returns the final result, or ABORT if any middleware short-circuits — caller decides how to |
| 179 | + * surface the abort (typically: use {@code reason()} as the result text the LLM sees). |
| 180 | + */ |
| 181 | + @Override |
| 182 | + public Decision<String> afterToolCall(AgentRunContext ctx, ToolInvocation call, String result) { |
| 183 | + String current = result; |
| 184 | + for (int i = middlewares.size() - 1; i >= 0; i--) { |
| 185 | + Decision<String> d = middlewares.get(i).afterToolCall(ctx, call, current); |
| 186 | + if (d.kind() == Decision.Kind.ABORT) return d; |
| 187 | + if (d.kind() == Decision.Kind.REPLACE) current = d.replacement(); |
| 188 | + } |
| 189 | + return Decision.of(result, current); |
| 190 | + } |
| 191 | + |
| 192 | + private static ApprovalMiddleware findApprovalMiddleware(List<AgentMiddleware> middlewares) { |
| 193 | + for (AgentMiddleware mw : middlewares) { |
| 194 | + if (mw instanceof ApprovalMiddleware) return (ApprovalMiddleware) mw; |
| 195 | + } |
| 196 | + return null; |
| 197 | + } |
| 198 | +} |
0 commit comments