This is an automated email from the ASF dual-hosted git repository.

lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git


The following commit(s) were added to refs/heads/master by this push:
     new de22d3d0f fix(ai): preserve separate code examples in enhanced prompts 
(#6878)
de22d3d0f is described below

commit de22d3d0f5fff3396de0e7ebe991f383b097ed36
Author: pilichoumao <[email protected]>
AuthorDate: Fri Nov 27 12:01:43 2026 +0800

    fix(ai): preserve separate code examples in enhanced prompts (#6878)
---
 .../ops/ai/conversation/agent/PromptEnhancer.java  | 30 ++++++---
 .../ai/conversation/agent/PromptEnhancerTest.java  | 73 ++++++++++++++++++++++
 2 files changed, 93 insertions(+), 10 deletions(-)

diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancer.java
 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancer.java
index 2164ee3a4..edb172f38 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancer.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancer.java
@@ -28,6 +28,8 @@ import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.Locale;
 import java.util.function.Consumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * Rewrites a user's message into a structured prompt before the agent run, 
streaming the rewrite as it
@@ -57,6 +59,9 @@ import java.util.function.Consumer;
 @Component
 public class PromptEnhancer {
 
+    private static final Pattern OPENING_FENCE = Pattern.compile("^ 
{0,3}(`{3,})([^`\\r\\n]*)\\r?$");
+    private static final Pattern CLOSING_FENCE = Pattern.compile("^ 
{0,3}(`{3,})[ \\t]*\\r?$");
+
     private static final String TEMPLATE_RESOURCE = 
"/prompts/enhance-prompt.txt";
     private static final String TEMPLATE = loadTemplate();
 
@@ -116,17 +121,22 @@ public class PromptEnhancer {
             return null;
         }
         String cleaned = enhanced.trim();
-        // Only a complete outer fence is stripped, and the whole opening fence
-        // line goes: the info string is not limited to letters (```json5,
-        // ```plain-text), and a letters-only pattern left its tail as the
-        // first line of the prompt. Fences embedded in the body and unclosed
-        // fences stay untouched.
+        // Strip a wrapper only when its first legal closing fence is the last 
line.
+        // A response can start and end with separate code examples; removing 
just
+        // those boundary lines would corrupt the prompt passed to the agent.
         String[] lines = cleaned.split("\n", -1);
-        if (lines.length >= 2 && lines[0].startsWith("```")
-                && lines[lines.length - 1].startsWith("```")
-                && lines[lines.length - 1].substring(3).trim().isEmpty()) {
-            cleaned = String.join("\n",
-                    java.util.Arrays.copyOfRange(lines, 1, lines.length - 
1)).trim();
+        Matcher opening = OPENING_FENCE.matcher(lines[0]);
+        if (lines.length < 2 || !opening.matches()) {
+            return cleaned;
+        }
+        int openingLength = opening.group(1).length();
+        for (int index = 1; index < lines.length; index++) {
+            Matcher closing = CLOSING_FENCE.matcher(lines[index]);
+            if (closing.matches() && closing.group(1).length() >= 
openingLength) {
+                return index == lines.length - 1
+                        ? String.join("\n", 
java.util.Arrays.copyOfRange(lines, 1, index)).trim()
+                        : cleaned;
+            }
         }
         return cleaned;
     }
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancerTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancerTest.java
index 4fa63eab4..f3ccccd86 100644
--- 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancerTest.java
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/agent/PromptEnhancerTest.java
@@ -16,11 +16,19 @@
  */
 package org.apache.rocketmq.studio.ops.ai.conversation.agent;
 
+import org.apache.rocketmq.studio.ops.ai.OpenAiCompatibleLlmClient;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 
+import java.util.function.Consumer;
+
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
 
 class PromptEnhancerTest {
 
@@ -54,4 +62,69 @@ class PromptEnhancerTest {
     void cleanReturnsNullForNullInputTest() {
         assertThat(PromptEnhancer.clean(null)).isNull();
     }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"\n", "\r\n"})
+    void cleanKeepsSeparateCodeExamplesTest(String eol) {
+        String input = String.join(eol,
+                "```json", "{\"key\":1}", "```", "Compare with this command:",
+                "```bash", "printf ok", "```");
+        assertThat(PromptEnhancer.clean(input)).isEqualTo(input);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"\n", "\r\n"})
+    void cleanKeepsAWrapperWithoutALegalClosingFenceTest(String eol) {
+        String input = String.join(eol, "````markdown", "Keep this example:", 
"```");
+        assertThat(PromptEnhancer.clean(input)).isEqualTo(input);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"```not-a-close", "    ```", "~~~", "```\ttext"})
+    void cleanKeepsInvalidClosingLinesTest(String closing) {
+        String input = "```text\nbody\n" + closing;
+        assertThat(PromptEnhancer.clean(input)).isEqualTo(input);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"\n", "\r\n"})
+    void cleanRemovesACompleteLongWrapperAroundShorterCodeFencesTest(String 
eol) {
+        String body = String.join(eol, "Example:", "```sql", "SELECT 1", 
"```");
+        String input = "````markdown" + eol + body + eol + "  `````\t";
+        assertThat(PromptEnhancer.clean(input)).isEqualTo(body);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"\n", "\r\n"})
+    void cleanAcceptsIndentedClosingFenceAndRetainsBodyLineEndingsTest(String 
eol) {
+        String body = "first" + eol + "second";
+        assertThat(PromptEnhancer.clean("```plain-text" + eol + body + eol + " 
  ```"))
+                .isEqualTo(body);
+    }
+
+    @Test
+    void cleanDoesNotTreatABacktickInTheInfoStringAsAWrapperTest() {
+        String input = "```invalid`info\nbody\n```";
+        assertThat(PromptEnhancer.clean(input)).isEqualTo(input);
+    }
+
+    @Test
+    void cleanHandlesEmptyWrappedContentTest() {
+        assertThat(PromptEnhancer.clean("```\n``` ")).isEmpty();
+        assertThat(PromptEnhancer.clean("  ")).isEmpty();
+    }
+
+    @Test
+    void enhancePreservesSeparateExamplesInTheReturnedPromptTest() {
+        String input = "```text\nread only\n```\nKeep both 
examples.\n```sql\nSELECT 1\n```";
+        OpenAiCompatibleLlmClient client = 
mock(OpenAiCompatibleLlmClient.class);
+        doAnswer(call -> {
+            Consumer<String> sink = call.getArgument(3);
+            sink.accept(input);
+            return null;
+        }).when(client).stream(any(), anyString(), isNull(), any());
+        PromptEnhancer enhancer = new PromptEnhancer(client, null);
+        assertThat(enhancer.enhance(null, "http", "Explain the query", 
null)).isEqualTo(input);
+    }
+
 }

Reply via email to