本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
示例
以下示例显示了常见拦截器用例的 Python AWS Lambda 函数。
Pass-through 拦截器
此示例演示了一个简单的拦截器,该拦截器记录 REQUEST 拦截器的 MCP 方法,并将所有请求和响应不加修改地传递给他们:
import json import logging # Configure logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): """ Lambda function that handles both REQUEST and RESPONSE interceptor types. For REQUEST interceptors: logs the MCP method and passes request through unchanged For RESPONSE interceptors: passes response through unchanged """ # Extract the MCP data from the event mcp_data = event.get('mcp', {}) # Check if this is a REQUEST or RESPONSE interceptor based on presence of gatewayResponse if 'gatewayResponse' in mcp_data and mcp_data['gatewayResponse'] != None: # This is a RESPONSE interceptor logger.info("Processing RESPONSE interceptor - passing through unchanged") # Pass through the original request and response unchanged response = { "interceptorOutputVersion": "1.0", "mcp": { "transformedGatewayResponse": { "body": mcp_data.get('gatewayResponse', {}).get('body', {}), "statusCode": mcp_data.get('gatewayResponse', {}).get('statusCode', 200) } } } else: # This is a REQUEST interceptor gateway_request = mcp_data.get('gatewayRequest', {}) request_body = gateway_request.get('body', {}) mcp_method = request_body.get('method', 'unknown') # Log the MCP method logger.info(f"Processing REQUEST interceptor - MCP method: {mcp_method}") # Pass through the original request unchanged response = { "interceptorOutputVersion": "1.0", "mcp": { "transformedGatewayRequest": { "body": request_body, } } } return response
此 Lambda 函数可以配置为请求和响应拦截器。当配置为请求拦截器时,它将记录来自传入请求的 MCP 方法。当配置为响应拦截器时,它只会原封不动地传递响应。两种拦截器类型均未经修改地返回原始数据,使其成为 “直通” 拦截器。
使用请求拦截器自定义模型路由
对于推理目标,网关使用基于模型的路由从model字段中选择目标。REQUEST 拦截器可以在网关评估路由model之前进行重写,这使您可以支持虚拟模型 ID:一个不映射到任何单一配置模型的稳定别名。拦截器在表单中将别名解析为具体的目标限定ID{targetName}/{modelId},因此调用者使用一个名称,而您集中控制模型选择。
HTTP 拦截器有效载荷
推理目标使用http拦截器负载,其中请求正文是 base64 编码的字符串。有关更多信息,请参阅 HTTP 目标的拦截器。
以下请求拦截器根据请求输入的大小auto-claude将虚拟模型 ID 解析为特定的 Anthropic 模型:anthropic/claude-haiku-4-5小型请求、anthropic/claude-sonnet-4-6中型请求和anthropic/claude-opus-4-7大型请求。调用者发送auto-claude,网关将每个请求路由到anthropic目标上的已解析模型。使用任何其他模型 ID 的请求将保持不变,并遵循基于模型的正常路由。
import base64 import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) # The virtual model ID that this interceptor resolves to a concrete # target-qualified ID in the form "{targetName}/{modelId}". VIRTUAL_MODEL = "auto-claude" # Approximate input-size thresholds (in characters) used to choose a model. SONNET_THRESHOLD = 2000 OPUS_THRESHOLD = 8000 def resolve_auto_claude(payload): """Choose an Anthropic model based on the size of the request input.""" input_size = len(json.dumps(payload.get("input", ""))) if input_size >= OPUS_THRESHOLD: return "anthropic/claude-opus-4-7" if input_size >= SONNET_THRESHOLD: return "anthropic/claude-sonnet-4-6" return "anthropic/claude-haiku-4-5" def lambda_handler(event, context): http = event.get("http", {}) request = http.get("gatewayRequest", {}) encoded_body = request.get("body") # Nothing to transform (for example, an empty body) - pass through. if not encoded_body: return {"interceptorOutputVersion": "1.0", "http": {}} try: payload = json.loads(base64.b64decode(encoded_body)) except (ValueError, TypeError) as exc: logger.warning("Passing request through unchanged; could not parse body: %s", exc) return {"interceptorOutputVersion": "1.0", "http": {}} # Only resolve the virtual model ID; let everything else route normally. if not isinstance(payload, dict) or payload.get("model") != VIRTUAL_MODEL: return {"interceptorOutputVersion": "1.0", "http": {}} resolved = resolve_auto_claude(payload) logger.info("Resolved virtual model %s -> %s", VIRTUAL_MODEL, resolved) payload["model"] = resolved encoded = base64.b64encode(json.dumps(payload).encode("utf-8")).decode("utf-8") return { "interceptorOutputVersion": "1.0", "http": { "transformedGatewayRequest": { "body": encoded } }, }
将该函数作为请求拦截器附加到您的网关。有关说明,请参阅配置拦截器。网关服务角色还必须具有调用该函数的权限。有关更多信息,请参阅拦截器的权限。
要查看分辨率,请发送使用auto-claude别名的请求。拦截器根据输入大小重写model为具体的 Anthropic 模型,然后网关将请求路由到目标上的该模型。anthropic
awscurl --service bedrock-agentcore --region us-west-2 -X POST \ "https://GATEWAY_ID.gateway.bedrock-agentcore.us-west-2.amazonaws.com/inference/v1/responses" \ -H "Content-Type: application/json" \ -d '{"model": "auto-claude", "input": "Hello!", "max_output_tokens": 50}'