diff --git a/src/crewai/task.py b/src/crewai/task.py index 46ffa5cb5..66d8ea6f2 100644 --- a/src/crewai/task.py +++ b/src/crewai/task.py @@ -1,3 +1,4 @@ +import re import threading import uuid from typing import Any, Dict, List, Optional, Type @@ -246,7 +247,16 @@ class Task(BaseModel): return exported_result.model_dump() return exported_result except Exception: - pass + # sometimes the response contains valid JSON in the middle of text + match = re.search(r"({.*})", result, re.DOTALL) + if match: + try: + exported_result = model.model_validate_json(match.group(0)) + if self.output_json: + return exported_result.model_dump() + return exported_result + except Exception: + pass llm = self.agent.function_calling_llm or self.agent.llm