BerriAI/litellm · error · Exception

Task ended with state

Error message

Task {task_id} ended with state: {state}

What it means

While polling a submitted task on a Pydantic AI agent, transformation.py reads result.status.state each cycle. If the state is 'failed' or 'canceled' (instead of 'completed'), the poll loop aborts immediately with this generic Exception carrying the task_id and terminal state. It means the agent accepted the job but the agent itself reported failure — the error originates upstream, not in LiteLLM.

Solutions

  1. Check the Pydantic AI agent server logs for the real failure behind the failed/canceled task
  2. Fix the upstream cause (agent's model credentials, tool code, or payload)
  3. Catch this exception in your caller and map it to a 5xx/upstream-error response instead of crashing the route
  4. If tasks are canceled by an aggressive agent-side limit, raise that limit or shorten request payloads

Example fix

# before
result = await PydanticAIHandler.handle_non_streaming(
    request_id=req_id, params=params, api_base=base
)

# after
try:
    result = await PydanticAIHandler.handle_non_streaming(
        request_id=req_id, params=params, api_base=base
    )
except Exception as e:
    if "ended with state" in str(e):
        raise HTTPException(status_code=502, detail=f"Agent task failed: {e}") from e
    raise
Defensive patterns

Strategy: try-catch

Try / catch

try:
    result = await PydanticAIHandler.handle_non_streaming(req_id, params, api_base)
except Exception as e:
    msg = str(e)
    if "ended with state" in msg:
        # upstream agent reported failed/canceled: do not retry blindly
        raise UpstreamTaskFailedError(msg) from e
    raise

Prevention

When it happens

Trigger: The Pydantic AI agent's internal LLM call or tool execution fails and it marks the A2A task as failed; the task is canceled (by the agent or an operator) while the poll loop is between attempts; sending a payload the agent cannot process so it terminates the task.

Common situations: Upstream model outages or bad API keys configured inside the Pydantic AI agent; agent-side tool exceptions surfacing only as a failed task state; long-running tasks being canceled by an agent-side timeout; version drift between what the agent writes into status.state and what the poller expects.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/611f66fbe0978852. Report an issue: GitHub.

Appendix: source

Thrown at litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py:147

                json=poll_request,
                headers={
                    **(agent_extra_headers or {}),
                    "Content-Type": "application/json",
                },
            )
            response.raise_for_status()
            poll_data = _STR_KEY_DICT_ADAPTER.validate_python(response.json())

            result = _STR_KEY_DICT_ADAPTER.validate_python(poll_data.get("result", {}))
            status = _STR_KEY_DICT_ADAPTER.validate_python(result.get("status", {}))
            state = status.get("state", "")

            verbose_logger.debug("Pydantic AI: Poll attempt %s/%s, state=%s", attempt + 1, max_attempts, state)

            if state == "completed":
                return poll_data
            elif state in ("failed", "canceled"):
                raise Exception(f"Task {task_id} ended with state: {state}")

            await asyncio.sleep(poll_interval)

        raise TimeoutError(f"Task {task_id} did not complete within {max_attempts * poll_interval} seconds")

    @staticmethod
    async def _send_and_poll_raw(
        api_base: str,
        request_id: str,
        params: "_SupportsModelDump | _SupportsPydanticDict | Mapping[str, object]",
        timeout: float = 60.0,
        agent_extra_headers: dict[str, str] | None = None,
    ) -> dict[str, object]:
        """
        Send a request to Pydantic AI agent and return the raw task response.

        This is an internal method used by both non-streaming and streaming handlers.
        Returns the raw Pydantic AI task format with history/artifacts.

View on GitHub (pinned to 77b7c6c40c)