AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(blocks): parse HTTP response media types without losing error bodies (#14008)
Jiahao3cacb9ba7604
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.pyindex 49641377c8..a68e9606ff 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py@@ -71,6 +71,7 @@ def create_token(payload, private_key=None, kid: str = _SIGNING_KID) -> str:"""Helper to create ES256 JWT tokens signed by the active JWKS key."""if private_key is None:private_key = _signing_key+ assert private_key is not Nonereturn jwt.encode(payload, private_key, algorithm="ES256", headers={"kid": kid})diff --git a/autogpt_platform/backend/backend/blocks/http.py b/autogpt_platform/backend/backend/blocks/http.pyindex 359183d813..357b30c613 100644--- a/autogpt_platform/backend/backend/blocks/http.py+++ b/autogpt_platform/backend/backend/blocks/http.py@@ -29,7 +29,7 @@ from backend.util.file import (get_mime_type,store_media_file,)-from backend.util.request import Requests+from backend.util.request import Requests, Responselogger = logging.getLogger(name=__name__)@@ -206,11 +206,7 @@ class SendWebRequestBlock(Block):json=body if (input_data.json_format and not use_files) else None,)- # Decide how to parse the response- if response.headers.get("content-type", "").startswith("application/json"):- result = None if response.status == 204 else response.json()- else:- result = response.text()+ result = _parse_response_body(response, input_data.method)# Yield according to status code bucketif 200 <= response.status < 300:@@ -221,6 +217,25 @@ class SendWebRequestBlock(Block):yield "server_error", result+def _parse_response_body(response: Response, method: HttpMethod):+ if method == HttpMethod.HEAD or response.status in {204, 205}:+ return None++ content_type = (+ response.headers.get("content-type", "").partition(";")[0].strip().lower()+ )+ main_type, _, subtype = content_type.partition("/")+ is_json = content_type == "application/json" or (+ bool(main_type) and len(subtype) > len("+json") and subtype.endswith("+json")+ )+ if is_json:+ try:+ return response.json()+ except ValueError:+ return response.text()+ return response.text()++class SendAuthenticatedWebRequestBlock(SendWebRequestBlock):class Input(SendWebRequestBlock.Input):credentials: HttpCredentials = CredentialsField(diff --git a/autogpt_platform/backend/backend/blocks/test/test_http.py b/autogpt_platform/backend/backend/blocks/test/test_http.pyindex e01b8e2c5b..3e567f8e93 100644--- a/autogpt_platform/backend/backend/blocks/test/test_http.py+++ b/autogpt_platform/backend/backend/blocks/test/test_http.py@@ -10,6 +10,7 @@ from backend.blocks.http import (HttpCredentials,HttpMethod,SendAuthenticatedWebRequestBlock,+ SendWebRequestBlock,)from backend.data.execution import ExecutionContextfrom backend.data.model import HostScopedCredentials@@ -27,6 +28,181 @@ def make_test_context()+ "content_type",+ [+ "application/problem+json; charset=utf-8",+ " APPLICATION/PROBLEM+JSON ; charset=utf-8",+ "application/json; charset=utf-8",+ "application/vnd.api+json",+ ],+)+@patch("backend.blocks.http.Requests")+async def test_http_block_parses_structured_json_response(+ mock_requests_class,+ content_type,+):+ response = MagicMock(spec=Response)+ response.status = 400+ response.headers = {"content-type": content_type}+ response.json.return_value = {+ "type": "https://example.com/problems/invalid-request",+ "title": "Invalid request",+ }+ response.text.return_value = (+ '{"type":"https://example.com/problems/invalid-request",'+ '"title":"Invalid request"}'+ )+ mock_requests = AsyncMock()+ mock_requests.request.return_value = response+ mock_requests_class.return_value = mock_requests++ outputs = [+ output+ async for output in SendWebRequestBlock().run(+ SendWebRequestBlock.Input(+ url="https://api.example.com/data",+ method=HttpMethod.GET,+ ),+ execution_context=make_test_context(),+ )+ ]++ assert outputs == [+ (+ "client_error",+ {+ "type": "https://example.com/problems/invalid-request",+ "title": "Invalid request",+ },+ )+ ]+ response.json.assert_called_once_with()+ response.text.assert_not_called()+++ "content_type,status,method,body,expected,output_name",+ [+ ("application/problem+json", 502, HttpMethod.GET, b"", "", "server_error"),+ (+ "application/problem+json",+ 502,+ HttpMethod.GET,+ b"<html>Unavailable</html>",+ "<html>Unavailable</html>",+ "server_error",+ ),+ (+ "application/json",+ 400,+ HttpMethod.GET,+ b"invalid",+ "invalid",+ "client_error",+ ),+ ("application/problem+json", 200, HttpMethod.HEAD, b"", None, "response"),+ ("application/json", 204, HttpMethod.GET, b"", None, "response"),+ ("text/plain", 204, HttpMethod.GET, b"", None, "response"),+ ("application/json", 205, HttpMethod.GET, b"", None, "response"),+ ("text/plain", 200, HttpMethod.GET, b'{"ok":true}', '{"ok":true}', "response"),+ (+ "text/html",+ 400,+ HttpMethod.GET,+ b"<html>Error</html>",+ "<html>Error</html>",+ "client_error",+ ),+ ("", 200, HttpMethod.GET, b'{"ok":true}', '{"ok":true}', "response"),+ ("application/xml", 200, HttpMethod.GET, b"<ok/>", "<ok/>", "response"),+ (+ "application/jsonl",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ '{"ok":true}',+ "response",+ ),+ (+ "application/json-seq",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ '{"ok":true}',+ "response",+ ),+ (+ "application/x-ndjson",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ '{"ok":true}',+ "response",+ ),+ (+ "application/json5",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ '{"ok":true}',+ "response",+ ),+ (+ "problem+json",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ '{"ok":true}',+ "response",+ ),+ (+ " APPLICATION/VND.API+JSON ; charset=utf-8",+ 200,+ HttpMethod.GET,+ b'{"ok":true}',+ {"ok": True},+ "response",+ ),+ ("application/json", 200, HttpMethod.GET, b"null", None, "response"),+ ("application/json", 200, HttpMethod.GET, b"[1,2]", [1, 2], "response"),+ ],+)+@patch("backend.blocks.http.Requests")+async def test_http_response_body_contract(+ mock_requests_class,+ content_type,+ status,+ method,+ body,+ expected,+ output_name,+):+ raw_response = MagicMock()+ raw_response.status = status+ raw_response.headers = {"content-type": content_type}+ response = Response(+ response=raw_response,+ url="https://api.example.com/data",+ body=body,+ )+ mock_requests = AsyncMock()+ mock_requests.request.return_value = response+ mock_requests_class.return_value = mock_requests++ outputs = [+ output+ async for output in SendWebRequestBlock().run(+ SendWebRequestBlock.Input(url=response.url, method=method),+ execution_context=make_test_context(),+ )+ ]++ assert outputs == [(output_name, expected)]++class TestHttpBlockWithHostScopedCredentials:"""Test suite for HTTP block integration with HostScopedCredentials."""