Skip to content

Commit 50ac799

Browse files
fix: Ensure agent names are valid Python identifiers for AutoGen v0.4
AutoGen v0.4 requires agent names to be valid Python identifiers, but role names like ''Narrative Designer'' contain spaces which are invalid. - Added sanitize_agent_name_for_autogen_v4() function to convert any string to a valid Python identifier - Applied sanitization only in AutoGen v0.4 code path for backward compatibility - AutoGen v0.2 and other frameworks remain unchanged - Handles spaces, special characters, Python keywords, and edge cases Resolves issue where ''Narrative Designer'' role causes error: ''The agent name must be a valid Python identifier'' Co-authored-by: Mervin Praison <[email protected]>
1 parent 93e2c0c commit 50ac799

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/praisonai/praisonai/agents_generator.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import importlib.util
1515
import os
1616
import logging
17+
import re
18+
import keyword
1719

1820
# Framework-specific imports with availability checks
1921
CREWAI_AVAILABLE = False
@@ -82,6 +84,40 @@ class BaseTool:
8284
def noop(*args, **kwargs):
8385
pass
8486

87+
def sanitize_agent_name_for_autogen_v4(name):
88+
"""
89+
Sanitize agent name to be a valid Python identifier for AutoGen v0.4.
90+
91+
Args:
92+
name (str): The original agent name
93+
94+
Returns:
95+
str: A valid Python identifier
96+
"""
97+
# Remove or replace invalid characters
98+
# First, replace spaces and hyphens with underscores, keep other valid chars
99+
sanitized = re.sub(r'[^a-zA-Z0-9_]', '_', str(name))
100+
101+
# Remove consecutive underscores
102+
sanitized = re.sub(r'_+', '_', sanitized)
103+
104+
# Remove trailing underscores only (preserve leading underscores as they're valid)
105+
sanitized = sanitized.rstrip('_')
106+
107+
# Ensure it starts with a letter or underscore (not a digit)
108+
if sanitized and sanitized[0].isdigit():
109+
sanitized = 'agent_' + sanitized
110+
111+
# Handle empty string or only invalid characters
112+
if not sanitized:
113+
sanitized = 'agent'
114+
115+
# Check if it's a Python keyword and append underscore if so
116+
if keyword.iskeyword(sanitized):
117+
sanitized += '_'
118+
119+
return sanitized
120+
85121
def disable_crewai_telemetry():
86122
if CREWAI_AVAILABLE:
87123
for attr in dir(Telemetry):
@@ -471,7 +507,9 @@ async def run_autogen_v4_async():
471507

472508
# Create agents from config
473509
for role, details in config['roles'].items():
510+
# For AutoGen v0.4, ensure agent name is a valid Python identifier
474511
agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
512+
agent_name = sanitize_agent_name_for_autogen_v4(agent_name)
475513
backstory = details['backstory'].format(topic=topic)
476514

477515
# Convert tools for v0.4 - simplified tool passing

0 commit comments

Comments
 (0)