openai.BadRequestError: Error code: 400 ..... does not match '^[a-zA-Z0-9_-]{1,64}$

I get this error randomly → I applied regex to name → this fix has solved the problem to certain extent but not completely. This error just randomly appear even though the name is in right format.

Can anyone suggest - a permanent fix?

Here is a sample error message
openai.BadRequestError: Error code: 400 - {‘error’: {‘message’: “‘Emily Brown’ does not match ‘[1]{1,64}$’ - ‘messages.2.name’”, ‘type’: ‘invalid_request_error’, ‘param’: None, ‘code’: None}}

Regards,


  1. a-zA-Z0-9_- ↩︎

2 Likes

You’ll need to simply strip spaces and other whitespace within a “name” if using this alongside “role”, or truncate at the first whitespace.

Or not allow user data as name parameter.


Robots offer help when asked nicely

Here’s how you can implement this in Python using the re module, using multiple steps of reprocessing (in the correct order, not ChatGPT’s mistakes).

import re

def process_name(name_field: str) -> str:
    # Step 1: Strip any whitespace characters from the beginning and end of the string
    name_field = name_field.strip()

    # Step 2: Replace white spaces within the string with underscores
    name_field = re.sub(r"\s+", "_", name_field)

    # Step 3: Remove any characters that do not match the [a-zA-Z0-9_-] pattern
    name_field = re.sub(r"[^a-zA-Z0-9_-]", "", name_field)

    # Step 4: Truncate to 63 characters
    name_field = name_field[:63]

    # Step 5: Validate against the regex pattern
    if not re.match(r"^[a-zA-Z0-9_-]{1,63}$", name_field):
        raise ValueError("Invalid characters in name field")

    return name_field

# Example usage
name_field = "  Emily Brown!  "
processed_name = process_name(name_field)
print(processed_name)  # Expected Output: Emily_Brown

1 Like

What I observed and it worked for me is that in the name field if I remove the space and use any other character (in my case underscore) it worked fine. In your case try “Emily_Brown” or simply use same name as the agent variable name (though this is not a requirement) e.g. I used
player_white = ConversableAgent(
name=“player_white”,

After making this change it worked fine.
Regards
Junaid