@@ -210,13 +210,50 @@ class ToolOrigin:
210210 agent_as_tool : Agent [Any ] | None = None
211211 """The agent object. Only set when type is AGENT_AS_TOOL."""
212212
213+ _agent_as_tool_ref : weakref .ReferenceType [Agent [Any ]] | None = field (
214+ default = None , init = False , repr = False
215+ )
216+ """Weak reference to agent_as_tool for memory management."""
217+
218+ def __post_init__ (self ) -> None :
219+ """Initialize weak reference for agent_as_tool."""
220+ if self .agent_as_tool is not None :
221+ self ._agent_as_tool_ref = weakref .ref (self .agent_as_tool )
222+
223+ def __getattribute__ (self , name : str ) -> Any :
224+ """Lazily resolve agent_as_tool via weakref when strong ref is cleared."""
225+ if name == "agent_as_tool" :
226+ # Check if strong reference still exists
227+ value = object .__getattribute__ (self , "__dict__" ).get ("agent_as_tool" )
228+ if value is not None :
229+ return value
230+ # Try to resolve via weakref
231+ ref = object .__getattribute__ (self , "_agent_as_tool_ref" )
232+ if ref is not None :
233+ agent = ref ()
234+ if agent is not None :
235+ return agent
236+ return None
237+ return super ().__getattribute__ (name )
238+
239+ def release_agent (self ) -> None :
240+ """Release the strong reference to agent_as_tool while keeping a weak reference."""
241+ if "agent_as_tool" not in self .__dict__ :
242+ return
243+ agent = self .__dict__ .get ("agent_as_tool" )
244+ if agent is not None :
245+ self ._agent_as_tool_ref = weakref .ref (agent )
246+ # Set to None instead of deleting so dataclass repr/asdict keep working.
247+ self .__dict__ ["agent_as_tool" ] = None
248+
213249 def __repr__ (self ) -> str :
214250 """Custom repr that only includes relevant fields."""
215251 parts = [f"type={ self .type .value !r} " ]
216252 if self .mcp_server is not None :
217253 parts .append (f"mcp_server_name={ self .mcp_server .name !r} " )
218- if self .agent_as_tool is not None :
219- parts .append (f"agent_as_tool_name={ self .agent_as_tool .name !r} " )
254+ agent = self .agent_as_tool
255+ if agent is not None :
256+ parts .append (f"agent_as_tool_name={ agent .name !r} " )
220257 return f"ToolOrigin({ ', ' .join (parts )} )"
221258
222259
0 commit comments