diff --git a/src/crewai/agents/parser.py b/src/crewai/agents/parser.py index a59a4611e..1cf05e455 100644 --- a/src/crewai/agents/parser.py +++ b/src/crewai/agents/parser.py @@ -91,14 +91,6 @@ class CrewAgentParser: r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" ) action_match = re.search(regex, text, re.DOTALL) - - # Check if both final answer and action are present - if includes_answer and action_match: - raise OutputParserException( - f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}" - ) - - # Handle final answer case if includes_answer: final_answer = text.split(FINAL_ANSWER_ACTION)[-1].strip() # Check whether the final answer ends with triple backticks. @@ -110,8 +102,11 @@ class CrewAgentParser: final_answer = final_answer[:-3].rstrip() return AgentFinish(thought, final_answer, text) - # Handle action case elif action_match: + if includes_answer: + raise OutputParserException( + f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}" + ) action = action_match.group(1) clean_action = self._clean_action(action) diff --git a/src/crewai/lite_agent.py b/src/crewai/lite_agent.py index d1451c68f..ede0f8d72 100644 --- a/src/crewai/lite_agent.py +++ b/src/crewai/lite_agent.py @@ -237,25 +237,15 @@ class LiteAgent(BaseModel): # Execute the agent using invoke loop agent_finish = self._invoke_loop() - formatted_result: Optional[BaseModel] = None if self.response_format: try: - final_answer_match = re.search( - r"Final Answer:\s*(.*?)(?:\n\n|$)", - agent_finish.output, - re.DOTALL, + # Cast to BaseModel to ensure type safety + result = self.response_format.model_validate_json( + agent_finish.output ) - if final_answer_match: - json_content = final_answer_match.group(1).strip() - result = self.response_format.model_validate_json(json_content) - if isinstance(result, BaseModel): - formatted_result = result - else: - self._printer.print( - content="Could not find Final Answer section in the output", - color="yellow", - ) + if isinstance(result, BaseModel): + formatted_result = result except Exception as e: self._printer.print( content=f"Failed to parse output into response format: {str(e)}",