|
| 1 | +import json |
| 2 | +from urllib.parse import urlencode |
| 3 | + |
| 4 | +from fastapi import Response |
| 5 | +from fastapi.responses import JSONResponse |
| 6 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 7 | + |
| 8 | + |
| 9 | +class BedrockAgentMiddleware(BaseHTTPMiddleware): |
| 10 | + async def dispatch(self, request, call_next): |
| 11 | + # pass through any non-events requests |
| 12 | + if request.url.path != "/events": |
| 13 | + return await call_next(request) |
| 14 | + |
| 15 | + # convert the request body to json object |
| 16 | + req_body = await request.body() |
| 17 | + req_body = json.loads(req_body) |
| 18 | + |
| 19 | + request.scope["path"] = req_body["apiPath"] |
| 20 | + request.scope["method"] = req_body["httpMethod"] |
| 21 | + |
| 22 | + # query params |
| 23 | + params = {} |
| 24 | + parameters = req_body.get("parameters", []) |
| 25 | + for item in parameters: |
| 26 | + params[item["name"]] = item["value"] |
| 27 | + request.scope["query_string"] = urlencode(params).encode() |
| 28 | + |
| 29 | + # body |
| 30 | + content = req_body.get("requestBody", {}).get("content", None) |
| 31 | + if content: |
| 32 | + for key in content.keys(): |
| 33 | + content_type = key |
| 34 | + break |
| 35 | + |
| 36 | + data = {} |
| 37 | + content_val = content.get(content_type, {}) |
| 38 | + for item in content_val.get("properties", []): |
| 39 | + data[item["name"]] = item["value"] |
| 40 | + request._body = json.dumps(data).encode() |
| 41 | + |
| 42 | + # Pass the request to be processed by the rest of the application |
| 43 | + response = await call_next(request) |
| 44 | + |
| 45 | + if isinstance(response, Response) and hasattr(response, "body"): |
| 46 | + res_body = response.body |
| 47 | + elif hasattr(response, "body_iterator"): |
| 48 | + res_body = b"" |
| 49 | + async for chunk in response.body_iterator: |
| 50 | + res_body += chunk |
| 51 | + response.body_iterator = self.recreate_iterator(res_body) |
| 52 | + else: |
| 53 | + res_body = None |
| 54 | + # Now you have the body, you can do whatever you want with it |
| 55 | + print(res_body) |
| 56 | + |
| 57 | + res_status_code = response.status_code |
| 58 | + res_content_type = response.headers["content-type"] |
| 59 | + |
| 60 | + response = JSONResponse( |
| 61 | + content={ |
| 62 | + "messageVersion": "1.0", |
| 63 | + "response": { |
| 64 | + "actionGroup": req_body["actionGroup"], |
| 65 | + "apiPath": req_body["apiPath"], |
| 66 | + "httpMethod": req_body["httpMethod"], |
| 67 | + "httpStatusCode": res_status_code, |
| 68 | + "responseBody": { |
| 69 | + res_content_type: {"body": res_body.decode("utf-8")} |
| 70 | + }, |
| 71 | + "sessionAttributes": req_body["sessionAttributes"], |
| 72 | + "promptSessionAttributes": req_body["promptSessionAttributes"], |
| 73 | + }, |
| 74 | + } |
| 75 | + ) |
| 76 | + |
| 77 | + print(response) |
| 78 | + return response |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + async def recreate_iterator(body): |
| 82 | + yield body |
0 commit comments