Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes interpolation issues when inputs are type dict,list specificall… #1992

Merged
merged 6 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 33 additions & 15 deletions src/crewai/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,9 @@ def _execute_core(
content = (
json_output
if json_output
else pydantic_output.model_dump_json() if pydantic_output else result
else pydantic_output.model_dump_json()
if pydantic_output
else result
)
self._save_file(content)

Expand All @@ -452,7 +454,7 @@ def prompt(self) -> str:
return "\n".join(tasks_slices)

def interpolate_inputs_and_add_conversation_history(
self, inputs: Dict[str, Union[str, int, float]]
self, inputs: Dict[str, Union[str, int, float, Dict[str, Any], List[Any]]]
) -> None:
"""Interpolate inputs into the task description, expected output, and output file path.
Add conversation history if present.
Expand Down Expand Up @@ -524,25 +526,49 @@ def interpolate_inputs_and_add_conversation_history(
)

def interpolate_only(
self, input_string: Optional[str], inputs: Dict[str, Union[str, int, float]]
self,
input_string: Optional[str],
inputs: Dict[str, Union[str, int, float, Dict[str, Any], List[Any]]],
) -> str:
"""Interpolate placeholders (e.g., {key}) in a string while leaving JSON untouched.

Args:
input_string: The string containing template variables to interpolate.
Can be None or empty, in which case an empty string is returned.
inputs: Dictionary mapping template variables to their values.
Supported value types are strings, integers, and floats.
If input_string is empty or has no placeholders, inputs can be empty.
Supported value types are strings, integers, floats, and dicts/lists
containing only these types and other nested dicts/lists.

Returns:
The interpolated string with all template variables replaced with their values.
Empty string if input_string is None or empty.

Raises:
ValueError: If a required template variable is missing from inputs.
KeyError: If a template variable is not found in the inputs dictionary.
ValueError: If a value contains unsupported types
"""

# Validation function for recursive type checking
def validate_type(value: Any) -> None:
if value is None:
return
if isinstance(value, (str, int, float, bool)):
return
if isinstance(value, (dict, list)):
for item in value.values() if isinstance(value, dict) else value:
validate_type(item)
return
raise ValueError(
f"Unsupported type {type(value).__name__} in inputs. "
"Only str, int, float, bool, dict, and list are allowed."
)

# Validate all input values
for key, value in inputs.items():
try:
validate_type(value)
except ValueError as e:
raise ValueError(f"Invalid value for key '{key}': {str(e)}") from e

if input_string is None or not input_string:
return ""
if "{" not in input_string and "}" not in input_string:
Expand All @@ -551,15 +577,7 @@ def interpolate_only(
raise ValueError(
"Inputs dictionary cannot be empty when interpolating variables"
)

try:
# Validate input types
for key, value in inputs.items():
if not isinstance(value, (str, int, float)):
raise ValueError(
f"Value for key '{key}' must be a string, integer, or float, got {type(value).__name__}"
)

escaped_string = input_string.replace("{", "{{").replace("}", "}}")

for key in inputs.keys():
Expand Down
Loading