{"record":{"id":"6487c2bb3e7ed43a","repo":"openai/openai-python","slug":"expected-azure-ad-token-provider-argument-to-ret","errorCode":null,"errorMessage":"Expected `azure_ad_token_provider` argument to return a non-empty string.","messagePattern":"Expected `azure_ad_token_provider` argument to return a non-empty string\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/openai/lib/azure.py","lineNumber":451,"sourceCode":"                \"azure_ad_token_provider\": azure_ad_token_provider,\n                **_extra_kwargs,\n            },\n        )\n\n    with_options = copy\n\n    def _get_azure_ad_token(self) -> str | None:\n        if self._azure_ad_token is not None:\n            return self._azure_ad_token\n\n        provider = self._azure_ad_token_provider\n        if provider is not None:\n            token = cast(object, provider())\n            if isinstance(token, str):\n                # Bypass subclass methods before validating or interpolating credentials.\n                token = str.__str__(token)\n            if not isinstance(token, str) or not token:\n                raise ValueError(\"Expected `azure_ad_token_provider` argument to return a non-empty string.\")\n            return token\n\n        return None\n\n    @override\n    def _auth_headers(self, security: SecurityOptions) -> dict[str, str]:  # noqa: ARG002\n        if self._azure_ad_token is not None:\n            return {\"Authorization\": f\"Bearer {self._azure_ad_token}\"}\n\n        if self.api_key and self.api_key != API_KEY_SENTINEL:\n            return {\"api-key\": self.api_key}\n\n        return {}\n\n    @override\n    def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None:\n        if _has_auth_header(headers) or _has_auth_header(custom_headers):\n            return","sourceCodeStart":433,"sourceCodeEnd":469,"githubUrl":"https://github.com/openai/openai-python/blob/9917c6e28e66e90e1227b3d223c06a8c5441515a/src/openai/lib/azure.py#L433-L469","documentation":"The sync Azure client invokes your azure_ad_token_provider callable before each request and requires it to return a non-empty string. It raises ValueError if the callable returns None, an empty string, or any non-string value.","triggerScenarios":"Passing azure_ad_token_provider=lambda: None, a function whose credential lookup fails silently and returns empty, or one that returns bytes/an object instead of str.","commonSituations":"Using azure.identity DefaultAzureCredential token providers in an environment where the credential is unauthenticated; cached token helpers returning '' after expiry; providers with buggy string handling (str subclass bypass is attempted first).","solutions":["Make the provider raise on failure instead of returning None/empty","Verify DefaultAzureCredential can actually acquire a token in that environment (az login, managed identity, env vars)","Return the plain str token: lambda: str(token)"],"exampleFix":"# before\nclient = AzureOpenAI(azure_ad_token_provider=lambda: \"\")\n# after\nfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider\nclient = AzureOpenAI(azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"))","handlingStrategy":"validation","validationCode":"def safe_provider():\n    token = raw_provider()\n    if not isinstance(token, str) or not token:\n        raise RuntimeError(\"token provider failed to yield a token\")\n    return token\nclient = AzureOpenAI(azure_ad_token_provider=safe_provider)","typeGuard":"def is_valid_token(t) -> bool:\n    return isinstance(t, str) and len(t) > 0","tryCatchPattern":"try:\n    resp = client.chat.completions.create(...)\nexcept ValueError as e:\n    if \"azure_ad_token_provider\" in str(e):\n        refresh_credentials(); retry()\n    raise","preventionTips":["Never let providers return None/empty; raise instead","Test token acquisition at startup","Use azure.identity's get_bearer_token_provider rather than hand-rolled lambdas"],"tags":["azure","authentication","token-provider","azure-ad"],"backgroundTag":"token-provider-invalid-return","analyzedSha":"9917c6e28e66e90e1227b3d223c06a8c5441515a","analyzedAt":"2026-08-28T11:46:34.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}