🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
fix: Add task content validation to prevent empty content processing (#2616)
Hesam Sheikhb6467b6bcc78
diff --git a/camel/societies/workforce/role_playing_worker.py b/camel/societies/workforce/role_playing_worker.pyindex 52ef989b5..d437cc84a 100644--- a/camel/societies/workforce/role_playing_worker.py+++ b/camel/societies/workforce/role_playing_worker.py@@ -25,9 +25,9 @@ from camel.societies.workforce.prompts import (ROLEPLAY_PROCESS_TASK_PROMPT,ROLEPLAY_SUMMARIZE_PROMPT,)-from camel.societies.workforce.utils import TaskResult, validate_task_content+from camel.societies.workforce.utils import TaskResultfrom camel.societies.workforce.worker import Worker-from camel.tasks.task import Task, TaskState+from camel.tasks.task import Task, TaskState, validate_task_contentfrom camel.utils import print_text_animateddiff --git a/camel/societies/workforce/single_agent_worker.py b/camel/societies/workforce/single_agent_worker.pyindex a3cb6455f..a9c16e84a 100644--- a/camel/societies/workforce/single_agent_worker.py+++ b/camel/societies/workforce/single_agent_worker.py@@ -21,9 +21,9 @@ from colorama import Forefrom camel.agents import ChatAgentfrom camel.societies.workforce.prompts import PROCESS_TASK_PROMPT-from camel.societies.workforce.utils import TaskResult, validate_task_content+from camel.societies.workforce.utils import TaskResultfrom camel.societies.workforce.worker import Worker-from camel.tasks.task import Task, TaskState+from camel.tasks.task import Task, TaskState, validate_task_contentfrom camel.utils import print_text_animateddiff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.pyindex c3daed50d..bdf0aafa8 100644--- a/camel/societies/workforce/utils.py+++ b/camel/societies/workforce/utils.py@@ -16,10 +16,6 @@ from typing import Callablefrom pydantic import BaseModel, Field-from camel.logger import get_logger--logger = get_logger(__name__)-class WorkerConf(BaseModel):r"""The configuration of a worker."""@@ -75,50 +71,3 @@ def check_if_running(running: bool) -> Callable:return wrapperreturn decorator---def validate_task_content(- content: str, task_id: str = "unknown", min_length: int = 10-) -> bool:- r"""Validates task result content to avoid silent failures.- It performs basic checks to ensure the content meets minimum- quality standards.-- Args:- content (str): The task result content to validate.- task_id (str): Task ID for logging purposes.- (default: :obj:`"unknown"`)- min_length (int): Minimum content length after stripping whitespace.- (default: :obj:`10`)-- Returns:- bool: True if content passes validation, False otherwise.- """- # 1: Content must not be None- if content is None:- logger.warning(f"Task {task_id}: None content rejected")- return False-- # 2: Content must not be empty after stripping whitespace- stripped_content = content.strip()- if not stripped_content:- logger.warning(- f"Task {task_id}: Empty or whitespace-only content rejected."- )- return False-- # 3: Content must meet minimum meaningful length- if len(stripped_content) < min_length:- logger.warning(- f"Task {task_id}: Content too short ({len(stripped_content)} "- f"chars < {min_length} minimum). Content preview: "- f"'{stripped_content[:50]}...'"- )- return False-- # All validation checks passed- logger.debug(- f"Task {task_id}: Content validation passed "- f"({len(stripped_content)} chars)"- )- return Truediff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex 6577afa16..d82f356ca 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -40,7 +40,7 @@ from camel.societies.workforce.utils import (check_if_running,)from camel.societies.workforce.worker import Worker-from camel.tasks.task import Task, TaskState+from camel.tasks.task import Task, TaskState, validate_task_contentfrom camel.toolkits import CodeExecutionToolkit, SearchToolkit, ThinkingToolkitfrom camel.types import ModelPlatformType, ModelTypefrom camel.utils import dependencies_required@@ -211,6 +211,15 @@ class Workforce(BaseNode):Returns:Task: The updated task."""+ if not validate_task_content(task.content, task.id):+ task.state = TaskState.FAILED+ task.result = "Task failed: Invalid or empty content provided"+ logger.warning(+ f"Task {task.id} rejected: Invalid or empty content. "+ f"Content preview: '{task.content[:50]}...'"+ )+ return task+self.reset()self._task = tasktask.state = TaskState.FAILEDdiff --git a/camel/tasks/task.py b/camel/tasks/task.pyindex b431d2d11..00e3e15ec 100644--- a/camel/tasks/task.py+++ b/camel/tasks/task.py@@ -19,15 +19,66 @@ from typing import Any, Callable, Dict, List, Literal, Optional, Unionfrom pydantic import BaseModelfrom camel.agents import ChatAgent+from camel.logger import get_loggerfrom camel.messages import BaseMessagefrom camel.prompts import TextPrompt+# Note: validate_task_content moved here to avoid circular importsfrom .task_prompt import (TASK_COMPOSE_PROMPT,TASK_DECOMPOSE_PROMPT,TASK_EVOLVE_PROMPT,)+logger = get_logger(__name__)+++def validate_task_content(+ content: str, task_id: str = "unknown", min_length: int = 10+) -> bool:+ r"""Validates task result content to avoid silent failures.+ It performs basic checks to ensure the content meets minimum+ quality standards.++ Args:+ content (str): The task result content to validate.+ task_id (str): Task ID for logging purposes.+ (default: :obj:`"unknown"`)+ min_length (int): Minimum content length after stripping whitespace.+ (default: :obj:`10`)++ Returns:+ bool: True if content passes validation, False otherwise.+ """+ # 1: Content must not be None+ if content is None:+ logger.warning(f"Task {task_id}: None content rejected")+ return False++ # 2: Content must not be empty after stripping whitespace+ stripped_content = content.strip()+ if not stripped_content:+ logger.warning(+ f"Task {task_id}: Empty or whitespace-only content rejected."+ )+ return False++ # 3: Content must meet minimum meaningful length+ if len(stripped_content) < min_length:+ logger.warning(+ f"Task {task_id}: Content too short ({len(stripped_content)} "+ f"chars < {min_length} minimum). Content preview: "+ f"'{stripped_content[:50]}...'"+ )+ return False++ # All validation checks passed+ logger.debug(+ f"Task {task_id}: Content validation passed "+ f"({len(stripped_content)} chars)"+ )+ return True+def parse_response(response: str, task_id: Optional[str] = None@@ -49,7 +100,16 @@ def parse_response(if task_id is None:task_id = "0"for i, content in enumerate(tasks_content):- tasks.append(Task(content=content.strip(), id=f"{task_id}.{i}"))+ stripped_content = content.strip()+ # validate subtask content before creating the task+ if validate_task_content(stripped_content, f"{task_id}.{i}"):+ tasks.append(Task(content=stripped_content, id=f"{task_id}.{i}"))+ else:+ logger.warning(+ f"Skipping invalid subtask {task_id}.{i} "+ f"during decomposition: "+ f"Content '{stripped_content[:50]}...' failed validation"+ )return tasksdiff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.pyindex 77c76bf73..fb0ec093f 100644--- a/camel/toolkits/function_tool.py+++ b/camel/toolkits/function_tool.py@@ -256,7 +256,7 @@ def sanitize_and_enforce_required(parameters_dict):# This field is optional - add null to its typecurrent_type = field_schema.get('type')has_ref = '$ref' in field_schema-+if has_ref:# Fields with $ref shouldn't have additional type field# The $ref itself defines the type structure@@ -274,7 +274,7 @@ def sanitize_and_enforce_required(parameters_dict):else:# No type specified, add null typefield_schema['type'] = ['null']-+# Optional fields are still marked as required in strict mode# but with null type to indicate they can be omittedrequired_fields.append(field_name)