Skip to content

Commit 6d6a9ad

Browse files
mltheuserMalte Heuserkpavlov
authored
KG-504 Change flushTextBuilder to flush whenever textBuilder is not empty (#1123)
Related to: [KG-504](https://youtrack.jetbrains.com/issue/KG-504) ## Motivation and Context The `ContentPartsBuilder` would fail to create a `ContentPart` for text that ended with `\n` or was followed by a DSL call like `br()` or `newline()`. This was because the internal `flushTextBuilder` method checked `caret.offset != 0` to detect pending text. A trailing newline can reset the offset to 0, causing the check to fail even when the `textBuilder` is not empty. This change proposes to check `textBuilder.isNotEmpty()` instead, ensuring all content is properly flushed. ## Breaking Changes <!-- Will users need to update their code or configurations? --> None. This is a non-breaking bug fix. Co-authored-by: Malte Heuser <malte.heuser@ing.com> Co-authored-by: Konstantin Pavlov <1517853+kpavlov@users.noreply.github.com>
1 parent c8513bd commit 6d6a9ad

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

prompt/prompt-model/src/commonMain/kotlin/ai/koog/prompt/dsl/ContentPartsBuilder.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ public class ContentPartsBuilder : TextContentBuilderBase<List<ContentPart>>() {
7070
* Flushes the text builder and adds its content as a text part if there is any.
7171
*/
7272
private fun flushTextBuilder() {
73-
if (caret.offset != 0) {
73+
if (textBuilder.isNotEmpty()) {
7474
parts.add(ContentPart.Text(textBuilder.toString()))
7575
textBuilder.clear()
7676
}

prompt/prompt-model/src/commonTest/kotlin/ai/koog/prompt/dsl/PromptBuilderTest.kt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import ai.koog.prompt.message.AttachmentContent
55
import ai.koog.prompt.message.ContentPart
66
import ai.koog.prompt.message.Message
77
import ai.koog.prompt.text.text
8+
import io.kotest.matchers.equals.shouldBeEqual
89
import kotlin.test.Ignore
910
import kotlin.test.Test
1011
import kotlin.test.assertEquals
@@ -918,4 +919,15 @@ class PromptBuilderTest {
918919
assertEquals(1, prompt.messages[1].parts.size, "Should have only text part")
919920
assertEquals(expectedText, prompt.messages[1].parts[0], "Should have same text")
920921
}
922+
923+
@Test
924+
fun testUserMessageWithTrailingNewline() {
925+
val prompt = Prompt.build("test") {
926+
user {
927+
+"Text\n"
928+
}
929+
}
930+
931+
prompt.messages[0].parts shouldBeEqual listOf(ContentPart.Text("Text\n"))
932+
}
921933
}

0 commit comments

Comments
 (0)