{"record":{"id":"7551961d6829a287","repo":"BerriAI/litellm","slug":"task-task-id-did-not-complete-within-max-attemp","errorCode":null,"errorMessage":"Task {task_id} did not complete within {max_attempts * poll_interval} seconds","messagePattern":"Task (.+?) did not complete within (.+?) seconds","errorType":"exception","errorClass":"TimeoutError","httpStatus":null,"severity":"error","filePath":"litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py","lineNumber":151,"sourceCode":"                },\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.\n\n        Args:\n            api_base: Base URL of the Pydantic AI agent\n            request_id: A2A JSON-RPC request ID","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py#L133-L169","documentation":"transformation.py polls the Pydantic AI agent's task endpoint up to max_attempts times, sleeping poll_interval seconds between tries. If the state never reaches 'completed' (and never hits failed/canceled) within that window, it raises TimeoutError with the total budget (max_attempts * poll_interval seconds). The task may still be running upstream — this is a client-side give-up, not proof of agent failure.","triggerScenarios":"A long-running agent task (big prompt, slow tools, cold-started model) exceeding the poll budget; the agent server stalling mid-task so state stays 'working'/'submitted'; poll_interval/max_attempts left at defaults for workloads that need minutes.","commonSituations":"Heavy RAG or multi-tool agent runs against a modest polling budget; agent server under load responding slowly; network latency inflating each poll cycle; tasks that legitimately run longer than the default budget in production but not in tests.","solutions":["Increase the poll budget (max_attempts / poll_interval, or the timeout kwarg) for long-running agents","Check the agent server to confirm whether the task eventually completes — if yes, only the budget needs raising","Catch TimeoutError and retry the request or surface a 504-style response","Optimize the agent (smaller context, faster tools) so tasks finish inside the window"],"exampleFix":"# before\nresult = await PydanticAIHandler.handle_non_streaming(\n    request_id=req_id, params=params, api_base=base, timeout=60.0\n)\n\n# after\ntry:\n    result = await PydanticAIHandler.handle_non_streaming(\n        request_id=req_id, params=params, api_base=base, timeout=300.0\n    )\nexcept TimeoutError:\n    raise HTTPException(status_code=504, detail=\"Agent task timed out; retry or raise poll budget\")\n","handlingStrategy":"retry","validationCode":"def poll_budget_sufficient(expected_seconds: float, max_attempts: int, poll_interval: float) -> bool:\n    return max_attempts * poll_interval >= expected_seconds\n","typeGuard":null,"tryCatchPattern":"try:\n    result = await PydanticAIHandler.handle_non_streaming(req_id, params, api_base, timeout=timeout)\nexcept TimeoutError:\n    # task may still complete upstream; retry or surface 504\n    return JSONResponse(status_code=504, content={\"detail\": \"agent task timed out\"})\n","preventionTips":["Size the poll budget (timeout / max_attempts) to your agent's worst-case task duration","Track p99 task durations per agent and alert when they approach the budget","Return 504 with retry guidance so callers back off instead of hard-failing"],"tags":["pydantic-ai","a2a","polling","timeout","long-running-task"],"backgroundTag":"polling-timeout","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}