小说组件:定义Claude Code的创新
When an LLM streams a tool use request, it doesn't send complete JSON all at once. Instead, you might receive fragments like:
当 LLM 流式传输工具使用请求时,它不会一次性发送完整的 JSON。相反,您可能会收到像这样的片段:
{"file_path": "/src/ {"file_path": "/src/main. {"file_path": "/src/main.ts", "old_str {"file_path": "/src/main.ts", "old_string": "console.log('hell
{"file_path": "/src/ {"file_path": "/src/main. {"file_path": "/src/main.ts", "old_str {"file_path": "/src/main.ts", "old_string": "console.log('hell
The streaming JSON parser solves this elegantly:
流式 JSON 解析器优雅地解决了这个问题:
class StreamingToolInputParser { private buffer: string = ''; private state = { depth: 0, inString: boolean, escape: boolean, stringChar: '"' | "'" | null, }; addChunk(chunk: string): ParseResult { this.buffer += chunk; for (let i = 0; i < chunk.length; i++) { const char = chunk[i]; const prevChar = i > 0 ? chunk[i-1] : this.buffer[this.buffer.length - chunk.length - 1]; if (this.escape) { this.escape = false; continue; } if (char === '\\\\' && this.state.inString) { this.escape = true; continue; } if (!this.state.inString && (char === '"' || char === "'")) { this.state.inString = true; this.state.stringChar = char; } else if (this.state.inString && char === this.state.stringChar) { this.state.inString = false; this.state.stringChar = null; } if (!this.state.inString) { if (char === '{' || char === '[') { this.state.depth++; } else if (char === '}' || char === ']') { this.state.depth--; if (this.state.depth === 0) { return this.tryParse(); } } } } if (this.buffer.length > 10000) { return this.tryParseWithRecovery(); } return { complete: false }; } private tryParse(): ParseResult { try { const parsed = JSON.parse(this.buffer); return { complete: true, value: parsed }; } catch (e) { return { complete: false, partial: this.buffer }; } } private tryParseWithRecovery(): ParseResult { let attemptBuffer = this.buffer; if (this.state.inString && this.state.stringChar) { attemptBuffer += this.state.stringChar; attemptBuffer += '}'.repeat(Math.max(0, this.state.depth)); attemptBu...