|
| 1 | +/* |
| 2 | + * Copyright 2024-2025 Embabel Software, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.embabel.common.core.thinking.spi |
| 17 | + |
| 18 | +import com.embabel.common.core.thinking.ThinkingBlock |
| 19 | +import com.embabel.common.core.thinking.ThinkingTagType |
| 20 | +import com.embabel.common.core.thinking.ThinkingTags |
| 21 | + |
| 22 | +/** |
| 23 | + * Extract all thinking blocks from input text. |
| 24 | + * |
| 25 | + * Processes the input text to find and extract all thinking content |
| 26 | + * in various formats (tagged, prefix, or untagged), returning detailed |
| 27 | + * metadata about each block found. |
| 28 | + */ |
| 29 | +@InternalThinkingApi |
| 30 | +fun extractAllThinkingBlocks(input: String): List<ThinkingBlock> { |
| 31 | + val blocks = mutableListOf<ThinkingBlock>() |
| 32 | + |
| 33 | + // Extract thinking blocks in priority order: Tags (most common) → Prefix → No Prefix (least common) |
| 34 | + |
| 35 | + // 1. First: Handle both predefined and dynamic XML-style tags (most common) |
| 36 | + |
| 37 | + // 1a. Extract predefined tags from ThinkingTags |
| 38 | + ThinkingTags.TAG_DEFINITIONS.forEach { (tagKey, tagPair) -> |
| 39 | + if (tagKey !in listOf("legacy_prefix", "no_prefix")) { |
| 40 | + val (startTag, endTag) = tagPair |
| 41 | + if (startTag.isNotEmpty() && endTag.isNotEmpty()) { |
| 42 | + val escapedStart = Regex.escape(startTag) |
| 43 | + val escapedEnd = Regex.escape(endTag) |
| 44 | + val pattern = "$escapedStart(.*?)$escapedEnd".toRegex(RegexOption.DOT_MATCHES_ALL) |
| 45 | + |
| 46 | + pattern.findAll(input).forEach { match -> |
| 47 | + blocks.add( |
| 48 | + ThinkingBlock( |
| 49 | + content = match.groupValues[1].trim(), |
| 50 | + tagType = ThinkingTagType.TAG, |
| 51 | + tagValue = tagKey |
| 52 | + ) |
| 53 | + ) |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // 1b. Extract any additional dynamic XML-style tags not in predefined list |
| 60 | + blocks.addAll(dynamicTagsDiscoveryAndExtraction(input, blocks)) |
| 61 | + |
| 62 | + // 2. Second: Handle //THINKING: prefix pattern (less common) |
| 63 | + val prefixPattern = "//THINKING:(.*)".toRegex(RegexOption.MULTILINE) |
| 64 | + prefixPattern.findAll(input).forEach { match -> |
| 65 | + blocks.add( |
| 66 | + ThinkingBlock( |
| 67 | + content = match.groupValues[1].trim(), |
| 68 | + tagType = ThinkingTagType.PREFIX, |
| 69 | + tagValue = "THINKING" |
| 70 | + ) |
| 71 | + ) |
| 72 | + } |
| 73 | + |
| 74 | + // 3. Last: Handle content before JSON pattern (fallback, least common) |
| 75 | + // Extract any remaining content that's not inside tags or prefix lines |
| 76 | + var remainingInput = input |
| 77 | + |
| 78 | + /** |
| 79 | + * Remove all extracted tagged content from input to prevent NO_PREFIX false positives. |
| 80 | + * |
| 81 | + * Handles both predefined tags (using ThinkingTags definitions) and dynamic tags |
| 82 | + * (using standard XML patterns). This ensures that already-extracted content |
| 83 | + * doesn't get picked up again as untagged NO_PREFIX content. |
| 84 | + */ |
| 85 | + blocks.filter { it.tagType == ThinkingTagType.TAG }.forEach { block -> |
| 86 | + val tagDefinition = ThinkingTags.TAG_DEFINITIONS[block.tagValue] |
| 87 | + if (tagDefinition != null) { |
| 88 | + // Remove predefined tags using their specific ThinkingTags format |
| 89 | + // Example: <think>content</think> or [REASONING]content[/REASONING] |
| 90 | + val (startTag, endTag) = tagDefinition |
| 91 | + val escapedStart = Regex.escape(startTag) |
| 92 | + val escapedEnd = Regex.escape(endTag) |
| 93 | + val pattern = "$escapedStart.*?$escapedEnd".toRegex(RegexOption.DOT_MATCHES_ALL) |
| 94 | + remainingInput = remainingInput.replace(pattern, "") |
| 95 | + } else { |
| 96 | + // Remove dynamic tags using standard XML pattern <tagname>content</tagname> |
| 97 | + // Escapes tag name for regex safety (e.g., "custom-tag" becomes "custom\-tag") |
| 98 | + // Pattern matches: <tagname optional-attrs>content</tagname> |
| 99 | + val escapedTagName = Regex.escape(block.tagValue) |
| 100 | + val pattern = "<$escapedTagName[^>]*>.*?</$escapedTagName>".toRegex(RegexOption.DOT_MATCHES_ALL) |
| 101 | + remainingInput = remainingInput.replace(pattern, "") |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + // Remove all prefix lines |
| 106 | + remainingInput = remainingInput.replace("//THINKING:.*".toRegex(RegexOption.MULTILINE), "") |
| 107 | + |
| 108 | + // Extract remaining content before JSON |
| 109 | + val noPrefixPattern = "^(.*?)(?=\\{)".toRegex(RegexOption.DOT_MATCHES_ALL) |
| 110 | + noPrefixPattern.find(remainingInput.trim())?.let { match -> |
| 111 | + val content = match.groupValues[1].trim() |
| 112 | + if (content.isNotEmpty()) { |
| 113 | + blocks.add( |
| 114 | + ThinkingBlock( |
| 115 | + content = content, |
| 116 | + tagType = ThinkingTagType.NO_PREFIX, |
| 117 | + tagValue = "" |
| 118 | + ) |
| 119 | + ) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + return blocks.sortedBy { input.indexOf(it.content) } |
| 124 | +} |
0 commit comments