-
Notifications
You must be signed in to change notification settings - Fork 35
feat(licensing): normalize provider HTTP errors via provider_errors module #926
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vldcmp-uipath
wants to merge
1
commit into
main
Choose a base branch
from
feat/provider-error-normalization
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+260
−76
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| """Normalize LLM provider HTTP errors into a common shape. | ||
|
|
||
| Providers behind the LLM Gateway each raise a different exception type, but all | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should |
||
| carry the same gateway body (``{status, detail, ...}``); only the attribute that | ||
| holds it differs. LangChain may wrap the SDK error, so the useful fields can sit | ||
| a few links down the ``__cause__`` chain — always together, on one link. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class ProviderError: | ||
| """Normalized provider HTTP error: status code + user-facing detail.""" | ||
|
|
||
| status_code: int | None = None | ||
| detail: str | None = None | ||
|
|
||
| def __bool__(self) -> bool: | ||
| """Truthy once we have a status code — the signal that a provider matched.""" | ||
| return self.status_code is not None | ||
|
|
||
|
|
||
| def _int(value: object) -> int | None: | ||
| """The value if it is an int (a real HTTP status), else None. | ||
|
|
||
| Guards against matching unrelated exceptions that happen to carry a | ||
| ``code``/``status_code`` attribute that isn't an HTTP status. | ||
| """ | ||
| return value if isinstance(value, int) else None | ||
|
vldcmp-uipath marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def _detail(body: object) -> str | None: | ||
| """The gateway ``detail`` message from a parsed body dict, if present.""" | ||
| if isinstance(body, dict): | ||
| return body.get("detail") | ||
|
|
||
| return None | ||
|
vldcmp-uipath marked this conversation as resolved.
|
||
|
|
||
|
|
||
| # One extractor per provider: read that SDK's status code and detail out of the exception, if present | ||
| # Returns an empty (falsy) ProviderError when ``e`` isn't that provider's error type | ||
|
|
||
|
|
||
| def _from_openai(e: BaseException) -> ProviderError: | ||
| """OpenAI / Anthropic: ``e.status_code`` + ``e.body``.""" | ||
| return ProviderError( | ||
| _int(getattr(e, "status_code", None)), _detail(getattr(e, "body", None)) | ||
| ) | ||
|
|
||
|
|
||
| def _from_vertex(e: BaseException) -> ProviderError: | ||
| """Vertex / google.genai ``APIError``.""" | ||
| return ProviderError( | ||
| _int(getattr(e, "code", None)), _detail(getattr(e, "details", None)) | ||
| ) | ||
|
|
||
|
|
||
| def _from_bedrock(e: BaseException) -> ProviderError: | ||
| """Bedrock — same ``e.status_code`` + ``e.body`` shape as OpenAI. | ||
|
|
||
| Bedrock requests go through the uipath-client ``WrappedBotoClient`` shim | ||
| rather than boto3. On a gateway HTTP error its ``raise_for_status`` raises a | ||
| ``UiPathPermissionDeniedError`` (a ``UiPathAPIError`` / ``httpx.HTTPStatusError`` | ||
| subclass) that exposes the OpenAI-style ``.status_code`` and ``.body``. | ||
| """ | ||
| return ProviderError( | ||
| _int(getattr(e, "status_code", None)), _detail(getattr(e, "body", None)) | ||
| ) | ||
|
|
||
|
|
||
| def _from_botocore(e: BaseException) -> ProviderError: | ||
| """Bedrock via legacy direct boto3 (``use_new_llm_clients=False``): a | ||
| ``botocore.exceptions.ClientError`` carrying everything in ``e.response``.""" | ||
| resp = getattr(e, "response", None) | ||
| if not isinstance(resp, dict): | ||
| return ProviderError() | ||
| return ProviderError( | ||
| _int(resp.get("ResponseMetadata", {}).get("HTTPStatusCode")), | ||
| _detail(resp.get("Error")), | ||
| ) | ||
|
|
||
|
|
||
| _PROVIDERS = (_from_openai, _from_vertex, _from_bedrock, _from_botocore) | ||
|
|
||
|
|
||
| def extract_provider_error(e: BaseException | None) -> ProviderError: | ||
| """Return the first provider that matches ``e`` or any of its ``__cause__`` links.""" | ||
| if e is None: | ||
| return ProviderError() | ||
| for extract in _PROVIDERS: | ||
| error = extract(e) | ||
| if error: | ||
| return error | ||
| return extract_provider_error(e.__cause__) | ||
|
vldcmp-uipath marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| """Tests for normalizing provider HTTP errors into a common shape. | ||
|
|
||
| Each provider behind the LLM Gateway raises a different exception type, but all | ||
| carry the same gateway body (``{status, detail, ...}``). ``extract_provider_error`` | ||
| reads the status code + detail off whichever attribute the SDK exposes, walking | ||
| the ``__cause__`` chain when LangChain wraps the SDK error. | ||
| """ | ||
|
|
||
| import pytest | ||
| from uipath.runtime.errors import UiPathErrorCategory | ||
|
|
||
| from uipath_langchain.agent.exceptions.exceptions import ( | ||
| AgentRuntimeError, | ||
| AgentRuntimeErrorCode, | ||
| ) | ||
| from uipath_langchain.agent.exceptions.licensing import raise_for_provider_http_error | ||
| from uipath_langchain.chat.provider_errors import ( | ||
| ProviderError, | ||
| extract_provider_error, | ||
| ) | ||
|
|
||
| _DETAIL = "License not available for LLM usage. You need additional 'AGU'." | ||
| _BODY = { | ||
| "title": "License not available", | ||
| "status": 403, | ||
| "detail": _DETAIL, | ||
| } | ||
|
|
||
|
|
||
| class TestExtractProviderError: | ||
| def test_openai_status_code_and_body(self) -> None: | ||
| class OpenAIError(Exception): | ||
| status_code = 403 | ||
| body = _BODY | ||
|
|
||
| result = extract_provider_error(OpenAIError("Forbidden")) | ||
| assert result == ProviderError(status_code=403, detail=_DETAIL) | ||
|
|
||
| def test_bedrock_uipath_api_error_same_shape_as_openai(self) -> None: | ||
| # Bedrock via WrappedBotoClient surfaces as a UiPathAPIError (httpx | ||
| # subclass) exposing OpenAI-style .status_code / .body. | ||
| class UiPathPermissionDeniedError(Exception): | ||
| status_code = 403 | ||
| body = _BODY | ||
|
|
||
| result = extract_provider_error(UiPathPermissionDeniedError("Forbidden")) | ||
| assert result == ProviderError(status_code=403, detail=_DETAIL) | ||
|
|
||
| def test_vertex_wrapped_in_langchain_error(self) -> None: | ||
| # google.genai exposes .code + .details; LangChain wraps it in a class | ||
| # that itself exposes nothing, so the fields live on the __cause__. | ||
| class GenAIError(Exception): | ||
| code = 403 | ||
| details = _BODY | ||
|
|
||
| class ChatGoogleGenerativeAIError(Exception): | ||
| pass | ||
|
|
||
| try: | ||
| try: | ||
| raise GenAIError("403") | ||
| except GenAIError as cause: | ||
| raise ChatGoogleGenerativeAIError("wrapped") from cause | ||
| except ChatGoogleGenerativeAIError as wrapper: | ||
| result = extract_provider_error(wrapper) | ||
|
|
||
| assert result == ProviderError(status_code=403, detail=_DETAIL) | ||
|
|
||
| def test_botocore_response_dict(self) -> None: | ||
| # Legacy direct boto3 path: botocore.ClientError carries a response dict. | ||
| class ClientError(Exception): | ||
| response = { | ||
| "ResponseMetadata": {"HTTPStatusCode": 403}, | ||
| "Error": {"Code": "AccessDenied", "detail": _BODY["detail"]}, | ||
| } | ||
|
|
||
| result = extract_provider_error(ClientError("denied")) | ||
| assert result.status_code == 403 | ||
|
|
||
| def test_none_returns_empty(self) -> None: | ||
| result = extract_provider_error(None) | ||
| assert result == ProviderError() | ||
| assert not result | ||
|
|
||
| def test_non_int_status_attribute_is_ignored(self) -> None: | ||
| # An unrelated exception that happens to carry a string `code` must not | ||
| # be mistaken for a provider HTTP error. | ||
| class OSLike(Exception): | ||
| code = "ENOENT" | ||
|
|
||
| assert extract_provider_error(OSLike("nope")) == ProviderError() | ||
|
|
||
|
|
||
| class TestRaiseForProviderHttpError: | ||
| def test_403_maps_to_license_not_available(self) -> None: | ||
| class OpenAIError(Exception): | ||
| status_code = 403 | ||
| body = _BODY | ||
|
|
||
| with pytest.raises(AgentRuntimeError) as exc_info: | ||
| raise_for_provider_http_error(OpenAIError("Forbidden")) | ||
|
|
||
| info = exc_info.value.error_info | ||
| assert info.status == 403 | ||
| assert info.category == UiPathErrorCategory.DEPLOYMENT | ||
| assert info.code.endswith(AgentRuntimeErrorCode.LICENSE_NOT_AVAILABLE.value) | ||
| assert _DETAIL in info.detail | ||
|
|
||
| def test_other_status_falls_back_to_http_error_and_str(self) -> None: | ||
| # Non-403 status, and no `detail` in the body → detail falls back to str(e). | ||
| class OpenAIError(Exception): | ||
| status_code = 500 | ||
| body: dict[str, str] = {} | ||
|
|
||
| with pytest.raises(AgentRuntimeError) as exc_info: | ||
| raise_for_provider_http_error(OpenAIError("boom")) | ||
|
|
||
| info = exc_info.value.error_info | ||
| assert info.status == 500 | ||
| assert info.category == UiPathErrorCategory.UNKNOWN | ||
| assert info.code.endswith(AgentRuntimeErrorCode.HTTP_ERROR.value) | ||
| assert "boom" in info.detail # str(e) fallback | ||
|
|
||
| def test_no_status_does_not_raise(self) -> None: | ||
| # No extractable HTTP status → no-op (the original exception is left to | ||
| # propagate from the caller). Reaching the end without raising is the assert. | ||
| raise_for_provider_http_error(ValueError("unrelated transport error")) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.