{"record":{"id":"512440a88c1d7ca6","repo":"BerriAI/litellm","slug":"error-msg-response-text","errorCode":null,"errorMessage":"{error_msg}: {response.text}","messagePattern":"\\{error_msg\\}: \\{response\\.text\\}","errorType":"http","errorClass":"AzureAIAgentsError","httpStatus":null,"severity":"error","filePath":"litellm/llms/azure_ai/agents/handler.py","lineNumber":233,"sourceCode":"\n        # Azure Foundry Agents uses Bearer token authentication\n        # The api_key here is expected to be an Azure AD token\n        if api_key:\n            headers[\"Authorization\"] = f\"Bearer {api_key}\"\n\n        api_version: Final = optional_params.get(\"api_version\", self.config.DEFAULT_API_VERSION)\n        agent_id: Final = self.config._get_agent_id(model, optional_params)\n        thread_id: Final = optional_params.get(\"thread_id\")\n        api_base = api_base.rstrip(\"/\")\n\n        verbose_logger.debug(\"Azure AI Agents completion - api_base: %s, agent_id: %s\", api_base, agent_id)\n\n        return headers, api_version, agent_id, thread_id, api_base\n\n    def _check_response(self, response: httpx.Response, expected_codes: list[int], error_msg: str):\n        \"\"\"Check response status and raise error if not expected.\"\"\"\n        if response.status_code not in expected_codes:\n            raise AzureAIAgentsError(\n                status_code=response.status_code,\n                message=f\"{error_msg}: {response.text}\",\n            )\n\n    # -------------------------------------------------------------------------\n    # Sync Completion\n    # -------------------------------------------------------------------------\n    def completion(\n        self,\n        model: str,\n        messages: list[dict[str, Any]],\n        api_base: str,\n        api_key: str,\n        model_response: ModelResponse,\n        logging_obj: LiteLLMLoggingObj,\n        optional_params: dict,\n        litellm_params: dict,\n        timeout: float,","sourceCodeStart":215,"sourceCodeEnd":251,"githubUrl":"https://github.com/BerriAI/litellm/blob/6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d/litellm/llms/azure_ai/agents/handler.py#L215-L251","documentation":"The Azure AI Foundry Agents handler wraps every raw HTTP call (create thread, add message, create run, list messages) with _check_response. If the Azure service returns a status code outside the small expected list (usually [200]/[201]), it raises AzureAIAgentsError carrying the real HTTP status code and the untouched response body. The message format is '<operation>: <response.text>', e.g. 'Failed to get run status: {\"error\":{...}}'.","triggerScenarios":"Any Azure AI Agents completion call where an underlying REST step fails: wrong or expired API key (401), wrong api_base/project endpoint (404), invalid agent id in the model string (404), throttling (429), or a malformed payload the service rejects (400). Also 'Failed to get messages' when the thread was deleted mid-run.","commonSituations":"Azure AD token expired (tokens from `az account get-access-token` last ~1h); using the wrong endpoint flavor (project endpoint vs. services.ai.azure.com); agent deleted in Azure AI Foundry portal but still referenced in code; api_version mismatch after Azure deprecated a preview version.","solutions":["Read the status_code and response.text embedded in the exception message — they are the raw Azure error and pinpoint the failing step.","401/403: refresh the Azure AD token or fix AZURE_TENANT_ID/AZURE_CLIENT_ID/AZURE_CLIENT_SECRET; if you got the token manually with az, re-run it.","404: verify api_base points at your Foundry project endpoint and the agent id in model='azure_ai_agents/<agent_id>' exists.","429: back off and retry; honor Retry-After from the failing response."],"exampleFix":"# before\ntry:\n    resp = litellm.completion(model='azure_ai_agents/my-agent', messages=msgs, api_base=..., api_key=...)\nexcept AzureAIAgentsError as e:\n    raise  # opaque crash\n\n# after\nexcept AzureAIAgentsError as e:\n    if e.status_code in (401, 403):\n        api_key = refresh_azure_token()  # az account get-access-token --resource https://ai.azure.com\n    elif e.status_code == 429:\n        time.sleep(5)\n    else:\n        logger.error('agents call failed: %s %s', e.status_code, e.message)","handlingStrategy":"retry","validationCode":null,"typeGuard":"def is_azure_ai_agents_error(e: BaseException) -> bool:\n    return type(e).__name__ == 'AzureAIAgentsError' and hasattr(e, 'status_code')","tryCatchPattern":"try:\n    result = litellm.completion(model='azure_ai_agents/agent', ...)\nexcept Exception as e:\n    if type(e).__name__ == 'AzureAIAgentsError':\n        if e.status_code in (429, 500, 503):\n            await asyncio.sleep(backoff()); retry()\n        elif e.status_code in (401, 403):\n            refresh_token_and_retry_once()\n        else:\n            alert(f'agents failed {e.status_code}: {e.message}')\n    raise","preventionTips":["Refresh Azure AD tokens before expiry (they last ~1h) instead of waiting for 401s.","Smoke-test api_base + agent id at deploy time with a 1-message completion.","Log status_code and message of every AzureAIAgentsError to distinguish auth/404/throttle quickly."],"tags":["azure","agents","http-error","foundry","auth"],"backgroundTag":null,"analyzedSha":"6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d","analyzedAt":"2026-08-15T07:12:03.035Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}