Best-effort conversion of arbitrary msg to str. Return empty string if conversion fails.
(msg: Any)
| 46 | |
| 47 | |
| 48 | def to_string(msg: Any) -> str: |
| 49 | """ |
| 50 | Best-effort conversion of arbitrary msg to str. |
| 51 | Return empty string if conversion fails. |
| 52 | """ |
| 53 | if msg is None: |
| 54 | return "" |
| 55 | if isinstance(msg, str): |
| 56 | return msg |
| 57 | if isinstance(msg, BaseModel): |
| 58 | return msg.model_dump_json() |
| 59 | # last resort: use json.dumps() or str() to make it a str |
| 60 | try: |
| 61 | return json.dumps(msg) |
| 62 | except Exception: |
| 63 | try: |
| 64 | return str(msg) |
| 65 | except Exception as e: |
| 66 | logger.error( |
| 67 | f""" |
| 68 | Error converting msg to str: {e}", |
| 69 | """, |
| 70 | exc_info=True, |
| 71 | ) |
| 72 | return "" |
| 73 | |
| 74 | |
| 75 | def from_string( |
no outgoing calls
no test coverage detected
searching dependent graphs…