| 1 | let boundaryTypeIndex = 0; |
| 2 | |
| 3 | // Poor models are really bad at following instructions |
| 4 | // Give some leeway in how the initiate |
| 5 | const acceptedToolStarts: [string, string][] = [ |
| 6 | ["```tool\n", "```tool\n"], |
| 7 | ["tool_name:", "```tool\nTOOL_NAME:"], |
| 8 | ]; |
| 9 | |
| 10 | export function detectToolCallStart(buffer: string) { |
| 11 | let modifiedBuffer = buffer; |
| 12 | let isInToolCall = false; |
| 13 | let isInPartialStart = false; |
| 14 | const lowerCaseBuffer = buffer.toLowerCase(); |
| 15 | for (let i = 0; i < acceptedToolStarts.length; i++) { |
| 16 | const [start, replacement] = acceptedToolStarts[i]; |
| 17 | if (lowerCaseBuffer.startsWith(start)) { |
| 18 | // for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive |
| 19 | if (i !== 0) { |
| 20 | modifiedBuffer = buffer.replace(new RegExp(start, "i"), replacement); |
| 21 | } |
| 22 | isInToolCall = true; |
| 23 | break; |
| 24 | } else if (start.startsWith(lowerCaseBuffer)) { |
| 25 | isInPartialStart = true; |
| 26 | } |
| 27 | } |
| 28 | return { |
| 29 | isInToolCall, |
| 30 | isInPartialStart, |
| 31 | modifiedBuffer, |
| 32 | }; |
| 33 | } |