如何基于Python asyncio实现SageMaker端点的非阻塞异步请求?
SageMaker asyncio非阻塞请求实现方案
核心结论
SageMaker Python SDK目前不支持基于asyncio事件循环的非阻塞同步推理请求——你找到的AsyncPredictor是为AWS官方的「Async Inference」功能设计的,和你需要的客户端非阻塞调用不是同一类异步实现。
可行实现方式
如果要在asyncio环境下发起非阻塞的多请求,目前只能通过aiobotocore手动创建异步会话来调用SageMaker Runtime API,示例代码如下:
import asyncio import aiobotocore async def call_endpoint(session, endpoint_name, payload): async with session.create_client('sagemaker-runtime') as client: resp = await client.invoke_endpoint( EndpointName=endpoint_name, ContentType='application/json', Body=payload ) return await resp['Body'].read() async def main(): session = aiobotocore.get_session() # 批量创建异步请求任务 tasks = [ call_endpoint(session, "your-endpoint-name", '{"data": "sample-1"}'), call_endpoint(session, "your-endpoint-name", '{"data": "sample-2"}'), # 可按需添加更多请求任务 ] # 并发执行所有任务并获取结果 results = await asyncio.gather(*tasks) # 处理返回结果 for res in results: print(res.decode('utf-8')) if __name__ == "__main__": asyncio.run(main())
关键概念区分
需要明确两种「异步」的本质差异:
- AWS官方的Async Inference是服务端异步:提交请求后无需等待,结果存储到S3后再获取,适用于长时推理或大负载场景
- 你需要的是客户端asyncio非阻塞调用:在客户端事件循环中同时发起多个请求,避免单个请求阻塞整个流程
内容的提问来源于stack exchange,提问作者knowledge_seeker
相关产品推荐
相关产品推荐

