Skip to content

Commit e477111

Browse files
committed
feat(prompting): enhance trimCodeSpace to handle Python code #316
Refactor trimCodeSpace to preserve code fences for Python and improve overall trimming logic.
1 parent 44d00c6 commit e477111

File tree

2 files changed

+44
-6
lines changed

2 files changed

+44
-6
lines changed

core/src/main/kotlin/cc/unitmesh/devti/prompting/optimizer/PromptOptimizer.kt

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,28 @@
11
package cc.unitmesh.devti.prompting.optimizer
22

3+
import cc.unitmesh.devti.util.parser.CodeFence
4+
35
object PromptOptimizer {
6+
fun trimCodeSpace(prompt: String): String {
7+
val fences = CodeFence.parseAll(prompt)
8+
return fences.joinToString("\n") {
9+
if (it.originLanguage == "python") {
10+
"```${it.originLanguage}\n${it.text}\n```"
11+
} else {
12+
trim(it.text)
13+
}
14+
}
15+
}
16+
417
/**
18+
* Related to [#317](https://github.com/unit-mesh/auto-dev/issues/317)
19+
*
520
* Similar to the following shell command:
621
* ```bash
722
* grep -Ev '^[ \t]*$ input.rs | sed 's/^[ \t]*\/\/' | sed 's/[ \t]$//'
823
* ```
924
*/
10-
fun trimCodeSpace(prompt: String): String {
11-
/// check language of CodeFence skip for Python
25+
private fun trim(prompt: String): String {
1226
return prompt.lines()
1327
.filter { it.isNotBlank() }
1428
.joinToString("\n") { it.trim() }

core/src/test/kotlin/cc/unitmesh/devti/prompting/optimizer/PromptOptimizerTest.kt

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,7 @@ impl Plot {
140140
val result = PromptOptimizer.trimCodeSpace(code)
141141

142142
// then
143-
val expected = """
144-
use crate::{find_target, Plot};
143+
val expected = """use crate::{find_target, Plot};
145144
use anyhow::{Context, Result};
146145
use std::{env, process};
147146
impl Plot {
@@ -174,7 +173,32 @@ process::Command::new(cargo)
174173
.context("⚠️ couldn't wait for the afl plot")?;
175174
Ok(())
176175
}
177-
}
178-
"""
176+
}"""
177+
178+
assertThat(result).isEqualTo(expected)
179+
}
180+
181+
@Test
182+
fun should_handle_for_python_code_in_issue() {
183+
@Language("Markdown")
184+
val code = """
185+
Here is the code:
186+
```python
187+
def foo():
188+
print("Hello, World!")
189+
```
190+
""".trimIndent()
191+
192+
// when
193+
val result = PromptOptimizer.trimCodeSpace(code)
194+
195+
// then
196+
val expected = """Here is the code:
197+
```python
198+
def foo():
199+
print("Hello, World!")
200+
```"""
201+
202+
assertThat(result).isEqualTo(expected)
179203
}
180204
}

0 commit comments

Comments
 (0)