| 1 | import { ToolCallDelta } from "../.."; |
| 2 | import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils"; |
| 3 | |
| 4 | export type ToolCallParseState = { |
| 5 | toolCallId: string; |
| 6 | isOnArgBeginLine: boolean; |
| 7 | currentArgName: string | undefined; |
| 8 | currentArgLines: string[]; |
| 9 | processedArgNames: Set<string>; |
| 10 | currentLineIndex: number; |
| 11 | lineChunks: string[][]; |
| 12 | done: boolean; |
| 13 | }; |
| 14 | |
| 15 | export const getInitialTooLCallParseState = (): ToolCallParseState => ({ |
| 16 | toolCallId: generateOpenAIToolCallId(), |
| 17 | isOnArgBeginLine: false, |
| 18 | currentArgName: undefined, |
| 19 | currentArgLines: [], |
| 20 | currentLineIndex: 0, |
| 21 | processedArgNames: new Set(), |
| 22 | lineChunks: [], |
| 23 | done: false, |
| 24 | }); |
| 25 | |
| 26 | /* |
| 27 | Efficiently applies chunks to a tool call state as they come in |
| 28 | Expects chunks to be broken so that new lines and codeblocks are alone |
| 29 | For now, this parser collects entire arg before |
| 30 | This is because support for JSON booleans is tricky otherwise |
| 31 | |
| 32 | */ |
| 33 | export function handleToolCallBuffer( |
| 34 | chunk: string, |
| 35 | state: ToolCallParseState, |
| 36 | ): ToolCallDelta | undefined { |
| 37 | // Add chunks |
| 38 | const lineIndex = state.currentLineIndex; |
| 39 | if (!state.lineChunks[lineIndex]) { |
| 40 | state.lineChunks[lineIndex] = []; |
| 41 | } |
| 42 | state.lineChunks[lineIndex].push(chunk); |
| 43 | |
| 44 | const isNewLine = chunk === "\n"; |
| 45 | if (isNewLine) { |
| 46 | state.currentLineIndex++; |
| 47 | } |
| 48 | |
| 49 | const line = state.lineChunks[lineIndex].join(""); |
| 50 | |
| 51 | switch (lineIndex) { |
| 52 | // The first line will be skipped (e.g. ```tool\n) |
| 53 | case 0: |
| 54 | // non-standard start sequences will sometimes include stuff in the tool_name line |
| 55 | const splitBuffer = line.split("\n"); |
| 56 | if (splitBuffer[0]) { |
| 57 | state.lineChunks[0] = [splitBuffer[0], "\n"]; |
| 58 | } |
| 59 | if (splitBuffer[1]) { |
| 60 | state.lineChunks[1] = [splitBuffer[1]]; |
| 61 | } |
| 62 | |
| 63 | state.currentLineIndex = 1; |
| 64 | // Tool name line - process once line 2 is reached |
| 65 | case 1: |
| 66 | if (isNewLine) { |
| 67 | const name = (line.split(/tool_?name:/i)[1] ?? "").trim(); |
| 68 | if (!name) { |
| 69 | throw new Error("Invalid tool name"); |
| 70 | } |
| 71 | return createDelta(name, "", state.toolCallId); |
| 72 | } |
| 73 | return; |
| 74 | default: |
| 75 | if (state.isOnArgBeginLine) { |
| 76 | if (isNewLine) { |
| 77 | const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim(); |
| 78 | if (!argName) { |
| 79 | throw new Error("Invalid begin arg line"); |
| 80 | } |
| 81 | state.currentArgName = argName; |
| 82 | state.isOnArgBeginLine = false; |
| 83 | const argPrefix = state.processedArgNames.size === 0 ? "{" : ","; |
| 84 | return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId); |
| 85 | } |
| 86 | } else if (state.currentArgName) { |
| 87 | if (isNewLine) { |
| 88 | const isEndArgTag = line.match(/end_?arg/i); |
| 89 | if (isEndArgTag) { |
| 90 | let trimmedValue = state.currentArgLines.join("").trim(); |
| 91 | state.currentArgLines.length = 0; |
| 92 | state.processedArgNames.add(state.currentArgName); |
| 93 | state.currentArgName = undefined; |
| 94 | |
| 95 | try { |
| 96 | if ( |
| 97 | trimmedValue.startsWith("[") || |
| 98 | trimmedValue.startsWith("{") |
| 99 | ) { |
| 100 | trimmedValue = trimmedValue.replace( |
| 101 | /"((?:\\[\s\S]|[^"\\])*?)"/g, |
| 102 | (match) => { |
| 103 | const content = match.slice(1, -1); |
| 104 | // Replace unescaped newlines |
| 105 | return ( |
| 106 | '"' + |
| 107 | content |
| 108 | .replace(/([^\\])\n/g, "$1\\n") |
| 109 | .replace(/^\n/g, "\\n") + |
| 110 | '"' |
| 111 | ); |
| 112 | }, |
| 113 | ); |
| 114 | } |
| 115 | const parsed = JSON.parse(trimmedValue); |
| 116 | const stringifiedArg = JSON.stringify(parsed); |
| 117 | return createDelta("", stringifiedArg, state.toolCallId); |
| 118 | } catch (e) { |
| 119 | const stringifiedArg = JSON.stringify(trimmedValue); |
| 120 | return createDelta("", stringifiedArg, state.toolCallId); |
| 121 | } |
| 122 | } else { |
| 123 | state.currentArgLines.push(line); |
| 124 | } |
| 125 | } |
| 126 | } else { |
| 127 | // Check for entry into arg |
| 128 | const isBeginArgLine = line.match(/begin_?arg:/i); |
| 129 | if (isBeginArgLine) { |
| 130 | state.isOnArgBeginLine = true; |
| 131 | } |
| 132 | |
| 133 | // Check for exit |
| 134 | if (line === "```" || isNewLine) { |
| 135 | state.done = true; |
| 136 | // finish args JSON if applicable |
| 137 | if (state.processedArgNames.size > 0) { |
| 138 | return createDelta("", "}", state.toolCallId); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | } |