in prompt/prompt-structure/src/commonMain/kotlin/ai/koog/prompt/structure/markdown/MarkdownParser.kt [220:254]
public suspend fun parseStream(markdownStream: Flow<String>) {
var buffer = ""
markdownStream.collect { chunk ->
buffer += chunk
// Check if we have a complete entry in the buffer
if (buffer.contains("\n# ") || chunk.contains("\n")) {
val sections = buffer.split(Regex("(?=\\n# )"))
for (i in 0 until sections.size - 1) {
var section = sections[i]
if (section.isEmpty()) continue
if (!section.startsWith("#")) {
// Add the header prefix to ensure proper parsing
section = "# $section"
}
// Parse the complete section
parser(section)
}
// Keep only the potentially incomplete last section in the buffer
buffer = sections.last()
}
}
// Process any remaining content in the buffer
if (buffer.isNotEmpty()) {
parser(buffer)
}
finishedHandler?.invoke(buffer)
}