Recursively serialize an agent, excluding non-serializable fields.
(agent: BaseAgent)
| 106 | |
| 107 | |
| 108 | def serialize_agent(agent: BaseAgent) -> dict[str, Any]: |
| 109 | """Recursively serialize an agent, excluding non-serializable fields.""" |
| 110 | agent_dict = {} |
| 111 | |
| 112 | for field_name, field_info in agent.__class__.model_fields.items(): |
| 113 | if field_name in SKIP_FIELDS or (field_info and field_info.exclude): |
| 114 | continue |
| 115 | |
| 116 | value = getattr(agent, field_name, None) |
| 117 | |
| 118 | if value is None: |
| 119 | continue |
| 120 | |
| 121 | # Handle sub_agents recursively |
| 122 | if field_name == "sub_agents": |
| 123 | agent_dict[field_name] = [ |
| 124 | serialize_agent(sub_agent) for sub_agent in value |
| 125 | ] |
| 126 | # Handle nodes field (for _Mesh/LlmAgent) |
| 127 | elif field_name == "nodes": |
| 128 | try: |
| 129 | serialized_nodes = [] |
| 130 | for node in value: |
| 131 | if hasattr(node, "model_fields"): |
| 132 | serialized_nodes.append(serialize_agent(node)) |
| 133 | else: |
| 134 | serialized_nodes.append(serialize_node(node)) |
| 135 | agent_dict[field_name] = serialized_nodes |
| 136 | except Exception as e: |
| 137 | logger.warning("Error serializing nodes field: %s", e) |
| 138 | # Handle graph field (Graph with nodes and edges) |
| 139 | elif field_name == "graph": |
| 140 | try: |
| 141 | graph_dict = {} |
| 142 | # Serialize nodes |
| 143 | if hasattr(value, "nodes") and value.nodes: |
| 144 | graph_dict["nodes"] = [serialize_node(node) for node in value.nodes] |
| 145 | # Serialize edges |
| 146 | if hasattr(value, "edges") and value.edges: |
| 147 | serialized_edges = [] |
| 148 | for edge in value.edges: |
| 149 | edge_dict = {} |
| 150 | if hasattr(edge, "from_node"): |
| 151 | edge_dict["from_node"] = serialize_node(edge.from_node) |
| 152 | if hasattr(edge, "to_node"): |
| 153 | edge_dict["to_node"] = serialize_node(edge.to_node) |
| 154 | if hasattr(edge, "route") and edge.route is not None: |
| 155 | edge_dict["route"] = edge.route |
| 156 | serialized_edges.append(edge_dict) |
| 157 | graph_dict["edges"] = serialized_edges |
| 158 | agent_dict[field_name] = graph_dict |
| 159 | except Exception: |
| 160 | pass |
| 161 | # Handle edges field (list of EdgeItems) |
| 162 | elif field_name == "edges": |
| 163 | try: |
| 164 | serialized_edges = [] |
| 165 | for edge_item in value: |