From 0a35868367b6a68fe28e87fbfa61929d2b502910 Mon Sep 17 00:00:00 2001 From: ftoppi <4704016+ftoppi@users.noreply.github.com> Date: Thu, 2 May 2024 08:26:34 +0200 Subject: [PATCH] Update task.py: try to find json in task output using regex (#491) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update task.py: try to find json in task output using regex Sometimes the model replies with a valid and additional text, let's try to extract and validate it first. It's cheaper than calling LLM for that. * Update task.py --------- Co-authored-by: João Moura --- src/crewai/task.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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