crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] `format_answer()` catches `OutputParserException`, breaking retry logic for malformed LLM outputs

Open jacoblam3112-glitch opened this issue 1 year ago • 8 comments

Description

When an LLM returns malformed output (e.g., missing colons in the Action/Action Input format), the format_answer() function in crewai/utilities/agent_utils.py catches all exceptions including OutputParserException and converts them to AgentFinish. This prevents the retry logic in _invoke_loop() from working correctly.

In agent_utils.py:

def format_answer(answer: str) -> Union[AgentAction, AgentFinish]:
    """Format a response from the LLM into an AgentAction or AgentFinish."""
    try:
        return CrewAgentParser.parse_text(answer)
    except Exception:  # ← Catches OutputParserException
        # If parsing fails, return a default AgentFinish
        return AgentFinish(
            thought="Failed to parse LLM response",
            output=answer,
            text=answer,

Example Malformed LLM Output:

Thought
The user wants to verify something.
Action
Video Analysis Tool
Action Input:
{"query": "Is there something?"}

(Missing colons after "Thought", "Action", and "Action Input")

Steps to Reproduce

  1. In crewai/agents/crew_agent_executor.py, hardcode a malformed LLM response after get_llm_response():
answer = get_llm_response(
    llm=self.llm,
    messages=self.messages,
    callbacks=self.callbacks,
    printer=self._printer,
)

# Override with malformed output (missing colons)
answer = '''Thought
The user wants to verify something.
Action
Video Analysis Tool
Action Input:
{"query": "Is there something?"}'''

formatted_answer = process_llm_response(answer, self.use_stop_words)
  1. Run any agent with a task
  2. Observe that the agent immediately returns an AgentFinish with the malformed text instead of retrying with an error message

Expected: The agent should retry with an error message like "Invalid Format: I missed the ':' after 'Action:'"

Actual: The agent exits with AgentFinish(thought="Failed to parse LLM response", output=<malformed text>)

Expected behavior

Expected Behavior: When parsing fails with OutputParserException, it should be re-raised so the _invoke_loop() in crew_agent_executor.py can catch it and append an error message to retry.

Actual Behavior: The exception is caught and converted to AgentFinish, causing the loop to exit prematurely instead of retrying.

Screenshots/Code snippets

Image

Operating System

Ubuntu 20.04

Python Version

3.11

crewAI Version

0.119.0

crewAI Tools Version

Dont know how to check it

Virtual Environment

Conda

Evidence

Image

Possible Solution

Proposed Fix:

def format_answer(answer: str) -> Union[AgentAction, AgentFinish]:
    """Format a response from the LLM into an AgentAction or AgentFinish."""
    try:
        return CrewAgentParser.parse_text(answer)
    except OutputParserException:
        # Re-raise OutputParserException so it can be handled by the retry logic
        raise
    except Exception:
        # If parsing fails with unexpected error, return a default AgentFinish
        return AgentFinish(
            thought="Failed to parse LLM response",
            output=answer,
            text=answer,
        )

Additional context

Can be provided if required

jacoblam3112-glitch avatar Oct 22 '25 01:10 jacoblam3112-glitch

Hi, I'd like to take a look at this issue. I'm a new contributor and this seems like a good place to start.

yashsham avatar Oct 27 '25 18:10 yashsham

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Nov 27 '25 12:11 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Dec 02 '25 12:12 github-actions[bot]

Bump - this is still a problem, and there is a PR that fixes (?) the issue. Can this be reopened?

ehansis avatar Dec 16 '25 12:12 ehansis

I think you should bump crewai version. Latest version doesn't have this.

Vidit-Ostwal avatar Dec 16 '25 12:12 Vidit-Ostwal

@Vidit-Ostwal Thanks for the suggestion.

However, looking at the current main branch, here is the code in question:

def format_answer(answer: str) -> AgentAction | AgentFinish:
    """Format a response from the LLM into an AgentAction or AgentFinish.

    Args:
        answer: The raw response from the LLM

    Returns:
        Either an AgentAction or AgentFinish
    """
    try:
        return parse(answer)
    except Exception:
        return AgentFinish(
            thought="Failed to parse LLM response",
            output=answer,
            text=answer,
        )

This swallows the OutputParserError Exceptions from parse and returns a regular AgentFinish, which is precisely what #3773 fixes. I don't see how the failed parsing is messaged to the CrewAgentExecutor in the current implementation.

But please correct me if I'm mistaken.

ehansis avatar Dec 16 '25 13:12 ehansis

My bad, didn't checked this throughly. Mind raising a seperate issue for the same.

Vidit-Ostwal avatar Dec 16 '25 13:12 Vidit-Ostwal

Done, #4113

ehansis avatar Dec 17 '25 13:12 ehansis