(cls, data: Dict[str, Any])
| 345 | |
| 346 | @classmethod |
| 347 | def from_dict(cls, data: Dict[str, Any]) -> "Message": |
| 348 | role_value = data.get("role") |
| 349 | if not role_value: |
| 350 | raise ValueError("message dict missing role") |
| 351 | role = MessageRole(role_value) |
| 352 | content = data.get("content") |
| 353 | if isinstance(content, list): |
| 354 | converted: List[MessageBlock] = [] |
| 355 | for block in content: |
| 356 | if isinstance(block, MessageBlock): |
| 357 | converted.append(block) |
| 358 | elif isinstance(block, dict): |
| 359 | try: |
| 360 | converted.append(MessageBlock.from_dict(block)) |
| 361 | except Exception: |
| 362 | # Preserve raw dict for debugging; text_content will stringify best-effort |
| 363 | converted.append( |
| 364 | MessageBlock( |
| 365 | type=MessageBlockType.DATA, |
| 366 | text=str(block), |
| 367 | data=block, |
| 368 | ) |
| 369 | ) |
| 370 | content = converted |
| 371 | tool_calls_data = data.get("tool_calls") or [] |
| 372 | tool_calls: List[ToolCallPayload] = [] |
| 373 | for item in tool_calls_data: |
| 374 | if not isinstance(item, dict): |
| 375 | continue |
| 376 | fn = item.get("function", {}) or {} |
| 377 | metadata = item.get("metadata") or {} |
| 378 | tool_calls.append( |
| 379 | ToolCallPayload( |
| 380 | id=item.get("id", ""), |
| 381 | function_name=fn.get("name", ""), |
| 382 | arguments=fn.get("arguments", ""), |
| 383 | type=item.get("type", "function"), |
| 384 | metadata=metadata, |
| 385 | ) |
| 386 | ) |
| 387 | return cls( |
| 388 | role=role, |
| 389 | content=content, |
| 390 | name=data.get("name"), |
| 391 | tool_call_id=data.get("tool_call_id"), |
| 392 | metadata=data.get("metadata") or {}, |
| 393 | tool_calls=tool_calls, |
| 394 | keep=bool(data.get("keep", False)), |
| 395 | preserve_role=bool(data.get("preserve_role", False)), |
| 396 | ) |
| 397 | |
| 398 | |
| 399 | def serialize_messages(messages: List[Message], *, include_data: bool = True) -> str: |
no test coverage detected