lc_core/structured_output/parser.rs
1// src/core/structured_output/parser.rs
2//! Incremental JSON parser for handling partial/incomplete JSON from streaming LLM output.
3
4use serde_json::Value;
5
6/// Errors produced by `PartialJsonParser`.
7#[derive(Debug, Clone, thiserror::Error)]
8#[non_exhaustive]
9pub enum PartialJsonError {
10 /// The buffer does not yet contain parseable JSON.
11 #[error("Incomplete JSON: {0}")]
12 Incomplete(String),
13
14 /// The accumulated text is not valid JSON even after repair attempts.
15 #[error("Invalid JSON: {0}")]
16 Invalid(String),
17}
18
19/// Incremental JSON parser that can handle partial/incomplete JSON.
20///
21/// Builds up a string token by token and attempts to parse at each step,
22/// returning the best partial result possible. This is designed for streaming
23/// LLM output where JSON arrives in small chunks and may be incomplete until
24/// the stream finishes.
25///
26/// # Strategy
27///
28/// 1. Accumulate tokens into an internal buffer.
29/// 2. On each `push_and_parse`, attempt to parse the buffer as complete JSON.
30/// 3. If that fails, try to repair the partial JSON by closing unclosed
31/// brackets/braces and truncating incomplete string values.
32/// 4. If repair yields valid JSON, return it; otherwise return
33/// `PartialJsonError::Incomplete`.
34///
35/// # Example
36///
37/// ```ignore
38/// let mut parser = PartialJsonParser::new();
39/// // Simulating token-by-token LLM output
40/// let _ = parser.push_and_parse(r#"{"name":"#); // Incomplete
41/// let v = parser.push_and_parse(r#""Alice","age":30}"#); // Ok({"name":"Alice","age":30})
42/// ```
43pub struct PartialJsonParser {
44 buffer: String,
45 depth: usize,
46 in_string: bool,
47 escape_next: bool,
48}
49
50impl PartialJsonParser {
51 /// Create a new, empty parser.
52 pub fn new() -> Self {
53 Self {
54 buffer: String::new(),
55 depth: 0,
56 in_string: false,
57 escape_next: false,
58 }
59 }
60
61 /// Push a new token and attempt to parse the accumulated buffer.
62 ///
63 /// Returns `Ok(value)` if the buffer (after optional repair) yields valid
64 /// JSON, or `Err(PartialJsonError::Incomplete)` if it does not yet form
65 /// any parseable JSON.
66 pub fn push_and_parse(&mut self, token: &str) -> Result<Value, PartialJsonError> {
67 // Update parser state by scanning the new token
68 for ch in token.chars() {
69 if self.escape_next {
70 self.escape_next = false;
71 continue;
72 }
73 if ch == '\\' && self.in_string {
74 self.escape_next = true;
75 continue;
76 }
77 if ch == '"' {
78 self.in_string = !self.in_string;
79 continue;
80 }
81 if !self.in_string {
82 match ch {
83 '{' | '[' => self.depth += 1,
84 '}' | ']' => {
85 if self.depth > 0 {
86 self.depth -= 1;
87 }
88 }
89 _ => {}
90 }
91 }
92 }
93
94 // Ensure we only push at character boundaries (M37: UTF-8 boundary check)
95 if token.is_char_boundary(0) {
96 self.buffer.push_str(token);
97 } else {
98 // Find the first valid char boundary
99 let mut pos = 0;
100 while pos < token.len() && !token.is_char_boundary(pos) {
101 pos += 1;
102 }
103 self.buffer.push_str(&token[pos..]);
104 }
105
106 // H4: 模型常把 JSON 包在 ```json ... ``` 围栏里(或先输出"结果是:"等
107 // 前导文本)。解析时先剥掉围栏/前导文本,只看真正的 JSON 值;否则带
108 // 围栏的合法 JSON 会被判为无法解析,流式结构化输出整条路径不可用。
109 let json = Self::strip_markdown_fence(&self.buffer);
110
111 // Fast path: try full parse first
112 if let Ok(value) = serde_json::from_str::<Value>(json) {
113 return Ok(value);
114 }
115
116 // Only attempt repair if we have at least opened a structure
117 let trimmed = json.trim();
118 if self.depth > 0 || trimmed.starts_with('{') || trimmed.starts_with('[') {
119 let repaired = Self::repair_partial_json(json);
120 if let Ok(value) = serde_json::from_str::<Value>(&repaired) {
121 return Ok(value);
122 }
123 }
124
125 Err(PartialJsonError::Incomplete(format!(
126 "Buffer has {} chars, depth={}",
127 self.buffer.len(),
128 self.depth
129 )))
130 }
131
132 /// Get the final complete value.
133 ///
134 /// Call this when the stream has ended. It first tries to parse the
135 /// fence-stripped buffer, then falls back to the repaired version.
136 pub fn finalize(self) -> Result<Value, PartialJsonError> {
137 // H4: 同样先剥 ```json 围栏,否则带围栏的完整 JSON 会被误判为 Invalid。
138 let json = Self::strip_markdown_fence(&self.buffer);
139
140 // Try full parse
141 if let Ok(value) = serde_json::from_str::<Value>(json) {
142 return Ok(value);
143 }
144
145 // Try repaired
146 let repaired = Self::repair_partial_json(json);
147 serde_json::from_str::<Value>(&repaired).map_err(|e| {
148 PartialJsonError::Invalid(format!(
149 "Failed to parse final buffer ({} chars): {}. Buffer: {}",
150 self.buffer.len(),
151 e,
152 &self.buffer[..std::cmp::min(200, self.buffer.len())]
153 ))
154 })
155 }
156
157 /// Return a reference to the current buffer contents.
158 pub fn buffer(&self) -> &str {
159 &self.buffer
160 }
161
162 /// Whether the parser is currently inside a JSON string.
163 pub fn is_in_string(&self) -> bool {
164 self.in_string
165 }
166
167 /// Current nesting depth of brackets/braces.
168 pub fn depth(&self) -> usize {
169 self.depth
170 }
171
172 /// Strip a markdown code fence and any leading/trailing non-JSON text,
173 /// returning the slice that holds the top-level JSON value.
174 ///
175 /// Streaming-safe: only reads what has been accumulated so far, so a
176 /// partially-delivered object still yields its partial JSON (e.g. while the
177 /// model is still emitting the closing brace).
178 ///
179 /// # Rules
180 ///
181 /// - Leading text up to the first `{` or `[` is dropped (covers a ```json
182 /// fence line, "结果是:" prose, and whitespace).
183 /// - Trailing text after the top-level structure closes is dropped (covers
184 /// the closing ``` fence).
185 /// - Returns `""` when no `{`/`[` has been seen yet (e.g. the buffer is
186 /// still just "```json").
187 pub(crate) fn strip_markdown_fence(buffer: &str) -> &str {
188 let bytes = buffer.as_bytes();
189 // First byte that opens the top-level JSON value. `{`/`[` are ASCII, so
190 // this byte index is always a UTF-8 char boundary.
191 let start = match bytes.iter().position(|b| *b == b'{' || *b == b'[') {
192 Some(i) => i,
193 None => return "",
194 };
195
196 // Walk from `start` tracking string/escape state; the top-level value
197 // ends where depth returns to 0. Everything after it (the closing ```
198 // fence) is dropped. Multi-byte UTF-8 never matches the structural
199 // ASCII bytes below, so byte-wise scanning is safe.
200 let mut depth: i64 = 0;
201 let mut in_string = false;
202 let mut escape_next = false;
203 let mut end = bytes.len();
204 let mut idx = start;
205 while idx < bytes.len() {
206 let b = bytes[idx];
207 if escape_next {
208 escape_next = false;
209 } else if b == b'\\' && in_string {
210 escape_next = true;
211 } else if b == b'"' {
212 in_string = !in_string;
213 } else if !in_string {
214 match b {
215 b'{' | b'[' => depth += 1,
216 b'}' | b']' => {
217 depth -= 1;
218 if depth == 0 {
219 end = idx + 1;
220 break;
221 }
222 }
223 _ => {}
224 }
225 }
226 idx += 1;
227 }
228 &buffer[start..end]
229 }
230
231 /// Repair a partial JSON string by closing unclosed structures and
232 /// truncating incomplete values.
233 pub(crate) fn repair_partial_json(text: &str) -> String {
234 let mut repaired = text.trim().to_string();
235
236 // Scan the text tracking string state to correctly count braces/brackets
237 // and quotes outside of strings (C20 + C21).
238 let mut in_string = false;
239 let mut escape_next = false;
240 let mut open_braces = 0usize;
241 let mut close_braces = 0usize;
242 let mut open_brackets = 0usize;
243 let mut close_brackets = 0usize;
244 let mut unescaped_quote_count = 0usize;
245
246 for ch in repaired.chars() {
247 if escape_next {
248 escape_next = false;
249 continue;
250 }
251 if ch == '\\' && in_string {
252 escape_next = true;
253 continue;
254 }
255 if ch == '"' {
256 unescaped_quote_count += 1;
257 in_string = !in_string;
258 continue;
259 }
260 if !in_string {
261 match ch {
262 '{' => open_braces += 1,
263 '}' => close_braces += 1,
264 '[' => open_brackets += 1,
265 ']' => close_brackets += 1,
266 _ => {}
267 }
268 }
269 }
270
271 // If we are in the middle of a string value, close it.
272 // Heuristic: odd number of unescaped quotes means an unclosed string.
273 if unescaped_quote_count % 2 != 0 {
274 repaired.push('"');
275 }
276
277 // Close unclosed braces first (before removing trailing commas,
278 // so that commas before the newly-added braces get removed)
279 for _ in close_braces..open_braces {
280 repaired.push('}');
281 }
282
283 // Close unclosed brackets
284 for _ in close_brackets..open_brackets {
285 repaired.push(']');
286 }
287
288 // Remove trailing commas before closing brackets/braces
289 // (must come after closing braces/brackets so we can detect them)
290 repaired = Self::remove_trailing_commas(&repaired);
291
292 repaired
293 }
294
295 /// Remove trailing commas before closing braces/brackets (invalid in strict JSON).
296 pub(crate) fn remove_trailing_commas(s: &str) -> String {
297 let mut result = String::with_capacity(s.len());
298 let chars: Vec<char> = s.chars().collect();
299 let mut i = 0;
300 while i < chars.len() {
301 if chars[i] == ',' && i + 1 < chars.len() {
302 let next_non_ws = chars[i + 1..].iter().find(|c| !c.is_whitespace());
303 if next_non_ws == Some(&'}') || next_non_ws == Some(&']') {
304 // Skip the trailing comma
305 i += 1;
306 continue;
307 }
308 }
309 result.push(chars[i]);
310 i += 1;
311 }
312 result
313 }
314}
315
316impl Default for PartialJsonParser {
317 fn default() -> Self {
318 Self::new()
319 }
320}