Skip to content

Commit

Permalink
Update task.py: try to find json in task output using regex (#491)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
ftoppi and joaomdmoura committed May 2, 2024
1 parent 608f869 commit 0a35868
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/crewai/task.py
@@ -1,3 +1,4 @@
import re
import threading
import uuid
from typing import Any, Dict, List, Optional, Type
Expand Down Expand Up @@ -246,7 +247,16 @@ def _export_output(self, result: str) -> Any:
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

Expand Down

0 comments on commit 0a35868

Please sign in to comment.