Skip to content

Commit 6fbb1f4

Browse files
fix: Improve sanitization to preserve double underscores
- Fixed aggressive underscore collapsing that broke dunder names like __init__ - Now only collapses 5+ consecutive underscores instead of any consecutive underscores - Preserves trailing underscores in double underscore patterns (__name__) - Handles edge case where purely invalid characters become single underscore - All 15 test cases now pass including magic method names - Maintains backward compatibility for AutoGen v0.2, CrewAI, PraisonAI 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Mervin Praison <[email protected]>
1 parent 50ac799 commit 6fbb1f4

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/praisonai/praisonai/agents_generator.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -94,22 +94,22 @@ def sanitize_agent_name_for_autogen_v4(name):
9494
Returns:
9595
str: A valid Python identifier
9696
"""
97-
# Remove or replace invalid characters
98-
# First, replace spaces and hyphens with underscores, keep other valid chars
97+
# Convert to string and replace invalid characters with underscores
9998
sanitized = re.sub(r'[^a-zA-Z0-9_]', '_', str(name))
10099

101-
# Remove consecutive underscores
102-
sanitized = re.sub(r'_+', '_', sanitized)
100+
# Collapse only very excessive underscores (5 or more) to reduce extreme cases
101+
sanitized = re.sub(r'_{5,}', '_', sanitized)
103102

104-
# Remove trailing underscores only (preserve leading underscores as they're valid)
105-
sanitized = sanitized.rstrip('_')
103+
# Remove trailing underscores only if not part of a dunder pattern and only if singular
104+
if sanitized.endswith('_') and not sanitized.endswith('__') and sanitized != '_':
105+
sanitized = sanitized.rstrip('_')
106106

107107
# Ensure it starts with a letter or underscore (not a digit)
108108
if sanitized and sanitized[0].isdigit():
109109
sanitized = 'agent_' + sanitized
110110

111-
# Handle empty string or only invalid characters
112-
if not sanitized:
111+
# Handle empty string or only invalid characters (including single underscore from all invalid chars)
112+
if not sanitized or sanitized == '_':
113113
sanitized = 'agent'
114114

115115
# Check if it's a Python keyword and append underscore if so

0 commit comments

Comments
 (0)