34
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

念願の!API Gateway + Lambdaでストリーミングレスポンス!Bedrockの応答でカタカタできる!

34
Posted at

念願のやつが来ました。これで、API Gateway経由でもBedrockの応答をそのままストリーミングできます。

特に意味はないですが、大阪リージョンで試しました。

設定

  1. マネコンでLambda管理画面を表示します

  2. 「一から作成」を選択します

    ランタイムはNode.js 22.x、アーキテクチャはarm64を選択しました。
    ap-northeast-3.console.aws.amazon.com_lambda_home_region=ap-northeast-3 (1).png

  3. コードを記述します

    index.mjs
    import { pipeline } from 'node:stream/promises';
    import { BedrockRuntimeClient, ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
    
    export const handler = awslambda.streamifyResponse(async (event, responseStream, _context) => {
      const client = new BedrockRuntimeClient({ region: "ap-northeast-3" });  
    
      const command = new ConverseStreamCommand({
        modelId: "jp.anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages: [{role: "user", content:[{text: "桃太郎と浦島太郎が戦う物語を作って"}]}]
      });
      
      const response = await client.send(command);
    
      responseStream = awslambda.HttpResponseStream.from(responseStream, {
        statusCode: 200,
        headers: {
          "Content-Type": "application/json",
        }
      });
    
      for await (const chunk of response.stream) {
        responseStream.write(JSON.stringify(chunk) + '\n');
      }
    
      responseStream.end();
    });
    
  4. デプロイします

  5. 設定タブの一般設定で、タイムアウト値を伸ばして、IAMロールにBedrockへのアクセス権限(とりあえずAmazonBedrockFullAccess)を付与します

  6. 画面上部の「トリガーを追加」をクリックします

  7. API Gatewayを選び、「REST API」を選びます。(HTTP APIは多分ストリームに未対応です)

  8. 設定タブのトリガーを開き、API名(Bedrock-API)をクリックします

  9. 左メニューの「リソース」を選び、ツリー表示部分の「ANY」を選び、「統合リクエスト」タブを選び、「編集」をクリックします

  10. レスポンス転送モードを「ストリーム」に変更します

  11. 「APIをデプロイ」ボタンをクリックし、デプロイします

cURLで呼び出す。

  1. ツリーを開いていき、GETのところのURLをコピーします

  2. cURLを実行

    curl --no-buffer https://fi6axpddsk.execute-api.ap-northeast-3.amazonaws.com/default/Bedrock
    

動画でどうぞ

いいねとチャンネル登録よろしくお願いします😁

34
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?