FastAPI の async def で Strands agent() を呼ぶとハングする
Strands エージェントを FastAPI で HTTP API 化しようとして、最初に async def でエンドポイントを定義したらリクエストがハングした。
@app.post("/invocations")
async def invoke(request: InvokeRequest):
result = agent(request.prompt) # ← ここでハング
return {"response": result.message["content"][0]["text"]}agent() はブロッキング呼び出しで、async def の中で実行するとイベントループ全体がブロックされる。def(同期関数)に変えるだけで解決する。
@app.post("/invocations")
def invoke(request: InvokeRequest):
result = agent(request.prompt) # ← スレッドプールで実行される
return {"response": result.message["content"][0]["text"]}FastAPI は def で定義されたエンドポイントを外部のスレッドプールで自動実行するため、メインのイベントループをブロックしない。デプロイ編 第 1 回で詳しく扱っている。
