|
| 1 | +""" |
| 2 | +Simplified streaming utilities for processing structured outputs from message content. |
| 3 | +
|
| 4 | +This module provides utilities for processing streaming responses that contain |
| 5 | +structured data directly in the message content (not in function calls). |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import Optional, Type, Union |
| 9 | + |
| 10 | +from pydantic import ValidationError |
| 11 | + |
| 12 | +from llama_index.core.base.llms.types import ChatResponse |
| 13 | +from llama_index.core.program.utils import ( |
| 14 | + FlexibleModel, |
| 15 | + _repair_incomplete_json, |
| 16 | + create_flexible_model, |
| 17 | +) |
| 18 | +from llama_index.core.types import Model |
| 19 | + |
| 20 | + |
| 21 | +def process_streaming_content_incremental( |
| 22 | + chat_response: ChatResponse, |
| 23 | + output_cls: Type[Model], |
| 24 | + cur_object: Optional[Union[Model, FlexibleModel]] = None, |
| 25 | +) -> Union[Model, FlexibleModel]: |
| 26 | + """ |
| 27 | + Process streaming response content with true incremental list handling. |
| 28 | +
|
| 29 | + This version can extract partial progress from incomplete JSON and build |
| 30 | + lists incrementally (e.g., 1 joke → 2 jokes → 3 jokes) rather than |
| 31 | + jumping from empty to complete lists. |
| 32 | +
|
| 33 | + Args: |
| 34 | + chat_response (ChatResponse): The chat response to process |
| 35 | + output_cls (Type[BaseModel]): The target output class |
| 36 | + cur_object (Optional[BaseModel]): Current best object (for comparison) |
| 37 | + flexible_mode (bool): Whether to use flexible schema during parsing |
| 38 | +
|
| 39 | + Returns: |
| 40 | + Union[BaseModel, FlexibleModel]: Processed object with incremental updates |
| 41 | +
|
| 42 | + """ |
| 43 | + partial_output_cls = create_flexible_model(output_cls) |
| 44 | + |
| 45 | + # Get content from message |
| 46 | + content = chat_response.message.content |
| 47 | + if not content: |
| 48 | + return cur_object if cur_object is not None else partial_output_cls() |
| 49 | + try: |
| 50 | + parsed_obj = partial_output_cls.model_validate_json(content) |
| 51 | + except (ValidationError, ValueError): |
| 52 | + try: |
| 53 | + repaired_json = _repair_incomplete_json(content) |
| 54 | + parsed_obj = partial_output_cls.model_validate_json(repaired_json) |
| 55 | + except (ValidationError, ValueError): |
| 56 | + extracted_obj = _extract_partial_list_progress( |
| 57 | + content, output_cls, cur_object, partial_output_cls |
| 58 | + ) |
| 59 | + parsed_obj = ( |
| 60 | + extracted_obj if extracted_obj is not None else partial_output_cls() |
| 61 | + ) |
| 62 | + |
| 63 | + # If we still couldn't parse anything, use previous object |
| 64 | + if parsed_obj is None: |
| 65 | + if cur_object is not None: |
| 66 | + return cur_object |
| 67 | + else: |
| 68 | + return partial_output_cls() |
| 69 | + |
| 70 | + # Use incremental comparison that considers list progress |
| 71 | + try: |
| 72 | + return output_cls.model_validate(parsed_obj.model_dump(exclude_unset=True)) |
| 73 | + except ValidationError: |
| 74 | + return parsed_obj |
| 75 | + |
| 76 | + |
| 77 | +def _extract_partial_list_progress( |
| 78 | + content: str, |
| 79 | + output_cls: Type[Model], |
| 80 | + cur_object: Optional[Union[Model, FlexibleModel]], |
| 81 | + partial_output_cls: Type[FlexibleModel], |
| 82 | +) -> Optional[FlexibleModel]: |
| 83 | + """ |
| 84 | + Try to extract partial list progress from incomplete JSON. |
| 85 | +
|
| 86 | + This attempts to build upon the current object by detecting partial |
| 87 | + list additions even when JSON is malformed. |
| 88 | + """ |
| 89 | + if not isinstance(content, str) or cur_object is None: |
| 90 | + return None |
| 91 | + |
| 92 | + try: |
| 93 | + import re |
| 94 | + |
| 95 | + # Try to extract list patterns from incomplete JSON |
| 96 | + # Look for patterns like: "jokes": [{"setup": "...", "punchline": "..."} |
| 97 | + list_pattern = r'"(\w+)":\s*\[([^\]]*)' |
| 98 | + matches = re.findall(list_pattern, content) |
| 99 | + |
| 100 | + if not matches: |
| 101 | + return None |
| 102 | + |
| 103 | + # Start with current object data |
| 104 | + current_data = ( |
| 105 | + cur_object.model_dump() if hasattr(cur_object, "model_dump") else {} |
| 106 | + ) |
| 107 | + |
| 108 | + for field_name, list_content in matches: |
| 109 | + if ( |
| 110 | + hasattr(output_cls, "model_fields") |
| 111 | + and field_name in output_cls.model_fields |
| 112 | + ): |
| 113 | + # Try to parse individual items from the list content |
| 114 | + items = _parse_partial_list_items(list_content, field_name, output_cls) |
| 115 | + if items: |
| 116 | + current_data[field_name] = items |
| 117 | + |
| 118 | + # Try to create object with updated data |
| 119 | + return partial_output_cls.model_validate(current_data) |
| 120 | + |
| 121 | + except Exception: |
| 122 | + return None |
| 123 | + |
| 124 | + |
| 125 | +def _parse_partial_list_items( |
| 126 | + list_content: str, field_name: str, output_cls: Type[Model] |
| 127 | +) -> list: |
| 128 | + """ |
| 129 | + Parse individual items from partial list content. |
| 130 | + """ |
| 131 | + try: |
| 132 | + import json |
| 133 | + import re |
| 134 | + |
| 135 | + items = [] |
| 136 | + |
| 137 | + # Look for complete object patterns within the list |
| 138 | + # Pattern: {"key": "value", "key2": "value2"} |
| 139 | + object_pattern = r"\{[^{}]*\}" |
| 140 | + object_matches = re.findall(object_pattern, list_content) |
| 141 | + |
| 142 | + for obj_str in object_matches: |
| 143 | + try: |
| 144 | + # Try to parse as complete JSON object |
| 145 | + obj_data = json.loads(obj_str) |
| 146 | + items.append(obj_data) |
| 147 | + except (json.JSONDecodeError, SyntaxError): |
| 148 | + # Try to repair and parse |
| 149 | + try: |
| 150 | + repaired = _repair_incomplete_json(obj_str) |
| 151 | + obj_data = json.loads(repaired) |
| 152 | + items.append(obj_data) |
| 153 | + except (json.JSONDecodeError, SyntaxError): |
| 154 | + continue |
| 155 | + |
| 156 | + return items |
| 157 | + |
| 158 | + except Exception: |
| 159 | + return [] |
0 commit comments