mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-20 21:38:14 +00:00
Enhance Tool Name Handling for LLM Compatibility
- Added a new function to replace invalid characters in function names with underscores, ensuring compatibility with LLM providers. - Updated the function to sanitize tool names before validation. - Modified the function to use sanitized names for tool registration. These changes improve the robustness of tool name handling, preventing potential issues with invalid characters in function names.
This commit is contained in:
@@ -105,6 +105,21 @@ def log_tool_conversion(tool: dict[str, Any], provider: str) -> None:
|
||||
logging.error(f"{provider}: Tool structure: {tool}")
|
||||
|
||||
|
||||
def sanitize_function_name(name: str) -> str:
|
||||
"""Sanitize function name for LLM provider compatibility.
|
||||
|
||||
Replaces invalid characters with underscores. Valid characters are:
|
||||
letters, numbers, underscore, dot, colon, and dash.
|
||||
|
||||
Args:
|
||||
name: Original function name
|
||||
|
||||
Returns:
|
||||
Sanitized function name with invalid characters replaced
|
||||
"""
|
||||
return re.sub(r"[^a-zA-Z0-9_.\-:]", "_", name)
|
||||
|
||||
|
||||
def safe_tool_conversion(
|
||||
tool: dict[str, Any], provider: str
|
||||
) -> tuple[str, str, dict[str, Any]]:
|
||||
@@ -127,7 +142,10 @@ def safe_tool_conversion(
|
||||
|
||||
name, description, parameters = extract_tool_info(tool)
|
||||
|
||||
validated_name = validate_function_name(name, provider)
|
||||
# Sanitize name before validation (replace invalid chars with underscores)
|
||||
sanitized_name = sanitize_function_name(name)
|
||||
|
||||
validated_name = validate_function_name(sanitized_name, provider)
|
||||
|
||||
logging.info(f"{provider}: Successfully validated tool '{validated_name}'")
|
||||
return validated_name, description, parameters
|
||||
|
||||
@@ -171,16 +171,18 @@ def convert_tools_to_openai_schema(
|
||||
# Extract the original description after "Tool Description:"
|
||||
description = description.split("Tool Description:")[-1].strip()
|
||||
|
||||
sanitized_name = re.sub(r"[^a-zA-Z0-9_.\-:]", "_", tool.name)
|
||||
|
||||
schema: dict[str, Any] = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tool.name,
|
||||
"name": sanitized_name,
|
||||
"description": description,
|
||||
"parameters": parameters,
|
||||
},
|
||||
}
|
||||
openai_tools.append(schema)
|
||||
available_functions[tool.name] = tool.run
|
||||
available_functions[sanitized_name] = tool.run # type: ignore[attr-defined]
|
||||
|
||||
return openai_tools, available_functions
|
||||
|
||||
|
||||
Reference in New Issue
Block a user