{"record":{"id":"9a18f16403664852","repo":"microsoft/autogen","slug":"the-agent-name-must-be-a-valid-python-identifier","errorCode":null,"errorMessage":"The agent name must be a valid Python identifier.","messagePattern":"The agent name must be a valid Python identifier\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py","lineNumber":49,"sourceCode":"    .. note::\n\n        The caller should only pass the new messages to the agent on each call\n        to the :meth:`on_messages` or :meth:`on_messages_stream` method.\n        Do not pass the entire conversation history to the agent on each call.\n        This design principle must be followed when creating a new agent.\n    \"\"\"\n\n    component_type = \"agent\"\n\n    def __init__(self, name: str, description: str) -> None:\n        \"\"\"Initialize the agent with a name and description.\"\"\"\n        with trace_create_agent_span(\n            agent_name=name,\n            agent_description=description,\n        ):\n            self._name = name\n            if self._name.isidentifier() is False:\n                raise ValueError(\"The agent name must be a valid Python identifier.\")\n            self._description = description\n\n    @property\n    def name(self) -> str:\n        \"\"\"The name of the agent. This is used by team to uniquely identify\n        the agent. It should be unique within the team.\"\"\"\n        return self._name\n\n    @property\n    def description(self) -> str:\n        \"\"\"The description of the agent. This is used by team to\n        make decisions about which agents to use. The description should\n        describe the agent's capabilities and how to interact with it.\"\"\"\n        return self._description\n\n    @property\n    @abstractmethod\n    def produced_message_types(self) -> Sequence[type[BaseChatMessage]]:","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py#L31-L67","documentation":"BaseChatAgent validates in its constructor that the agent name passes str.isidentifier(): it must be a valid Python identifier (letters, digits, underscores, not starting with a digit). Names are used as unique team identifiers and must stay identifier-safe.","triggerScenarios":"Constructing any agent (AssistantAgent, UserProxyAgent, CodeExecutorAgent, custom BaseChatAgent subclasses) with a name containing spaces, hyphens, dots, or starting with a digit, e.g. \"my-agent\", \"agent 1\", \"1writer\".","commonSituations":"Loading agent names from config files, URLs, or user input where hyphens/spaces are natural; copying display names into the name parameter.","solutions":["Rename the agent to a valid identifier, e.g. \"my_agent\" instead of \"my-agent\".","Sanitize externally sourced names before construction: re.sub(r'\\W|^(?=\\d)', '_', name).","Keep a display label separate from the agent name if pretty names are needed."],"exampleFix":"// before\nagent = AssistantAgent(name=\"helpful-agent\", model_client=client)\n\n// after\nagent = AssistantAgent(name=\"helpful_agent\", model_client=client)","handlingStrategy":"validation","validationCode":"import re\n\ndef safe_agent_name(raw: str) -> str:\n    name = re.sub(r'\\W+', '_', raw).strip('_')\n    if not name or name[0].isdigit():\n        name = 'a' + name\n    assert name.isidentifier()\n    return name\n\nagent = AssistantAgent(name=safe_agent_name(display_name), model_client=client)","typeGuard":"def is_valid_agent_name(name: str) -> bool:\n    return isinstance(name, str) and name.isidentifier()","tryCatchPattern":"try:\n    agent = AssistantAgent(name=name, model_client=client)\nexcept ValueError as e:\n    if \"valid Python identifier\" in str(e):\n        name = re.sub(r'\\W+', '_', name).strip('_')\n        agent = AssistantAgent(name=name, model_client=client)\n    else:\n        raise","preventionTips":["Sanitize names loaded from config/URLs/user input before constructing agents.","Adopt a convention of snake_case agent names.","Validate all names once at app startup."],"tags":["validation","naming","constructor"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}