|
8 | 8 |
|
9 | 9 | def _serialize_value(value: Any) -> Any: |
10 | 10 | """Convert a value to a JSON-serializable representation.""" |
11 | | - if value is None or isinstance(value, bool | int | float | str): |
| 11 | + if value is None or isinstance(value, (bool, int, float, str)): |
12 | 12 | return value |
13 | 13 | if isinstance(value, ModuleType): |
14 | 14 | return f"<module '{value.__name__}'>" |
15 | | - if isinstance(value, list | tuple): |
| 15 | + if isinstance(value, (list, tuple)): |
16 | 16 | return [_serialize_value(v) for v in value] |
17 | 17 | if isinstance(value, dict): |
18 | 18 | return {str(k): _serialize_value(v) for k, v in value.items()} |
@@ -213,20 +213,40 @@ class QueryMetadata: |
213 | 213 | context_total_length: int |
214 | 214 | context_type: str |
215 | 215 |
|
216 | | - def __init__(self, prompt: str | list[str] | dict[Any, str] | list[dict[Any, str]]): |
| 216 | + def __init__(self, prompt: str | list[str] | dict[Any, Any] | list[dict[Any, Any]]): |
217 | 217 | if isinstance(prompt, str): |
218 | 218 | self.context_lengths = [len(prompt)] |
219 | 219 | self.context_type = "str" |
220 | | - elif isinstance(prompt, dict[Any, str]): |
221 | | - self.context_lengths = [len(chunk) for chunk in prompt.values()] |
| 220 | + elif isinstance(prompt, dict): |
| 221 | + self.context_type = "dict" |
| 222 | + self.context_lengths = [] |
| 223 | + for chunk in prompt.values(): |
| 224 | + if isinstance(chunk, str): |
| 225 | + self.context_lengths.append(len(chunk)) |
| 226 | + continue |
| 227 | + try: |
| 228 | + import json |
| 229 | + |
| 230 | + self.context_lengths.append(len(json.dumps(chunk, default=str))) |
| 231 | + except Exception: |
| 232 | + self.context_lengths.append(len(repr(chunk))) |
222 | 233 | self.context_type = "dict" |
223 | 234 | elif isinstance(prompt, list): |
224 | 235 | self.context_type = "list" |
225 | | - if isinstance(prompt[0], dict): |
| 236 | + if len(prompt) == 0: |
| 237 | + self.context_lengths = [0] |
| 238 | + elif isinstance(prompt[0], dict): |
226 | 239 | if "content" in prompt[0]: |
227 | | - self.context_lengths = [len(chunk["content"]) for chunk in prompt] |
| 240 | + self.context_lengths = [len(str(chunk.get("content", ""))) for chunk in prompt] |
228 | 241 | else: |
229 | | - self.context_lengths = [len(chunk) for chunk in prompt] |
| 242 | + self.context_lengths = [] |
| 243 | + for chunk in prompt: |
| 244 | + try: |
| 245 | + import json |
| 246 | + |
| 247 | + self.context_lengths.append(len(json.dumps(chunk, default=str))) |
| 248 | + except Exception: |
| 249 | + self.context_lengths.append(len(repr(chunk))) |
230 | 250 | else: |
231 | 251 | self.context_lengths = [len(chunk) for chunk in prompt] |
232 | 252 | else: |
|
0 commit comments