1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! Re-exports from the standalone [`llm-output-parser`] crate.
//!
//! The parser implementation now lives in the separate `llm-output-parser` crate.
//! This module re-exports its public API for backward compatibility so existing
//! `use llm_pipeline::output_parser::parse_json` paths continue to work.
pub use llm_output_parser::*;
/// Streaming JSON parser with auto-completion for truncated output.
///
/// These utilities are pipeline-specific and not part of the standalone
/// `llm-output-parser` crate.
pub mod streaming {
use serde_json::Value;
/// Auto-complete a truncated JSON string by closing unclosed delimiters.
///
/// Handles:
/// - Unclosed strings (adds `"`)
/// - Unclosed objects (adds `}`)
/// - Unclosed arrays (adds `]`)
/// - Nested combinations
/// - Trailing commas before closing
/// - Think tags (strips them first)
///
/// Returns `Some(valid_json_string)` if completion was possible,
/// or `None` if the input doesn't look like JSON at all.
///
/// # Example
///
/// ```
/// use llm_pipeline::output_parser::streaming::auto_complete_json;
///
/// let completed = auto_complete_json(r#"{"name": "Alice", "age": 3"#).unwrap();
/// let v: serde_json::Value = serde_json::from_str(&completed).unwrap();
/// assert_eq!(v["name"], "Alice");
/// ```
pub fn auto_complete_json(input: &str) -> Option<String> {
// Strip think tags first
let cleaned = llm_output_parser::strip_think_tags(input);
let trimmed = cleaned.trim();
if trimmed.is_empty() {
return None;
}
// Already valid JSON? Return as-is.
if serde_json::from_str::<Value>(trimmed).is_ok() {
return Some(trimmed.to_string());
}
// Must start with { or [ to be JSON
if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
return None;
}
let mut result = String::with_capacity(trimmed.len() + 16);
let mut stack: Vec<char> = Vec::new();
let mut in_string = false;
let mut escaped = false;
for ch in trimmed.chars() {
result.push(ch);
if escaped {
escaped = false;
continue;
}
if ch == '\\' && in_string {
escaped = true;
continue;
}
if ch == '"' {
in_string = !in_string;
continue;
}
if in_string {
continue;
}
match ch {
'{' => stack.push('}'),
'[' => stack.push(']'),
'}' | ']' => {
if let Some(expected) = stack.last() {
if *expected == ch {
stack.pop();
}
}
}
_ => {}
}
}
// If we're inside a string, close it
if in_string {
result.push('"');
}
// Clean up trailing incomplete key-value pairs before closing.
loop {
let t = result.trim_end();
if t.ends_with(',') {
if let Some(without_suffix) = t.strip_suffix(',') {
result = without_suffix.to_string();
} else {
break;
}
} else if let Some(before_colon) = t.strip_suffix(':') {
let without_colon = before_colon.trim_end();
if let Some(quote_pos) = without_colon.rfind('"') {
if let Some(open_pos) = without_colon[..quote_pos].rfind('"') {
let before_key = without_colon[..open_pos].trim_end();
result = if let Some(stripped) = before_key.strip_suffix(',') {
stripped.to_string()
} else {
before_key.to_string()
};
} else {
break;
}
} else {
break;
}
} else {
break;
}
}
// Check for orphan key at the end
if stack.last() == Some(&'}') {
let t = result.trim_end();
if t.ends_with('"') && !t.ends_with("\\\"") {
let inner = &t[..t.len() - 1];
if let Some(open_pos) = inner.rfind('"') {
let before = inner[..open_pos].trim_end();
if before.ends_with(',') {
if let Some(without_suffix) = before.strip_suffix(',') {
result = without_suffix.to_string();
}
}
}
}
}
// Close all unclosed delimiters
while let Some(closer) = stack.pop() {
result.push(closer);
}
// Verify the result is valid JSON
if serde_json::from_str::<Value>(&result).is_ok() {
Some(result)
} else {
None
}
}
/// Progressive JSON parser for streaming LLM output.
///
/// Tracks the accumulating text during a streaming call and caches
/// the last successful JSON parse. Useful for partial results displays.
///
/// # Example
///
/// ```
/// use llm_pipeline::output_parser::streaming::StreamingJsonParser;
///
/// let mut parser = StreamingJsonParser::new();
///
/// parser.push(r#"{"name": "#);
/// // Auto-complete may produce a partial value here
///
/// parser.push(r#""Alice", "age": 30}"#);
/// let val = parser.current_value().unwrap();
/// assert_eq!(val["name"], "Alice");
/// ```
#[derive(Debug)]
pub struct StreamingJsonParser {
buffer: String,
cached_value: Option<Value>,
last_parsed_len: usize,
}
impl StreamingJsonParser {
/// Create a new empty streaming parser.
pub fn new() -> Self {
Self {
buffer: String::new(),
cached_value: None,
last_parsed_len: 0,
}
}
/// Append new text to the buffer and attempt to parse.
pub fn push(&mut self, text: &str) {
self.buffer.push_str(text);
self.try_parse();
}
/// Get the current parsed value, if any.
pub fn current_value(&self) -> Option<&Value> {
self.cached_value.as_ref()
}
/// Get the raw accumulated text.
pub fn buffer(&self) -> &str {
&self.buffer
}
/// Clear the parser state.
pub fn clear(&mut self) {
self.buffer.clear();
self.cached_value = None;
self.last_parsed_len = 0;
}
/// Try to parse the current buffer content.
fn try_parse(&mut self) {
if self.buffer.len() == self.last_parsed_len {
return;
}
let trimmed = self.buffer.trim();
if let Ok(val) = serde_json::from_str::<Value>(trimmed) {
self.cached_value = Some(val);
self.last_parsed_len = self.buffer.len();
return;
}
if let Some(completed) = auto_complete_json(trimmed) {
if let Ok(val) = serde_json::from_str::<Value>(&completed) {
self.cached_value = Some(val);
}
}
self.last_parsed_len = self.buffer.len();
}
}
impl Default for StreamingJsonParser {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_auto_complete_closes_string() {
let result = auto_complete_json(r#"{"name": "Alice"#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["name"], "Alice");
}
#[test]
fn test_auto_complete_closes_brace() {
let result = auto_complete_json(r#"{"key": "value""#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["key"], "value");
}
#[test]
fn test_auto_complete_closes_bracket() {
let result = auto_complete_json(r#"["a", "b", "c""#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
let arr = v.as_array().unwrap();
assert_eq!(arr.len(), 3);
}
#[test]
fn test_auto_complete_nested() {
let result = auto_complete_json(r#"{"items": [{"name": "a"}, {"name": "b""#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert!(v["items"].is_array());
}
#[test]
fn test_auto_complete_with_null_fill() {
let result = auto_complete_json(r#"{"name": "Alice", "age": "#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["name"], "Alice");
}
#[test]
fn test_auto_complete_already_valid() {
let input = r#"{"complete": true}"#;
let result = auto_complete_json(input).unwrap();
assert_eq!(result, input);
}
#[test]
fn test_auto_complete_not_json() {
assert!(auto_complete_json("just plain text").is_none());
assert!(auto_complete_json("").is_none());
}
#[test]
fn test_auto_complete_with_think_tags() {
let input = r#"<think>hmm</think>{"key": "val"#;
let result = auto_complete_json(input).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["key"], "val");
}
#[test]
fn test_streaming_parser_progressive() {
let mut parser = StreamingJsonParser::new();
parser.push(r#"{"name""#);
parser.push(r#": "Alice", "age": 30}"#);
let val = parser.current_value().unwrap();
assert_eq!(val["name"], "Alice");
assert_eq!(val["age"], 30);
}
#[test]
fn test_streaming_parser_cache_no_reparse() {
let mut parser = StreamingJsonParser::new();
parser.push(r#"{"complete": true}"#);
let val1 = parser.current_value().cloned();
let val2 = parser.current_value().cloned();
assert_eq!(val1, val2);
}
#[test]
fn test_streaming_parser_clear_resets() {
let mut parser = StreamingJsonParser::new();
parser.push(r#"{"a": 1}"#);
assert!(parser.current_value().is_some());
parser.clear();
assert!(parser.current_value().is_none());
assert!(parser.buffer().is_empty());
}
#[test]
fn test_json_parser_recovers_truncated_object() {
let result =
auto_complete_json(r#"{"title": "Matrix", "year": 1999, "rating"#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["title"], "Matrix");
assert_eq!(v["year"], 1999);
}
#[test]
fn test_json_parser_recovers_truncated_array() {
let result = auto_complete_json(r#"[1, 2, 3, "#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
let arr = v.as_array().unwrap();
assert!(arr.len() >= 3);
}
#[test]
fn test_json_parser_truncated_in_string() {
let result = auto_complete_json(r#"{"msg": "hello wor"#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert!(v["msg"].as_str().unwrap().starts_with("hello wor"));
}
#[test]
fn test_auto_complete_trailing_comma() {
let result = auto_complete_json(r#"{"a": 1, "b": 2,"#).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(v["a"], 1);
assert_eq!(v["b"], 2);
}
}
}