{"record":{"id":"611f66fbe0978852","repo":"BerriAI/litellm","slug":"task-task-id-ended-with-state-state","errorCode":null,"errorMessage":"Task {task_id} ended with state: {state}","messagePattern":"Task (.+?) ended with state: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py","lineNumber":147,"sourceCode":"                json=poll_request,\n                headers={\n                    **(agent_extra_headers or {}),\n                    \"Content-Type\": \"application/json\",\n                },\n            )\n            response.raise_for_status()\n            poll_data = _STR_KEY_DICT_ADAPTER.validate_python(response.json())\n\n            result = _STR_KEY_DICT_ADAPTER.validate_python(poll_data.get(\"result\", {}))\n            status = _STR_KEY_DICT_ADAPTER.validate_python(result.get(\"status\", {}))\n            state = status.get(\"state\", \"\")\n\n            verbose_logger.debug(\"Pydantic AI: Poll attempt %s/%s, state=%s\", attempt + 1, max_attempts, state)\n\n            if state == \"completed\":\n                return poll_data\n            elif state in (\"failed\", \"canceled\"):\n                raise Exception(f\"Task {task_id} ended with state: {state}\")\n\n            await asyncio.sleep(poll_interval)\n\n        raise TimeoutError(f\"Task {task_id} did not complete within {max_attempts * poll_interval} seconds\")\n\n    @staticmethod\n    async def _send_and_poll_raw(\n        api_base: str,\n        request_id: str,\n        params: \"_SupportsModelDump | _SupportsPydanticDict | Mapping[str, object]\",\n        timeout: float = 60.0,\n        agent_extra_headers: dict[str, str] | None = None,\n    ) -> dict[str, object]:\n        \"\"\"\n        Send a request to Pydantic AI agent and return the raw task response.\n\n        This is an internal method used by both non-streaming and streaming handlers.\n        Returns the raw Pydantic AI task format with history/artifacts.","sourceCodeStart":129,"sourceCodeEnd":165,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py#L129-L165","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check the Pydantic AI agent server logs for the real failure behind the failed/canceled task","Fix the upstream cause (agent's model credentials, tool code, or payload)","Catch this exception in your caller and map it to a 5xx/upstream-error response instead of crashing the route","If tasks are canceled by an aggressive agent-side limit, raise that limit or shorten request payloads"],"exampleFix":"# before\nresult = await PydanticAIHandler.handle_non_streaming(\n    request_id=req_id, params=params, api_base=base\n)\n\n# after\ntry:\n    result = await PydanticAIHandler.handle_non_streaming(\n        request_id=req_id, params=params, api_base=base\n    )\nexcept Exception as e:\n    if \"ended with state\" in str(e):\n        raise HTTPException(status_code=502, detail=f\"Agent task failed: {e}\") from e\n    raise\n","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    result = await PydanticAIHandler.handle_non_streaming(req_id, params, api_base)\nexcept Exception as e:\n    msg = str(e)\n    if \"ended with state\" in msg:\n        # upstream agent reported failed/canceled: do not retry blindly\n        raise UpstreamTaskFailedError(msg) from e\n    raise\n","preventionTips":["Monitor agent-side task failure rates and alert on spikes","Validate message payloads against the agent's expected input schema before sending","Keep agent dependencies (model keys, tools) healthy so tasks do not enter failed state"],"tags":["pydantic-ai","a2a","task-state","polling","upstream-failure"],"backgroundTag":"background-task-failed","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}