Langchain-Openai Passes Unvalidated Message/Tool Names To OpenAI API Causing Cryptic 400 Errors
When agent or tool names contain spaces or special characters, langchain-openai forwards them directly to OpenAI, which rejects the request with a 400 invalid_request_error. The fix adds OpenAI-specific name validation in serialization to raise a clear ValueError.
langchain-openai's _convert_message_to_dict and tool serialization functions pass `message.name` and tool/function names to the OpenAI API without validating against the required pattern `^[^\s<|\\/>]+$`. Names with spaces or characters like `<`, `|`, `/`, `>` cause OpenAI to return a 400 error, obscuring the real cause.
1. Install langchain-openai (any recent version).
2. Create a ChatOpenAI instance and an agent using `create_agent(name="User Onboarding Agent")` or define a tool with name containing spaces.
3. Invoke the model so that the agent/tool name is included in the messages payload.
4. Observe the OpenAI API 400 error: `Invalid 'messages[2].name': string does not match pattern. Expected a string that matches the pattern '^[^\s<|\\/>]+$'.`
5. Note the error does not point to the agent name set in create_agent, leading to debugging confusion.
Fixing Code Block
import re
OPENAI_NAME_PATTERN = re.compile(r'^[^\s<|\\/>]+$')
def _validate_openai_name(name: str, context: str) -> None:
if not OPENAI_NAME_PATTERN.match(name):
raise ValueError(
f"Invalid {context} name: {name!r}. "
f"OpenAI requires names to match the pattern '{OPENAI_NAME_PATTERN.pattern}' "
f"(no spaces or special characters like <, |, \\, /, >). "
f"Use snake_case instead (e.g., 'my_agent' instead of 'My Agent')."
)
# In _convert_message_to_dict:
if (name := message.name or message.additional_kwargs.get("name")) is not None:
_validate_openai_name(name, "message")
message_dict["name"] = name
# In _format_tool_to_openai_function:
def _format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
function = {
"name": tool.name,
"description": tool.description,
"parameters": _format_tool_parameters(tool.args),
}
_validate_openai_name(function["name"], "tool")
return function
# In _lc_tool_call_to_openai_tool_call:
def _lc_tool_call_to_openai_tool_call(tool_call: ToolCall) -> dict:
name = tool_call["name"]
_validate_openai_name(name, "tool call")
return {
"id": tool_call["id"],
"type": "function",
"function": {
"name": name,
"arguments": json.dumps(tool_call["args"], ensure_ascii=False),
},
}
Adds a regex-based validation helper `_validate_openai_name` that checks names against OpenAI's required pattern. This helper is called in `_convert_message_to_dict` for message names and in both tool serialization functions for tool/function names. If a name violates the pattern, a clear `ValueError` is raised before the API request, guiding the user to use snake_case.
Edge Case Audit
Raising ValueError changes exception type from an OpenAI API 400 to a local Python error; code that currently catches API errors and handles them may break. If OpenAI relaxes or modifies its name pattern, this regex could become stale and block valid names, requiring maintenance. The validation is synchronous and pure, so no concurrency issues. Rollback: remove the validation calls and helper to restore previous behavior, but then cryptic 400 errors will return.